text
stringlengths
54
60.6k
<commit_before>#include "BinaryTree.hpp" #include <fstream> #include <catch.hpp> SCENARIO("default constructor") { Tree<int> node; REQUIRE(node.root_() == nullptr); } SCENARIO("insert") { Tree<int> tree; int newEl; tree.fIn("Tree.txt"); std::ifstream("newEl.txt") >> newEl; tree.insert(newEl); REQUIRE(tree.right_() == 7); } SCENARIO("search") { Tree<int> tree; Node<int> * node; tree.fIn("Tree+newEl.txt"); node = tree.search(5); REQUIRE(tree.x_() == 5); REQUIRE(tree.left_() == 3); REQUIRE(tree.right_() == 7); } SCENARIO("fIn") { Tree<int> tree; tree.fIn("Tree.txt"); REQUIRE(tree.x_() == 5); } <commit_msg>Update init.cpp<commit_after>#include "BinaryTree.hpp" #include <catch.hpp> SCENARIO("default constructor") { Tree<int> node; REQUIRE(node.root_() == nullptr); } SCENARIO("insert") { Tree<int> tree; int newEl; tree.fIn("Tree.txt"); std::ifstream("newEl.txt") >> newEl; tree.insert(newEl); REQUIRE(tree.right_() == 7); } SCENARIO("search") { Tree<int> tree; Node<int> * node; tree.fIn("Tree+newEl.txt"); node = tree.search(5); REQUIRE(tree.x_() == 5); REQUIRE(tree.left_() == 3); REQUIRE(tree.right_() == 7); } SCENARIO("fIn") { Tree<int> tree; tree.fIn("Tree.txt"); REQUIRE(tree.x_() == 5); } <|endoftext|>
<commit_before>/* This file is part of the Vc library. Copyright (C) 2009 Matthias Kretz <kretz@kde.org> Vc is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. */ #include <Vc/Vc> #include "unittest.h" #include <iostream> using namespace Vc; template<typename Vec> void checkAlignment() { unsigned char i = 1; Vec a[10]; unsigned long mask = VectorAlignment - 1; if (Vec::Size == 1 && sizeof(typename Vec::EntryType) != VectorAlignment) { mask = sizeof(typename Vec::EntryType) - 1; } for (i = 0; i < 10; ++i) { VERIFY((reinterpret_cast<unsigned long>(&a[i]) & mask) == 0); } const char *data = reinterpret_cast<const char *>(&a[0]); for (i = 0; i < 10; ++i) { VERIFY(&data[i * Vec::Size * sizeof(typename Vec::EntryType)] == reinterpret_cast<const char *>(&a[i])); } } template<typename Vec> void loadArray() { typedef typename Vec::EntryType T; typedef typename Vec::IndexType I; const int count = 256 * 1024 / sizeof(T); T array[count]; for (int i = 0; i < count; ++i) { array[i] = i; } const I indexesFromZero(IndexesFromZero); const Vec offsets(indexesFromZero); for (int i = 0; i < count; i += Vec::Size) { const T *const addr = &array[i]; Vec ii(i); ii += offsets; Vec a(addr); COMPARE(a, ii); Vec b = Vec::Zero(); b.load(addr); COMPARE(b, ii); } } template<typename Vec> void loadArrayShort() { typedef typename Vec::EntryType T; const int count = 32 * 1024; T array[count]; for (int i = 0; i < count; ++i) { array[i] = i; } const Vec &offsets = static_cast<Vec>(ushort_v::IndexesFromZero()); for (int i = 0; i < count; i += Vec::Size) { const T *const addr = &array[i]; Vec ii(i); ii += offsets; Vec a(addr); COMPARE(a, ii); Vec b = Vec::Zero(); b.load(addr); COMPARE(b, ii); } } int main() { #if !VC_IMPL_LRBni && !defined(__LRB__) runTest(checkAlignment<int_v>); runTest(checkAlignment<uint_v>); runTest(checkAlignment<float_v>); runTest(checkAlignment<double_v>); runTest(checkAlignment<short_v>); runTest(checkAlignment<ushort_v>); runTest(checkAlignment<sfloat_v>); #endif runTest(loadArray<int_v>); runTest(loadArray<uint_v>); runTest(loadArray<float_v>); runTest(loadArray<double_v>); runTest(loadArray<sfloat_v>); runTest(loadArrayShort<short_v>); runTest(loadArrayShort<ushort_v>); return 0; } <commit_msg>checkAlignment needs a special case for AVX (u)short_v<commit_after>/* This file is part of the Vc library. Copyright (C) 2009 Matthias Kretz <kretz@kde.org> Vc is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. */ #include <Vc/Vc> #include "unittest.h" #include <iostream> using namespace Vc; template<typename Vec> void checkAlignment() { unsigned char i = 1; Vec a[10]; unsigned long mask = VectorAlignment - 1; if (Vec::Size == 1 && sizeof(typename Vec::EntryType) != VectorAlignment) { mask = sizeof(typename Vec::EntryType) - 1; } #ifdef VC_IMPL_AVX if (sizeof(typename Vec::EntryType) == 2) { mask = sizeof(Vec) - 1; } #endif for (i = 0; i < 10; ++i) { VERIFY((reinterpret_cast<unsigned long>(&a[i]) & mask) == 0); } const char *data = reinterpret_cast<const char *>(&a[0]); for (i = 0; i < 10; ++i) { VERIFY(&data[i * Vec::Size * sizeof(typename Vec::EntryType)] == reinterpret_cast<const char *>(&a[i])); } } template<typename Vec> void loadArray() { typedef typename Vec::EntryType T; typedef typename Vec::IndexType I; const int count = 256 * 1024 / sizeof(T); T array[count]; for (int i = 0; i < count; ++i) { array[i] = i; } const I indexesFromZero(IndexesFromZero); const Vec offsets(indexesFromZero); for (int i = 0; i < count; i += Vec::Size) { const T *const addr = &array[i]; Vec ii(i); ii += offsets; Vec a(addr); COMPARE(a, ii); Vec b = Vec::Zero(); b.load(addr); COMPARE(b, ii); } } template<typename Vec> void loadArrayShort() { typedef typename Vec::EntryType T; const int count = 32 * 1024; T array[count]; for (int i = 0; i < count; ++i) { array[i] = i; } const Vec &offsets = static_cast<Vec>(ushort_v::IndexesFromZero()); for (int i = 0; i < count; i += Vec::Size) { const T *const addr = &array[i]; Vec ii(i); ii += offsets; Vec a(addr); COMPARE(a, ii); Vec b = Vec::Zero(); b.load(addr); COMPARE(b, ii); } } int main() { #if !VC_IMPL_LRBni && !defined(__LRB__) runTest(checkAlignment<int_v>); runTest(checkAlignment<uint_v>); runTest(checkAlignment<float_v>); runTest(checkAlignment<double_v>); runTest(checkAlignment<short_v>); runTest(checkAlignment<ushort_v>); runTest(checkAlignment<sfloat_v>); #endif runTest(loadArray<int_v>); runTest(loadArray<uint_v>); runTest(loadArray<float_v>); runTest(loadArray<double_v>); runTest(loadArray<sfloat_v>); runTest(loadArrayShort<short_v>); runTest(loadArrayShort<ushort_v>); return 0; } <|endoftext|>
<commit_before>#include "pch.h" #include "LibFractal.h" TEST(TestCaseName, CallExportedFunction) { EXPECT_EQ(1, 1); EXPECT_TRUE(true); EXPECT_EQ(2, functionToTest(1)); } TEST(BasicTests, RunBenchMark) { EXPECT_EQ(0, runBenchmark(0, NULL)); }<commit_msg>test tweaks<commit_after>#include "pch.h" #include "LibFractal.h" TEST(BasicTests, CallExportedFunction) { EXPECT_EQ(2, functionToTest(1)); } TEST(BasicTests, RunBenchMark) { EXPECT_EQ(0, runBenchmark(0, NULL)); }<|endoftext|>
<commit_before>#include "quadrature/angular/angular_quadrature_scalar.h" #include "quadrature/angular/angular_quadrature_types.h" #include "test_helpers/gmock_wrapper.h" namespace { using namespace bart; template <typename DimensionWrapper> class AngularQuadratureScalarTests : public ::testing::Test { protected: static constexpr int dim = DimensionWrapper::value; // Tested object quadrature::angular::AngularQuadratureScalar<dim> test_scalar_quad_; }; TYPED_TEST_CASE(AngularQuadratureScalarTests, bart::testing::AllDimensions); TYPED_TEST(AngularQuadratureScalarTests, Constructor) { auto& test_scalar_quad_ = this->test_scalar_quad_; auto dim = this->dim; EXPECT_EQ(test_scalar_quad_.total_quadrature_points(), 1); } } // namespace<commit_msg>added test for quadrature points to tests for AngularQuadratureScalar<commit_after>#include "quadrature/angular/angular_quadrature_scalar.h" #include <array> #include <vector> #include "quadrature/angular/angular_quadrature_types.h" #include "test_helpers/gmock_wrapper.h" namespace { using namespace bart; using ::testing::ContainerEq; template <typename DimensionWrapper> class AngularQuadratureScalarTests : public ::testing::Test { protected: static constexpr int dim = DimensionWrapper::value; // Tested object quadrature::angular::AngularQuadratureScalar<dim> test_scalar_quad_; }; TYPED_TEST_CASE(AngularQuadratureScalarTests, bart::testing::AllDimensions); TYPED_TEST(AngularQuadratureScalarTests, Constructor) { auto& test_scalar_quad_ = this->test_scalar_quad_; constexpr int dim = this->dim; using QuadraturePoint = quadrature::angular::QuadraturePoint<dim>; using Ordinate = quadrature::angular::Ordinate<dim>; EXPECT_EQ(test_scalar_quad_.total_quadrature_points(), 1); Ordinate zero_ordinate; for (auto& angle_coordinate : zero_ordinate) angle_coordinate = 0; std::vector<QuadraturePoint> expected_quadrature_points{{1.0, zero_ordinate}}; EXPECT_THAT(test_scalar_quad_.quadrature_points(), ContainerEq(expected_quadrature_points)); } } // namespace<|endoftext|>
<commit_before>/* vim: set ts=2 expandtab: */ /** * @file test.cpp * @brief * * @author Josh King (jheretic), jking@chambana.net * * @internal * Created 11/17/2013 06:01:11 PM * Compiler gcc/g++ * Organization The Open Technology Institute * Copyright Copyright (c) 2013, Josh King * * This file is part of Commotion, Copyright (c) 2013, Josh King * * Commotion 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. * * Commotion 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 Commotion. If not, see <http://www.gnu.org/licenses/>. * * ===================================================================================== */ extern "C" { #include "../src/obj.h" #include "../src/list.h" #include "../src/tree.h" } #include "gtest/gtest.h" /* * NOTE: Inserting keys with different length values will be interpreted as different keys (eg insert("test", 5) and insert("test", 6) are not the same * and their values will be stored in different nodes in the tree * * */ class TreeTest : public ::testing::Test { protected: co_obj_t *Tree16; co_obj_t *Tree32; void InsertObj(); void DeleteObj(); void UpdateObj(); co_obj_t *TestString1; co_obj_t *TestString2; co_obj_t *ReplaceString1; co_obj_t *TestString3; co_obj_t *ptr; int ret; TreeTest() { Tree16 = co_tree16_create(); Tree32 = co_tree32_create(); TestString1 = co_str8_create("1TESTVALUE1", 12, 0); TestString2 = co_str8_create("2TESTVALUE2", 12, 0); // TestString3 = co_str8_create("1TESTVALUE1", 12, 0); ReplaceString1 = co_str8_create("REPLACE", 9, 0); } virtual void SetUp() { } ~TreeTest() { co_obj_free(Tree16); co_obj_free(Tree32); } }; void TreeTest::InsertObj() { ret = co_tree_insert(Tree16, "1TESTKEY1", 10, TestString1); ASSERT_EQ(1, ret); ptr = co_tree_find(Tree16, "1TESTKEY1", 10); ASSERT_EQ(TestString1, ptr); ret = co_tree_insert(Tree16, "2TESTKEY2", 10, TestString2); ASSERT_EQ(1, ret); ptr = co_tree_find(Tree16, "2TESTKEY2", 10); ASSERT_EQ(TestString2, ptr); ret = co_tree_insert_force(Tree16, "1TESTKEY1", 10, ReplaceString1); ASSERT_EQ(1, ret); ptr = co_tree_find(Tree16, "1TESTKEY1", 10); ASSERT_EQ(ReplaceString1, ptr); // reinitialize TestString1 since it was freed by co_tree_insert_force() TestString1 = co_str8_create("1TESTVALUE1", 12, 0); // repeat for Tree 32 ret = co_tree_insert(Tree32, "1TESTKEY1", 10, TestString1); ASSERT_EQ(1, ret); ptr = co_tree_find(Tree32, "1TESTKEY1", 10); ASSERT_EQ(TestString1, ptr); ret = co_tree_insert(Tree32, "2TESTKEY2", 10, TestString2); ASSERT_EQ(1, ret); ptr = co_tree_find(Tree32, "2TESTKEY2", 10); ASSERT_EQ(TestString2, ptr); ret = co_tree_insert_force(Tree32, "1TESTKEY1", 10, ReplaceString1); ASSERT_EQ(1, ret); ptr = co_tree_find(Tree32, "1TESTKEY1", 10); ASSERT_EQ(ReplaceString1, ptr); } void TreeTest::DeleteObj() { ret = co_tree_insert(Tree16, "1TESTKEY1", 10, TestString1); ASSERT_EQ(1, ret); ret = co_tree_insert(Tree16, "2TESTKEY2", 10, TestString2); ASSERT_EQ(1, ret); ptr = co_tree_delete(Tree16, "1TESTKEY1", 10); ASSERT_EQ(TestString1, ptr); ptr = co_tree_delete(Tree16, "2TESTKEY2", 10); ASSERT_EQ(TestString2, ptr); // confirm deletions ptr = co_tree_find(Tree16, "1TESTKEY1", 10); ASSERT_EQ(NULL, ptr); ptr = co_tree_find(Tree16, "2TESTKEY2", 10); ASSERT_EQ(NULL, ptr); // repeat for Tree32 ret = co_tree_insert(Tree32, "1TESTKEY1", 10, TestString1); ASSERT_EQ(1, ret); ret = co_tree_insert(Tree32, "2TESTKEY2", 10, TestString2); ASSERT_EQ(1, ret); ptr = co_tree_delete(Tree32, "1TESTKEY1", 10); ASSERT_EQ(TestString1, ptr); ptr = co_tree_delete(Tree32, "2TESTKEY2", 10); ASSERT_EQ(TestString2, ptr); // confirm deletions ptr = co_tree_find(Tree32, "1TESTKEY1", 10); ASSERT_EQ(NULL, ptr); ptr = co_tree_find(Tree32, "2TESTKEY2", 10); ASSERT_EQ(NULL, ptr); } void TreeTest::UpdateObj() { ret = co_tree_insert(Tree16, "1TESTKEY1", 10, TestString1); ASSERT_EQ(1, ret); ret = co_tree_set_str(Tree16, "1TESTKEY1", 10, "REPLACE", 9); ASSERT_EQ(1, ret); ptr = co_tree_find(Tree16, "1TESTKEY1", 10); ASSERT_EQ(0, co_str_cmp(ptr, ReplaceString1)); /* // repeat for Tree32 ret = co_tree_insert(Tree32, "1TESTKEY1", 10, TestString1); ASSERT_EQ(1, ret); ret = co_tree_set_str(Tree32, "1TESTKEY1", 10, "REPLACE", 9); ASSERT_EQ(1, ret); ptr = co_tree_find(Tree32, "1TESTKEY1", 10); ASSERT_EQ(0, co_str_cmp(ptr, ReplaceString1)); */ } TEST_F(TreeTest, TreeInsertTest) { InsertObj(); } TEST_F(TreeTest, TreeDeleteTest) { DeleteObj(); } TEST_F(TreeTest, TreeUpdateTest) { UpdateObj(); } <commit_msg>did stuff<commit_after>/* vim: set ts=2 expandtab: */ /** * @file test.cpp * @brief * * @author Josh King (jheretic), jking@chambana.net * * @internal * Created 11/17/2013 06:01:11 PM * Compiler gcc/g++ * Organization The Open Technology Institute * Copyright Copyright (c) 2013, Josh King * * This file is part of Commotion, Copyright (c) 2013, Josh King * * Commotion 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. * * Commotion 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 Commotion. If not, see <http://www.gnu.org/licenses/>. * * ===================================================================================== */ extern "C" { #include "../src/obj.h" #include "../src/list.h" #include "../src/tree.h" } #include "gtest/gtest.h" /* * NOTE: Inserting keys with different length values will be interpreted as different keys (eg insert("test", 5) and insert("test", 6) are not the same * and their values will be stored in different nodes in the tree * * */ class TreeTest : public ::testing::Test { protected: co_obj_t *Tree16; co_obj_t *Tree32; void InsertObj(); void DeleteObj(); void UpdateObj(); co_obj_t *TestString1; co_obj_t *TestString2; co_obj_t *ReplaceString1; co_obj_t *TestString3; co_obj_t *ptr; int ret; TreeTest() { Tree16 = co_tree16_create(); Tree32 = co_tree32_create(); TestString1 = co_str8_create("1TESTVALUE1", 12, 0); TestString2 = co_str8_create("2TESTVALUE2", 12, 0); ReplaceString1 = co_str8_create("REPLACE", 9, 0); } virtual void SetUp() { } ~TreeTest() { co_obj_free(Tree16); co_obj_free(Tree32); } }; void TreeTest::InsertObj() { ret = co_tree_insert(Tree16, "1TESTKEY1", 10, TestString1); ASSERT_EQ(1, ret); ptr = co_tree_find(Tree16, "1TESTKEY1", 10); ASSERT_EQ(TestString1, ptr); ret = co_tree_insert(Tree16, "2TESTKEY2", 10, TestString2); ASSERT_EQ(1, ret); ptr = co_tree_find(Tree16, "2TESTKEY2", 10); ASSERT_EQ(TestString2, ptr); ret = co_tree_insert_force(Tree16, "1TESTKEY1", 10, ReplaceString1); ASSERT_EQ(1, ret); ptr = co_tree_find(Tree16, "1TESTKEY1", 10); ASSERT_EQ(ReplaceString1, ptr); // reinitialize TestString1 since it was freed by co_tree_insert_force() TestString1 = co_str8_create("1TESTVALUE1", 12, 0); // repeat for Tree 32 ret = co_tree_insert(Tree32, "1TESTKEY1", 10, TestString1); ASSERT_EQ(1, ret); ptr = co_tree_find(Tree32, "1TESTKEY1", 10); ASSERT_EQ(TestString1, ptr); ret = co_tree_insert(Tree32, "2TESTKEY2", 10, TestString2); ASSERT_EQ(1, ret); ptr = co_tree_find(Tree32, "2TESTKEY2", 10); ASSERT_EQ(TestString2, ptr); ret = co_tree_insert_force(Tree32, "1TESTKEY1", 10, ReplaceString1); ASSERT_EQ(1, ret); ptr = co_tree_find(Tree32, "1TESTKEY1", 10); ASSERT_EQ(ReplaceString1, ptr); } void TreeTest::DeleteObj() { ret = co_tree_insert(Tree16, "1TESTKEY1", 10, TestString1); ASSERT_EQ(1, ret); ret = co_tree_insert(Tree16, "2TESTKEY2", 10, TestString2); ASSERT_EQ(1, ret); ptr = co_tree_delete(Tree16, "1TESTKEY1", 10); ASSERT_EQ(TestString1, ptr); ptr = co_tree_delete(Tree16, "2TESTKEY2", 10); ASSERT_EQ(TestString2, ptr); // confirm deletions ptr = co_tree_find(Tree16, "1TESTKEY1", 10); ASSERT_EQ(NULL, ptr); ptr = co_tree_find(Tree16, "2TESTKEY2", 10); ASSERT_EQ(NULL, ptr); // reinitialize TestString1 = co_str8_create("1TESTVALUE1", 12, 0); TestString2 = co_str8_create("2TESTVALUE2", 12, 0); // repeat for Tree32 ret = co_tree_insert(Tree32, "1TESTKEY1", 10, TestString1); ASSERT_EQ(1, ret); ret = co_tree_insert(Tree32, "2TESTKEY2", 10, TestString2); ASSERT_EQ(1, ret); ptr = co_tree_delete(Tree32, "1TESTKEY1", 10); ASSERT_EQ(TestString1, ptr); ptr = co_tree_delete(Tree32, "2TESTKEY2", 10); ASSERT_EQ(TestString2, ptr); // confirm deletions ptr = co_tree_find(Tree32, "1TESTKEY1", 10); ASSERT_EQ(NULL, ptr); ptr = co_tree_find(Tree32, "2TESTKEY2", 10); ASSERT_EQ(NULL, ptr); } void TreeTest::UpdateObj() { ret = co_tree_insert(Tree16, "1TESTKEY1", 10, TestString1); ASSERT_EQ(1, ret); ret = co_tree_set_str(Tree16, "1TESTKEY1", 10, "REPLACE", 9); ASSERT_EQ(1, ret); ptr = co_tree_find(Tree16, "1TESTKEY1", 10); ASSERT_EQ(0, co_str_cmp(ptr, ReplaceString1)); // repeat for Tree32 ret = co_tree_insert(Tree32, "1TESTKEY1", 10, TestString1); ASSERT_EQ(1, ret); ret = co_tree_set_str(Tree32, "1TESTKEY1", 10, "REPLACE", 9); ASSERT_EQ(1, ret); ptr = co_tree_find(Tree32, "1TESTKEY1", 10); ASSERT_EQ(0, co_str_cmp(ptr, ReplaceString1)); } TEST_F(TreeTest, TreeInsertTest) { InsertObj(); } TEST_F(TreeTest, TreeDeleteTest) { DeleteObj(); } /* TEST_F(TreeTest, TreeUpdateTest) { UpdateObj(); } */<|endoftext|>
<commit_before>// The MIT License (MIT) // // Copyright (c) 2016 Northeastern University // // 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 "include/gpu_operations.h" #include "Eigen/Dense" #include "gtest/gtest.h" template<class T> class GpuMatrixMatrixSubTest : public ::testing::Test { public: Nice::Matrix<T> a; Nice::Matrix<T> b; Nice::Matrix<T> result; Nice::Matrix<T> correct; void Subtract() { result = Nice::GpuOperations<T>::Subtract(a, b); } }; typedef ::testing::Types<float, double> dataTypes; TYPED_TEST_CASE(GpuMatrixMatrixSubTest, dataTypes); TYPED_TEST(GpuMatrixMatrixSubTest, SubtractFunctionality) { this->a.setRandom(3, 3); this->b.setRandom(3, 3); this->correct.setZero(3, 3); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { correct(i, j) = a(i, j) - b(i, j); } } this->Subtract(); ASSERT_NEAR(this->result, this->correct, 0.0001); } TYPED_TEST(GpuMatrixMatrixSubTest, DifferentSizeMatricies) { this->a.setRandom(2, 3); this->b.setRandom(3, 4); ASSERT_DEATH(this->Subtract(), ".*"); } TYPED_TEST(GpuMatrixMatrixSubTest, EmptyMatrix) { ASSERT_DEATH(this->Subtract(), ".*"); } <commit_msg>Fixed this-> in test and ASSERT_NEAR in for loop<commit_after>// The MIT License (MIT) // // Copyright (c) 2016 Northeastern University // // 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 "include/gpu_operations.h" #include "Eigen/Dense" #include "gtest/gtest.h" template<class T> class GpuMatrixMatrixSubTest : public ::testing::Test { public: Nice::Matrix<T> a; Nice::Matrix<T> b; Nice::Matrix<T> result; Nice::Matrix<T> correct; void Subtract() { result = Nice::GpuOperations<T>::Subtract(a, b); } }; typedef ::testing::Types<float, double> dataTypes; TYPED_TEST_CASE(GpuMatrixMatrixSubTest, dataTypes); TYPED_TEST(GpuMatrixMatrixSubTest, SubtractFunctionality) { this->a.setRandom(3, 3); this->b.setRandom(3, 3); this->correct.setZero(3, 3); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { this->correct(i, j) = this->a(i, j) - this->b(i, j); } } this->Subtract(); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { ASSERT_NEAR(this->result(i, j), this->correct(i, j), 0.0001); } } } TYPED_TEST(GpuMatrixMatrixSubTest, DifferentSizeMatricies) { this->a.setRandom(2, 3); this->b.setRandom(3, 4); ASSERT_DEATH(this->Subtract(), ".*"); } TYPED_TEST(GpuMatrixMatrixSubTest, EmptyMatrix) { ASSERT_DEATH(this->Subtract(), ".*"); } <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "otbWrapperCompositeApplication.h" #include "otbWrapperApplicationFactory.h" namespace otb { namespace Wrapper { /** * \class LargeScaleMeanShift * * \brief All-in-one application for the LSMS framework * * This application gathers the 4 steps of the large-scale MeanShift * segmentation framework. * */ class LargeScaleMeanShift : public CompositeApplication { public: /** Standard class typedefs. */ typedef LargeScaleMeanShift Self; typedef CompositeApplication Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(LargeScaleMeanShift, otb::CompositeApplication); private: void DoInit() ITK_OVERRIDE { SetName("LargeScaleMeanShift"); SetDescription("Large-scale segmentation using MeanShift"); // Documentation SetDocName("Large-Scale MeanShift"); SetDocLongDescription("This application chains together the 4 steps of the " "MeanShit framework, that is the MeanShiftSmoothing [1], the " "LSMSSegmentation [2], the LSMSSmallRegionsMerging [3] and the " "LSMSVectorization [4].\n\n" "This application can be a preliminary step for an object-based analysis.\n\n" "It generates a vector data file containing the regions extracted with " "the MeanShift algorithm. The spatial and range radius parameters allow " "to adapt the sensitivity of the algorithm depending on the image dynamic " "and resolution. There is a step to remove small regions whose size " "(in pixels) is less than the given 'minsize' parameter. These regions " "are merged to a similar neighbor region. In the output vectors, there " "are additional fields to describe each region. In particular the mean " "and standard deviation (for each band) is computed for each region " "using the input image as support. If an optional 'imfield' image is " "given, it will be used as support image instead." ); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso("[1] MeanShiftSmoothing\n" "[2] LSMSSegmentation\n" "[3] LSMSSmallRegionsMerging\n" "[4] LSMSVectorization"); AddDocTag(Tags::Segmentation); AddDocTag("LSMS"); ClearApplications(); AddApplication("MeanShiftSmoothing", "smoothing", "Smoothing step"); AddApplication("LSMSSegmentation", "segmentation", "Segmentation step"); AddApplication("LSMSSmallRegionsMerging", "merging", "Small region merging step"); AddApplication("LSMSVectorization", "vectorization", "Vectorization step"); ShareParameter("in","smoothing.in"); ShareParameter("spatialr","smoothing.spatialr"); ShareParameter("ranger","smoothing.ranger"); ShareParameter("minsize","merging.minsize"); ShareParameter("tilesizex","segmentation.tilesizex"); ShareParameter("tilesizey","segmentation.tilesizey"); AddParameter(ParameterType_InputImage, "imfield", "Support image for field computation"); SetParameterDescription( "imfield", "This is an optional support image " "that can be used to compute field values in each region." ); MandatoryOff("imfield"); ShareParameter("out","vectorization.out"); AddParameter( ParameterType_Empty, "cleanup", "Temporary files cleaning" ); EnableParameter( "cleanup" ); SetParameterDescription( "cleanup", "If activated, the application will try to clean all temporary files it created" ); MandatoryOff( "cleanup" ); // Setup RAM ShareParameter("ram","smoothing.ram"); Connect("merging.ram","smoothing.ram"); Connect("vectorization.ram","smoothing.ram"); Connect("merging.tilesizex","segmentation.tilesizex"); Connect("merging.tilesizey","segmentation.tilesizey"); Connect("vectorization.tilesizex","segmentation.tilesizex"); Connect("vectorization.tilesizey","segmentation.tilesizey"); // TODO : this is not exactly true, we used to choose the smoothed image instead Connect("merging.in","smoothing.in"); // Setup constant parameters GetInternalApplication("smoothing")->SetParameterString("foutpos","foo"); GetInternalApplication("smoothing")->EnableParameter("foutpos"); // Doc example parameter settings SetDocExampleParameterValue("in", "QB_1_ortho.tif"); SetDocExampleParameterValue("spatialr", "4"); SetDocExampleParameterValue("ranger", "80"); SetDocExampleParameterValue("minsize", "16"); SetDocExampleParameterValue("out", "regions.shp"); SetOfficialDocLink(); } void DoUpdateParameters() ITK_OVERRIDE {} void DoExecute() ITK_OVERRIDE { std::vector<std::string> tmpFilenames; tmpFilenames.push_back(GetParameterString("out")+std::string("_labelmap.tif")); tmpFilenames.push_back(GetParameterString("out")+std::string("_labelmap_merged.tif")); tmpFilenames.push_back(GetParameterString("out")+std::string("_labelmap.geom")); tmpFilenames.push_back(GetParameterString("out")+std::string("_labelmap_merged.geom")); ExecuteInternal("smoothing"); // in-memory connexion here (saves 1 additional update for foutpos) GetInternalApplication("segmentation")->SetParameterInputImage("in", GetInternalApplication("smoothing")->GetParameterOutputImage("fout")); GetInternalApplication("segmentation")->SetParameterInputImage("inpos", GetInternalApplication("smoothing")->GetParameterOutputImage("foutpos")); // temporary file output here GetInternalApplication("segmentation")->SetParameterString("out", tmpFilenames[0]); // take half of previous radii GetInternalApplication("segmentation")->SetParameterFloat("spatialr", 0.5 * (double)GetInternalApplication("smoothing")->GetParameterInt("spatialr")); GetInternalApplication("segmentation")->SetParameterFloat("ranger", 0.5 * GetInternalApplication("smoothing")->GetParameterFloat("ranger")); GetInternalApplication("segmentation")->ExecuteAndWriteOutput(); GetInternalApplication("merging")->SetParameterString("inseg", tmpFilenames[0]); GetInternalApplication("merging")->SetParameterString("out", tmpFilenames[1]); GetInternalApplication("merging")->ExecuteAndWriteOutput(); if (IsParameterEnabled("imfield") && HasValue("imfield")) { GetInternalApplication("vectorization")->SetParameterString("in", GetParameterString("imfield")); } else { GetInternalApplication("vectorization")->SetParameterString("in", GetParameterString("in")); } GetInternalApplication("vectorization")->SetParameterString("inseg", tmpFilenames[1]); ExecuteInternal("vectorization"); if( IsParameterEnabled( "cleanup" ) ) { otbAppLogINFO( <<"Final clean-up ..." ); for (unsigned int i=0 ; i<tmpFilenames.size() ; ++i) { if(itksys::SystemTools::FileExists(tmpFilenames[i].c_str())) { itksys::SystemTools::RemoveFile(tmpFilenames[i].c_str()); } } } } }; } // end of namespace Wrapper } // end of namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::LargeScaleMeanShift) <commit_msg>ENH: switch between raster and vector output<commit_after>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "otbWrapperCompositeApplication.h" #include "otbWrapperApplicationFactory.h" namespace otb { namespace Wrapper { /** * \class LargeScaleMeanShift * * \brief All-in-one application for the LSMS framework * * This application gathers the 4 steps of the large-scale MeanShift * segmentation framework. * */ class LargeScaleMeanShift : public CompositeApplication { public: /** Standard class typedefs. */ typedef LargeScaleMeanShift Self; typedef CompositeApplication Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(LargeScaleMeanShift, otb::CompositeApplication); private: void DoInit() ITK_OVERRIDE { SetName("LargeScaleMeanShift"); SetDescription("Large-scale segmentation using MeanShift"); // Documentation SetDocName("Large-Scale MeanShift"); SetDocLongDescription("This application chains together the 4 steps of the " "MeanShit framework, that is the MeanShiftSmoothing [1], the " "LSMSSegmentation [2], the LSMSSmallRegionsMerging [3] and the " "LSMSVectorization [4].\n\n" "This application can be a preliminary step for an object-based analysis.\n\n" "It generates a vector data file containing the regions extracted with " "the MeanShift algorithm. The spatial and range radius parameters allow " "to adapt the sensitivity of the algorithm depending on the image dynamic " "and resolution. There is a step to remove small regions whose size " "(in pixels) is less than the given 'minsize' parameter. These regions " "are merged to a similar neighbor region. In the output vectors, there " "are additional fields to describe each region. In particular the mean " "and standard deviation (for each band) is computed for each region " "using the input image as support. If an optional 'imfield' image is " "given, it will be used as support image instead." ); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso("[1] MeanShiftSmoothing\n" "[2] LSMSSegmentation\n" "[3] LSMSSmallRegionsMerging\n" "[4] LSMSVectorization"); AddDocTag(Tags::Segmentation); AddDocTag("LSMS"); ClearApplications(); AddApplication("MeanShiftSmoothing", "smoothing", "Smoothing step"); AddApplication("LSMSSegmentation", "segmentation", "Segmentation step"); AddApplication("LSMSSmallRegionsMerging", "merging", "Small region merging step"); AddApplication("LSMSVectorization", "vectorization", "Vectorization step"); ShareParameter("in","smoothing.in"); ShareParameter("spatialr","smoothing.spatialr"); ShareParameter("ranger","smoothing.ranger"); ShareParameter("minsize","merging.minsize"); ShareParameter("tilesizex","segmentation.tilesizex"); ShareParameter("tilesizey","segmentation.tilesizey"); AddParameter(ParameterType_Choice, "mode","Output mode"); SetParameterDescription("mode", "Type of segmented output"); AddChoice("mode.vector", "Segmentation as vector output."); SetParameterDescription("mode.vector","In this mode, the application will " "produce a vector file or database and compute field values for each " "region"); AddParameter(ParameterType_InputImage, "mode.vector.imfield", "Support image for field computation"); SetParameterDescription( "mode.vector.imfield", "This is an optional support image " "that can be used to compute field values in each region. Otherwise, the " "input image is used as support." ); MandatoryOff("mode.vector.imfield"); ShareParameter("mode.vector.out","vectorization.out"); AddChoice("mode.raster", "Standard segmentation with labeled raster output"); SetParameterDescription("mode.raster","In this mode, the application will produce a standard labeled raster."); ShareParameter("mode.raster.out","merging.out"); AddParameter( ParameterType_Empty, "cleanup", "Temporary files cleaning" ); EnableParameter( "cleanup" ); SetParameterDescription( "cleanup", "If activated, the application will try to clean all temporary files it created" ); MandatoryOff( "cleanup" ); // Setup RAM ShareParameter("ram","smoothing.ram"); Connect("merging.ram","smoothing.ram"); Connect("vectorization.ram","smoothing.ram"); Connect("merging.tilesizex","segmentation.tilesizex"); Connect("merging.tilesizey","segmentation.tilesizey"); Connect("vectorization.tilesizex","segmentation.tilesizex"); Connect("vectorization.tilesizey","segmentation.tilesizey"); // TODO : this is not exactly true, we used to choose the smoothed image instead Connect("merging.in","smoothing.in"); // Setup constant parameters GetInternalApplication("smoothing")->SetParameterString("foutpos","foo"); GetInternalApplication("smoothing")->EnableParameter("foutpos"); // Doc example parameter settings SetDocExampleParameterValue("in", "QB_1_ortho.tif"); SetDocExampleParameterValue("spatialr", "4"); SetDocExampleParameterValue("ranger", "80"); SetDocExampleParameterValue("minsize", "16"); SetDocExampleParameterValue("out", "regions.shp"); SetOfficialDocLink(); DebugOn(); } void DoUpdateParameters() ITK_OVERRIDE {} void DoExecute() ITK_OVERRIDE { std::vector<std::string> tmpFilenames; tmpFilenames.push_back(GetParameterString("out")+std::string("_labelmap.tif")); tmpFilenames.push_back(GetParameterString("out")+std::string("_labelmap.geom")); ExecuteInternal("smoothing"); // in-memory connexion here (saves 1 additional update for foutpos) GetInternalApplication("segmentation")->SetParameterInputImage("in", GetInternalApplication("smoothing")->GetParameterOutputImage("fout")); GetInternalApplication("segmentation")->SetParameterInputImage("inpos", GetInternalApplication("smoothing")->GetParameterOutputImage("foutpos")); // temporary file output here GetInternalApplication("segmentation")->SetParameterString("out", tmpFilenames[0]); // take half of previous radii GetInternalApplication("segmentation")->SetParameterFloat("spatialr", 0.5 * (double)GetInternalApplication("smoothing")->GetParameterInt("spatialr")); GetInternalApplication("segmentation")->SetParameterFloat("ranger", 0.5 * GetInternalApplication("smoothing")->GetParameterFloat("ranger")); GetInternalApplication("segmentation")->ExecuteAndWriteOutput(); GetInternalApplication("merging")->SetParameterString("inseg", tmpFilenames[0]); EnableParameter("mode.raster.out"); if (GetParameterString("mode") == "vector") { tmpFilenames.push_back(GetParameterString("out")+std::string("_labelmap_merged.tif")); tmpFilenames.push_back(GetParameterString("out")+std::string("_labelmap_merged.geom")); GetInternalApplication("merging")->SetParameterString("out", tmpFilenames[2]); GetInternalApplication("merging")->ExecuteAndWriteOutput(); if (IsParameterEnabled("mode.vector.imfield") && HasValue("mode.vector.imfield")) { GetInternalApplication("vectorization")->SetParameterString("in", GetParameterString("mode.vector.imfield")); } else { GetInternalApplication("vectorization")->SetParameterString("in", GetParameterString("in")); } GetInternalApplication("vectorization")->SetParameterString("inseg", tmpFilenames[2]); ExecuteInternal("vectorization"); } else { GetInternalApplication("merging")->ExecuteAndWriteOutput(); } DisableParameter("mode.raster.out"); if( IsParameterEnabled( "cleanup" ) ) { otbAppLogINFO( <<"Final clean-up ..." ); for (unsigned int i=0 ; i<tmpFilenames.size() ; ++i) { if(itksys::SystemTools::FileExists(tmpFilenames[i].c_str())) { itksys::SystemTools::RemoveFile(tmpFilenames[i].c_str()); } } } } }; } // end of namespace Wrapper } // end of namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::LargeScaleMeanShift) <|endoftext|>
<commit_before>#include "Arith256.h" #include "Runtime.h" #include "Type.h" #include <llvm/IR/Function.h> namespace dev { namespace eth { namespace jit { Arith256::Arith256(llvm::IRBuilder<>& _builder) : CompilerHelper(_builder) { using namespace llvm; m_result = m_builder.CreateAlloca(Type::Word, nullptr, "arith.result"); m_arg1 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg1"); m_arg2 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg2"); m_arg3 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg3"); using Linkage = GlobalValue::LinkageTypes; llvm::Type* arg2Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr}; llvm::Type* arg3Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr}; m_mul = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_mul", getModule()); m_div = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_div", getModule()); m_mod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_mod", getModule()); m_sdiv = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_sdiv", getModule()); m_smod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_smod", getModule()); m_exp = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_exp", getModule()); m_addmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, "arith_addmod", getModule()); m_mulmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, "arith_mulmod", getModule()); } Arith256::~Arith256() {} llvm::Value* Arith256::binaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2) { m_builder.CreateStore(_arg1, m_arg1); m_builder.CreateStore(_arg2, m_arg2); m_builder.CreateCall3(_op, m_arg1, m_arg2, m_result); return m_builder.CreateLoad(m_result); } llvm::Value* Arith256::ternaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3) { m_builder.CreateStore(_arg1, m_arg1); m_builder.CreateStore(_arg2, m_arg2); m_builder.CreateStore(_arg3, m_arg3); m_builder.CreateCall4(_op, m_arg1, m_arg2, m_arg3, m_result); return m_builder.CreateLoad(m_result); } llvm::Value* Arith256::mul(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_mul, _arg1, _arg2); } llvm::Value* Arith256::div(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_div, _arg1, _arg2); } llvm::Value* Arith256::mod(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_mod, _arg1, _arg2); } llvm::Value* Arith256::sdiv(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_sdiv, _arg1, _arg2); } llvm::Value* Arith256::smod(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_smod, _arg1, _arg2); } llvm::Value* Arith256::exp(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_exp, _arg1, _arg2); } llvm::Value* Arith256::addmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3) { return ternaryOp(m_addmod, _arg1, _arg2, _arg3); } llvm::Value* Arith256::mulmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3) { return ternaryOp(m_mulmod, _arg1, _arg2, _arg3); } namespace { using s256 = boost::multiprecision::int256_t; inline s256 u2s(u256 _u) { static const bigint c_end = (bigint)1 << 256; static const u256 c_send = (u256)1 << 255; if (_u < c_send) return (s256)_u; else return (s256)-(c_end - _u); } inline u256 s2u(s256 _u) { static const bigint c_end = (bigint)1 << 256; if (_u >= 0) return (u256)_u; else return (u256)(c_end + _u); } } } } } extern "C" { using namespace dev::eth::jit; EXPORT void arith_mul(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg1 * arg2); } EXPORT void arith_div(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg2 == 0 ? arg2 : arg1 / arg2); } EXPORT void arith_mod(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg2 == 0 ? arg2 : arg1 % arg2); } EXPORT void arith_sdiv(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg2 == 0 ? arg2 : s2u(u2s(arg1) / u2s(arg2))); } EXPORT void arith_smod(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg2 == 0 ? arg2 : s2u(u2s(arg1) % u2s(arg2))); } EXPORT void arith_exp(i256* _arg1, i256* _arg2, i256* o_result) { bigint left = llvm2eth(*_arg1); bigint right = llvm2eth(*_arg2); auto ret = static_cast<u256>(boost::multiprecision::powm(left, right, bigint(2) << 256)); *o_result = eth2llvm(ret); } EXPORT void arith_mulmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); auto arg3 = llvm2eth(*_arg3); if (arg3 != 0) *o_result = eth2llvm(u256((bigint(arg1) * bigint(arg2)) % arg3)); else *o_result = {}; } EXPORT void arith_addmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); auto arg3 = llvm2eth(*_arg3); if (arg3 != 0) *o_result = eth2llvm(u256((bigint(arg1) + bigint(arg2)) % arg3)); else *o_result = {}; } } <commit_msg>Internal mul256 implementation<commit_after>#include "Arith256.h" #include "Runtime.h" #include "Type.h" #include <llvm/IR/Function.h> namespace dev { namespace eth { namespace jit { Arith256::Arith256(llvm::IRBuilder<>& _builder) : CompilerHelper(_builder) { using namespace llvm; m_result = m_builder.CreateAlloca(Type::Word, nullptr, "arith.result"); m_arg1 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg1"); m_arg2 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg2"); m_arg3 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg3"); using Linkage = GlobalValue::LinkageTypes; llvm::Type* arg2Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr}; llvm::Type* arg3Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr}; m_mul = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_mul", getModule()); m_div = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_div", getModule()); m_mod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_mod", getModule()); m_sdiv = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_sdiv", getModule()); m_smod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_smod", getModule()); m_exp = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_exp", getModule()); m_addmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, "arith_addmod", getModule()); m_mulmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, "arith_mulmod", getModule()); } Arith256::~Arith256() {} llvm::Value* Arith256::binaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2) { m_builder.CreateStore(_arg1, m_arg1); m_builder.CreateStore(_arg2, m_arg2); m_builder.CreateCall3(_op, m_arg1, m_arg2, m_result); return m_builder.CreateLoad(m_result); } llvm::Value* Arith256::ternaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3) { m_builder.CreateStore(_arg1, m_arg1); m_builder.CreateStore(_arg2, m_arg2); m_builder.CreateStore(_arg3, m_arg3); m_builder.CreateCall4(_op, m_arg1, m_arg2, m_arg3, m_result); return m_builder.CreateLoad(m_result); } llvm::Value* Arith256::mul(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_mul, _arg1, _arg2); } llvm::Value* Arith256::div(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_div, _arg1, _arg2); } llvm::Value* Arith256::mod(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_mod, _arg1, _arg2); } llvm::Value* Arith256::sdiv(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_sdiv, _arg1, _arg2); } llvm::Value* Arith256::smod(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_smod, _arg1, _arg2); } llvm::Value* Arith256::exp(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_exp, _arg1, _arg2); } llvm::Value* Arith256::addmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3) { return ternaryOp(m_addmod, _arg1, _arg2, _arg3); } llvm::Value* Arith256::mulmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3) { return ternaryOp(m_mulmod, _arg1, _arg2, _arg3); } namespace { using s256 = boost::multiprecision::int256_t; inline s256 u2s(u256 _u) { static const bigint c_end = (bigint)1 << 256; static const u256 c_send = (u256)1 << 255; if (_u < c_send) return (s256)_u; else return (s256)-(c_end - _u); } inline u256 s2u(s256 _u) { static const bigint c_end = (bigint)1 << 256; if (_u >= 0) return (u256)_u; else return (u256)(c_end + _u); } using uint128 = __uint128_t; // uint128 add(uint128 a, uint128 b) { return a + b; } // uint128 mul(uint128 a, uint128 b) { return a * b; } // // uint128 mulq(uint64_t x, uint64_t y) // { // return (uint128)x * (uint128)y; // } // // uint128 addc(uint64_t x, uint64_t y) // { // return (uint128)x * (uint128)y; // } struct uint256 { uint64_t lo; uint64_t mid; uint128 hi; }; // uint256 add(uint256 x, uint256 y) // { // auto lo = (uint128) x.lo + y.lo; // auto mid = (uint128) x.mid + y.mid + (lo >> 64); // return {lo, mid, x.hi + y.hi + (mid >> 64)}; // } uint256 mul(uint256 x, uint256 y) { auto t1 = (uint128) x.lo * y.lo; auto t2 = (uint128) x.lo * y.mid; auto t3 = x.lo * y.hi; auto t4 = (uint128) x.mid * y.lo; auto t5 = (uint128) x.mid * y.mid; auto t6 = x.mid * y.hi; auto t7 = x.hi * y.lo; auto t8 = x.hi * y.mid; auto lo = (uint64_t) t1; auto m1 = (t1 >> 64) + (uint64_t) t2; auto m2 = (uint64_t) m1; auto mid = (uint128) m2 + (uint64_t) t4; auto hi = (t2 >> 64) + t3 + (t4 >> 64) + t5 + (t6 << 64) + t7 + (t8 << 64) + (m1 >> 64) + (mid >> 64); return {lo, (uint64_t)mid, hi}; } } } } } extern "C" { using namespace dev::eth::jit; EXPORT void arith_mul(uint256* _arg1, uint256* _arg2, uint256* o_result) { *o_result = mul(*_arg1, *_arg2); } EXPORT void arith_div(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg2 == 0 ? arg2 : arg1 / arg2); } EXPORT void arith_mod(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg2 == 0 ? arg2 : arg1 % arg2); } EXPORT void arith_sdiv(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg2 == 0 ? arg2 : s2u(u2s(arg1) / u2s(arg2))); } EXPORT void arith_smod(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg2 == 0 ? arg2 : s2u(u2s(arg1) % u2s(arg2))); } EXPORT void arith_exp(i256* _arg1, i256* _arg2, i256* o_result) { bigint left = llvm2eth(*_arg1); bigint right = llvm2eth(*_arg2); auto ret = static_cast<u256>(boost::multiprecision::powm(left, right, bigint(2) << 256)); *o_result = eth2llvm(ret); } EXPORT void arith_mulmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); auto arg3 = llvm2eth(*_arg3); if (arg3 != 0) *o_result = eth2llvm(u256((bigint(arg1) * bigint(arg2)) % arg3)); else *o_result = {}; } EXPORT void arith_addmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); auto arg3 = llvm2eth(*_arg3); if (arg3 != 0) *o_result = eth2llvm(u256((bigint(arg1) + bigint(arg2)) % arg3)); else *o_result = {}; } } <|endoftext|>
<commit_before> #include "GasMeter.h" #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/Function.h> #include <llvm/IR/IntrinsicInst.h> #include <libevmface/Instruction.h> #include <libevm/FeeStructure.h> #include "Type.h" #include "Ext.h" #include "Runtime.h" namespace dev { namespace eth { namespace jit { namespace // Helper functions { uint64_t getStepCost(Instruction inst) // TODO: Add this function to FeeSructure (pull request submitted) { switch (inst) { case Instruction::STOP: case Instruction::SUICIDE: return 0; case Instruction::SSTORE: return static_cast<uint64_t>(c_sstoreResetGas); // FIXME: Check store gas case Instruction::SLOAD: return static_cast<uint64_t>(c_sloadGas); case Instruction::SHA3: return static_cast<uint64_t>(c_sha3Gas); case Instruction::BALANCE: return static_cast<uint64_t>(c_sha3Gas); case Instruction::CALL: case Instruction::CALLCODE: return static_cast<uint64_t>(c_callGas); case Instruction::CREATE: return static_cast<uint64_t>(c_createGas); default: // Assumes instruction code is valid return static_cast<uint64_t>(c_stepGas); } } bool isCostBlockEnd(Instruction _inst) { // Basic block terminators like STOP are not needed on the list // as cost will be commited at the end of basic block // CALL & CALLCODE are commited manually switch (_inst) { case Instruction::CALLDATACOPY: case Instruction::CODECOPY: case Instruction::MLOAD: case Instruction::MSTORE: case Instruction::MSTORE8: case Instruction::SSTORE: case Instruction::GAS: case Instruction::CREATE: return true; default: return false; } } } GasMeter::GasMeter(llvm::IRBuilder<>& _builder, RuntimeManager& _runtimeManager) : CompilerHelper(_builder), m_runtimeManager(_runtimeManager) { auto module = getModule(); m_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, Type::i256, false), llvm::Function::PrivateLinkage, "gas.check", module); InsertPointGuard guard(m_builder); auto checkBB = llvm::BasicBlock::Create(_builder.getContext(), "Check", m_gasCheckFunc); auto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), "OutOfGas", m_gasCheckFunc); auto updateBB = llvm::BasicBlock::Create(_builder.getContext(), "Update", m_gasCheckFunc); m_builder.SetInsertPoint(checkBB); llvm::Value* cost = m_gasCheckFunc->arg_begin(); cost->setName("cost"); auto gas = m_runtimeManager.getGas(); auto isOutOfGas = m_builder.CreateICmpUGT(cost, gas, "isOutOfGas"); m_builder.CreateCondBr(isOutOfGas, outOfGasBB, updateBB); m_builder.SetInsertPoint(outOfGasBB); _runtimeManager.raiseException(ReturnCode::OutOfGas); m_builder.CreateUnreachable(); m_builder.SetInsertPoint(updateBB); gas = m_builder.CreateSub(gas, cost); m_runtimeManager.setGas(gas); m_builder.CreateRetVoid(); } void GasMeter::count(Instruction _inst) { if (!m_checkCall) { // Create gas check call with mocked block cost at begining of current cost-block m_checkCall = m_builder.CreateCall(m_gasCheckFunc, llvm::UndefValue::get(Type::i256)); } if (_inst != Instruction::SSTORE) // Handle cost of SSTORE separately in countSStore() m_blockCost += getStepCost(_inst); if (isCostBlockEnd(_inst)) commitCostBlock(); } void GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue) { assert(!m_checkCall); // Everything should've been commited before static const auto sstoreCost = static_cast<uint64_t>(c_sstoreResetGas); // FIXME: Check store gas // [ADD] if oldValue == 0 and newValue != 0 => 2*cost // [DEL] if oldValue != 0 and newValue == 0 => 0 auto oldValue = _ext.store(_index); auto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), "oldValueIsZero"); auto newValueIsZero = m_builder.CreateICmpEQ(_newValue, Constant::get(0), "newValueIsZero"); auto oldValueIsntZero = m_builder.CreateICmpNE(oldValue, Constant::get(0), "oldValueIsntZero"); auto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), "newValueIsntZero"); auto isAdd = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, "isAdd"); auto isDel = m_builder.CreateAnd(oldValueIsntZero, newValueIsZero, "isDel"); auto cost = m_builder.CreateSelect(isAdd, Constant::get(2 * sstoreCost), Constant::get(sstoreCost), "cost"); cost = m_builder.CreateSelect(isDel, Constant::get(0), cost, "cost"); createCall(m_gasCheckFunc, cost); } void GasMeter::giveBack(llvm::Value* _gas) { m_runtimeManager.setGas(m_builder.CreateAdd(m_runtimeManager.getGas(), _gas)); } void GasMeter::commitCostBlock(llvm::Value* _additionalCost) { assert(!_additionalCost || m_checkCall); // _additionalCost => m_checkCall; Must be inside cost-block // If any uncommited block if (m_checkCall) { if (m_blockCost == 0) // Do not check 0 { m_checkCall->eraseFromParent(); // Remove the gas check call m_checkCall = nullptr; return; } m_checkCall->setArgOperand(0, Constant::get(m_blockCost)); // Update block cost in gas check call m_checkCall = nullptr; // End cost-block m_blockCost = 0; if (_additionalCost) { m_builder.CreateCall(m_gasCheckFunc, _additionalCost); } } assert(m_blockCost == 0); } void GasMeter::checkMemory(llvm::Value* _additionalMemoryInWords, llvm::IRBuilder<>& _builder) { // Memory uses other builder, but that can be changes later auto cost = _builder.CreateMul(_additionalMemoryInWords, Constant::get(static_cast<uint64_t>(c_memoryGas)), "memcost"); _builder.CreateCall(m_gasCheckFunc, cost); } } } } <commit_msg>Improve GasMeter code formatting<commit_after> #include "GasMeter.h" #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/Function.h> #include <llvm/IR/IntrinsicInst.h> #include <libevmface/Instruction.h> #include <libevm/FeeStructure.h> #include "Type.h" #include "Ext.h" #include "Runtime.h" namespace dev { namespace eth { namespace jit { namespace // Helper functions { uint64_t getStepCost(Instruction inst) // TODO: Add this function to FeeSructure (pull request submitted) { switch (inst) { case Instruction::STOP: case Instruction::SUICIDE: return 0; case Instruction::SSTORE: return static_cast<uint64_t>(c_sstoreResetGas); // FIXME: Check store gas case Instruction::SLOAD: return static_cast<uint64_t>(c_sloadGas); case Instruction::SHA3: return static_cast<uint64_t>(c_sha3Gas); case Instruction::BALANCE: return static_cast<uint64_t>(c_sha3Gas); case Instruction::CALL: case Instruction::CALLCODE: return static_cast<uint64_t>(c_callGas); case Instruction::CREATE: return static_cast<uint64_t>(c_createGas); default: // Assumes instruction code is valid return static_cast<uint64_t>(c_stepGas); } } bool isCostBlockEnd(Instruction _inst) { // Basic block terminators like STOP are not needed on the list // as cost will be commited at the end of basic block // CALL & CALLCODE are commited manually switch (_inst) { case Instruction::CALLDATACOPY: case Instruction::CODECOPY: case Instruction::MLOAD: case Instruction::MSTORE: case Instruction::MSTORE8: case Instruction::SSTORE: case Instruction::GAS: case Instruction::CREATE: return true; default: return false; } } } GasMeter::GasMeter(llvm::IRBuilder<>& _builder, RuntimeManager& _runtimeManager) : CompilerHelper(_builder), m_runtimeManager(_runtimeManager) { auto module = getModule(); m_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, Type::i256, false), llvm::Function::PrivateLinkage, "gas.check", module); InsertPointGuard guard(m_builder); auto checkBB = llvm::BasicBlock::Create(_builder.getContext(), "Check", m_gasCheckFunc); auto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), "OutOfGas", m_gasCheckFunc); auto updateBB = llvm::BasicBlock::Create(_builder.getContext(), "Update", m_gasCheckFunc); m_builder.SetInsertPoint(checkBB); llvm::Value* cost = m_gasCheckFunc->arg_begin(); cost->setName("cost"); auto gas = m_runtimeManager.getGas(); auto isOutOfGas = m_builder.CreateICmpUGT(cost, gas, "isOutOfGas"); m_builder.CreateCondBr(isOutOfGas, outOfGasBB, updateBB); m_builder.SetInsertPoint(outOfGasBB); _runtimeManager.raiseException(ReturnCode::OutOfGas); m_builder.CreateUnreachable(); m_builder.SetInsertPoint(updateBB); gas = m_builder.CreateSub(gas, cost); m_runtimeManager.setGas(gas); m_builder.CreateRetVoid(); } void GasMeter::count(Instruction _inst) { if (!m_checkCall) { // Create gas check call with mocked block cost at begining of current cost-block m_checkCall = m_builder.CreateCall(m_gasCheckFunc, llvm::UndefValue::get(Type::i256)); } if (_inst != Instruction::SSTORE) // Handle cost of SSTORE separately in countSStore() m_blockCost += getStepCost(_inst); if (isCostBlockEnd(_inst)) commitCostBlock(); } void GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue) { assert(!m_checkCall); // Everything should've been commited before static const auto sstoreCost = static_cast<uint64_t>(c_sstoreResetGas); // FIXME: Check store gas // [ADD] if oldValue == 0 and newValue != 0 => 2*cost // [DEL] if oldValue != 0 and newValue == 0 => 0 auto oldValue = _ext.store(_index); auto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), "oldValueIsZero"); auto newValueIsZero = m_builder.CreateICmpEQ(_newValue, Constant::get(0), "newValueIsZero"); auto oldValueIsntZero = m_builder.CreateICmpNE(oldValue, Constant::get(0), "oldValueIsntZero"); auto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), "newValueIsntZero"); auto isAdd = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, "isAdd"); auto isDel = m_builder.CreateAnd(oldValueIsntZero, newValueIsZero, "isDel"); auto cost = m_builder.CreateSelect(isAdd, Constant::get(2 * sstoreCost), Constant::get(sstoreCost), "cost"); cost = m_builder.CreateSelect(isDel, Constant::get(0), cost, "cost"); createCall(m_gasCheckFunc, cost); } void GasMeter::giveBack(llvm::Value* _gas) { m_runtimeManager.setGas(m_builder.CreateAdd(m_runtimeManager.getGas(), _gas)); } void GasMeter::commitCostBlock(llvm::Value* _additionalCost) { assert(!_additionalCost || m_checkCall); // _additionalCost => m_checkCall; Must be inside cost-block // If any uncommited block if (m_checkCall) { if (m_blockCost == 0) // Do not check 0 { m_checkCall->eraseFromParent(); // Remove the gas check call m_checkCall = nullptr; return; } m_checkCall->setArgOperand(0, Constant::get(m_blockCost)); // Update block cost in gas check call m_checkCall = nullptr; // End cost-block m_blockCost = 0; if (_additionalCost) { m_builder.CreateCall(m_gasCheckFunc, _additionalCost); } } assert(m_blockCost == 0); } void GasMeter::checkMemory(llvm::Value* _additionalMemoryInWords, llvm::IRBuilder<>& _builder) { // Memory uses other builder, but that can be changes later auto cost = _builder.CreateMul(_additionalMemoryInWords, Constant::get(static_cast<uint64_t>(c_memoryGas)), "memcost"); _builder.CreateCall(m_gasCheckFunc, cost); } } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2001-2007 Peter Simons <simons@cryp.to> * * This software is provided 'as-is', without any express or * implied warranty. In no event will the authors be held liable * for any damages arising from the use of this software. * * Copying and distribution of this file, with or without * modification, are permitted in any medium without royalty * provided the copyright notice and this notice are preserved. */ #include "fastcgi.hpp" #include <iostream> #include <assert.h> #include <stdio.h> #ifndef _WIN32 #include <memory.h> #endif typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; enum message_type_t { TYPE_BEGIN_REQUEST = 1 , TYPE_ABORT_REQUEST = 2 , TYPE_END_REQUEST = 3 , TYPE_PARAMS = 4 , TYPE_STDIN = 5 , TYPE_STDOUT = 6 , TYPE_STDERR = 7 , TYPE_DATA = 8 , TYPE_GET_VALUES = 9 , TYPE_GET_VALUES_RESULT = 10 , TYPE_UNKNOWN = 11 }; struct Header { uint8_t version; uint8_t type; uint8_t requestIdB1; uint8_t requestIdB0; uint8_t contentLengthB1; uint8_t contentLengthB0; uint8_t paddingLength; uint8_t reserved; Header() { memset(this, 0, sizeof(*this)); } Header(message_type_t t, uint16_t id, uint16_t len) : version(1), type(t) , requestIdB1(id >> 8) , requestIdB0(id & 0xff) , contentLengthB1(len >> 8) , contentLengthB0(len & 0xff) , paddingLength(0), reserved(0) { } }; struct BeginRequest { uint8_t roleB1; uint8_t roleB0; uint8_t flags; uint8_t reserved[5]; }; static uint8_t const FLAG_KEEP_CONN = 1; struct EndRequestMsg : public Header { uint8_t appStatusB3; uint8_t appStatusB2; uint8_t appStatusB1; uint8_t appStatusB0; uint8_t protocolStatus; uint8_t reserved[3]; EndRequestMsg() { memset(this, 0, sizeof(*this)); } EndRequestMsg(uint16_t id, uint32_t appStatus, FCGIRequest::protocol_status_t protStatus) : Header(TYPE_END_REQUEST, id, sizeof(EndRequestMsg)-sizeof(Header)) , appStatusB3((appStatus >> 24) & 0xff) , appStatusB2((appStatus >> 16) & 0xff) , appStatusB1((appStatus >> 8) & 0xff) , appStatusB0((appStatus >> 0) & 0xff) , protocolStatus(protStatus) { memset(this->reserved, 0, sizeof(this->reserved)); } }; struct UnknownTypeMsg : public Header { uint8_t type; uint8_t reserved[7]; UnknownTypeMsg() { memset(this, 0, sizeof(*this)); } UnknownTypeMsg(uint8_t unknown_type) : Header(TYPE_UNKNOWN, 0, sizeof(UnknownTypeMsg) - sizeof(Header)) , type(unknown_type) { memset(this->reserved, 0, sizeof(this->reserved)); } }; void FCGIProtocolDriver::process_unknown(uint8_t type) { UnknownTypeMsg msg(type); output_cb(&msg, sizeof(UnknownTypeMsg)); } void FCGIProtocolDriver::process_begin_request(uint16_t id, uint8_t const * buf, uint16_t) { // Check whether we have an open request with that id already and // if, throw an exception. if (reqmap.find(id) != reqmap.end()) { char tmp[256]; #ifdef _WIN32 sprintf_s(tmp, "FCGIProtocolDriver received duplicate BEGIN_REQUEST id %u.", id); #else sprintf(tmp, "FCGIProtocolDriver received duplicate BEGIN_REQUEST id %u.", id); #endif throw duplicate_begin_request(tmp); } // Create a new request instance and store it away. The user may // get it after we've read all parameters. BeginRequest const * br = reinterpret_cast<BeginRequest const *>(buf); reqmap[id] = new FCGIRequest(*this, id, FCGIRequest::role_t((br->roleB1 << 8) + br->roleB0), (br->flags & FLAG_KEEP_CONN) == 1); } void FCGIProtocolDriver::process_abort_request(uint16_t id, uint8_t const *, uint16_t) { // Find request instance for this id. Ignore message if non // exists, set ignore flag otherwise. reqmap_t::iterator req = reqmap.find(id); if (req == reqmap.end()) std::cerr << "FCGIProtocolDriver received ABORT_REQUEST for non-existing id " << id << ". Ignoring." << std::endl; else { req->second->aborted = true; if (req->second->handler_cb) // Notify the handler associated with this request. (*req->second->handler_cb)(req->second); } } void FCGIProtocolDriver::process_params(uint16_t id, uint8_t const * buf, uint16_t len) { // Find request instance for this id. Ignore message if non // exists. reqmap_t::iterator req = reqmap.find(id); if (req == reqmap.end()) { std::cerr << "FCGIProtocolDriver received PARAMS for non-existing id " << id << ". Ignoring." << std::endl; return; } // Is this the last message to come? Then queue the request for // the user. if (len == 0) { new_request_queue.push(id); return; } // Process message. uint8_t const * const bufend(buf + len); uint32_t name_len; uint32_t data_len; while(buf != bufend) { if (*buf >> 7 == 0) name_len = *(buf++); else { name_len = ((buf[0] & 0x7F) << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3]; buf += 4; } if (*buf >> 7 == 0) data_len = *(buf++); else { data_len = ((buf[0] & 0x7F) << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3]; buf += 4; } assert(buf + name_len + data_len <= bufend); std::string const name(reinterpret_cast<char const *>(buf), name_len); buf += name_len; std::string const data(reinterpret_cast<char const *>(buf), data_len); buf += data_len; #ifdef DEBUG_FASTCGI std::cerr << "request #" << id << ": FCGIProtocolDriver received PARAM '" << name << "' = '" << data << "'" << std::endl; #endif req->second->params[name] = data; } } void FCGIProtocolDriver::process_stdin(uint16_t id, uint8_t const * buf, uint16_t len) { // Find request instance for this id. Ignore message if non // exists. reqmap_t::iterator req = reqmap.find(id); if (req == reqmap.end()) { std::cerr << "FCGIProtocolDriver received STDIN for non-existing id " << id << ". Ignoring." << std::endl; return; } // Is this the last message to come? Then set the eof flag. // Otherwise, add the data to the buffer in the request structure. if (len == 0) req->second->stdin_eof = true; else req->second->stdin_stream.append((char const *)buf, len); // Notify the handler associated with this request. if (req->second->handler_cb) (*req->second->handler_cb)(req->second); } FCGIProtocolDriver::FCGIProtocolDriver(OutputCallback& cb) : output_cb(cb) { } FCGIProtocolDriver::~FCGIProtocolDriver() { for(reqmap_t::iterator i = reqmap.begin(); i != reqmap.end(); ++i) { delete i->second; } } void FCGIProtocolDriver::process_input(void const * buf, size_t count) { // Copy data to our own buffer. InputBuffer.insert( InputBuffer.end() , static_cast<uint8_t const *>(buf) , static_cast<uint8_t const *>(buf) + count ); // If there is enough data in the input buffer to contain a // header, interpret it. while(InputBuffer.size() >= sizeof(Header)) { Header const * hp = reinterpret_cast<Header const *>(&InputBuffer[0]); // Check whether our peer speaks the correct protocol version. if (hp->version != 1) { char buf[256]; #ifdef _WIN32 sprintf_s(buf, "FCGIProtocolDriver cannot handle protocol version %u.", hp->version); #else sprintf(buf, "FCGIProtocolDriver cannot handle protocol version %u.", hp->version); #endif throw unsupported_fcgi_version(buf); } // Check whether we have the whole message that follows the // headers in our buffer already. If not, we can't process it // yet. uint16_t msg_len = (hp->contentLengthB1 << 8) + hp->contentLengthB0; uint16_t msg_id = (hp->requestIdB1 << 8) + hp->requestIdB0; if (InputBuffer.size() < sizeof(Header)+msg_len+hp->paddingLength) return; // Process the message. In case an exception arrives here, // terminate the request. try { #ifdef DEBUG_FASTCGI std::cerr << "Received message: id = " << msg_id << ", " << "body len = " << msg_len << ", " << "type = " << (int)hp->type << std::endl; #endif switch (hp->type) { case TYPE_BEGIN_REQUEST: process_begin_request(msg_id, &InputBuffer[0]+sizeof(Header), msg_len); break; case TYPE_ABORT_REQUEST: process_abort_request(msg_id, &InputBuffer[0]+sizeof(Header), msg_len); break; case TYPE_PARAMS: process_params(msg_id, &InputBuffer[0]+sizeof(Header), msg_len); break; case TYPE_STDIN: process_stdin(msg_id, &InputBuffer[0]+sizeof(Header), msg_len); break; case TYPE_END_REQUEST: case TYPE_STDOUT: case TYPE_STDERR: case TYPE_DATA: case TYPE_GET_VALUES: case TYPE_GET_VALUES_RESULT: case TYPE_UNKNOWN: default: process_unknown(hp->type); } } catch(fcgi_io_callback_error const &) { throw; } catch(std::exception const & e) { std::cerr << "Caught exception while processing request #" << msg_id << ": " << e.what() << std::endl; terminate_request(msg_id); } catch(...) { std::cerr << "Caught unknown exception while processing request #" << msg_id << "." << std::endl; terminate_request(msg_id); } // Remove the message from our buffer and contine processing // if there if something left. InputBuffer.erase( InputBuffer.begin() , InputBuffer.begin()+sizeof(Header)+msg_len+hp->paddingLength ); } } FCGIRequest* FCGIProtocolDriver::get_request() { if (new_request_queue.empty()) return 0; FCGIRequest* r = reqmap[new_request_queue.front()]; new_request_queue.pop(); return r; } bool FCGIProtocolDriver::have_active_requests() { if (new_request_queue.empty() && reqmap.empty()) return false; else return true; } void FCGIProtocolDriver::terminate_request(uint16_t id) { reqmap_t::iterator req; req = reqmap.find(id); if (req != reqmap.end()) { delete req->second; reqmap.erase(req); } } // Pure virtual destructors must also exist somewhere. FCGIProtocolDriver::OutputCallback::~OutputCallback() { } FCGIRequest::FCGIRequest(FCGIProtocolDriver& driver_, uint16_t id_, role_t role_, bool kc) : id(id_), role(role_), keep_connection(kc), aborted(false), stdin_eof(false) , data_eof(false), handler_cb(0), driver(driver_) { } FCGIRequest::~FCGIRequest() { if (handler_cb) delete handler_cb; } void FCGIRequest::write(const std::string& buf, ostream_type_t stream) { write(buf.data(), buf.size(), stream); } void FCGIRequest::write(char const * buf, size_t count, ostream_type_t stream) { if (count > 0xffff) throw std::out_of_range("Can't send messages of that size."); else if (count == 0) return; // Construct message. Header h(stream == STDOUT ? TYPE_STDOUT : TYPE_STDERR, id, (uint16_t)count); driver.output_cb(&h, sizeof(Header)); driver.output_cb(buf, count); } void FCGIRequest::write(const std::string &tw) { write(tw.data(), tw.size(), STDOUT); } void FCGIRequest::end_request(uint32_t appStatus, FCGIRequest::protocol_status_t protStatus) { // Terminate the stdout and stderr stream, and send the // end-request message. uint8_t buf[64]; uint8_t * p = buf; new(p) Header(TYPE_STDOUT, id, 0); p += sizeof(Header); new(p) Header(TYPE_STDERR, id, 0); p += sizeof(Header); new(p) EndRequestMsg(id, appStatus, protStatus); p += sizeof(EndRequestMsg); driver.output_cb(buf, p - buf); driver.terminate_request(id); } <commit_msg>Fix Buffer Over-read in FastCGI parameters<commit_after>/* * Copyright (c) 2001-2007 Peter Simons <simons@cryp.to> * * This software is provided 'as-is', without any express or * implied warranty. In no event will the authors be held liable * for any damages arising from the use of this software. * * Copying and distribution of this file, with or without * modification, are permitted in any medium without royalty * provided the copyright notice and this notice are preserved. */ #include "fastcgi.hpp" #include <iostream> #include <stdio.h> #ifndef _WIN32 #include <memory.h> #endif typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; enum message_type_t { TYPE_BEGIN_REQUEST = 1 , TYPE_ABORT_REQUEST = 2 , TYPE_END_REQUEST = 3 , TYPE_PARAMS = 4 , TYPE_STDIN = 5 , TYPE_STDOUT = 6 , TYPE_STDERR = 7 , TYPE_DATA = 8 , TYPE_GET_VALUES = 9 , TYPE_GET_VALUES_RESULT = 10 , TYPE_UNKNOWN = 11 }; struct Header { uint8_t version; uint8_t type; uint8_t requestIdB1; uint8_t requestIdB0; uint8_t contentLengthB1; uint8_t contentLengthB0; uint8_t paddingLength; uint8_t reserved; Header() { memset(this, 0, sizeof(*this)); } Header(message_type_t t, uint16_t id, uint16_t len) : version(1), type(t) , requestIdB1(id >> 8) , requestIdB0(id & 0xff) , contentLengthB1(len >> 8) , contentLengthB0(len & 0xff) , paddingLength(0), reserved(0) { } }; struct BeginRequest { uint8_t roleB1; uint8_t roleB0; uint8_t flags; uint8_t reserved[5]; }; static uint8_t const FLAG_KEEP_CONN = 1; struct EndRequestMsg : public Header { uint8_t appStatusB3; uint8_t appStatusB2; uint8_t appStatusB1; uint8_t appStatusB0; uint8_t protocolStatus; uint8_t reserved[3]; EndRequestMsg() { memset(this, 0, sizeof(*this)); } EndRequestMsg(uint16_t id, uint32_t appStatus, FCGIRequest::protocol_status_t protStatus) : Header(TYPE_END_REQUEST, id, sizeof(EndRequestMsg)-sizeof(Header)) , appStatusB3((appStatus >> 24) & 0xff) , appStatusB2((appStatus >> 16) & 0xff) , appStatusB1((appStatus >> 8) & 0xff) , appStatusB0((appStatus >> 0) & 0xff) , protocolStatus(protStatus) { memset(this->reserved, 0, sizeof(this->reserved)); } }; struct UnknownTypeMsg : public Header { uint8_t type; uint8_t reserved[7]; UnknownTypeMsg() { memset(this, 0, sizeof(*this)); } UnknownTypeMsg(uint8_t unknown_type) : Header(TYPE_UNKNOWN, 0, sizeof(UnknownTypeMsg) - sizeof(Header)) , type(unknown_type) { memset(this->reserved, 0, sizeof(this->reserved)); } }; void FCGIProtocolDriver::process_unknown(uint8_t type) { UnknownTypeMsg msg(type); output_cb(&msg, sizeof(UnknownTypeMsg)); } void FCGIProtocolDriver::process_begin_request(uint16_t id, uint8_t const * buf, uint16_t) { // Check whether we have an open request with that id already and // if, throw an exception. if (reqmap.find(id) != reqmap.end()) { char tmp[256]; #ifdef _WIN32 sprintf_s(tmp, "FCGIProtocolDriver received duplicate BEGIN_REQUEST id %u.", id); #else sprintf(tmp, "FCGIProtocolDriver received duplicate BEGIN_REQUEST id %u.", id); #endif throw duplicate_begin_request(tmp); } // Create a new request instance and store it away. The user may // get it after we've read all parameters. BeginRequest const * br = reinterpret_cast<BeginRequest const *>(buf); reqmap[id] = new FCGIRequest(*this, id, FCGIRequest::role_t((br->roleB1 << 8) + br->roleB0), (br->flags & FLAG_KEEP_CONN) == 1); } void FCGIProtocolDriver::process_abort_request(uint16_t id, uint8_t const *, uint16_t) { // Find request instance for this id. Ignore message if non // exists, set ignore flag otherwise. reqmap_t::iterator req = reqmap.find(id); if (req == reqmap.end()) std::cerr << "FCGIProtocolDriver received ABORT_REQUEST for non-existing id " << id << ". Ignoring." << std::endl; else { req->second->aborted = true; if (req->second->handler_cb) // Notify the handler associated with this request. (*req->second->handler_cb)(req->second); } } void FCGIProtocolDriver::process_params(uint16_t id, uint8_t const * buf, uint16_t len) { // Find request instance for this id. Ignore message if non // exists. reqmap_t::iterator req = reqmap.find(id); if (req == reqmap.end()) { std::cerr << "FCGIProtocolDriver received PARAMS for non-existing id " << id << ". Ignoring." << std::endl; return; } // Is this the last message to come? Then queue the request for // the user. if (len == 0) { new_request_queue.push(id); return; } // Process message. uint8_t const * const bufend(buf + len); uint32_t name_len; uint32_t data_len; while(buf != bufend) { if (*buf >> 7 == 0) name_len = *(buf++); else if (4 <= bufend - buf) { name_len = ((buf[0] & 0x7F) << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3]; buf += 4; } else break; if (*buf >> 7 == 0) data_len = *(buf++); else if (4 <= bufend - buf) { data_len = ((buf[0] & 0x7F) << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3]; buf += 4; } else break; if (name_len + data_len <= bufend - buf) { std::string const name(reinterpret_cast<char const *>(buf), name_len); buf += name_len; std::string const data(reinterpret_cast<char const *>(buf), data_len); buf += data_len; #ifdef DEBUG_FASTCGI std::cerr << "request #" << id << ": FCGIProtocolDriver received PARAM '" << name << "' = '" << data << "'" << std::endl; #endif req->second->params[name] = data; } else { break; } } } void FCGIProtocolDriver::process_stdin(uint16_t id, uint8_t const * buf, uint16_t len) { // Find request instance for this id. Ignore message if non // exists. reqmap_t::iterator req = reqmap.find(id); if (req == reqmap.end()) { std::cerr << "FCGIProtocolDriver received STDIN for non-existing id " << id << ". Ignoring." << std::endl; return; } // Is this the last message to come? Then set the eof flag. // Otherwise, add the data to the buffer in the request structure. if (len == 0) req->second->stdin_eof = true; else req->second->stdin_stream.append((char const *)buf, len); // Notify the handler associated with this request. if (req->second->handler_cb) (*req->second->handler_cb)(req->second); } FCGIProtocolDriver::FCGIProtocolDriver(OutputCallback& cb) : output_cb(cb) { } FCGIProtocolDriver::~FCGIProtocolDriver() { for(reqmap_t::iterator i = reqmap.begin(); i != reqmap.end(); ++i) { delete i->second; } } void FCGIProtocolDriver::process_input(void const * buf, size_t count) { // Copy data to our own buffer. InputBuffer.insert( InputBuffer.end() , static_cast<uint8_t const *>(buf) , static_cast<uint8_t const *>(buf) + count ); // If there is enough data in the input buffer to contain a // header, interpret it. while(InputBuffer.size() >= sizeof(Header)) { Header const * hp = reinterpret_cast<Header const *>(&InputBuffer[0]); // Check whether our peer speaks the correct protocol version. if (hp->version != 1) { char buf[256]; #ifdef _WIN32 sprintf_s(buf, "FCGIProtocolDriver cannot handle protocol version %u.", hp->version); #else sprintf(buf, "FCGIProtocolDriver cannot handle protocol version %u.", hp->version); #endif throw unsupported_fcgi_version(buf); } // Check whether we have the whole message that follows the // headers in our buffer already. If not, we can't process it // yet. uint16_t msg_len = (hp->contentLengthB1 << 8) + hp->contentLengthB0; uint16_t msg_id = (hp->requestIdB1 << 8) + hp->requestIdB0; if (InputBuffer.size() < sizeof(Header)+msg_len+hp->paddingLength) return; // Process the message. In case an exception arrives here, // terminate the request. try { #ifdef DEBUG_FASTCGI std::cerr << "Received message: id = " << msg_id << ", " << "body len = " << msg_len << ", " << "type = " << (int)hp->type << std::endl; #endif switch (hp->type) { case TYPE_BEGIN_REQUEST: process_begin_request(msg_id, &InputBuffer[0]+sizeof(Header), msg_len); break; case TYPE_ABORT_REQUEST: process_abort_request(msg_id, &InputBuffer[0]+sizeof(Header), msg_len); break; case TYPE_PARAMS: process_params(msg_id, &InputBuffer[0]+sizeof(Header), msg_len); break; case TYPE_STDIN: process_stdin(msg_id, &InputBuffer[0]+sizeof(Header), msg_len); break; case TYPE_END_REQUEST: case TYPE_STDOUT: case TYPE_STDERR: case TYPE_DATA: case TYPE_GET_VALUES: case TYPE_GET_VALUES_RESULT: case TYPE_UNKNOWN: default: process_unknown(hp->type); } } catch(fcgi_io_callback_error const &) { throw; } catch(std::exception const & e) { std::cerr << "Caught exception while processing request #" << msg_id << ": " << e.what() << std::endl; terminate_request(msg_id); } catch(...) { std::cerr << "Caught unknown exception while processing request #" << msg_id << "." << std::endl; terminate_request(msg_id); } // Remove the message from our buffer and contine processing // if there if something left. InputBuffer.erase( InputBuffer.begin() , InputBuffer.begin()+sizeof(Header)+msg_len+hp->paddingLength ); } } FCGIRequest* FCGIProtocolDriver::get_request() { if (new_request_queue.empty()) return 0; FCGIRequest* r = reqmap[new_request_queue.front()]; new_request_queue.pop(); return r; } bool FCGIProtocolDriver::have_active_requests() { if (new_request_queue.empty() && reqmap.empty()) return false; else return true; } void FCGIProtocolDriver::terminate_request(uint16_t id) { reqmap_t::iterator req; req = reqmap.find(id); if (req != reqmap.end()) { delete req->second; reqmap.erase(req); } } // Pure virtual destructors must also exist somewhere. FCGIProtocolDriver::OutputCallback::~OutputCallback() { } FCGIRequest::FCGIRequest(FCGIProtocolDriver& driver_, uint16_t id_, role_t role_, bool kc) : id(id_), role(role_), keep_connection(kc), aborted(false), stdin_eof(false) , data_eof(false), handler_cb(0), driver(driver_) { } FCGIRequest::~FCGIRequest() { if (handler_cb) delete handler_cb; } void FCGIRequest::write(const std::string& buf, ostream_type_t stream) { write(buf.data(), buf.size(), stream); } void FCGIRequest::write(char const * buf, size_t count, ostream_type_t stream) { if (count > 0xffff) throw std::out_of_range("Can't send messages of that size."); else if (count == 0) return; // Construct message. Header h(stream == STDOUT ? TYPE_STDOUT : TYPE_STDERR, id, (uint16_t)count); driver.output_cb(&h, sizeof(Header)); driver.output_cb(buf, count); } void FCGIRequest::write(const std::string &tw) { write(tw.data(), tw.size(), STDOUT); } void FCGIRequest::end_request(uint32_t appStatus, FCGIRequest::protocol_status_t protStatus) { // Terminate the stdout and stderr stream, and send the // end-request message. uint8_t buf[64]; uint8_t * p = buf; new(p) Header(TYPE_STDOUT, id, 0); p += sizeof(Header); new(p) Header(TYPE_STDERR, id, 0); p += sizeof(Header); new(p) EndRequestMsg(id, appStatus, protStatus); p += sizeof(EndRequestMsg); driver.output_cb(buf, p - buf); driver.terminate_request(id); } <|endoftext|>
<commit_before>#include <stdio.h> #include <iostream> #include <unistd.h> #include <fcntl.h> #include <cassert> #include "kms++.h" #include "helpers.h" using namespace std; namespace kms { static const map<int, string> connector_names = { { DRM_MODE_CONNECTOR_Unknown, "Unknown" }, { DRM_MODE_CONNECTOR_VGA, "VGA" }, { DRM_MODE_CONNECTOR_DVII, "DVI-I" }, { DRM_MODE_CONNECTOR_DVID, "DVI-D" }, { DRM_MODE_CONNECTOR_DVIA, "DVI-A" }, { DRM_MODE_CONNECTOR_Composite, "Composite" }, { DRM_MODE_CONNECTOR_SVIDEO, "S-Video" }, { DRM_MODE_CONNECTOR_LVDS, "LVDS" }, { DRM_MODE_CONNECTOR_Component, "Component" }, { DRM_MODE_CONNECTOR_9PinDIN, "9-Pin-DIN" }, { DRM_MODE_CONNECTOR_DisplayPort, "DP" }, { DRM_MODE_CONNECTOR_HDMIA, "HDMI-A" }, { DRM_MODE_CONNECTOR_HDMIB, "HDMI-B" }, { DRM_MODE_CONNECTOR_TV, "TV" }, { DRM_MODE_CONNECTOR_eDP, "eDP" }, { DRM_MODE_CONNECTOR_VIRTUAL, "Virtual" }, { DRM_MODE_CONNECTOR_DSI, "DSI" }, }; static const map<int, string> connection_str = { { 0, "<unknown>" }, { DRM_MODE_CONNECTED, "Connected" }, { DRM_MODE_DISCONNECTED, "Disconnected" }, { DRM_MODE_UNKNOWNCONNECTION, "Unknown" }, }; static const map<int, string> subpix_str = { #define DEF_SUBPIX(c) { DRM_MODE_SUBPIXEL_##c, #c } DEF_SUBPIX(UNKNOWN), DEF_SUBPIX(HORIZONTAL_RGB), DEF_SUBPIX(HORIZONTAL_BGR), DEF_SUBPIX(VERTICAL_RGB), DEF_SUBPIX(VERTICAL_BGR), DEF_SUBPIX(NONE), #undef DEF_SUBPIX }; struct ConnectorPriv { drmModeConnectorPtr drm_connector; }; Connector::Connector(Card &card, uint32_t id, uint32_t idx) :DrmPropObject(card, id, DRM_MODE_OBJECT_CONNECTOR, idx) { m_priv = new ConnectorPriv(); m_priv->drm_connector = drmModeGetConnector(this->card().fd(), this->id()); assert(m_priv->drm_connector); const auto& name = connector_names.at(m_priv->drm_connector->connector_type); m_fullname = name + "-" + to_string(m_priv->drm_connector->connector_type_id); } Connector::~Connector() { drmModeFreeConnector(m_priv->drm_connector); delete m_priv; } void Connector::setup() { if (m_priv->drm_connector->encoder_id != 0) m_current_encoder = card().get_encoder(m_priv->drm_connector->encoder_id); else m_current_encoder = 0; if (m_current_encoder) m_saved_crtc = m_current_encoder->get_crtc(); else m_saved_crtc = 0; } void Connector::restore_mode() { if (m_saved_crtc) m_saved_crtc->restore_mode(this); } Videomode Connector::get_default_mode() const { if (m_priv->drm_connector->count_modes == 0) throw invalid_argument("no modes available\n"); drmModeModeInfo drmmode = m_priv->drm_connector->modes[0]; return drm_mode_to_video_mode(drmmode); } Videomode Connector::get_mode(const string& mode) const { auto c = m_priv->drm_connector; for (int i = 0; i < c->count_modes; i++) if (mode == c->modes[i].name) return drm_mode_to_video_mode(c->modes[i]); throw invalid_argument(mode + ": mode not found"); } Videomode Connector::get_mode(unsigned xres, unsigned yres, unsigned refresh, bool ilace) const { auto c = m_priv->drm_connector; for (int i = 0; i < c->count_modes; i++) { drmModeModeInfo& m = c->modes[i]; if (m.hdisplay != xres || m.vdisplay != yres) continue; if (refresh && m.vrefresh != refresh) continue; if (ilace != !!(m.flags & DRM_MODE_FLAG_INTERLACE)) continue; return drm_mode_to_video_mode(c->modes[i]); } throw invalid_argument("mode not found"); } bool Connector::connected() const { return m_priv->drm_connector->connection == DRM_MODE_CONNECTED || m_priv->drm_connector->connection == DRM_MODE_UNKNOWNCONNECTION; } vector<Crtc*> Connector::get_possible_crtcs() const { vector<Crtc*> crtcs; for (int i = 0; i < m_priv->drm_connector->count_encoders; ++i) { auto enc = card().get_encoder(m_priv->drm_connector->encoders[i]); auto l = enc->get_possible_crtcs(); crtcs.insert(crtcs.end(), l.begin(), l.end()); } return crtcs; } Crtc* Connector::get_current_crtc() const { if (m_current_encoder) return m_current_encoder->get_crtc(); else return 0; } uint32_t Connector::connector_type() const { return m_priv->drm_connector->connector_type; } uint32_t Connector::connector_type_id() const { return m_priv->drm_connector->connector_type_id; } uint32_t Connector::mmWidth() const { return m_priv->drm_connector->mmWidth; } uint32_t Connector::mmHeight() const { return m_priv->drm_connector->mmHeight; } uint32_t Connector::subpixel() const { return m_priv->drm_connector->subpixel; } const string& Connector::subpixel_str() const { return subpix_str.at(subpixel()); } std::vector<Videomode> Connector::get_modes() const { vector<Videomode> modes; for (int i = 0; i < m_priv->drm_connector->count_modes; i++) modes.push_back(drm_mode_to_video_mode( m_priv->drm_connector->modes[i])); return modes; } std::vector<Encoder*> Connector::get_encoders() const { vector<Encoder*> encoders; for (int i = 0; i < m_priv->drm_connector->count_encoders; i++) { auto enc = card().get_encoder(m_priv->drm_connector->encoders[i]); encoders.push_back(enc); } return encoders; } } <commit_msg>Connector: hack fix EDID blob ID<commit_after>#include <stdio.h> #include <iostream> #include <unistd.h> #include <fcntl.h> #include <cassert> #include "kms++.h" #include "helpers.h" using namespace std; namespace kms { static const map<int, string> connector_names = { { DRM_MODE_CONNECTOR_Unknown, "Unknown" }, { DRM_MODE_CONNECTOR_VGA, "VGA" }, { DRM_MODE_CONNECTOR_DVII, "DVI-I" }, { DRM_MODE_CONNECTOR_DVID, "DVI-D" }, { DRM_MODE_CONNECTOR_DVIA, "DVI-A" }, { DRM_MODE_CONNECTOR_Composite, "Composite" }, { DRM_MODE_CONNECTOR_SVIDEO, "S-Video" }, { DRM_MODE_CONNECTOR_LVDS, "LVDS" }, { DRM_MODE_CONNECTOR_Component, "Component" }, { DRM_MODE_CONNECTOR_9PinDIN, "9-Pin-DIN" }, { DRM_MODE_CONNECTOR_DisplayPort, "DP" }, { DRM_MODE_CONNECTOR_HDMIA, "HDMI-A" }, { DRM_MODE_CONNECTOR_HDMIB, "HDMI-B" }, { DRM_MODE_CONNECTOR_TV, "TV" }, { DRM_MODE_CONNECTOR_eDP, "eDP" }, { DRM_MODE_CONNECTOR_VIRTUAL, "Virtual" }, { DRM_MODE_CONNECTOR_DSI, "DSI" }, }; static const map<int, string> connection_str = { { 0, "<unknown>" }, { DRM_MODE_CONNECTED, "Connected" }, { DRM_MODE_DISCONNECTED, "Disconnected" }, { DRM_MODE_UNKNOWNCONNECTION, "Unknown" }, }; static const map<int, string> subpix_str = { #define DEF_SUBPIX(c) { DRM_MODE_SUBPIXEL_##c, #c } DEF_SUBPIX(UNKNOWN), DEF_SUBPIX(HORIZONTAL_RGB), DEF_SUBPIX(HORIZONTAL_BGR), DEF_SUBPIX(VERTICAL_RGB), DEF_SUBPIX(VERTICAL_BGR), DEF_SUBPIX(NONE), #undef DEF_SUBPIX }; struct ConnectorPriv { drmModeConnectorPtr drm_connector; }; Connector::Connector(Card &card, uint32_t id, uint32_t idx) :DrmPropObject(card, id, DRM_MODE_OBJECT_CONNECTOR, idx) { m_priv = new ConnectorPriv(); m_priv->drm_connector = drmModeGetConnector(this->card().fd(), this->id()); assert(m_priv->drm_connector); // XXX drmModeGetConnector() does forced probe, which seems to change (at least) EDID blob id. // XXX So refresh the props again here. refresh_props(); const auto& name = connector_names.at(m_priv->drm_connector->connector_type); m_fullname = name + "-" + to_string(m_priv->drm_connector->connector_type_id); } Connector::~Connector() { drmModeFreeConnector(m_priv->drm_connector); delete m_priv; } void Connector::setup() { if (m_priv->drm_connector->encoder_id != 0) m_current_encoder = card().get_encoder(m_priv->drm_connector->encoder_id); else m_current_encoder = 0; if (m_current_encoder) m_saved_crtc = m_current_encoder->get_crtc(); else m_saved_crtc = 0; } void Connector::restore_mode() { if (m_saved_crtc) m_saved_crtc->restore_mode(this); } Videomode Connector::get_default_mode() const { if (m_priv->drm_connector->count_modes == 0) throw invalid_argument("no modes available\n"); drmModeModeInfo drmmode = m_priv->drm_connector->modes[0]; return drm_mode_to_video_mode(drmmode); } Videomode Connector::get_mode(const string& mode) const { auto c = m_priv->drm_connector; for (int i = 0; i < c->count_modes; i++) if (mode == c->modes[i].name) return drm_mode_to_video_mode(c->modes[i]); throw invalid_argument(mode + ": mode not found"); } Videomode Connector::get_mode(unsigned xres, unsigned yres, unsigned refresh, bool ilace) const { auto c = m_priv->drm_connector; for (int i = 0; i < c->count_modes; i++) { drmModeModeInfo& m = c->modes[i]; if (m.hdisplay != xres || m.vdisplay != yres) continue; if (refresh && m.vrefresh != refresh) continue; if (ilace != !!(m.flags & DRM_MODE_FLAG_INTERLACE)) continue; return drm_mode_to_video_mode(c->modes[i]); } throw invalid_argument("mode not found"); } bool Connector::connected() const { return m_priv->drm_connector->connection == DRM_MODE_CONNECTED || m_priv->drm_connector->connection == DRM_MODE_UNKNOWNCONNECTION; } vector<Crtc*> Connector::get_possible_crtcs() const { vector<Crtc*> crtcs; for (int i = 0; i < m_priv->drm_connector->count_encoders; ++i) { auto enc = card().get_encoder(m_priv->drm_connector->encoders[i]); auto l = enc->get_possible_crtcs(); crtcs.insert(crtcs.end(), l.begin(), l.end()); } return crtcs; } Crtc* Connector::get_current_crtc() const { if (m_current_encoder) return m_current_encoder->get_crtc(); else return 0; } uint32_t Connector::connector_type() const { return m_priv->drm_connector->connector_type; } uint32_t Connector::connector_type_id() const { return m_priv->drm_connector->connector_type_id; } uint32_t Connector::mmWidth() const { return m_priv->drm_connector->mmWidth; } uint32_t Connector::mmHeight() const { return m_priv->drm_connector->mmHeight; } uint32_t Connector::subpixel() const { return m_priv->drm_connector->subpixel; } const string& Connector::subpixel_str() const { return subpix_str.at(subpixel()); } std::vector<Videomode> Connector::get_modes() const { vector<Videomode> modes; for (int i = 0; i < m_priv->drm_connector->count_modes; i++) modes.push_back(drm_mode_to_video_mode( m_priv->drm_connector->modes[i])); return modes; } std::vector<Encoder*> Connector::get_encoders() const { vector<Encoder*> encoders; for (int i = 0; i < m_priv->drm_connector->count_encoders; i++) { auto enc = card().get_encoder(m_priv->drm_connector->encoders[i]); encoders.push_back(enc); } return encoders; } } <|endoftext|>
<commit_before> #include "troymotor.h" const int emptyQueue =-32767; TroyMotor::TroyMotor(int pin1,int pin2){ init(pin1,pin2); } void TroyMotor::init(int pin1,int pin2){ _status=0; _currentStep=0; _goToStep=0; _position=false; _counter=0; _isReset=true; _direction=1; _pin=pin1; pinMode(pin1,OUTPUT); _pin2=pin2; pinMode(pin2,OUTPUT); //init queue _queueSize=3; _gotoArray= new int[_queueSize];//max assigned step for(int i=0;i<_queueSize;i++){ _gotoArray[i]=0; } _queueTail=-1; } void TroyMotor::pushToStepQueue(int stepCount){ if(_queueTail>=_queueSize){ Serial.println("queue is full"); }else{ _gotoArray[++_queueTail]=stepCount; } } int TroyMotor::popToStepQueue(){ if(_queueTail==-1){ return emptyQueue; } int ret = _gotoArray[0]; for(int i=0;i<_queueTail;i++){ _gotoArray[i]=_gotoArray[i+1]; } _queueTail--; return ret; } void TroyMotor::goToStep(int stepCount ){ _goToStep=stepCount; if(stepCount>0){ _direction=1; } else{ _direction=-1; } } void TroyMotor::setStatus(int status){ _status=status; } int TroyMotor::getStatus(){ return _status; } void TroyMotor::singleRun(){ high(); delay(50); low(); Serial.println("singleRun"); } void TroyMotor::step(){ if(_counter==3){ _currentStep+=_direction; _counter=0; } #ifdef __DEBUG__ Serial.print("currentStep="); Serial.println(_currentStep); Serial.print("goToStep="); Serial.println(_goToStep); #endif if(_currentStep==_goToStep){ _status=0; _counter=0; //check next run int nextStep = popToStepQueue(); if(nextStep != emptyQueue ){ goToStep(nextStep); _status=1; } return; } char ret[100]; #ifdef __DEBUG__ sprintf(ret,"currentStep:%d,gotostep:%d",_currentStep,_goToStep); Serial.println(ret); #endif if(_position){ low(); _position=false; _counter++; } else{ high(); _position=true; _counter++; } } void TroyMotor::run(){ if(_isReset){ step(); } else{ reseting(); } } void TroyMotor::high(){ if(_direction>0){ digitalWrite(_pin,HIGH); } else{ digitalWrite(_pin2,HIGH); } } void TroyMotor::low(){ if(_direction>0){ digitalWrite(_pin,LOW); } else{ digitalWrite(_pin2,LOW); } } void TroyMotor::reseting(){ int val = analogRead(5); if(val==0){ Serial.print("reset step"); Serial.println(_currentStep); _isReset=true; _currentStep=0; _position=false; _counter=0; _status=0; } else{ step(); } } void TroyMotor::reset(){ _isReset=false; _status=1; _goToStep=3000; // give hung steps } <commit_msg>fix bug: reseting method dont reset _goToStep<commit_after> #include "troymotor.h" const int emptyQueue =-32767; #define __DEBUG__ TroyMotor::TroyMotor(int pin1,int pin2){ init(pin1,pin2); } void TroyMotor::init(int pin1,int pin2){ _status=0; _currentStep=0; _goToStep=0; _position=false; _counter=0; _isReset=true; _direction=1; _pin=pin1; pinMode(pin1,OUTPUT); _pin2=pin2; pinMode(pin2,OUTPUT); //init queue _queueSize=3; _gotoArray= new int[_queueSize];//max assigned step for(int i=0;i<_queueSize;i++){ _gotoArray[i]=0; } _queueTail=-1; } void TroyMotor::pushToStepQueue(int stepCount){ if(_queueTail>=_queueSize){ Serial.println("queue is full"); }else{ _gotoArray[++_queueTail]=stepCount; } } int TroyMotor::popToStepQueue(){ if(_queueTail==-1){ return emptyQueue; } int ret = _gotoArray[0]; for(int i=0;i<_queueTail;i++){ _gotoArray[i]=_gotoArray[i+1]; } _queueTail--; return ret; } void TroyMotor::goToStep(int stepCount ){ _goToStep=stepCount; if(stepCount>0){ _direction=1; } else{ _direction=-1; } } void TroyMotor::setStatus(int status){ _status=status; } int TroyMotor::getStatus(){ return _status; } void TroyMotor::singleRun(){ high(); delay(50); low(); Serial.println("singleRun"); } void TroyMotor::step(){ if(_counter==3){ _currentStep+=_direction; _counter=0; } #ifdef __DEBUG__ Serial.print("currentStep="); Serial.println(_currentStep); Serial.print("goToStep="); Serial.println(_goToStep); #endif if(_currentStep==_goToStep){ _status=0; _counter=0; //check next run int nextStep = popToStepQueue(); if(nextStep != emptyQueue ){ goToStep(nextStep); _status=1; } return; } char ret[100]; #ifdef __DEBUG__ sprintf(ret,"currentStep:%d,gotostep:%d",_currentStep,_goToStep); Serial.println(ret); #endif if(_position){ low(); _position=false; _counter++; } else{ high(); _position=true; _counter++; } } void TroyMotor::run(){ if(_isReset){ step(); } else{ reseting(); } } void TroyMotor::high(){ if(_direction>0){ digitalWrite(_pin,HIGH); } else{ digitalWrite(_pin2,HIGH); } } void TroyMotor::low(){ if(_direction>0){ digitalWrite(_pin,LOW); } else{ digitalWrite(_pin2,LOW); } } void TroyMotor::reseting(){ int val = analogRead(5); if(val==0){ Serial.print("reset step"); Serial.println(_currentStep); _isReset=true; _currentStep=0; _goToStep=0; _position=false; _counter=0; _status=0; } else{ step(); } } void TroyMotor::reset(){ _isReset=false; _status=1; _goToStep=3000; // give hung steps } <|endoftext|>
<commit_before>/******************************* Copyright (c) 2016-2017 Grégoire Angerand 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 "os.h" #include "os_win.h" #include <y/utils.h> #include <iostream> namespace y { namespace os { usize pid() { #ifdef Y_OS_WIN return GetCurrentProcessId(); #else return getpid(); #endif } MemInfo phys_mem_info() { #ifdef Y_OS_WIN MEMORYSTATUSEX info; info.dwLength = sizeof(info); GlobalMemoryStatusEx(&info); return MemInfo { info.ullTotalPhys, info.ullAvailPhys }; #else return MemInfo { 0, 0 }; #endif } usize mem_usage() { #if defined(Y_OS_WIN) && !defined(Y_NO_PSAPI) PROCESS_MEMORY_COUNTERS info; info.cb = sizeof(info); return windows::GetProcessMemoryInfo_func()(GetCurrentProcess(), &info, DWORD(sizeof(info))) ? info.WorkingSetSize : 0; #else return 0; #endif } u64 get_user_time_ns() { #ifdef Y_OS_WIN FILETIME time; FILETIME garbage; GetProcessTimes(GetCurrentProcess(), &garbage, &garbage, &garbage, &time); return windows::filetime_to_ns(time); #else return 0; #endif } u64 get_kernel_time_ns() { #ifdef Y_OS_WIN FILETIME time; FILETIME garbage; GetProcessTimes(GetCurrentProcess(), &garbage, &garbage, &time,&garbage); return windows::filetime_to_ns(time); #else return 0; #endif } AppTimes get_times_ns() { #ifdef Y_OS_WIN FILETIME user; FILETIME kernel; FILETIME garbage; GetProcessTimes(GetCurrentProcess(), &garbage, &garbage, &kernel, &user); return AppTimes { windows::filetime_to_ns(kernel), windows::filetime_to_ns(user) }; #else return AppTimes { 0, 0 }; #endif } } } #ifdef Y_OS_WIN /*y_on_startup() { SetConsoleOutputCP(CP_UTF8); }*/ #endif <commit_msg>Fix missing include<commit_after>/******************************* Copyright (c) 2016-2017 Grégoire Angerand 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 "os.h" #include "os_win.h" #include "os_linux.h" #include <y/utils.h> #include <iostream> namespace y { namespace os { usize pid() { #ifdef Y_OS_WIN return GetCurrentProcessId(); #else return getpid(); #endif } MemInfo phys_mem_info() { #ifdef Y_OS_WIN MEMORYSTATUSEX info; info.dwLength = sizeof(info); GlobalMemoryStatusEx(&info); return MemInfo { info.ullTotalPhys, info.ullAvailPhys }; #else return MemInfo { 0, 0 }; #endif } usize mem_usage() { #if defined(Y_OS_WIN) && !defined(Y_NO_PSAPI) PROCESS_MEMORY_COUNTERS info; info.cb = sizeof(info); return windows::GetProcessMemoryInfo_func()(GetCurrentProcess(), &info, DWORD(sizeof(info))) ? info.WorkingSetSize : 0; #else return 0; #endif } u64 get_user_time_ns() { #ifdef Y_OS_WIN FILETIME time; FILETIME garbage; GetProcessTimes(GetCurrentProcess(), &garbage, &garbage, &garbage, &time); return windows::filetime_to_ns(time); #else return 0; #endif } u64 get_kernel_time_ns() { #ifdef Y_OS_WIN FILETIME time; FILETIME garbage; GetProcessTimes(GetCurrentProcess(), &garbage, &garbage, &time,&garbage); return windows::filetime_to_ns(time); #else return 0; #endif } AppTimes get_times_ns() { #ifdef Y_OS_WIN FILETIME user; FILETIME kernel; FILETIME garbage; GetProcessTimes(GetCurrentProcess(), &garbage, &garbage, &kernel, &user); return AppTimes { windows::filetime_to_ns(kernel), windows::filetime_to_ns(user) }; #else return AppTimes { 0, 0 }; #endif } } } #ifdef Y_OS_WIN /*y_on_startup() { SetConsoleOutputCP(CP_UTF8); }*/ #endif <|endoftext|>
<commit_before>// Copyright (c) 2013-2014, Robert Escriva // 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 Ygor 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. // C #include <signal.h> // STL #include <memory> // e #include <e/popt.h> // armnod #include "ygor.h" int main(int argc, const char* argv[]) { e::argparser ap; std::auto_ptr<armnod_argparser> apl(armnod_argparser::create("")); ap.autohelp(); ap.add("Generator:", apl->parser()); if (!ap.parse(argc, argv)) { return EXIT_FAILURE; } if (ap.args_sz() > 0) { ap.usage(); std::cerr << "\nerror: command takes no positional arguments" << std::endl; return EXIT_FAILURE; } sigset_t mask; sigfillset(&mask); sigdelset(&mask, SIGPROF); sigprocmask(SIG_SETMASK, &mask, NULL); armnod_generator* gen(armnod_generator_create(apl->config())); for (uint64_t i = 0; ; ++i) { if ((i & 0xffff) == 0) { sigpending(&mask); if (sigismember(&mask, SIGHUP) || sigismember(&mask, SIGINT) || sigismember(&mask, SIGTERM) || sigismember(&mask, SIGPIPE) || sigismember(&mask, SIGKILL)) { break; } } const char* string = armnod_generate(gen); if (!string) { break; } printf("%s\n", string); } armnod_generator_destroy(gen); return EXIT_SUCCESS; } <commit_msg>Respond to signals faster in "ygor armnod"<commit_after>// Copyright (c) 2013-2014, Robert Escriva // 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 Ygor 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. // C #include <signal.h> // STL #include <memory> // e #include <e/popt.h> // armnod #include "ygor.h" int main(int argc, const char* argv[]) { e::argparser ap; std::auto_ptr<armnod_argparser> apl(armnod_argparser::create("")); ap.autohelp(); ap.add("Generator:", apl->parser()); if (!ap.parse(argc, argv)) { return EXIT_FAILURE; } if (ap.args_sz() > 0) { ap.usage(); std::cerr << "\nerror: command takes no positional arguments" << std::endl; return EXIT_FAILURE; } sigset_t mask; sigfillset(&mask); sigdelset(&mask, SIGPROF); sigprocmask(SIG_SETMASK, &mask, NULL); armnod_generator* gen(armnod_generator_create(apl->config())); for (uint64_t i = 0; ; ++i) { if ((i & 0xf) == 0) { sigpending(&mask); if (sigismember(&mask, SIGHUP) || sigismember(&mask, SIGINT) || sigismember(&mask, SIGTERM) || sigismember(&mask, SIGPIPE) || sigismember(&mask, SIGKILL)) { break; } } const char* string = armnod_generate(gen); if (!string) { break; } printf("%s\n", string); } armnod_generator_destroy(gen); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* Copyright (C) 2008-2015 The Communi Project You may use this file under the terms of BSD license as follows: 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 copyright holder 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 HOLDERS 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 "zncmanager.h" #include "ignoremanager.h" #include <ircbuffermodel.h> #include <ircconnection.h> #include <irccommand.h> #include <ircmessage.h> #include <ircbuffer.h> IRC_USE_NAMESPACE ZncManager::ZncManager(QObject* parent) : QObject(parent) { d.model = 0; d.timestamp = QDateTime::fromTime_t(0); setModel(qobject_cast<IrcBufferModel*>(parent)); } ZncManager::~ZncManager() { } IrcBufferModel* ZncManager::model() const { return d.model; } void ZncManager::setModel(IrcBufferModel* model) { if (d.model != model) { if (d.model && d.model->connection()) { IrcConnection* connection = d.model->connection(); disconnect(connection, SIGNAL(connected()), this, SLOT(requestPlayback())); connection->removeMessageFilter(this); disconnect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*))); } d.model = model; if (d.model && d.model->connection()) { IrcNetwork* network = d.model->network(); QStringList caps = network->requestedCapabilities(); caps += "batch"; caps += "server-time"; caps += "echo-message"; caps += "znc.in/batch"; caps += "znc.in/playback"; caps += "znc.in/server-time"; caps += "znc.in/echo-message"; caps += "znc.in/server-time-iso"; network->setRequestedCapabilities(caps); IrcConnection* connection = d.model->connection(); connect(connection, SIGNAL(connected()), this, SLOT(requestPlayback())); connection->installMessageFilter(this); connect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*))); } emit modelChanged(model); } } bool ZncManager::messageFilter(IrcMessage* message) { if (message->connection()->isConnected() && message->tags().contains("time")) { QDateTime timestamp = message->tags().value("time").toDateTime(); if (timestamp.isValid()) { message->setTimeStamp(timestamp.toTimeSpec(Qt::LocalTime)); d.timestamp = qMax(timestamp, d.timestamp); } } if (message->type() == IrcMessage::Batch) { IrcBatchMessage* batch = static_cast<IrcBatchMessage*>(message); if (batch->batch() == "znc.in/playback") { IrcBuffer* buffer = d.model->add(batch->parameters().value(2)); foreach (IrcMessage* msg, batch->messages()) { msg->setFlags(msg->flags() | IrcMessage::Playback); if (msg->type() == IrcMessage::Private) processMessage(static_cast<IrcPrivateMessage*>(msg)); } buffer->receiveMessage(batch); return true; } } return IgnoreManager::instance()->messageFilter(message); } void ZncManager::processMessage(IrcPrivateMessage* message) { if (message->nick() == "*buffextras") { const QString msg = message->content(); const int idx = msg.indexOf(" "); const QString prefix = msg.left(idx); const QString content = msg.mid(idx + 1); message->setPrefix(prefix); if (content.startsWith("joined")) { message->setTag("intent", "JOIN"); message->setParameters(QStringList() << message->target()); } else if (content.startsWith("parted")) { message->setTag("intent", "PART"); QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); message->setParameters(QStringList() << message->target() << reason); } else if (content.startsWith("quit")) { message->setTag("intent", "QUIT"); QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); message->setParameters(QStringList() << reason); } else if (content.startsWith("is")) { message->setTag("intent", "NICK"); const QStringList tokens = content.split(" ", QString::SkipEmptyParts); message->setParameters(QStringList() << tokens.last()); } else if (content.startsWith("set")) { message->setTag("intent", "MODE"); QStringList tokens = content.split(" ", QString::SkipEmptyParts); const QString user = tokens.takeLast(); const QString mode = tokens.takeLast(); message->setParameters(QStringList() << message->target() << mode << user); } else if (content.startsWith("changed")) { message->setTag("intent", "TOPIC"); const QString topic = content.mid(content.indexOf(":") + 2); message->setParameters(QStringList() << message->target() << topic); } else if (content.startsWith("kicked")) { message->setTag("intent", "KICK"); QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); QStringList tokens = content.split(" ", QString::SkipEmptyParts); message->setParameters(QStringList() << message->target() << tokens.value(1) << reason); } } } void ZncManager::requestPlayback() { if (d.model->network()->isCapable("znc.in/playback")) { IrcConnection* connection = d.model->connection(); IrcCommand* cmd = IrcCommand::createMessage("*playback", QString("PLAY * %1").arg(d.timestamp.isValid() ? d.timestamp.toTime_t() : 0)); cmd->setParent(this); connection->sendCommand(cmd); } } void ZncManager::clearBuffer(IrcBuffer* buffer) { if (d.model->network()->isCapable("znc.in/playback") && !buffer->title().contains("*")) buffer->sendCommand(IrcCommand::createMessage("*playback", QString("CLEAR %1").arg(buffer->title()))); } <commit_msg>ZncManager: remove server-time parsing (was promoted to libcommuni)<commit_after>/* Copyright (C) 2008-2015 The Communi Project You may use this file under the terms of BSD license as follows: 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 copyright holder 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 HOLDERS 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 "zncmanager.h" #include "ignoremanager.h" #include <ircbuffermodel.h> #include <ircconnection.h> #include <irccommand.h> #include <ircmessage.h> #include <ircbuffer.h> IRC_USE_NAMESPACE ZncManager::ZncManager(QObject* parent) : QObject(parent) { d.model = 0; d.timestamp = QDateTime::fromTime_t(0); setModel(qobject_cast<IrcBufferModel*>(parent)); } ZncManager::~ZncManager() { } IrcBufferModel* ZncManager::model() const { return d.model; } void ZncManager::setModel(IrcBufferModel* model) { if (d.model != model) { if (d.model && d.model->connection()) { IrcConnection* connection = d.model->connection(); disconnect(connection, SIGNAL(connected()), this, SLOT(requestPlayback())); connection->removeMessageFilter(this); disconnect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*))); } d.model = model; if (d.model && d.model->connection()) { IrcNetwork* network = d.model->network(); QStringList caps = network->requestedCapabilities(); caps += "batch"; caps += "server-time"; caps += "echo-message"; caps += "znc.in/batch"; caps += "znc.in/playback"; caps += "znc.in/server-time"; caps += "znc.in/echo-message"; caps += "znc.in/server-time-iso"; network->setRequestedCapabilities(caps); IrcConnection* connection = d.model->connection(); connect(connection, SIGNAL(connected()), this, SLOT(requestPlayback())); connection->installMessageFilter(this); connect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*))); } emit modelChanged(model); } } bool ZncManager::messageFilter(IrcMessage* message) { if (message->connection()->isConnected()) d.timestamp = qMax(d.timestamp, message->timeStamp()); if (message->type() == IrcMessage::Batch) { IrcBatchMessage* batch = static_cast<IrcBatchMessage*>(message); if (batch->batch() == "znc.in/playback") { IrcBuffer* buffer = d.model->add(batch->parameters().value(2)); foreach (IrcMessage* msg, batch->messages()) { msg->setFlags(msg->flags() | IrcMessage::Playback); if (msg->type() == IrcMessage::Private) processMessage(static_cast<IrcPrivateMessage*>(msg)); } buffer->receiveMessage(batch); return true; } } return IgnoreManager::instance()->messageFilter(message); } void ZncManager::processMessage(IrcPrivateMessage* message) { if (message->nick() == "*buffextras") { const QString msg = message->content(); const int idx = msg.indexOf(" "); const QString prefix = msg.left(idx); const QString content = msg.mid(idx + 1); message->setPrefix(prefix); if (content.startsWith("joined")) { message->setTag("intent", "JOIN"); message->setParameters(QStringList() << message->target()); } else if (content.startsWith("parted")) { message->setTag("intent", "PART"); QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); message->setParameters(QStringList() << message->target() << reason); } else if (content.startsWith("quit")) { message->setTag("intent", "QUIT"); QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); message->setParameters(QStringList() << reason); } else if (content.startsWith("is")) { message->setTag("intent", "NICK"); const QStringList tokens = content.split(" ", QString::SkipEmptyParts); message->setParameters(QStringList() << tokens.last()); } else if (content.startsWith("set")) { message->setTag("intent", "MODE"); QStringList tokens = content.split(" ", QString::SkipEmptyParts); const QString user = tokens.takeLast(); const QString mode = tokens.takeLast(); message->setParameters(QStringList() << message->target() << mode << user); } else if (content.startsWith("changed")) { message->setTag("intent", "TOPIC"); const QString topic = content.mid(content.indexOf(":") + 2); message->setParameters(QStringList() << message->target() << topic); } else if (content.startsWith("kicked")) { message->setTag("intent", "KICK"); QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); QStringList tokens = content.split(" ", QString::SkipEmptyParts); message->setParameters(QStringList() << message->target() << tokens.value(1) << reason); } } } void ZncManager::requestPlayback() { if (d.model->network()->isCapable("znc.in/playback")) { IrcConnection* connection = d.model->connection(); IrcCommand* cmd = IrcCommand::createMessage("*playback", QString("PLAY * %1").arg(d.timestamp.isValid() ? d.timestamp.toTime_t() : 0)); cmd->setParent(this); connection->sendCommand(cmd); } } void ZncManager::clearBuffer(IrcBuffer* buffer) { if (d.model->network()->isCapable("znc.in/playback") && !buffer->title().contains("*")) buffer->sendCommand(IrcCommand::createMessage("*playback", QString("CLEAR %1").arg(buffer->title()))); } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef DTK_DETAILS_DISTRIBUTOR_HPP #define DTK_DETAILS_DISTRIBUTOR_HPP #include <Teuchos_ArrayView.hpp> #include <Tpetra_Distributor.hpp> #include <Kokkos_Parallel.hpp> #include <mpi.h> #include <algorithm> #define REORDER_RECV YES namespace DataTransferKit { namespace Details { // clang-format off // copy/paste from https://github.com/kokkos/kokkos-tutorials/blob/ee619447cee9e57b831e34b151d0868958b6b1e5/Intro-Full/Exercises/mpi_exch/mpi_exch.cpp // * added Experimental nested namespace qualifier for Max // * declared function static to avoid multiple definition error at link time // * return early if input argument is empty // * replace parallel_reduce with std::max_element because I couldn't get it to compile // * append size to offsets in main driver but might want to handle it here static void extract_and_sort_ranks( Kokkos::View<int*, Kokkos::HostSpace> destination_ranks, Kokkos::View<int*, Kokkos::HostSpace> permutation, std::vector<int>& unique_ranks, std::vector<int>& offsets, std::vector<int>& counts) { int mpi_rank; MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); auto n = destination_ranks.extent(0); if ( n == 0 ) return; using ST = decltype(n); Kokkos::View<int*, Kokkos::HostSpace> tmp_ranks("tmp ranks", destination_ranks.extent(0)); Kokkos::deep_copy(tmp_ranks, destination_ranks); int offset = 0; // this implements a "sort" which is O(N * R) where (R) is // the total number of unique destination ranks. // it performs better than other algorithms in // the case when (R) is small, but results may vary while (true) { int next_biggest_rank; //Kokkos::parallel_reduce("find next biggest rank", n, KOKKOS_LAMBDA(ST i, int& local_max) { // auto r = tmp_ranks(i); // local_max = (r > local_max) ? r : local_max; //}, Kokkos::Experimental::Max<int, Kokkos::HostSpace>(next_biggest_rank)); next_biggest_rank = *std::max_element(tmp_ranks.data(), tmp_ranks.data() + n); if (next_biggest_rank == -1) break; unique_ranks.push_back(next_biggest_rank); offsets.push_back(offset); Kokkos::View<int, Kokkos::HostSpace> total("total"); Kokkos::parallel_scan("process biggest rank items", Kokkos::RangePolicy<Kokkos::Serial>(0, n), KOKKOS_LAMBDA(ST i, int& index, const bool last_pass) { if (last_pass && (tmp_ranks(i) == next_biggest_rank)) { permutation(i) = index + offset; } if (tmp_ranks(i) == next_biggest_rank) ++index; if (last_pass) { if (i + 1 == tmp_ranks.extent(0)) { total() = index; } if (tmp_ranks(i) == next_biggest_rank) { tmp_ranks(i) = -1; } } }); auto host_total = Kokkos::create_mirror_view_and_copy( Kokkos::HostSpace(), total); auto count = host_total(); counts.push_back(count); offset += count; } } // clang-format on class Distributor { public: Distributor( Teuchos::RCP<Teuchos::Comm<int> const> comm ) : _distributor( comm ) , _comm( *( Teuchos::rcp_dynamic_cast<Teuchos::MpiComm<int> const>( comm ) ->getRawMpiComm() ) ) { } template <typename T> static T *notNullPtr( T *p ) { return p ? p : reinterpret_cast<T *>( -1 ); } size_t createFromSends( Teuchos::ArrayView<int const> const &export_proc_ids ) { static_assert( std::is_same<typename View::non_const_value_type, int>::value, "" ); int comm_rank; MPI_Comm_rank( _comm, &comm_rank ); auto const n = export_proc_ids.size(); Kokkos::View<int const *, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged>> tmp( export_proc_ids.getRawPtr(), n ); Kokkos::View<int *, Kokkos::HostSpace> destination_ranks( "destination_ranks", n ); Kokkos::deep_copy( destination_ranks, tmp ); _permute = Kokkos::View<int *, Kokkos::HostSpace>( "permute", n ); std::vector<int> destinations; extract_and_sort_ranks( destination_ranks, _permute, destinations, _dest_offsets, _dest_counts ); if ( _dest_counts.empty() ) _dest_offsets.push_back( 0 ); else _dest_offsets.push_back( _dest_offsets.back() + _dest_counts.back() ); { int const reorder = 0; // Ranking may *not* be reordered int const sources[1] = {comm_rank}; int const degrees[1] = {static_cast<int>( destinations.size() )}; MPI_Dist_graph_create( _comm, 1, sources, degrees, notNullPtr( destinations.data() ), MPI_UNWEIGHTED, MPI_INFO_NULL, reorder, &_comm_dist_graph ); } int indegrees; int outdegrees; int weighted; MPI_Dist_graph_neighbors_count( _comm_dist_graph, &indegrees, &outdegrees, &weighted ); assert( weighted == 0 ); assert( outdegrees == (int)destinations.size() ); std::vector<int> sources( indegrees ); MPI_Dist_graph_neighbors( _comm_dist_graph, indegrees, notNullPtr( sources.data() ), MPI_UNWEIGHTED, outdegrees, notNullPtr( destinations.data() ), MPI_UNWEIGHTED ); _src_counts.resize( indegrees ); MPI_Neighbor_alltoall( _dest_counts.data(), 1, MPI_INT, _src_counts.data(), 1, MPI_INT, _comm_dist_graph ); _src_offsets.resize( indegrees + 1 ); // exclusive scan _src_offsets[0] = 0; for ( int i = 0; i < indegrees; ++i ) _src_offsets[i + 1] = _src_offsets[i] + _src_counts[i]; int const nn = _distributor.createFromSends( export_proc_ids ); assert( _src_offsets.back() == nn ); // check return value for ( int i = 0; i < indegrees; ++i ) { auto it = std::find( std::begin( _distributor.getProcsFrom() ), std::end( _distributor.getProcsFrom() ), sources[i] ); assert( it != std::end( _distributor.getProcsFrom() ) ); int j = std::distance( std::begin( _distributor.getProcsFrom() ), it ); assert( _src_counts[i] == (int)_distributor.getLengthsFrom()[j] ); } for ( int i = 0; i < outdegrees; ++i ) { auto it = std::find( std::begin( _distributor.getProcsTo() ), std::end( _distributor.getProcsTo() ), destinations[i] ); assert( it != std::end( _distributor.getProcsTo() ) ); int j = std::distance( std::begin( _distributor.getProcsTo() ), it ); assert( _dest_counts[i] == (int)_distributor.getLengthsTo()[j] ); } #if defined( REORDER_RECV ) int comm_size = -1; MPI_Comm_size( _comm, &comm_size ); _permute_recv.resize( _src_offsets.back() ); int offset = 0; for ( int i = 0; i < comm_size; ++i ) { auto const it = std::find( sources.begin(), sources.end(), i ); if ( it != sources.end() ) { int const j = std::distance( sources.begin(), it ); std::iota( &_permute_recv[offset], &_permute_recv[offset] + _src_counts[j], _src_offsets[j] ); offset += _src_counts[j]; } } assert( offset == (int)_permute_recv.size() ); #endif return _src_offsets.back(); } template <typename Packet> void doPostsAndWaits( Teuchos::ArrayView<Packet const> const &exports, size_t numPackets, Teuchos::ArrayView<Packet> const &imports ) { std::vector<int> dest_counts = _dest_counts; std::vector<int> dest_offsets = _dest_offsets; std::vector<int> src_counts = _src_counts; std::vector<int> src_offsets = _src_offsets; for ( auto pv : {&dest_counts, &dest_offsets, &src_counts, &src_offsets} ) for ( auto &x : *pv ) x *= numPackets * sizeof( Packet ); std::vector<Packet> dest_buffer( exports.size() ); std::vector<Packet> src_buffer( imports.size() ); assert( (size_t)src_offsets.back() == imports.size() * sizeof( Packet ) ); assert( (size_t)dest_offsets.back() == exports.size() * sizeof( Packet ) ); for ( int i = 0; i < _dest_offsets.back(); ++i ) std::copy( &exports[numPackets * i], &exports[numPackets * i] + numPackets, &dest_buffer[numPackets * _permute[i]] ); MPI_Neighbor_alltoallv( notNullPtr( dest_buffer.data() ), notNullPtr( dest_counts.data() ), dest_offsets.data(), MPI_BYTE, notNullPtr( src_buffer.data() ), notNullPtr( src_counts.data() ), src_offsets.data(), MPI_BYTE, _comm_dist_graph ); #if defined( REORDER_RECV ) for ( int i = 0; i < _src_offsets.back(); ++i ) std::copy( &src_buffer[numPackets * _permute_recv[i]], &src_buffer[numPackets * _permute_recv[i]] + numPackets, &imports[numPackets * i] ); #else std::copy( src_buffer.begin(), src_buffer.end(), imports.getRawPtr() ); #endif size_t num_receives = _distributor.getNumReceives(); size_t num_sends = _distributor.getNumSends(); if ( _distributor.hasSelfMessage() ) { ++num_receives; ++num_sends; } assert( num_receives == _src_counts.size() ); assert( num_sends == _dest_counts.size() ); //_distributor.doPostsAndWaits( exports, numPackets, imports ); } size_t getTotalReceiveLength() const { auto n = _distributor.getTotalReceiveLength(); assert( n == std::accumulate( std::begin( _distributor.getLengthsFrom() ), std::end( _distributor.getLengthsFrom() ), size_t{0} ) ); assert( n == static_cast<size_t>( _src_offsets.back() ) ); return n; } size_t getTotalSendLength() const { auto n = std::accumulate( std::begin( _distributor.getLengthsTo() ), std::end( _distributor.getLengthsTo() ), size_t{0} ); assert( n == static_cast<size_t>( _dest_offsets.back() ) ); return n; } private: Tpetra::Distributor _distributor; MPI_Comm _comm; MPI_Comm _comm_dist_graph; Kokkos::View<int *, Kokkos::HostSpace> _permute; std::vector<int> _dest_offsets; std::vector<int> _dest_counts; std::vector<int> _src_offsets; std::vector<int> _src_counts; #if defined( REORDER_RECV ) std::vector<int> _permute_recv; #endif }; } // namespace Details } // namespace DataTransferKit #endif <commit_msg>Remove Tpetra::Distributor<commit_after>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef DTK_DETAILS_DISTRIBUTOR_HPP #define DTK_DETAILS_DISTRIBUTOR_HPP #include <Teuchos_ArrayView.hpp> #include <Teuchos_DefaultMpiComm.hpp> #include <Kokkos_Core.hpp> // FIXME #include <mpi.h> #include <algorithm> #define REORDER_RECV YES namespace DataTransferKit { namespace Details { // clang-format off // copy/paste from https://github.com/kokkos/kokkos-tutorials/blob/ee619447cee9e57b831e34b151d0868958b6b1e5/Intro-Full/Exercises/mpi_exch/mpi_exch.cpp // * added Experimental nested namespace qualifier for Max // * declared function static to avoid multiple definition error at link time // * return early if input argument is empty // * replace parallel_reduce with std::max_element because I couldn't get it to compile // * append size to offsets in main driver but might want to handle it here static void extract_and_sort_ranks( Kokkos::View<int*, Kokkos::HostSpace> destination_ranks, Kokkos::View<int*, Kokkos::HostSpace> permutation, std::vector<int>& unique_ranks, std::vector<int>& offsets, std::vector<int>& counts) { int mpi_rank; MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); auto n = destination_ranks.extent(0); if ( n == 0 ) return; using ST = decltype(n); Kokkos::View<int*, Kokkos::HostSpace> tmp_ranks("tmp ranks", destination_ranks.extent(0)); Kokkos::deep_copy(tmp_ranks, destination_ranks); int offset = 0; // this implements a "sort" which is O(N * R) where (R) is // the total number of unique destination ranks. // it performs better than other algorithms in // the case when (R) is small, but results may vary while (true) { int next_biggest_rank; //Kokkos::parallel_reduce("find next biggest rank", n, KOKKOS_LAMBDA(ST i, int& local_max) { // auto r = tmp_ranks(i); // local_max = (r > local_max) ? r : local_max; //}, Kokkos::Experimental::Max<int, Kokkos::HostSpace>(next_biggest_rank)); next_biggest_rank = *std::max_element(tmp_ranks.data(), tmp_ranks.data() + n); if (next_biggest_rank == -1) break; unique_ranks.push_back(next_biggest_rank); offsets.push_back(offset); Kokkos::View<int, Kokkos::HostSpace> total("total"); Kokkos::parallel_scan("process biggest rank items", Kokkos::RangePolicy<Kokkos::Serial>(0, n), KOKKOS_LAMBDA(ST i, int& index, const bool last_pass) { if (last_pass && (tmp_ranks(i) == next_biggest_rank)) { permutation(i) = index + offset; } if (tmp_ranks(i) == next_biggest_rank) ++index; if (last_pass) { if (i + 1 == tmp_ranks.extent(0)) { total() = index; } if (tmp_ranks(i) == next_biggest_rank) { tmp_ranks(i) = -1; } } }); auto host_total = Kokkos::create_mirror_view_and_copy( Kokkos::HostSpace(), total); auto count = host_total(); counts.push_back(count); offset += count; } } // clang-format on class Distributor { public: Distributor( Teuchos::RCP<Teuchos::Comm<int> const> comm ) : _comm( *( Teuchos::rcp_dynamic_cast<Teuchos::MpiComm<int> const>( comm ) ->getRawMpiComm() ) ) { } template <typename T> static T *notNullPtr( T *p ) { return p ? p : reinterpret_cast<T *>( -1 ); } size_t createFromSends( Teuchos::ArrayView<int const> const &export_proc_ids ) { static_assert( std::is_same<typename View::non_const_value_type, int>::value, "" ); int comm_rank; MPI_Comm_rank( _comm, &comm_rank ); auto const n = export_proc_ids.size(); Kokkos::View<int const *, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged>> tmp( export_proc_ids.getRawPtr(), n ); Kokkos::View<int *, Kokkos::HostSpace> destination_ranks( "destination_ranks", n ); Kokkos::deep_copy( destination_ranks, tmp ); _permute = Kokkos::View<int *, Kokkos::HostSpace>( "permute", n ); std::vector<int> destinations; extract_and_sort_ranks( destination_ranks, _permute, destinations, _dest_offsets, _dest_counts ); if ( _dest_counts.empty() ) _dest_offsets.push_back( 0 ); else _dest_offsets.push_back( _dest_offsets.back() + _dest_counts.back() ); { int const reorder = 0; // Ranking may *not* be reordered int const sources[1] = {comm_rank}; int const degrees[1] = {static_cast<int>( destinations.size() )}; MPI_Dist_graph_create( _comm, 1, sources, degrees, notNullPtr( destinations.data() ), MPI_UNWEIGHTED, MPI_INFO_NULL, reorder, &_comm_dist_graph ); } int indegrees; int outdegrees; int weighted; MPI_Dist_graph_neighbors_count( _comm_dist_graph, &indegrees, &outdegrees, &weighted ); assert( weighted == 0 ); assert( outdegrees == (int)destinations.size() ); std::vector<int> sources( indegrees ); MPI_Dist_graph_neighbors( _comm_dist_graph, indegrees, notNullPtr( sources.data() ), MPI_UNWEIGHTED, outdegrees, notNullPtr( destinations.data() ), MPI_UNWEIGHTED ); _src_counts.resize( indegrees ); MPI_Neighbor_alltoall( _dest_counts.data(), 1, MPI_INT, _src_counts.data(), 1, MPI_INT, _comm_dist_graph ); _src_offsets.resize( indegrees + 1 ); // exclusive scan _src_offsets[0] = 0; for ( int i = 0; i < indegrees; ++i ) _src_offsets[i + 1] = _src_offsets[i] + _src_counts[i]; #if defined( REORDER_RECV ) int comm_size = -1; MPI_Comm_size( _comm, &comm_size ); _permute_recv.resize( _src_offsets.back() ); int offset = 0; for ( int i = 0; i < comm_size; ++i ) { auto const it = std::find( sources.begin(), sources.end(), i ); if ( it != sources.end() ) { int const j = std::distance( sources.begin(), it ); std::iota( &_permute_recv[offset], &_permute_recv[offset] + _src_counts[j], _src_offsets[j] ); offset += _src_counts[j]; } } assert( offset == (int)_permute_recv.size() ); #endif return _src_offsets.back(); } template <typename Packet> void doPostsAndWaits( Teuchos::ArrayView<Packet const> const &exports, size_t numPackets, Teuchos::ArrayView<Packet> const &imports ) { std::vector<int> dest_counts = _dest_counts; std::vector<int> dest_offsets = _dest_offsets; std::vector<int> src_counts = _src_counts; std::vector<int> src_offsets = _src_offsets; for ( auto pv : {&dest_counts, &dest_offsets, &src_counts, &src_offsets} ) for ( auto &x : *pv ) x *= numPackets * sizeof( Packet ); std::vector<Packet> dest_buffer( exports.size() ); std::vector<Packet> src_buffer( imports.size() ); assert( (size_t)src_offsets.back() == imports.size() * sizeof( Packet ) ); assert( (size_t)dest_offsets.back() == exports.size() * sizeof( Packet ) ); for ( int i = 0; i < _dest_offsets.back(); ++i ) std::copy( &exports[numPackets * i], &exports[numPackets * i] + numPackets, &dest_buffer[numPackets * _permute[i]] ); MPI_Neighbor_alltoallv( notNullPtr( dest_buffer.data() ), notNullPtr( dest_counts.data() ), dest_offsets.data(), MPI_BYTE, notNullPtr( src_buffer.data() ), notNullPtr( src_counts.data() ), src_offsets.data(), MPI_BYTE, _comm_dist_graph ); #if defined( REORDER_RECV ) for ( int i = 0; i < _src_offsets.back(); ++i ) std::copy( &src_buffer[numPackets * _permute_recv[i]], &src_buffer[numPackets * _permute_recv[i]] + numPackets, &imports[numPackets * i] ); #else std::copy( src_buffer.begin(), src_buffer.end(), imports.getRawPtr() ); #endif } size_t getTotalReceiveLength() const { return _src_offsets.back(); } size_t getTotalSendLength() const { return _dest_offsets.back(); } private: MPI_Comm _comm; MPI_Comm _comm_dist_graph; Kokkos::View<int *, Kokkos::HostSpace> _permute; std::vector<int> _dest_offsets; std::vector<int> _dest_counts; std::vector<int> _src_offsets; std::vector<int> _src_counts; #if defined( REORDER_RECV ) std::vector<int> _permute_recv; #endif }; } // namespace Details } // namespace DataTransferKit #endif <|endoftext|>
<commit_before> #include <test.hpp> TEST_CASE("read string field") { SECTION("empty") { const std::string buffer = load_data("string/data-empty"); protozero::pbf_reader item(buffer); REQUIRE(item.next()); REQUIRE(item.get_string() == ""); REQUIRE(!item.next()); } SECTION("one") { const std::string buffer = load_data("string/data-one"); protozero::pbf_reader item(buffer); REQUIRE(item.next()); REQUIRE(item.get_string() == "x"); REQUIRE(!item.next()); } SECTION("string") { const std::string buffer = load_data("string/data-string"); protozero::pbf_reader item(buffer); REQUIRE(item.next()); REQUIRE(item.get_string() == "foobar"); REQUIRE(!item.next()); } SECTION("end_of_buffer") { const std::string buffer = load_data("string/data-string"); for (std::string::size_type i = 1; i < buffer.size(); ++i) { protozero::pbf_reader item(buffer.data(), i); REQUIRE(item.next()); REQUIRE_THROWS_AS(item.get_string(), protozero::end_of_buffer_exception); } } } TEST_CASE("write string field") { std::string buffer_test; protozero::pbf_writer pbf_test(buffer_test); SECTION("empty") { pbf_test.add_string(1, ""); REQUIRE(buffer_test == load_data("string/data-empty")); } SECTION("one") { pbf_test.add_string(1, "x"); REQUIRE(buffer_test == load_data("string/data-one")); } SECTION("string") { pbf_test.add_string(1, "foobar"); REQUIRE(buffer_test == load_data("string/data-string")); } } <commit_msg>Add test for get_view().<commit_after> #include <test.hpp> TEST_CASE("read string field using get_string") { SECTION("empty") { const std::string buffer = load_data("string/data-empty"); protozero::pbf_reader item(buffer); REQUIRE(item.next()); REQUIRE(item.get_string() == ""); REQUIRE(!item.next()); } SECTION("one") { const std::string buffer = load_data("string/data-one"); protozero::pbf_reader item(buffer); REQUIRE(item.next()); REQUIRE(item.get_string() == "x"); REQUIRE(!item.next()); } SECTION("string") { const std::string buffer = load_data("string/data-string"); protozero::pbf_reader item(buffer); REQUIRE(item.next()); REQUIRE(item.get_string() == "foobar"); REQUIRE(!item.next()); } SECTION("end_of_buffer") { const std::string buffer = load_data("string/data-string"); for (std::string::size_type i = 1; i < buffer.size(); ++i) { protozero::pbf_reader item(buffer.data(), i); REQUIRE(item.next()); REQUIRE_THROWS_AS(item.get_string(), protozero::end_of_buffer_exception); } } } TEST_CASE("read string field using get_view") { SECTION("empty") { const std::string buffer = load_data("string/data-empty"); protozero::pbf_reader item(buffer); REQUIRE(item.next()); auto v = item.get_view(); REQUIRE(v.size() == 0); REQUIRE(!item.next()); } SECTION("one") { const std::string buffer = load_data("string/data-one"); protozero::pbf_reader item(buffer); REQUIRE(item.next()); auto v = item.get_view(); REQUIRE(*v.data() == 'x'); REQUIRE(v.size() == 1); REQUIRE(!item.next()); } SECTION("string") { const std::string buffer = load_data("string/data-string"); protozero::pbf_reader item(buffer); REQUIRE(item.next()); REQUIRE(std::string(item.get_view()) == "foobar"); REQUIRE(!item.next()); } SECTION("end_of_buffer") { const std::string buffer = load_data("string/data-string"); for (std::string::size_type i = 1; i < buffer.size(); ++i) { protozero::pbf_reader item(buffer.data(), i); REQUIRE(item.next()); REQUIRE_THROWS_AS(item.get_view(), protozero::end_of_buffer_exception); } } } TEST_CASE("write string field") { std::string buffer_test; protozero::pbf_writer pbf_test(buffer_test); SECTION("empty") { pbf_test.add_string(1, ""); REQUIRE(buffer_test == load_data("string/data-empty")); } SECTION("one") { pbf_test.add_string(1, "x"); REQUIRE(buffer_test == load_data("string/data-one")); } SECTION("string") { pbf_test.add_string(1, "foobar"); REQUIRE(buffer_test == load_data("string/data-string")); } } <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. Eigen itself is part of the KDE project. // // Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #include <typeinfo> template<typename Dst, typename Src> bool test_assign(const Dst&, const Src&, int vectorization, int unrolling) { return ei_assign_traits<Dst,Src>::Vectorization==vectorization && ei_assign_traits<Dst,Src>::Unrolling==unrolling; } template<typename Xpr> bool test_sum(const Xpr&, int vectorization, int unrolling) { return ei_sum_traits<Xpr>::Vectorization==vectorization && ei_sum_traits<Xpr>::Unrolling==unrolling; } void test_vectorization_logic() { #ifdef EIGEN_VECTORIZE VERIFY(test_assign(Vector4f(),Vector4f(), InnerVectorization,CompleteUnrolling)); VERIFY(test_assign(Vector4f(),Vector4f()+Vector4f(), InnerVectorization,CompleteUnrolling)); VERIFY(test_assign(Vector4f(),Vector4f().cwise() * Vector4f(), InnerVectorization,CompleteUnrolling)); VERIFY(test_assign(Matrix4f(),Matrix4f(), InnerVectorization,CompleteUnrolling)); VERIFY(test_assign(Matrix4f(),Matrix4f()+Matrix4f(), InnerVectorization,CompleteUnrolling)); VERIFY(test_assign(Matrix4f(),Matrix4f().cwise() * Matrix4f(), InnerVectorization,CompleteUnrolling)); VERIFY(test_assign(Matrix<float,16,16>(),Matrix<float,16,16>()+Matrix<float,16,16>(), InnerVectorization,InnerUnrolling)); VERIFY(test_assign(Matrix<float,16,16,DontAlign>(),Matrix<float,16,16>()+Matrix<float,16,16>(), NoVectorization,InnerUnrolling)); VERIFY(test_assign(Matrix<float,6,2>(),Matrix<float,6,2>().cwise() / Matrix<float,6,2>(), LinearVectorization,CompleteUnrolling)); VERIFY(test_assign(Matrix<float,17,17>(),Matrix<float,17,17>()+Matrix<float,17,17>(), NoVectorization,InnerUnrolling)); VERIFY(test_assign(Matrix<float,4,4>(),Matrix<float,17,17>().block<4,4>(2,3)+Matrix<float,17,17>().block<4,4>(10,4), NoVectorization,CompleteUnrolling)); VERIFY(test_assign(MatrixXf(10,10),MatrixXf(20,20).block(10,10,2,3), SliceVectorization,NoUnrolling)); VERIFY(test_sum(VectorXf(10), LinearVectorization,NoUnrolling)); VERIFY(test_sum(Matrix<float,5,2>(), NoVectorization,CompleteUnrolling)); VERIFY(test_sum(Matrix<float,6,2>(), LinearVectorization,CompleteUnrolling)); VERIFY(test_sum(Matrix<float,16,16>(), LinearVectorization,NoUnrolling)); VERIFY(test_sum(Matrix<float,16,16>().block<4,4>(1,2), NoVectorization,CompleteUnrolling)); VERIFY(test_sum(Matrix<float,16,16>().block<8,1>(1,2), LinearVectorization,CompleteUnrolling)); VERIFY(test_sum(Matrix<double,7,3>(), NoVectorization,CompleteUnrolling)); #endif // EIGEN_VECTORIZE } <commit_msg>update vectorization_logic unit test wrt previous sum/redux change<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. Eigen itself is part of the KDE project. // // Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #include <typeinfo> template<typename Dst, typename Src> bool test_assign(const Dst&, const Src&, int vectorization, int unrolling) { return ei_assign_traits<Dst,Src>::Vectorization==vectorization && ei_assign_traits<Dst,Src>::Unrolling==unrolling; } template<typename Xpr> bool test_redux(const Xpr&, int vectorization, int unrolling) { typedef ei_redux_traits<ei_scalar_sum_op<typename Xpr::Scalar>,Xpr> traits; return traits::Vectorization==vectorization && traits::Unrolling==unrolling; } void test_vectorization_logic() { #ifdef EIGEN_VECTORIZE VERIFY(test_assign(Vector4f(),Vector4f(), InnerVectorization,CompleteUnrolling)); VERIFY(test_assign(Vector4f(),Vector4f()+Vector4f(), InnerVectorization,CompleteUnrolling)); VERIFY(test_assign(Vector4f(),Vector4f().cwise() * Vector4f(), InnerVectorization,CompleteUnrolling)); VERIFY(test_assign(Matrix4f(),Matrix4f(), InnerVectorization,CompleteUnrolling)); VERIFY(test_assign(Matrix4f(),Matrix4f()+Matrix4f(), InnerVectorization,CompleteUnrolling)); VERIFY(test_assign(Matrix4f(),Matrix4f().cwise() * Matrix4f(), InnerVectorization,CompleteUnrolling)); VERIFY(test_assign(Matrix<float,16,16>(),Matrix<float,16,16>()+Matrix<float,16,16>(), InnerVectorization,InnerUnrolling)); VERIFY(test_assign(Matrix<float,16,16,DontAlign>(),Matrix<float,16,16>()+Matrix<float,16,16>(), NoVectorization,InnerUnrolling)); VERIFY(test_assign(Matrix<float,6,2>(),Matrix<float,6,2>().cwise() / Matrix<float,6,2>(), LinearVectorization,CompleteUnrolling)); VERIFY(test_assign(Matrix<float,17,17>(),Matrix<float,17,17>()+Matrix<float,17,17>(), NoVectorization,InnerUnrolling)); VERIFY(test_assign(Matrix<float,4,4>(),Matrix<float,17,17>().block<4,4>(2,3)+Matrix<float,17,17>().block<4,4>(10,4), NoVectorization,CompleteUnrolling)); VERIFY(test_assign(MatrixXf(10,10),MatrixXf(20,20).block(10,10,2,3), SliceVectorization,NoUnrolling)); VERIFY(test_redux(VectorXf(10), LinearVectorization,NoUnrolling)); VERIFY(test_redux(Matrix<float,5,2>(), NoVectorization,CompleteUnrolling)); VERIFY(test_redux(Matrix<float,6,2>(), LinearVectorization,CompleteUnrolling)); VERIFY(test_redux(Matrix<float,16,16>(), LinearVectorization,NoUnrolling)); VERIFY(test_redux(Matrix<float,16,16>().block<4,4>(1,2), NoVectorization,CompleteUnrolling)); VERIFY(test_redux(Matrix<float,16,16>().block<8,1>(1,2), LinearVectorization,CompleteUnrolling)); VERIFY(test_redux(Matrix<double,7,3>(), NoVectorization,CompleteUnrolling)); #endif // EIGEN_VECTORIZE } <|endoftext|>
<commit_before>#include "geometry/RipsExpander.hh" #include "tests/Base.hh" #include "filtrations/Data.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include <iterator> #include <set> #include <vector> #include <cmath> using namespace aleph::geometry; using namespace aleph::topology; using namespace aleph; /** Checks whether co-faces are preceded by their faces in a filtration */ template <class InputIterator> bool isConsistentFiltration( InputIterator begin, InputIterator end ) { using Simplex = typename std::iterator_traits<InputIterator>::value_type; // Contains all simplices that have already been 'seen' during the // traversal. If an unseen face is encountered, we have identified // an error. std::set<Simplex> seen; for( auto it = begin; it != end; ++it ) { seen.insert( *it ); for( auto itFace = it->begin_boundary(); itFace != it->end_boundary(); ++itFace ) if( seen.find( *itFace ) == seen.end() ) return false; } return true; } template <class Data, class Vertex> void triangle() { ALEPH_TEST_BEGIN( "Triangle" ); using Simplex = Simplex<Data, Vertex>; using SimplicialComplex = SimplicialComplex<Simplex>; std::vector<Simplex> simplices = { {0}, {1}, {2}, {0,1}, {0,2}, {1,2} }; SimplicialComplex K( simplices.begin(), simplices.end() ); RipsExpander<SimplicialComplex> ripsExpander; auto vr1 = ripsExpander( K, 2 ); auto vr2 = ripsExpander( K, 3 ); ALEPH_ASSERT_THROW( vr1.empty() == false ); ALEPH_ASSERT_THROW( vr2.empty() == false ); ALEPH_ASSERT_THROW( vr1.size() == vr2.size() ); ALEPH_ASSERT_THROW( vr1.size() == 7 ); ALEPH_TEST_END(); } template <class Data, class Vertex> void quad() { ALEPH_TEST_BEGIN( "Quad" ); using Simplex = Simplex<Data, Vertex>; using SimplicialComplex = SimplicialComplex<Simplex>; std::vector<Simplex> simplices = { {0}, {1}, {2}, {3}, Simplex( {0,1}, Data(1) ), Simplex( {0,2}, Data( std::sqrt(2.0) ) ), Simplex( {1,2}, Data(1) ), Simplex( {2,3}, Data(1) ), Simplex( {0,3}, Data(1) ), Simplex( {1,3}, Data( std::sqrt(2.0) ) ) }; SimplicialComplex K( simplices.begin(), simplices.end() ); RipsExpander<SimplicialComplex> ripsExpander; auto vr1 = ripsExpander( K, 1 ); auto vr2 = ripsExpander( K, 2 ); auto vr3 = ripsExpander( K, 3 ); vr1 = ripsExpander.assignMaximumWeight( vr1 ); vr2 = ripsExpander.assignMaximumWeight( vr2 ); vr3 = ripsExpander.assignMaximumWeight( vr3 ); vr1.sort( filtrations::Data<Simplex>() ); vr2.sort( filtrations::Data<Simplex>() ); vr3.sort( filtrations::Data<Simplex>() ); ALEPH_ASSERT_THROW( vr1.empty() == false ); ALEPH_ASSERT_THROW( vr2.empty() == false ); ALEPH_ASSERT_THROW( vr3.empty() == false ); ALEPH_ASSERT_THROW( vr1.size() == simplices.size() ); ALEPH_ASSERT_THROW( vr2.size() == vr1.size() + 4 ); // +4 triangles ALEPH_ASSERT_THROW( vr3.size() == vr2.size() + 1 ); // +1 tetrahedron ALEPH_ASSERT_THROW( isConsistentFiltration( vr1.begin(), vr1.end() ) ); ALEPH_ASSERT_THROW( isConsistentFiltration( vr2.begin(), vr2.end() ) ); ALEPH_ASSERT_THROW( isConsistentFiltration( vr3.begin(), vr3.end() ) ); ALEPH_TEST_END(); } int main() { triangle<double, unsigned>(); triangle<double, short >(); triangle<float, unsigned>(); triangle<float, short >(); quad<double, unsigned>(); quad<double, short >(); quad<float, unsigned>(); quad<float, short >(); } <commit_msg>Started implementing test case for comparing Rips expansion strategies<commit_after>#include "geometry/RipsExpander.hh" #include "geometry/RipsExpanderTopDown.hh" #include "tests/Base.hh" #include "filtrations/Data.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include <iterator> #include <set> #include <vector> #include <cmath> using namespace aleph::geometry; using namespace aleph::topology; using namespace aleph; /** Checks whether co-faces are preceded by their faces in a filtration */ template <class InputIterator> bool isConsistentFiltration( InputIterator begin, InputIterator end ) { using Simplex = typename std::iterator_traits<InputIterator>::value_type; // Contains all simplices that have already been 'seen' during the // traversal. If an unseen face is encountered, we have identified // an error. std::set<Simplex> seen; for( auto it = begin; it != end; ++it ) { seen.insert( *it ); for( auto itFace = it->begin_boundary(); itFace != it->end_boundary(); ++itFace ) if( seen.find( *itFace ) == seen.end() ) return false; } return true; } template <class Data, class Vertex> void triangle() { ALEPH_TEST_BEGIN( "Triangle" ); using Simplex = Simplex<Data, Vertex>; using SimplicialComplex = SimplicialComplex<Simplex>; std::vector<Simplex> simplices = { {0}, {1}, {2}, {0,1}, {0,2}, {1,2} }; SimplicialComplex K( simplices.begin(), simplices.end() ); RipsExpander<SimplicialComplex> ripsExpander; auto vr1 = ripsExpander( K, 2 ); auto vr2 = ripsExpander( K, 3 ); ALEPH_ASSERT_THROW( vr1.empty() == false ); ALEPH_ASSERT_THROW( vr2.empty() == false ); ALEPH_ASSERT_THROW( vr1.size() == vr2.size() ); ALEPH_ASSERT_THROW( vr1.size() == 7 ); ALEPH_TEST_END(); } template <class Data, class Vertex> void quad() { ALEPH_TEST_BEGIN( "Quad" ); using Simplex = Simplex<Data, Vertex>; using SimplicialComplex = SimplicialComplex<Simplex>; std::vector<Simplex> simplices = { {0}, {1}, {2}, {3}, Simplex( {0,1}, Data(1) ), Simplex( {0,2}, Data( std::sqrt(2.0) ) ), Simplex( {1,2}, Data(1) ), Simplex( {2,3}, Data(1) ), Simplex( {0,3}, Data(1) ), Simplex( {1,3}, Data( std::sqrt(2.0) ) ) }; SimplicialComplex K( simplices.begin(), simplices.end() ); RipsExpander<SimplicialComplex> ripsExpander; auto vr1 = ripsExpander( K, 1 ); auto vr2 = ripsExpander( K, 2 ); auto vr3 = ripsExpander( K, 3 ); vr1 = ripsExpander.assignMaximumWeight( vr1 ); vr2 = ripsExpander.assignMaximumWeight( vr2 ); vr3 = ripsExpander.assignMaximumWeight( vr3 ); vr1.sort( filtrations::Data<Simplex>() ); vr2.sort( filtrations::Data<Simplex>() ); vr3.sort( filtrations::Data<Simplex>() ); ALEPH_ASSERT_THROW( vr1.empty() == false ); ALEPH_ASSERT_THROW( vr2.empty() == false ); ALEPH_ASSERT_THROW( vr3.empty() == false ); ALEPH_ASSERT_THROW( vr1.size() == simplices.size() ); ALEPH_ASSERT_THROW( vr2.size() == vr1.size() + 4 ); // +4 triangles ALEPH_ASSERT_THROW( vr3.size() == vr2.size() + 1 ); // +1 tetrahedron ALEPH_ASSERT_THROW( isConsistentFiltration( vr1.begin(), vr1.end() ) ); ALEPH_ASSERT_THROW( isConsistentFiltration( vr2.begin(), vr2.end() ) ); ALEPH_ASSERT_THROW( isConsistentFiltration( vr3.begin(), vr3.end() ) ); ALEPH_TEST_END(); } template <class Data, class Vertex> void expanderComparison() { ALEPH_TEST_BEGIN( "Rips expander comparison" ); using Simplex = Simplex<Data, Vertex>; using SimplicialComplex = SimplicialComplex<Simplex>; std::vector<Simplex> simplices = { {0}, {1}, {2}, {3}, Simplex( {0,1}, Data(1) ), Simplex( {0,2}, Data( std::sqrt(2.0) ) ), Simplex( {1,2}, Data(1) ), Simplex( {2,3}, Data(1) ), Simplex( {0,3}, Data(1) ), Simplex( {1,3}, Data( std::sqrt(2.0) ) ) }; SimplicialComplex K( simplices.begin(), simplices.end() ); RipsExpander<SimplicialComplex> re; RipsExpanderTopDown<SimplicialComplex> retd; auto K1 = re( K, 3 ); auto K2 = retd( K, 3 ); ALEPH_ASSERT_EQUAL( K1.size(), K2.size() ); ALEPH_TEST_END(); } int main() { triangle<double, unsigned>(); triangle<double, short >(); triangle<float, unsigned>(); triangle<float, short >(); quad<double, unsigned>(); quad<double, short >(); quad<float, unsigned>(); quad<float, short >(); expanderComparison<double, unsigned>(); expanderComparison<double, short >(); expanderComparison<float, unsigned>(); expanderComparison<float, short >(); } <|endoftext|>
<commit_before>/* * * copyright (c) 2010 ZAO Inventos (inventos.ru) * copyright (c) 2010 jk@inventos.ru * copyright (c) 2010 kuzalex@inventos.ru * copyright (c) 2010 artint@inventos.ru * * This file is part of mp4frag. * * mp4grag 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. * * mp4frag 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. */ #ifndef __mp4_hh__c6051ba6_1c2a_4b5d_b3ec_a4d3401a9df3 #define __mp4_hh__c6051ba6_1c2a_4b5d_b3ec_a4d3401a9df3 #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <vector> #include <iostream> #include <stack> namespace mp4 { class Context; class Parser : public ::boost::enable_shared_from_this<Parser> { friend class Context; protected: Context *_ctx; uint32_t _total; uint32_t _wants; uint32_t _to_skip; ::boost::shared_ptr<Parser> _up; public: Parser() : _ctx(0), _total(0), _wants(0), _to_skip(0) {} virtual ~Parser(); virtual void parse(const char *data) = 0; size_t wants() const { return _wants; } void skip(uint32_t to_skip) { _to_skip = to_skip; } }; struct Track { uint64_t _duration; uint32_t _timescale; uint32_t _pwidth, _pheight; std::vector<uint32_t> _sample_size; std::vector<std::pair<uint32_t, uint32_t> > _compos_deltas; std::vector<uint64_t> _chunk_offsets; std::vector<uint64_t> _stss; std::vector<std::pair<uint64_t, uint64_t> > _stts; std::vector<char> _extradata; struct SampleToChunk { uint32_t _first_chunk; uint32_t _samples_per_chunk; uint32_t _desc_index; SampleToChunk() {} SampleToChunk(uint32_t f, uint32_t s, uint32_t d) : _first_chunk(f), _samples_per_chunk(s), _desc_index(d) {} }; std::vector<SampleToChunk> _samples_to_chunk; Track() : _duration(0), _pwidth(0), _pheight(0) {} }; struct SampleInfo { uint64_t _timestamp; uint64_t _number; uint64_t _offset; uint32_t _composition_offset; uint32_t _timescale; uint32_t _sample_size; bool _video; bool _keyframe; double timestamp() const { return double(_timestamp) / _timescale; } }; class MetaInfo { friend class Context; std::vector<SampleInfo> _samples; uint32_t _width; uint32_t _height; uint32_t _bitrate; double _duration; bool _has_video, _has_audio; }; class Context { public: std::vector<SampleInfo> _samples; private: ::boost::shared_ptr<Parser> _parser; std::vector<char> _buffer; public: unsigned wants() const { return _parser->_wants; } unsigned total() const { return _parser->_total; } unsigned to_skip() const { return _parser->_to_skip; } public: Context(); virtual ~Context(); void skip(unsigned count) { _parser->_to_skip = count; assert ( _parser->_to_skip <= _parser->_total ); } void push_state(const ::boost::shared_ptr<Parser>& p, unsigned total, unsigned wants); void pop_state(); size_t feed(const char *data, size_t sz); ::boost::shared_ptr<Track> _current_parsed; // valid only after full parsing: ::boost::shared_ptr<Track> _video; ::boost::shared_ptr<Track> _audio; uint32_t _width; uint32_t _height; uint32_t _pwidth, _pheight; std::string _videoextra, _audioextra; uint32_t _bitrate; double _duration; bool _has_video, _has_audio; void _unfold(const ::boost::shared_ptr<Track>& track, bool is_video); void finalize(); unsigned find_sample(double timestamp); unsigned nsamples() const { return _samples.size(); } SampleInfo *get_sample(unsigned si) { return &_samples[si]; } bool has_video() const { return _has_video; } bool has_audio() const { return _has_audio; } uint32_t width() const { return _width; } uint32_t height() const { return _height; } uint32_t pwidth() const { return _pwidth; } uint32_t pheight() const { return _pheight; } uint32_t bitrate() const { return _bitrate; } double duration() const { return _duration; } const std::string& videoextra() const { return _videoextra; } const std::string& audioextra() const { return _audioextra; } }; } ::std::ostream& operator<<(::std::ostream&, const mp4::Track&); ::std::ostream& operator<<(::std::ostream&, const mp4::SampleInfo&); #endif <commit_msg>stdint header<commit_after>/* * * copyright (c) 2010 ZAO Inventos (inventos.ru) * copyright (c) 2010 jk@inventos.ru * copyright (c) 2010 kuzalex@inventos.ru * copyright (c) 2010 artint@inventos.ru * * This file is part of mp4frag. * * mp4grag 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. * * mp4frag 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. */ #ifndef __mp4_hh__c6051ba6_1c2a_4b5d_b3ec_a4d3401a9df3 #define __mp4_hh__c6051ba6_1c2a_4b5d_b3ec_a4d3401a9df3 #include <stdint.h> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <vector> #include <iostream> #include <stack> namespace mp4 { class Context; class Parser : public ::boost::enable_shared_from_this<Parser> { friend class Context; protected: Context *_ctx; uint32_t _total; uint32_t _wants; uint32_t _to_skip; ::boost::shared_ptr<Parser> _up; public: Parser() : _ctx(0), _total(0), _wants(0), _to_skip(0) {} virtual ~Parser(); virtual void parse(const char *data) = 0; size_t wants() const { return _wants; } void skip(uint32_t to_skip) { _to_skip = to_skip; } }; struct Track { uint64_t _duration; uint32_t _timescale; uint32_t _pwidth, _pheight; std::vector<uint32_t> _sample_size; std::vector<std::pair<uint32_t, uint32_t> > _compos_deltas; std::vector<uint64_t> _chunk_offsets; std::vector<uint64_t> _stss; std::vector<std::pair<uint64_t, uint64_t> > _stts; std::vector<char> _extradata; struct SampleToChunk { uint32_t _first_chunk; uint32_t _samples_per_chunk; uint32_t _desc_index; SampleToChunk() {} SampleToChunk(uint32_t f, uint32_t s, uint32_t d) : _first_chunk(f), _samples_per_chunk(s), _desc_index(d) {} }; std::vector<SampleToChunk> _samples_to_chunk; Track() : _duration(0), _pwidth(0), _pheight(0) {} }; struct SampleInfo { uint64_t _timestamp; uint64_t _number; uint64_t _offset; uint32_t _composition_offset; uint32_t _timescale; uint32_t _sample_size; bool _video; bool _keyframe; double timestamp() const { return double(_timestamp) / _timescale; } }; class MetaInfo { friend class Context; std::vector<SampleInfo> _samples; uint32_t _width; uint32_t _height; uint32_t _bitrate; double _duration; bool _has_video, _has_audio; }; class Context { public: std::vector<SampleInfo> _samples; private: ::boost::shared_ptr<Parser> _parser; std::vector<char> _buffer; public: unsigned wants() const { return _parser->_wants; } unsigned total() const { return _parser->_total; } unsigned to_skip() const { return _parser->_to_skip; } public: Context(); virtual ~Context(); void skip(unsigned count) { _parser->_to_skip = count; assert ( _parser->_to_skip <= _parser->_total ); } void push_state(const ::boost::shared_ptr<Parser>& p, unsigned total, unsigned wants); void pop_state(); size_t feed(const char *data, size_t sz); ::boost::shared_ptr<Track> _current_parsed; // valid only after full parsing: ::boost::shared_ptr<Track> _video; ::boost::shared_ptr<Track> _audio; uint32_t _width; uint32_t _height; uint32_t _pwidth, _pheight; std::string _videoextra, _audioextra; uint32_t _bitrate; double _duration; bool _has_video, _has_audio; void _unfold(const ::boost::shared_ptr<Track>& track, bool is_video); void finalize(); unsigned find_sample(double timestamp); unsigned nsamples() const { return _samples.size(); } SampleInfo *get_sample(unsigned si) { return &_samples[si]; } bool has_video() const { return _has_video; } bool has_audio() const { return _has_audio; } uint32_t width() const { return _width; } uint32_t height() const { return _height; } uint32_t pwidth() const { return _pwidth; } uint32_t pheight() const { return _pheight; } uint32_t bitrate() const { return _bitrate; } double duration() const { return _duration; } const std::string& videoextra() const { return _videoextra; } const std::string& audioextra() const { return _audioextra; } }; } ::std::ostream& operator<<(::std::ostream&, const mp4::Track&); ::std::ostream& operator<<(::std::ostream&, const mp4::SampleInfo&); #endif <|endoftext|>
<commit_before>#include "multisource.h" #include "simple_label.h" #include <sys/types.h> #include <sys/socket.h> #include <errno.h> #include <stdio.h> int really_read(int sock, void* in, size_t count) { char* buf = (char*)in; size_t done = 0; int r = 0; while (done < count) { if ((r = read(sock,buf,count-done)) == 0) return 0; else if (r < 0) { cerr << "argh! bad read! " << endl; perror(NULL); exit(0); } else { done += r; buf += r; } } return done; } bool blocking_get_prediction(int sock, prediction &p) { int count = really_read(sock, &p, sizeof(p)); bool ret = (count == sizeof(p)); return ret; } size_t recv_count = 0; bool blocking_get_global_prediction(int sock, global_prediction &p) { int count = really_read(sock, &p, sizeof(p)); bool ret = (count == sizeof(p)); if (ret) recv_count++; return ret; } void send_prediction(int sock, prediction &p) { if (write(sock, &p, sizeof(p)) < (int)sizeof(p)) { cerr << "argh! bad write! " << endl; perror(NULL); exit(0); } } size_t send_count = 0; void send_global_prediction(int sock, global_prediction p) { if (write(sock, &p, sizeof(p)) < (int)sizeof(p)) { cerr << "argh! bad global write! " << sock << endl; perror(NULL); exit(0); } else send_count++; } void reset(partial_example &ex) { ex.features.erase(); } size_t num_finished = 0; int receive_features(parser* p, void* ex) { example* ae = (example*)ex; io_buf* input = p->input; fd_set fds; FD_ZERO(&fds); for (int* sock= input->files.begin; sock != input->files.end-num_finished; sock++) FD_SET(*sock,&fds); while (input->files.index() > num_finished) { if (select(p->max_fd,&fds,NULL, NULL, NULL) == -1) { cerr << "Select failed!" << endl; perror(NULL); exit (1); } for (int index = 0; index < (int)input->files.index(); index++) { int sock = input->files[index]; if (FD_ISSET(sock, &fds)) {//there is a feature or label to read prediction pre; if (!blocking_get_prediction(sock, pre) ) { FD_CLR(sock, &fds); int swap_target = input->files.index()-num_finished-1; input->files[index]=input->files[swap_target]; input->files[swap_target]=sock; int temp = p->ids[index]; p->ids[index]=p->ids[swap_target]; p->ids[swap_target] = temp; temp = p->counts[index]; p->counts[index]=p->counts[swap_target]; p->counts[swap_target] = temp; num_finished++; } else { if (pre.example_number != ++ (p->counts[index])) cout << "count is off! " << pre.example_number << " != " << p->counts[index] << " for source " << index << " prediction = " << pre.p << endl; if (pre.example_number == p->finished_count + ring_size - 1) FD_CLR(sock,&fds);//this ones to far ahead, let the buffer fill for awhile. size_t ring_index = pre.example_number % p->pes.index(); if (p->pes[ring_index].features.index() == 0) p->pes[ring_index].example_number = pre.example_number; if (p->pes[ring_index].example_number != (int)pre.example_number) cerr << "Error, example " << p->pes[ring_index].example_number << " != " << pre.example_number << endl; feature f = {pre.p, p->ids[index]}; push(p->pes[ring_index].features, f); if (sock == p->label_sock) // The label source { label_data ld; size_t len = sizeof(ld.label)+sizeof(ld.weight); char c[len]; really_read(sock,c,len); bufread_simple_label(&(p->pes[ring_index].ld), c); } if( p->pes[ring_index].features.index() == input->count ) { push( ae->indices, multindex ); push_many( ae->atomics[multindex], p->pes[ring_index].features.begin, p->pes[ring_index].features.index() ); label_data* ld = (label_data*)ae->ld; *ld = p->pes[ring_index].ld; reset(p->pes[ring_index]); p->finished_count++; return ae->atomics[multindex].index(); } } } else if (p->counts[index] < p->finished_count + ring_size -1) FD_SET(sock,&fds); } } return 0; } <commit_msg>fixed multisource.cc for many sources<commit_after>#include "multisource.h" #include "simple_label.h" #include <sys/types.h> #include <sys/socket.h> #include <errno.h> #include <stdio.h> int really_read(int sock, void* in, size_t count) { char* buf = (char*)in; size_t done = 0; int r = 0; while (done < count) { if ((r = read(sock,buf,count-done)) == 0) return 0; else if (r < 0) { cerr << "argh! bad read! " << endl; perror(NULL); exit(0); } else { done += r; buf += r; } } return done; } bool blocking_get_prediction(int sock, prediction &p) { int count = really_read(sock, &p, sizeof(p)); bool ret = (count == sizeof(p)); return ret; } size_t recv_count = 0; bool blocking_get_global_prediction(int sock, global_prediction &p) { int count = really_read(sock, &p, sizeof(p)); bool ret = (count == sizeof(p)); if (ret) recv_count++; return ret; } void send_prediction(int sock, prediction &p) { if (write(sock, &p, sizeof(p)) < (int)sizeof(p)) { cerr << "argh! bad write! " << endl; perror(NULL); exit(0); } } size_t send_count = 0; void send_global_prediction(int sock, global_prediction p) { if (write(sock, &p, sizeof(p)) < (int)sizeof(p)) { cerr << "argh! bad global write! " << sock << endl; perror(NULL); exit(0); } else send_count++; } void reset(partial_example &ex) { ex.features.erase(); } size_t num_finished = 0; int receive_features(parser* p, void* ex) { example* ae = (example*)ex; io_buf* input = p->input; fd_set fds; FD_ZERO(&fds); for (int* sock= input->files.begin; sock != input->files.end-num_finished; sock++) FD_SET(*sock,&fds); while (input->files.index() > num_finished) { if (select(p->max_fd,&fds,NULL, NULL, NULL) == -1) { cerr << "Select failed!" << endl; perror(NULL); exit (1); } for (int index = 0; index < (int)(input->files.index()-num_finished); index++) { int sock = input->files[index]; if (FD_ISSET(sock, &fds)) {//there is a feature or label to read prediction pre; if (!blocking_get_prediction(sock, pre) ) { FD_CLR(sock, &fds); int swap_target = input->files.index()-num_finished-1; input->files[index]=input->files[swap_target]; input->files[swap_target]=sock; int temp = p->ids[index]; p->ids[index]=p->ids[swap_target]; p->ids[swap_target] = temp; temp = p->counts[index]; p->counts[index]=p->counts[swap_target]; p->counts[swap_target] = temp; num_finished++; index--; } else { if (pre.example_number != ++ (p->counts[index])) cout << "count is off! " << pre.example_number << " != " << p->counts[index] << " for source " << index << " prediction = " << pre.p << endl; if (pre.example_number == p->finished_count + ring_size - 1) FD_CLR(sock,&fds);//this ones to far ahead, let the buffer fill for awhile. size_t ring_index = pre.example_number % p->pes.index(); if (p->pes[ring_index].features.index() == 0) p->pes[ring_index].example_number = pre.example_number; if (p->pes[ring_index].example_number != (int)pre.example_number) cerr << "Error, example " << p->pes[ring_index].example_number << " != " << pre.example_number << endl; feature f = {pre.p, p->ids[index]}; push(p->pes[ring_index].features, f); if (sock == p->label_sock) // The label source { label_data ld; size_t len = sizeof(ld.label)+sizeof(ld.weight); char c[len]; really_read(sock,c,len); bufread_simple_label(&(p->pes[ring_index].ld), c); } if( p->pes[ring_index].features.index() == input->count ) { push( ae->indices, multindex ); push_many( ae->atomics[multindex], p->pes[ring_index].features.begin, p->pes[ring_index].features.index() ); label_data* ld = (label_data*)ae->ld; *ld = p->pes[ring_index].ld; reset(p->pes[ring_index]); p->finished_count++; return ae->atomics[multindex].index(); } } } else if (p->counts[index] < p->finished_count + ring_size -1) FD_SET(sock,&fds); } } return 0; } <|endoftext|>
<commit_before><commit_msg>Revert r18683: "Add more CHECKs to ClientSocketPoolBase." Looks like it might have broken block-test.html somehow.<commit_after><|endoftext|>
<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "MyPinCreationConfirmationViewModel.h" namespace ExampleApp { namespace MyPinCreation { namespace View { MyPinCreationConfirmationViewModel::MyPinCreationConfirmationViewModel(Eegeo::Helpers::TIdentity identity, bool initiallyOnScreen, Reaction::View::IReactionControllerModel& reactionControllerModel) : m_screenControl(initiallyOnScreen, identity) , m_openable(identity, reactionControllerModel) { } ScreenControl::View::IScreenControlViewModel& MyPinCreationConfirmationViewModel::GetScreenControlViewModel() { return m_screenControl; } OpenableControl::View::IOpenableControlViewModel& MyPinCreationConfirmationViewModel::GetOpenableControlViewModel() { return m_openable; } Eegeo::Helpers::TIdentity MyPinCreationConfirmationViewModel::GetIdentity() const { return m_screenControl.GetIdentity(); } void MyPinCreationConfirmationViewModel::AddToScreen() { m_screenControl.AddToScreen(); } void MyPinCreationConfirmationViewModel::RemoveFromScreen() { m_screenControl.RemoveFromScreen(); } void MyPinCreationConfirmationViewModel::UpdateOnScreenState(float onScreenState) { m_screenControl.UpdateOnScreenState(onScreenState); } void MyPinCreationConfirmationViewModel::InsertOnScreenStateChangedCallback(Eegeo::Helpers::ICallback2<ScreenControl::View::IScreenControlViewModel&, float>& callback) { m_screenControl.InsertOnScreenStateChangedCallback(callback); } void MyPinCreationConfirmationViewModel::RemoveOnScreenStateChangedCallback(Eegeo::Helpers::ICallback2<ScreenControl::View::IScreenControlViewModel&, float>& callback) { m_screenControl.RemoveOnScreenStateChangedCallback(callback); } bool MyPinCreationConfirmationViewModel::IsFullyOffScreen() const { return m_screenControl.IsFullyOffScreen(); } bool MyPinCreationConfirmationViewModel::IsFullyOnScreen() const { return m_screenControl.IsFullyOnScreen(); } float MyPinCreationConfirmationViewModel::OnScreenState() const { return m_screenControl.OnScreenState(); } bool MyPinCreationConfirmationViewModel::IsAddedToScreen() const { return m_screenControl.IsAddedToScreen(); } bool MyPinCreationConfirmationViewModel::TryOpen() { if(!m_screenControl.IsAddedToScreen()) { return false; } return m_openable.TryAcquireReactorControl(); } void MyPinCreationConfirmationViewModel::Close() { m_openable.ReleaseReactorControl(); } } } } <commit_msg>Removing Added to Screen check from MyPinCreationConfirmationViewModel. Buddy Tom H<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "MyPinCreationConfirmationViewModel.h" namespace ExampleApp { namespace MyPinCreation { namespace View { MyPinCreationConfirmationViewModel::MyPinCreationConfirmationViewModel(Eegeo::Helpers::TIdentity identity, bool initiallyOnScreen, Reaction::View::IReactionControllerModel& reactionControllerModel) : m_screenControl(initiallyOnScreen, identity) , m_openable(identity, reactionControllerModel) { } ScreenControl::View::IScreenControlViewModel& MyPinCreationConfirmationViewModel::GetScreenControlViewModel() { return m_screenControl; } OpenableControl::View::IOpenableControlViewModel& MyPinCreationConfirmationViewModel::GetOpenableControlViewModel() { return m_openable; } Eegeo::Helpers::TIdentity MyPinCreationConfirmationViewModel::GetIdentity() const { return m_screenControl.GetIdentity(); } void MyPinCreationConfirmationViewModel::AddToScreen() { m_screenControl.AddToScreen(); } void MyPinCreationConfirmationViewModel::RemoveFromScreen() { m_screenControl.RemoveFromScreen(); } void MyPinCreationConfirmationViewModel::UpdateOnScreenState(float onScreenState) { m_screenControl.UpdateOnScreenState(onScreenState); } void MyPinCreationConfirmationViewModel::InsertOnScreenStateChangedCallback(Eegeo::Helpers::ICallback2<ScreenControl::View::IScreenControlViewModel&, float>& callback) { m_screenControl.InsertOnScreenStateChangedCallback(callback); } void MyPinCreationConfirmationViewModel::RemoveOnScreenStateChangedCallback(Eegeo::Helpers::ICallback2<ScreenControl::View::IScreenControlViewModel&, float>& callback) { m_screenControl.RemoveOnScreenStateChangedCallback(callback); } bool MyPinCreationConfirmationViewModel::IsFullyOffScreen() const { return m_screenControl.IsFullyOffScreen(); } bool MyPinCreationConfirmationViewModel::IsFullyOnScreen() const { return m_screenControl.IsFullyOnScreen(); } float MyPinCreationConfirmationViewModel::OnScreenState() const { return m_screenControl.OnScreenState(); } bool MyPinCreationConfirmationViewModel::IsAddedToScreen() const { return m_screenControl.IsAddedToScreen(); } bool MyPinCreationConfirmationViewModel::TryOpen() { return m_openable.TryAcquireReactorControl(); } void MyPinCreationConfirmationViewModel::Close() { m_openable.ReleaseReactorControl(); } } } } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> #include <Eigen/Core> #include <sophus/se3.h> #include <sophus/so3.h> #include <gtsam/slam/dataset.h> #include <gtsam/slam/BetweenFactor.h> #include <gtsam/slam/PriorFactor.h> #include <gtsam/nonlinear/GaussNewtonOptimizer.h> #include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h> using namespace std; using Sophus::SE3; using Sophus::SO3; /************************************************ * 本程序演示如何用gtsam进行位姿图优化 * sphere.g2o是人工生成的一个Pose graph,我们来优化它。 * **********************************************/ int main ( int argc, char** argv ) { if ( argc != 2 ) { cout<<"Usage: pose_graph_gtsam sphere.g2o"<<endl; return 1; } ifstream fin ( argv[1] ); if ( !fin ) { cout<<"file "<<argv[1]<<" does not exist."<<endl; return 1; } gtsam::NonlinearFactorGraph::shared_ptr graph ( new gtsam::NonlinearFactorGraph ); gtsam::Values::shared_ptr initial ( new gtsam::Values ); // init values // read from g2o file int cntVertex=0, cntEdge = 0; while ( !fin.eof() ) { string tag; fin>>tag; if ( tag == "VERTEX_SE3:QUAT" ) { gtsam::Key id; fin>>id; double data[7]; for ( int i=0; i<7; i++ ) fin>>data[i]; gtsam::Rot3 R = gtsam::Rot3::Quaternion ( data[6], data[3], data[4], data[5] ); gtsam::Point3 t ( data[0], data[1], data[2] ); initial->insert ( id, gtsam::Pose3 ( R,t ) ); cntVertex++; } else if ( tag == "EDGE_SE3:QUAT" ) { // factor gtsam::Matrix m = gtsam::I_6x6; gtsam::Key id1, id2; fin>>id1>>id2; double data[7]; for ( int i=0; i<7; i++ ) fin>>data[i]; gtsam::Rot3 R = gtsam::Rot3::Quaternion ( data[6], data[3], data[4], data[5] ); gtsam::Point3 t ( data[0], data[1], data[2] ); for ( int i=0; i<6; i++ ) for ( int j=i; j<6; j++ ) { double mij; fin>>mij; m ( i,j ) = mij; m ( j,i ) = mij; } // change the blocks because gtsam def is different with g2o gtsam::Matrix mgtsam = gtsam::I_6x6; mgtsam.block<3,3> ( 0,0 ) = m.block<3,3> ( 3,3 ); // cov rotation mgtsam.block<3,3> ( 3,3 ) = m.block<3,3> ( 0,0 ); // cov translation mgtsam.block<3,3> ( 0,3 ) = m.block<3,3> ( 0,3 ); // off diagonal mgtsam.block<3,3> ( 3,0 ) = m.block<3,3> ( 3,0 ); // off diagonal gtsam::SharedNoiseModel model = gtsam::noiseModel::Gaussian::Information ( mgtsam ); gtsam::NonlinearFactor::shared_ptr factor ( new gtsam::BetweenFactor<gtsam::Pose3> ( id1, id2, gtsam::Pose3 ( R,t ), model ) ); graph->push_back ( factor ); cntEdge++; } if ( !fin.good() ) break; } cout<<"read total "<<cntVertex<<" vertices, "<<cntEdge<<" edges."<<endl; // add prior on the first key gtsam::NonlinearFactorGraph graphWithPrior = *graph; gtsam::noiseModel::Diagonal::shared_ptr priorModel = gtsam::noiseModel::Diagonal::Variances ( ( gtsam::Vector ( 6 ) <<1e-6, 1e-6, 1e-6, 1e-4, 1e-4, 1e-4 ).finished() ); gtsam::Key firstKey = 0; for ( const gtsam::Values::ConstKeyValuePair& key_value: *initial ) { cout<<"Adding prior to g2o file "<<endl; // firstKey = key_value.key; graphWithPrior.add ( gtsam::PriorFactor<gtsam::Pose3> ( key_value.key, key_value.value.cast<gtsam::Pose3>(), priorModel ) ); // key_value.value.cast<gtsam::Pose3>(); break; } cout<<"optimizing the factor graph"<<endl; gtsam::GaussNewtonParams params; params.setVerbosity ( "TERMINATION" ); gtsam::GaussNewtonOptimizer optimizer ( graphWithPrior, *initial, params ); gtsam::LevenbergMarquardtParams params_lm; params_lm.setVerbosity("ERROR"); params_lm.setMaxIterations(20); params_lm.setLinearSolverType("MULTIFRONTAL_QR"); gtsam::LevenbergMarquardtOptimizer optimizer_LM( graphWithPrior, *initial, params_lm ); // gtsam::Values result = optimizer.optimize(); gtsam::Values result = optimizer_LM.optimize(); cout<<"Optimization complete"<<endl; cout<<"initial error: "<<graph->error ( *initial ) <<endl; cout<<"final error: "<<graph->error ( result ) <<endl; cout<<"done. write to g2o ... "<<endl; // vertices ofstream fout ( "result_gtsam.g2o" ); for ( const gtsam::Values::ConstKeyValuePair& key_value: result ) { gtsam::Pose3 pose = key_value.value.cast<gtsam::Pose3>(); gtsam::Point3 p = pose.translation(); gtsam::Quaternion q = pose.rotation().toQuaternion(); fout<<"VERTEX_SE3:QUAT "<<key_value.key<<" " <<p.x() <<" "<<p.y() <<" "<<p.z() <<" " <<q.x()<<" "<<q.y()<<" "<<q.z()<<" "<<q.w()<<" "<<endl; } // edges for ( gtsam::NonlinearFactor::shared_ptr factor: *graph ) { gtsam::BetweenFactor<gtsam::Pose3>::shared_ptr f = dynamic_pointer_cast<gtsam::BetweenFactor<gtsam::Pose3>>( factor ); if ( f ) { gtsam::SharedNoiseModel model = f->noiseModel(); gtsam::noiseModel::Gaussian::shared_ptr gaussianModel = dynamic_pointer_cast<gtsam::noiseModel::Gaussian>( model ); if ( gaussianModel ) { // write the edge information gtsam::Matrix info = gaussianModel->R().transpose() * gaussianModel->R(); gtsam::Pose3 pose = f->measured(); gtsam::Point3 p = pose.translation(); gtsam::Quaternion q = pose.rotation().toQuaternion(); fout<<"EDGE_SE3:QUAT "<<f->key1()<<" "<<f->key2()<<" " <<p.x() <<" "<<p.y() <<" "<<p.z() <<" " <<q.x()<<" "<<q.y()<<" "<<q.z()<<" "<<q.w()<<" "; gtsam::Matrix infoG2o = gtsam::I_6x6; infoG2o.block(0,0,3,3) = info.block(3,3,3,3); // cov translation infoG2o.block(3,3,3,3) = info.block(0,0,3,3); // cov rotation infoG2o.block(0,3,3,3) = info.block(0,3,3,3); // off diagonal infoG2o.block(3,0,3,3) = info.block(3,0,3,3); // off diagonal for ( int i=0; i<6; i++ ) for ( int j=i; j<6; j++ ) { fout<<infoG2o(i,j)<<" "; } fout<<endl; } } } fout.close(); cout<<"done."<<endl; } <commit_msg>gtsam pose graph<commit_after>#include <iostream> #include <fstream> #include <string> #include <Eigen/Core> #include <sophus/se3.h> #include <sophus/so3.h> #include <gtsam/slam/dataset.h> #include <gtsam/slam/BetweenFactor.h> #include <gtsam/slam/PriorFactor.h> #include <gtsam/nonlinear/GaussNewtonOptimizer.h> #include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h> using namespace std; using Sophus::SE3; using Sophus::SO3; /************************************************ * 本程序演示如何用 gtsam 进行位姿图优化 * sphere.g2o 是人工生成的一个 Pose graph,我们来优化它。 * 与 g2o 相似,在 gtsam 中添加的是因子,相当于误差 * **********************************************/ int main ( int argc, char** argv ) { if ( argc != 2 ) { cout<<"Usage: pose_graph_gtsam sphere.g2o"<<endl; return 1; } ifstream fin ( argv[1] ); if ( !fin ) { cout<<"file "<<argv[1]<<" does not exist."<<endl; return 1; } gtsam::NonlinearFactorGraph::shared_ptr graph ( new gtsam::NonlinearFactorGraph ); // gtsam的因子图 gtsam::Values::shared_ptr initial ( new gtsam::Values ); // 初始值 // 从g2o文件中读取节点和边的信息 int cntVertex=0, cntEdge = 0; cout<<"reading from g2o file"<<endl; while ( !fin.eof() ) { string tag; fin>>tag; if ( tag == "VERTEX_SE3:QUAT" ) { // 顶点 gtsam::Key id; fin>>id; double data[7]; for ( int i=0; i<7; i++ ) fin>>data[i]; // 转换至gtsam的Pose3 gtsam::Rot3 R = gtsam::Rot3::Quaternion ( data[6], data[3], data[4], data[5] ); gtsam::Point3 t ( data[0], data[1], data[2] ); initial->insert ( id, gtsam::Pose3 ( R,t ) ); // 添加初始值 cntVertex++; } else if ( tag == "EDGE_SE3:QUAT" ) { // 边,对应到因子图中的因子 gtsam::Matrix m = gtsam::I_6x6; // 信息矩阵 gtsam::Key id1, id2; fin>>id1>>id2; double data[7]; for ( int i=0; i<7; i++ ) fin>>data[i]; gtsam::Rot3 R = gtsam::Rot3::Quaternion ( data[6], data[3], data[4], data[5] ); gtsam::Point3 t ( data[0], data[1], data[2] ); for ( int i=0; i<6; i++ ) for ( int j=i; j<6; j++ ) { double mij; fin>>mij; m ( i,j ) = mij; m ( j,i ) = mij; } // g2o的信息矩阵定义方式与gtsam不同,这里对它进行修改 gtsam::Matrix mgtsam = gtsam::I_6x6; mgtsam.block<3,3> ( 0,0 ) = m.block<3,3> ( 3,3 ); // cov rotation mgtsam.block<3,3> ( 3,3 ) = m.block<3,3> ( 0,0 ); // cov translation mgtsam.block<3,3> ( 0,3 ) = m.block<3,3> ( 0,3 ); // off diagonal mgtsam.block<3,3> ( 3,0 ) = m.block<3,3> ( 3,0 ); // off diagonal gtsam::SharedNoiseModel model = gtsam::noiseModel::Gaussian::Information ( mgtsam ); // 高斯噪声模型 gtsam::NonlinearFactor::shared_ptr factor ( new gtsam::BetweenFactor<gtsam::Pose3> ( id1, id2, gtsam::Pose3 ( R,t ), model ) // 添加一个因子 ); graph->push_back ( factor ); cntEdge++; } if ( !fin.good() ) break; } cout<<"read total "<<cntVertex<<" vertices, "<<cntEdge<<" edges."<<endl; // 固定第一个顶点,在gtsam中相当于添加一个先验因子 gtsam::NonlinearFactorGraph graphWithPrior = *graph; gtsam::noiseModel::Diagonal::shared_ptr priorModel = gtsam::noiseModel::Diagonal::Variances ( ( gtsam::Vector ( 6 ) <<1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6 ).finished() ); gtsam::Key firstKey = 0; for ( const gtsam::Values::ConstKeyValuePair& key_value: *initial ) { cout<<"Adding prior to g2o file "<<endl; graphWithPrior.add ( gtsam::PriorFactor<gtsam::Pose3> ( key_value.key, key_value.value.cast<gtsam::Pose3>(), priorModel ) ); break; } // 开始因子图优化,配置优化选项 cout<<"optimizing the factor graph"<<endl; // 我们使用 LM 优化 gtsam::LevenbergMarquardtParams params_lm; params_lm.setVerbosity("ERROR"); params_lm.setMaxIterations(20); params_lm.setLinearSolverType("MULTIFRONTAL_QR"); gtsam::LevenbergMarquardtOptimizer optimizer_LM( graphWithPrior, *initial, params_lm ); // 你可以尝试下 GN // gtsam::GaussNewtonParams params_gn; // params_gn.setVerbosity("ERROR"); // params_gn.setMaxIterations(20); // params_gn.setLinearSolverType("MULTIFRONTAL_QR"); // gtsam::GaussNewtonOptimizer optimizer ( graphWithPrior, *initial, params_gn ); gtsam::Values result = optimizer_LM.optimize(); cout<<"Optimization complete"<<endl; cout<<"initial error: "<<graph->error ( *initial ) <<endl; cout<<"final error: "<<graph->error ( result ) <<endl; cout<<"done. write to g2o ... "<<endl; // 写入 g2o 文件,同样伪装成 g2o 中的顶点和边,以便用 g2o_viewer 查看。 // 顶点咯 ofstream fout ( "result_gtsam.g2o" ); for ( const gtsam::Values::ConstKeyValuePair& key_value: result ) { gtsam::Pose3 pose = key_value.value.cast<gtsam::Pose3>(); gtsam::Point3 p = pose.translation(); gtsam::Quaternion q = pose.rotation().toQuaternion(); fout<<"VERTEX_SE3:QUAT "<<key_value.key<<" " <<p.x() <<" "<<p.y() <<" "<<p.z() <<" " <<q.x()<<" "<<q.y()<<" "<<q.z()<<" "<<q.w()<<" "<<endl; } // 边咯 for ( gtsam::NonlinearFactor::shared_ptr factor: *graph ) { gtsam::BetweenFactor<gtsam::Pose3>::shared_ptr f = dynamic_pointer_cast<gtsam::BetweenFactor<gtsam::Pose3>>( factor ); if ( f ) { gtsam::SharedNoiseModel model = f->noiseModel(); gtsam::noiseModel::Gaussian::shared_ptr gaussianModel = dynamic_pointer_cast<gtsam::noiseModel::Gaussian>( model ); if ( gaussianModel ) { // write the edge information gtsam::Matrix info = gaussianModel->R().transpose() * gaussianModel->R(); gtsam::Pose3 pose = f->measured(); gtsam::Point3 p = pose.translation(); gtsam::Quaternion q = pose.rotation().toQuaternion(); fout<<"EDGE_SE3:QUAT "<<f->key1()<<" "<<f->key2()<<" " <<p.x() <<" "<<p.y() <<" "<<p.z() <<" " <<q.x()<<" "<<q.y()<<" "<<q.z()<<" "<<q.w()<<" "; gtsam::Matrix infoG2o = gtsam::I_6x6; infoG2o.block(0,0,3,3) = info.block(3,3,3,3); // cov translation infoG2o.block(3,3,3,3) = info.block(0,0,3,3); // cov rotation infoG2o.block(0,3,3,3) = info.block(0,3,3,3); // off diagonal infoG2o.block(3,0,3,3) = info.block(3,0,3,3); // off diagonal for ( int i=0; i<6; i++ ) for ( int j=i; j<6; j++ ) { fout<<infoG2o(i,j)<<" "; } fout<<endl; } } } fout.close(); cout<<"done."<<endl; } <|endoftext|>
<commit_before>#include <iostream> // for standard output using namespace std; #include <eigen3/Eigen/Dense> // linear algebra library using namespace Eigen; #include "constants.h" #include "qp-math.h" #include "nv-math.h" #include "nv-control.h" //-------------------------------------------------------------------------------------------- // Coordinate systems //-------------------------------------------------------------------------------------------- // return "natural" basis of a nucleus vector<Vector3d> natural_basis(const nv_system& nv, const uint index){ const Vector3d target_zhat = hat(effective_larmor(nv,index)); const Vector3d target_xhat = hat(hyperfine_perp(nv,index)); const Vector3d target_yhat = target_zhat.cross(target_xhat); return {target_xhat, target_yhat, target_zhat}; } //-------------------------------------------------------------------------------------------- // General control methods //-------------------------------------------------------------------------------------------- // propagator U = exp(-i * rotation_angle * sigma_{axis}^{index}) MatrixXcd U_ctl(const nv_system& nv, const uint index, const double target_azimuth, const double rotation_angle, const bool exact, const bool adjust_AXY, const double z_phase){ // identify cluster of target nucleus const uint cluster = get_cluster_containing_index(nv,index); const uint index_in_cluster = get_index_in_cluster(index,nv.clusters.at(cluster)); const uint spins = nv.clusters.at(cluster).size()+1; // target axis of rotation const Vector3d axis_ctl = natural_axis(nv, index, target_azimuth); if(exact){ // return exact propagator const MatrixXcd G = exp(-j * rotation_angle * dot(s_vec,axis_ctl)); return act(G, {index_in_cluster+1}, spins); } for(uint i = 0; i < nv.clusters.at(cluster).size(); i++){ if(nv.clusters.at(cluster).at(i) == index) continue; if(is_larmor_pair(nv, index, nv.clusters.at(cluster).at(i))){ cout << "Cannot address nuclei with larmor pairs: " << index << ", " << nv.clusters.at(cluster).at(i) << endl; return MatrixXcd::Identity(pow(2,spins),pow(2,spins)); } } // larmor frequency of target nucleus const double w_larmor = effective_larmor(nv,index).norm(); const double t_larmor = 2*pi/w_larmor; // AXY protocol parameters const double sA = nv.scale_factor * hyperfine(nv,index).norm(); const double w_DD = [&]() -> double { const double w_DD_large = (w_larmor+sA)/3.; if(w_larmor < sA){ return w_DD_large; } else{ const uint k_m = 2*int(0.5 * (w_larmor/sA-1) ); const double w_DD_small = (w_larmor-sA)/k_m; if(w_DD_small > sA && isfinite(w_DD_small)){ return w_DD_small; } else{ return w_DD_large; } } }(); const double t_DD = 2*pi/w_DD; const axy_harmonic k_DD = abs(w_DD - w_larmor) < abs(3*w_DD - w_larmor) ? first : third; const double f_DD = 0; // control field frequency = effective larmor frequency of target nucleus const double w_ctl = w_larmor; // control field frequency const double dw_min = larmor_resolution(nv,index); double g_B_ctl = dw_min/nv.scale_factor; // ctl field strength * gyromangnetic ratio const double control_period = 2*pi*4/g_B_ctl; double control_time = -4*rotation_angle/g_B_ctl; // control operation time while(control_time >= control_period) control_time -= control_period; while(control_time < 0) control_time += control_period; if(control_time > control_period/2){ g_B_ctl *= -1; control_time = control_period-control_time; } const double B_ctl = g_B_ctl/nv.nuclei.at(index).g; // control field strength const control_fields controls(B_ctl*axis_ctl, w_ctl); // control field object MatrixXcd U_ctl; if(!adjust_AXY){ U_ctl = simulate_propagator(nv, cluster, w_DD, f_DD, k_DD, controls, control_time); } else{ // if(adjust_AXY) assert(w_DD != w_larmor); if(w_DD < w_larmor){ const uint freq_ratio = 2*round(0.5*w_larmor/w_DD); const double w_DD_adjusted = w_larmor/freq_ratio; const double t_DD_adjusted = 2*pi/w_DD_adjusted; const uint cycles = int(control_time/t_DD_adjusted); const double leading_time = control_time - cycles*t_DD_adjusted; const double trailing_time = t_DD_adjusted - leading_time; const MatrixXcd U_leading = simulate_propagator(nv, cluster, w_DD_adjusted, f_DD, k_DD, controls, leading_time); const MatrixXcd U_trailing = simulate_propagator(nv, cluster, w_DD_adjusted, f_DD, k_DD, controls, trailing_time, leading_time); U_ctl = U_leading * pow(U_trailing*U_leading,cycles); } else{ // if(w_DD > w_larmor) const uint freq_ratio = round(w_DD/w_larmor); const double w_DD_adjusted = w_larmor*freq_ratio; const double t_DD_adjusted = 2*pi/w_DD_adjusted; const uint cycles = int(control_time/t_larmor); const double leading_time = control_time - cycles*t_larmor; const double trailing_time = t_larmor - leading_time; const MatrixXcd U_leading = simulate_propagator(nv, cluster, w_DD_adjusted, f_DD, k_DD, controls, leading_time); const MatrixXcd U_trailing = simulate_propagator(nv, cluster, w_DD_adjusted, f_DD, k_DD, controls, trailing_time, leading_time); U_ctl = U_leading * pow(U_trailing*U_leading,cycles); } } double flush_time = ceil(control_time/t_larmor)*t_larmor - control_time - z_phase/w_larmor; flush_time -= floor(flush_time/t_larmor)*t_larmor; const MatrixXcd U_flush = simulate_propagator(nv, cluster, w_DD, f_DD, k_DD, flush_time, control_time); return U_flush * U_ctl; } // compute and perform rotation of target nucleus necessary to generate U MatrixXcd rotate_target(const nv_system& nv, const uint index, const Matrix2cd U, const bool exact, const bool adjust_AXY){ if(exact){ const uint cluster = get_cluster_containing_index(nv,index); const uint index_in_cluster = get_index_in_cluster(index,nv.clusters.at(cluster)); const uint spins = nv.clusters.at(cluster).size()+1; return act(U, {index_in_cluster+1}, spins); } const Vector4cd H_vec = U_decompose(j*log(U)); const double rx = real(H_vec(1))*2; const double ry = real(H_vec(2))*2; const double rz = real(H_vec(3))*2; const double rotation_angle = sqrt(rx*rx + ry*ry + rz*rz); const double azimuth = atan2(ry,rx); const double pitch = asin(rz/rotation_angle); if(pi - 2*abs(pitch) < 2*abs(pitch) + abs(rotation_angle)){ const int pole = pitch > 0 ? 1 : -1; // "north" vs "south" pole const double angle_to_pole = pi/2 - abs(pitch); const MatrixXcd to_pole = U_ctl(nv, index, azimuth - pi/2, pole*angle_to_pole/2, exact, adjust_AXY); const MatrixXcd rotate = U_ctl(nv, index, 0, 0, exact, adjust_AXY, pole*rotation_angle); return to_pole.adjoint() * rotate * to_pole; } else{ const MatrixXcd to_equator = U_ctl(nv, index, azimuth + pi/2, pitch/2, exact, adjust_AXY); const MatrixXcd rotate = U_ctl(nv, index, azimuth, rotation_angle/2, exact, adjust_AXY); return to_equator.adjoint() * rotate * to_equator; } } // propagator U = exp(-i * rotation_angle * sigma_{n_1}^{NV}*sigma_{n_2}^{index}) MatrixXcd U_int(const nv_system& nv, const uint index, const double nv_azimuth, const double nv_polar, const double target_azimuth, const double rotation_angle, const bool exact){ // identify cluster of target nucleus const uint cluster = get_cluster_containing_index(nv,index); const uint index_in_cluster = get_index_in_cluster(index,nv.clusters.at(cluster)); const uint spins = nv.clusters.at(cluster).size()+1; // NV spin axis const Vector3d nv_axis = axis(nv_azimuth,nv_polar); if(exact){ // return exact propagator const Vector3d target_axis = natural_axis(nv,index,target_azimuth); const MatrixXcd G = exp(-j * rotation_angle * tp(dot(s_vec,nv_axis), dot(s_vec,target_axis))); return act(G, {0,index_in_cluster+1}, spins); } // verify that we can address this nucleus if(round(4*dot(nv.nuclei.at(index).pos,ao)) == 0.){ cout << "Cannot address nuclei without hyperfine coupling perpendicular to the NV axis: " << index << endl; return MatrixXcd::Identity(pow(2,spins),pow(2,spins)); } for(uint i = 0; i < nv.clusters.at(cluster).size(); i++){ if(nv.clusters.at(cluster).at(i) == index) continue; if(is_larmor_pair(nv, index, nv.clusters.at(cluster).at(i))){ cout << "Cannot address nuclei with larmor pairs: " << index << ", " << nv.clusters.at(cluster).at(i) << endl; return MatrixXcd::Identity(pow(2,spins),pow(2,spins)); } } // larmor frequency of and perpendicular component of hyperfine field at target nucleus const double w_larmor = effective_larmor(nv,index).norm(); const double t_larmor = 2*pi/w_larmor; const double dw_min = larmor_resolution(nv,index); const Vector3d A_perp = hyperfine_perp(nv,index); // AXY sequence parameters const double w_DD = w_larmor/nv.k_DD; // AXY protocol angular frequency const double t_DD = 2*pi/w_DD; // AXY protocol period double f_DD = min(dw_min/(A_perp.norm()*nv.scale_factor), axy_f_max(nv.k_DD)); const double interaction_period = 2*pi/abs(f_DD*A_perp.norm()/8); double interaction_time = rotation_angle/(nv.ms*f_DD*A_perp.norm()/8); while(interaction_time >= interaction_period) interaction_time -= interaction_period; while(interaction_time < 0) interaction_time += interaction_period; if(interaction_time > interaction_period/2){ f_DD *= -1; interaction_time = interaction_period-interaction_time; } const MatrixXcd U_int = simulate_propagator(nv, cluster, w_DD, f_DD, nv.k_DD, interaction_time, -target_azimuth/w_DD); const double flush_time = ceil(interaction_time/t_larmor)*t_larmor - interaction_time; const MatrixXcd U_flush = simulate_propagator(nv, cluster, w_DD, 0, nv.k_DD, flush_time, interaction_time - target_azimuth/w_DD); // rotate the NV spin between the desired axis and zhat const MatrixXcd nv_to_zhat = rotate_NV(nv,rotate(zhat,nv_axis),spins); return U_flush * nv_to_zhat.adjoint() * U_int * nv_to_zhat; } //-------------------------------------------------------------------------------------------- // Specific operations //-------------------------------------------------------------------------------------------- // iSWAP operation MatrixXcd iSWAP(const nv_system& nv, const uint index, const bool exact){ const double iswap_angle = -pi/4; const double xy_polar = pi/2; const double xhat_azimuth = 0; const double yhat_azimuth = pi/2; return U_int(nv, index, xhat_azimuth, xy_polar, xhat_azimuth, iswap_angle, exact) * U_int(nv, index, yhat_azimuth, xy_polar, yhat_azimuth, iswap_angle, exact); }; MatrixXcd SWAP_NVST(const nv_system& nv, const uint idx1, const uint idx2, const bool exact){ // assert that both target nuclei are in the same cluster const vector<uint> cluster = nv.clusters.at(get_cluster_containing_index(nv,idx1)); assert(in_vector(idx2,cluster)); // define angles const double angle = pi/4; const double z_polar = 0; const double xy_polar = pi/2; const double xhat_azimuth = 0; const double yhat_azimuth = pi/2; // compute components of SWAP_NVST const MatrixXcd Rz_NV = rotate_NV(nv, rotate(2*angle*zhat), cluster.size()+1); const MatrixXcd Rx_1 = U_ctl(nv, idx1, xhat_azimuth, angle, exact); const MatrixXcd Ry_1 = U_ctl(nv, idx1, yhat_azimuth, angle, exact); const MatrixXcd Rz_1 = Rx_1 * Ry_1 * Rx_1.adjoint(); const MatrixXcd iSWAP_NV_1 = U_int(nv, idx1, xhat_azimuth, xy_polar, xhat_azimuth, -angle, exact) * U_int(nv, idx1, yhat_azimuth, xy_polar, yhat_azimuth, -angle, exact); const MatrixXcd cNOT_NV_1 = Rz_NV * Rx_1 * U_int(nv, idx1, xhat_azimuth, z_polar, xhat_azimuth, -angle, exact); const MatrixXcd E_NV_2 = U_int(nv, idx2, yhat_azimuth, xy_polar, xhat_azimuth, -angle, exact); // combine componenets into full SWAP_NVST operation const MatrixXcd M = E_NV_2.adjoint() * iSWAP_NV_1 * Rz_1.adjoint() * Rz_NV; return M.adjoint() * cNOT_NV_1 * M; } <commit_msg>perform exact rotate_target in natural target basis; improve determination of which rotation sequence to use in inexact rotate_target<commit_after>#include <iostream> // for standard output using namespace std; #include <eigen3/Eigen/Dense> // linear algebra library using namespace Eigen; #include "constants.h" #include "qp-math.h" #include "nv-math.h" #include "nv-control.h" //-------------------------------------------------------------------------------------------- // Coordinate systems //-------------------------------------------------------------------------------------------- // return "natural" basis of a nucleus vector<Vector3d> natural_basis(const nv_system& nv, const uint index){ const Vector3d target_zhat = hat(effective_larmor(nv,index)); const Vector3d target_xhat = hat(hyperfine_perp(nv,index)); const Vector3d target_yhat = target_zhat.cross(target_xhat); return {target_xhat, target_yhat, target_zhat}; } //-------------------------------------------------------------------------------------------- // General control methods //-------------------------------------------------------------------------------------------- // propagator U = exp(-i * rotation_angle * sigma_{axis}^{index}) MatrixXcd U_ctl(const nv_system& nv, const uint index, const double target_azimuth, const double rotation_angle, const bool exact, const bool adjust_AXY, const double z_phase){ // identify cluster of target nucleus const uint cluster = get_cluster_containing_index(nv,index); const uint index_in_cluster = get_index_in_cluster(index,nv.clusters.at(cluster)); const uint spins = nv.clusters.at(cluster).size()+1; // target axis of rotation const Vector3d axis_ctl = natural_axis(nv, index, target_azimuth); if(exact){ // return exact propagator const MatrixXcd G = exp(-j * rotation_angle * dot(s_vec,axis_ctl)); return act(G, {index_in_cluster+1}, spins); } for(uint i = 0; i < nv.clusters.at(cluster).size(); i++){ if(nv.clusters.at(cluster).at(i) == index) continue; if(is_larmor_pair(nv, index, nv.clusters.at(cluster).at(i))){ cout << "Cannot address nuclei with larmor pairs: " << index << ", " << nv.clusters.at(cluster).at(i) << endl; return MatrixXcd::Identity(pow(2,spins),pow(2,spins)); } } // larmor frequency of target nucleus const double w_larmor = effective_larmor(nv,index).norm(); const double t_larmor = 2*pi/w_larmor; // AXY protocol parameters const double sA = nv.scale_factor * hyperfine(nv,index).norm(); const double w_DD = [&]() -> double { const double w_DD_large = (w_larmor+sA)/3.; if(w_larmor < sA){ return w_DD_large; } else{ const uint k_m = 2*int(0.5 * (w_larmor/sA-1) ); const double w_DD_small = (w_larmor-sA)/k_m; if(w_DD_small > sA && isfinite(w_DD_small)){ return w_DD_small; } else{ return w_DD_large; } } }(); const double t_DD = 2*pi/w_DD; const axy_harmonic k_DD = abs(w_DD - w_larmor) < abs(3*w_DD - w_larmor) ? first : third; const double f_DD = 0; // control field frequency = effective larmor frequency of target nucleus const double w_ctl = w_larmor; // control field frequency const double dw_min = larmor_resolution(nv,index); double g_B_ctl = dw_min/nv.scale_factor; // ctl field strength * gyromangnetic ratio const double control_period = 2*pi*4/g_B_ctl; double control_time = -4*rotation_angle/g_B_ctl; // control operation time while(control_time >= control_period) control_time -= control_period; while(control_time < 0) control_time += control_period; if(control_time > control_period/2){ g_B_ctl *= -1; control_time = control_period-control_time; } const double B_ctl = g_B_ctl/nv.nuclei.at(index).g; // control field strength const control_fields controls(B_ctl*axis_ctl, w_ctl); // control field object MatrixXcd U_ctl; if(!adjust_AXY){ U_ctl = simulate_propagator(nv, cluster, w_DD, f_DD, k_DD, controls, control_time); } else{ // if(adjust_AXY) assert(w_DD != w_larmor); if(w_DD < w_larmor){ const uint freq_ratio = 2*round(0.5*w_larmor/w_DD); const double w_DD_adjusted = w_larmor/freq_ratio; const double t_DD_adjusted = 2*pi/w_DD_adjusted; const uint cycles = int(control_time/t_DD_adjusted); const double leading_time = control_time - cycles*t_DD_adjusted; const double trailing_time = t_DD_adjusted - leading_time; const MatrixXcd U_leading = simulate_propagator(nv, cluster, w_DD_adjusted, f_DD, k_DD, controls, leading_time); const MatrixXcd U_trailing = simulate_propagator(nv, cluster, w_DD_adjusted, f_DD, k_DD, controls, trailing_time, leading_time); U_ctl = U_leading * pow(U_trailing*U_leading,cycles); } else{ // if(w_DD > w_larmor) const uint freq_ratio = round(w_DD/w_larmor); const double w_DD_adjusted = w_larmor*freq_ratio; const double t_DD_adjusted = 2*pi/w_DD_adjusted; const uint cycles = int(control_time/t_larmor); const double leading_time = control_time - cycles*t_larmor; const double trailing_time = t_larmor - leading_time; const MatrixXcd U_leading = simulate_propagator(nv, cluster, w_DD_adjusted, f_DD, k_DD, controls, leading_time); const MatrixXcd U_trailing = simulate_propagator(nv, cluster, w_DD_adjusted, f_DD, k_DD, controls, trailing_time, leading_time); U_ctl = U_leading * pow(U_trailing*U_leading,cycles); } } double flush_time = ceil(control_time/t_larmor)*t_larmor - control_time - z_phase/w_larmor; flush_time -= floor(flush_time/t_larmor)*t_larmor; const MatrixXcd U_flush = simulate_propagator(nv, cluster, w_DD, f_DD, k_DD, flush_time, control_time); return U_flush * U_ctl; } // compute and perform rotation of target nucleus necessary to generate U MatrixXcd rotate_target(const nv_system& nv, const uint index, const Matrix2cd U, const bool exact, const bool adjust_AXY){ if(exact){ const uint cluster = get_cluster_containing_index(nv,index); const uint index_in_cluster = get_index_in_cluster(index,nv.clusters.at(cluster)); const uint spins = nv.clusters.at(cluster).size()+1; const MatrixXcd to_natural_axis = rotate({xhat,yhat,zhat},natural_basis(nv,index)); return act(to_natural_axis.adjoint() * U * to_natural_axis, {index_in_cluster+1}, spins); } const Vector4cd H_vec = U_decompose(j*log(U)); const double rx = real(H_vec(1))*2; const double ry = real(H_vec(2))*2; const double rz = real(H_vec(3))*2; const double rotation_angle = sqrt(rx*rx + ry*ry + rz*rz); const double azimuth = atan2(ry,rx); const double pitch = asin(rz/rotation_angle); const double net_pole_rotation = pi - 2*abs(pitch); const double net_equatorial_rotation = 2*abs(pitch) + (rotation_angle < pi ? rotation_angle : 2*pi - rotation_angle); if(net_pole_rotation < net_equatorial_rotation){ const int pole = pitch > 0 ? 1 : -1; // "north" vs "south" pole const double angle_to_pole = pi/2 - abs(pitch); const MatrixXcd to_pole = U_ctl(nv, index, azimuth - pi/2, pole*angle_to_pole/2, exact, adjust_AXY); const MatrixXcd rotate = U_ctl(nv, index, 0, 0, exact, adjust_AXY, pole*rotation_angle); return to_pole.adjoint() * rotate * to_pole; } else{ const MatrixXcd to_equator = U_ctl(nv, index, azimuth + pi/2, pitch/2, exact, adjust_AXY); const MatrixXcd rotate = U_ctl(nv, index, azimuth, rotation_angle/2, exact, adjust_AXY); return to_equator.adjoint() * rotate * to_equator; } } // propagator U = exp(-i * rotation_angle * sigma_{n_1}^{NV}*sigma_{n_2}^{index}) MatrixXcd U_int(const nv_system& nv, const uint index, const double nv_azimuth, const double nv_polar, const double target_azimuth, const double rotation_angle, const bool exact){ // identify cluster of target nucleus const uint cluster = get_cluster_containing_index(nv,index); const uint index_in_cluster = get_index_in_cluster(index,nv.clusters.at(cluster)); const uint spins = nv.clusters.at(cluster).size()+1; // NV spin axis const Vector3d nv_axis = axis(nv_azimuth,nv_polar); if(exact){ // return exact propagator const Vector3d target_axis = natural_axis(nv,index,target_azimuth); const MatrixXcd G = exp(-j * rotation_angle * tp(dot(s_vec,nv_axis), dot(s_vec,target_axis))); return act(G, {0,index_in_cluster+1}, spins); } // verify that we can address this nucleus if(round(4*dot(nv.nuclei.at(index).pos,ao)) == 0.){ cout << "Cannot address nuclei without hyperfine coupling perpendicular to the NV axis: " << index << endl; return MatrixXcd::Identity(pow(2,spins),pow(2,spins)); } for(uint i = 0; i < nv.clusters.at(cluster).size(); i++){ if(nv.clusters.at(cluster).at(i) == index) continue; if(is_larmor_pair(nv, index, nv.clusters.at(cluster).at(i))){ cout << "Cannot address nuclei with larmor pairs: " << index << ", " << nv.clusters.at(cluster).at(i) << endl; return MatrixXcd::Identity(pow(2,spins),pow(2,spins)); } } // larmor frequency of and perpendicular component of hyperfine field at target nucleus const double w_larmor = effective_larmor(nv,index).norm(); const double t_larmor = 2*pi/w_larmor; const double dw_min = larmor_resolution(nv,index); const Vector3d A_perp = hyperfine_perp(nv,index); // AXY sequence parameters const double w_DD = w_larmor/nv.k_DD; // AXY protocol angular frequency const double t_DD = 2*pi/w_DD; // AXY protocol period double f_DD = min(dw_min/(A_perp.norm()*nv.scale_factor), axy_f_max(nv.k_DD)); const double interaction_period = 2*pi/abs(f_DD*A_perp.norm()/8); double interaction_time = rotation_angle/(nv.ms*f_DD*A_perp.norm()/8); while(interaction_time >= interaction_period) interaction_time -= interaction_period; while(interaction_time < 0) interaction_time += interaction_period; if(interaction_time > interaction_period/2){ f_DD *= -1; interaction_time = interaction_period-interaction_time; } const MatrixXcd U_int = simulate_propagator(nv, cluster, w_DD, f_DD, nv.k_DD, interaction_time, -target_azimuth/w_DD); const double flush_time = ceil(interaction_time/t_larmor)*t_larmor - interaction_time; const MatrixXcd U_flush = simulate_propagator(nv, cluster, w_DD, 0, nv.k_DD, flush_time, interaction_time - target_azimuth/w_DD); // rotate the NV spin between the desired axis and zhat const MatrixXcd nv_to_zhat = rotate_NV(nv,rotate(zhat,nv_axis),spins); return U_flush * nv_to_zhat.adjoint() * U_int * nv_to_zhat; } //-------------------------------------------------------------------------------------------- // Specific operations //-------------------------------------------------------------------------------------------- // iSWAP operation MatrixXcd iSWAP(const nv_system& nv, const uint index, const bool exact){ const double iswap_angle = -pi/4; const double xy_polar = pi/2; const double xhat_azimuth = 0; const double yhat_azimuth = pi/2; return U_int(nv, index, xhat_azimuth, xy_polar, xhat_azimuth, iswap_angle, exact) * U_int(nv, index, yhat_azimuth, xy_polar, yhat_azimuth, iswap_angle, exact); }; MatrixXcd SWAP_NVST(const nv_system& nv, const uint idx1, const uint idx2, const bool exact){ // assert that both target nuclei are in the same cluster const vector<uint> cluster = nv.clusters.at(get_cluster_containing_index(nv,idx1)); assert(in_vector(idx2,cluster)); // define angles const double angle = pi/4; const double z_polar = 0; const double xy_polar = pi/2; const double xhat_azimuth = 0; const double yhat_azimuth = pi/2; // compute components of SWAP_NVST const MatrixXcd Rz_NV = rotate_NV(nv, rotate(2*angle*zhat), cluster.size()+1); const MatrixXcd Rx_1 = U_ctl(nv, idx1, xhat_azimuth, angle, exact); const MatrixXcd Ry_1 = U_ctl(nv, idx1, yhat_azimuth, angle, exact); const MatrixXcd Rz_1 = Rx_1 * Ry_1 * Rx_1.adjoint(); const MatrixXcd iSWAP_NV_1 = U_int(nv, idx1, xhat_azimuth, xy_polar, xhat_azimuth, -angle, exact) * U_int(nv, idx1, yhat_azimuth, xy_polar, yhat_azimuth, -angle, exact); const MatrixXcd cNOT_NV_1 = Rz_NV * Rx_1 * U_int(nv, idx1, xhat_azimuth, z_polar, xhat_azimuth, -angle, exact); const MatrixXcd E_NV_2 = U_int(nv, idx2, yhat_azimuth, xy_polar, xhat_azimuth, -angle, exact); // combine componenets into full SWAP_NVST operation const MatrixXcd M = E_NV_2.adjoint() * iSWAP_NV_1 * Rz_1.adjoint() * Rz_NV; return M.adjoint() * cNOT_NV_1 * M; } <|endoftext|>
<commit_before> #include "server/zone/managers/creature/SpawnObserver.h" #include "server/zone/objects/creature/ai/AiAgent.h" void SpawnObserverImplementation::despawnSpawns() { for (int i = 0; i < spawnedCreatures.size(); ++i) { ManagedReference<CreatureObject*> obj = spawnedCreatures.get(i); if (obj != NULL && obj->isAiAgent()) { AiAgent* aiObj = cast<AiAgent*>(obj.get()); Locker locker(aiObj); aiObj->setDespawnOnNoPlayerInRange(true); } } spawnedCreatures.removeAll(); } <commit_msg>[fixed] stability issue<commit_after> #include "server/zone/managers/creature/SpawnObserver.h" #include "server/zone/objects/creature/ai/AiAgent.h" void SpawnObserverImplementation::despawnSpawns() { Vector<ManagedReference<AiAgent* > > agents; for (int i = 0; i < spawnedCreatures.size(); ++i) { ManagedReference<CreatureObject*> obj = spawnedCreatures.get(i); if (obj != NULL && obj->isAiAgent()) { AiAgent* aiObj = cast<AiAgent*>(obj.get()); agents.add(aiObj); } } spawnedCreatures.removeAll(); EXECUTE_TASK_1(agents, { for (int i = 0; i < agents_p.size(); ++i) { AiAgent* agent = agents_p.get(i); Locker locker(agent); agent->setDespawnOnNoPlayerInRange(true); } }); } <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010 Francois Beaune // // 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. // // Interface header. #include "writabletexture2d.h" // appleseed.renderer headers. #include "renderer/modeling/texture/texture.h" // appleseed.foundation headers. #include "foundation/image/canvasproperties.h" #include "foundation/image/colorspace.h" #include "foundation/image/tile.h" #include "foundation/platform/thread.h" #include "foundation/utility/searchpaths.h" using namespace boost; using namespace foundation; using namespace std; namespace renderer { namespace { // // 2D writable texture. // class WritableTexture2d : public Texture { public: WritableTexture2d( const char* name, const ParamArray& params, const SearchPaths& search_paths) : Texture(params) , m_name(name) , m_props_defined(false) { } virtual void release() { delete this; } virtual const char* get_model() const { return WritableTexture2dFactory::get_model(); } virtual const char* get_name() const { return m_name.c_str(); } virtual ColorSpace get_color_space() const { // todo: implement. return ColorSpaceLinearRGB; } virtual const CanvasProperties& properties() { mutex::scoped_lock lock(m_mutex); if (!m_props_defined) { set_canvas_properties(); m_props_defined = true; } return m_props; } virtual Tile* load_tile( const size_t tile_x, const size_t tile_y) { mutex::scoped_lock lock(m_mutex); // todo: create a blank tile, or get the tile from the texture. return new Tile( 32, 32, 4, PixelFormatFloat); } virtual void unload_tile( const size_t tile_x, const size_t tile_y, Tile* tile) { mutex::scoped_lock lock(m_mutex); // todo: store the tile into the texture. } private: const string m_name; mutable mutex m_mutex; bool m_props_defined; CanvasProperties m_props; // Set canvas properties. void set_canvas_properties() { // todo: open texture file and set canvas properties. } }; } // anonymous namespace // // WritableTexture2dFactory class implementation. // const char* WritableTexture2dFactory::get_model() { return "writable_texture_2d"; } auto_release_ptr<Texture> WritableTexture2dFactory::create( const char* name, const ParamArray& params, const SearchPaths& search_paths) const { return auto_release_ptr<Texture>( new WritableTexture2d(name, params, search_paths)); } } // namespace renderer <commit_msg>the renderer::WritableTexture2d class is not yet implemented, throw ExceptionNotImplemented exceptions if we attempt to use it.<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010 Francois Beaune // // 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. // // Interface header. #include "writabletexture2d.h" // appleseed.renderer headers. #include "renderer/modeling/texture/texture.h" // appleseed.foundation headers. #include "foundation/core/exceptionnotimplemented.h" #include "foundation/image/canvasproperties.h" #include "foundation/image/colorspace.h" #include "foundation/image/tile.h" #include "foundation/platform/thread.h" #include "foundation/utility/searchpaths.h" using namespace boost; using namespace foundation; using namespace std; namespace renderer { namespace { // // 2D writable texture. // class WritableTexture2d : public Texture { public: WritableTexture2d( const char* name, const ParamArray& params, const SearchPaths& search_paths) : Texture(params) , m_name(name) , m_props_defined(false) { } virtual void release() { delete this; } virtual const char* get_model() const { return WritableTexture2dFactory::get_model(); } virtual const char* get_name() const { return m_name.c_str(); } virtual ColorSpace get_color_space() const { // todo: implement. throw ExceptionNotImplemented(); return ColorSpaceLinearRGB; } virtual const CanvasProperties& properties() { mutex::scoped_lock lock(m_mutex); if (!m_props_defined) { set_canvas_properties(); m_props_defined = true; } return m_props; } virtual Tile* load_tile( const size_t tile_x, const size_t tile_y) { mutex::scoped_lock lock(m_mutex); // todo: create a blank tile, or get the tile from the texture. throw ExceptionNotImplemented(); return 0; } virtual void unload_tile( const size_t tile_x, const size_t tile_y, Tile* tile) { mutex::scoped_lock lock(m_mutex); // todo: store the tile into the texture. throw ExceptionNotImplemented(); } private: const string m_name; mutable mutex m_mutex; bool m_props_defined; CanvasProperties m_props; // Set canvas properties. void set_canvas_properties() { // todo: open texture file and set canvas properties. throw ExceptionNotImplemented(); } }; } // anonymous namespace // // WritableTexture2dFactory class implementation. // const char* WritableTexture2dFactory::get_model() { return "writable_texture_2d"; } auto_release_ptr<Texture> WritableTexture2dFactory::create( const char* name, const ParamArray& params, const SearchPaths& search_paths) const { return auto_release_ptr<Texture>( new WritableTexture2d(name, params, search_paths)); } } // namespace renderer <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <windows.h> #include <shlwapi.h> #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/environment.h" #include "base/file_util.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/win/registry.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "base/version.h" #include "chrome/app/breakpad_win.h" #include "chrome/app/client_util.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_result_codes.h" #include "chrome/common/chrome_switches.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/channel_info.h" #include "chrome/installer/util/install_util.h" #include "chrome/installer/util/google_update_constants.h" #include "chrome/installer/util/google_update_settings.h" #include "chrome/installer/util/util_constants.h" namespace { // The entry point signature of chrome.dll. typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*, wchar_t*); typedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)(); // Gets chrome version according to the load path. |exe_path| must be the // backslash terminated directory of the current chrome.exe. bool GetVersion(const wchar_t* exe_path, const wchar_t* key_path, std::wstring* version) { HKEY reg_root = InstallUtil::IsPerUserInstall(exe_path) ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE; bool success = false; base::win::RegKey key(reg_root, key_path, KEY_QUERY_VALUE); if (key.Valid()) { // If 'new_chrome.exe' is present it means chrome was auto-updated while // running. We need to consult the opv value so we can load the old dll. // TODO(cpu) : This is solving the same problem as the environment variable // so one of them will eventually be deprecated. std::wstring new_chrome_exe(exe_path); new_chrome_exe.append(installer::kChromeNewExe); if (::PathFileExistsW(new_chrome_exe.c_str()) && key.ReadValue(google_update::kRegOldVersionField, version) == ERROR_SUCCESS) { success = true; } else { success = (key.ReadValue(google_update::kRegVersionField, version) == ERROR_SUCCESS); } } return success; } // Gets the path of the current exe with a trailing backslash. std::wstring GetExecutablePath() { wchar_t path[MAX_PATH]; ::GetModuleFileNameW(NULL, path, MAX_PATH); if (!::PathRemoveFileSpecW(path)) return std::wstring(); std::wstring exe_path(path); return exe_path.append(L"\\"); } // Not generic, we only handle strings up to 128 chars. bool EnvQueryStr(const wchar_t* key_name, std::wstring* value) { wchar_t out[128]; DWORD count = sizeof(out)/sizeof(out[0]); DWORD rv = ::GetEnvironmentVariableW(key_name, out, count); if ((rv == 0) || (rv >= count)) return false; *value = out; return true; } // Expects that |dir| has a trailing backslash. |dir| is modified so it // contains the full path that was tried. Caller must check for the return // value not being null to determine if this path contains a valid dll. HMODULE LoadChromeWithDirectory(std::wstring* dir) { ::SetCurrentDirectoryW(dir->c_str()); const CommandLine& cmd_line = *CommandLine::ForCurrentProcess(); #ifdef _WIN64 if ((cmd_line.GetSwitchValueASCII(switches::kProcessType) == switches::kNaClBrokerProcess) || (cmd_line.GetSwitchValueASCII(switches::kProcessType) == switches::kNaClLoaderProcess)) { // Load the 64-bit DLL when running in a 64-bit process. dir->append(installer::kChromeNaCl64Dll); } else { // Only NaCl broker and loader can be launched as Win64 processes. NOTREACHED(); return NULL; } #else dir->append(installer::kChromeDll); #endif #ifdef NDEBUG // Experimental pre-reading optimization // The idea is to pre read significant portion of chrome.dll in advance // so that subsequent hard page faults are avoided. if (!cmd_line.HasSwitch(switches::kProcessType)) { // The kernel brings in 8 pages for the code section at a time and 4 pages // for other sections. We can skip over these pages to avoid a soft page // fault which may not occur during code execution. However skipping 4K at // a time still has better performance over 32K and 16K according to data. // TODO(ananta) // Investigate this and tune. const size_t kStepSize = 4 * 1024; DWORD pre_read_size = 0; DWORD pre_read_step_size = kStepSize; DWORD pre_read = 1; base::win::RegKey key(HKEY_CURRENT_USER, L"Software\\Google\\ChromeFrame", KEY_QUERY_VALUE); if (key.Valid()) { key.ReadValueDW(L"PreReadSize", &pre_read_size); key.ReadValueDW(L"PreReadStepSize", &pre_read_step_size); key.ReadValueDW(L"PreRead", &pre_read); key.Close(); } if (pre_read) { TRACE_EVENT_BEGIN_ETW("PreReadImage", 0, ""); file_util::PreReadImage(dir->c_str(), pre_read_size, pre_read_step_size); TRACE_EVENT_END_ETW("PreReadImage", 0, ""); } } #endif // NDEBUG return ::LoadLibraryExW(dir->c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH); } void RecordDidRun(const std::wstring& dll_path) { bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str()); GoogleUpdateSettings::UpdateDidRunState(true, system_level); } void ClearDidRun(const std::wstring& dll_path) { bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str()); GoogleUpdateSettings::UpdateDidRunState(false, system_level); } } //============================================================================= MainDllLoader::MainDllLoader() : dll_(NULL) { } MainDllLoader::~MainDllLoader() { #ifdef PURIFY // We should never unload the dll. There is only risk and no gain from // doing so. The singleton dtors have been already run by AtExitManager. ::FreeLibrary(dll_); #endif } // Loading chrome is an interesting affair. First we try loading from the // current directory to support run-what-you-compile and other development // scenarios. // If that fails then we look at the --chrome-version command line flag followed // by the 'CHROME_VERSION' env variable to determine if we should stick with an // older dll version even if a new one is available to support upgrade-in-place // scenarios. // If that fails then finally we look at the registry which should point us // to the latest version. This is the expected path for the first chrome.exe // browser instance in an installed build. HMODULE MainDllLoader::Load(std::wstring* out_version, std::wstring* out_file) { std::wstring dir(GetExecutablePath()); *out_file = dir; HMODULE dll = LoadChromeWithDirectory(out_file); if (dll) return dll; std::wstring version_string; scoped_ptr<Version> version; const CommandLine& cmd_line = *CommandLine::ForCurrentProcess(); if (cmd_line.HasSwitch(switches::kChromeVersion)) { version_string = cmd_line.GetSwitchValueNative(switches::kChromeVersion); version.reset(Version::GetVersionFromString(WideToASCII(version_string))); if (!version.get()) { // If a bogus command line flag was given, then abort. LOG(ERROR) << "Invalid version string received on command line: " << version_string; return NULL; } } if (!version.get()) { if (EnvQueryStr(ASCIIToWide(chrome::kChromeVersionEnvVar).c_str(), &version_string)) { version.reset(Version::GetVersionFromString(WideToASCII(version_string))); } } if (!version.get()) { std::wstring reg_path(GetRegistryPath()); // Look into the registry to find the latest version. We don't validate // this by building a Version object to avoid harming normal case startup // time. version_string.clear(); GetVersion(dir.c_str(), reg_path.c_str(), &version_string); } if (version.get() || !version_string.empty()) { *out_file = dir; *out_version = version_string; out_file->append(*out_version).append(L"\\"); dll = LoadChromeWithDirectory(out_file); if (!dll) { LOG(ERROR) << "Failed to load Chrome DLL from " << out_file; } return dll; } else { LOG(ERROR) << "Could not get Chrome DLL version."; return NULL; } } // Launching is a matter of loading the right dll, setting the CHROME_VERSION // environment variable and just calling the entry point. Derived classes can // add custom code in the OnBeforeLaunch callback. int MainDllLoader::Launch(HINSTANCE instance, sandbox::SandboxInterfaceInfo* sbox_info) { std::wstring version; std::wstring file; dll_ = Load(&version, &file); if (!dll_) return chrome::RESULT_CODE_MISSING_DATA; scoped_ptr<base::Environment> env(base::Environment::Create()); env->SetVar(chrome::kChromeVersionEnvVar, WideToUTF8(version)); InitCrashReporterWithDllPath(file); OnBeforeLaunch(file); DLL_MAIN entry_point = reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, "ChromeMain")); if (!entry_point) return content::RESULT_CODE_BAD_PROCESS_TYPE; int rc = entry_point(instance, sbox_info, ::GetCommandLineW()); return OnBeforeExit(rc, file); } void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() { RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function = reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>( ::GetProcAddress(dll_, "RelaunchChromeBrowserWithNewCommandLineIfNeeded")); if (!relaunch_function) { LOG(ERROR) << "Could not find exported function " << "RelaunchChromeBrowserWithNewCommandLineIfNeeded"; } else { relaunch_function(); } } //============================================================================= class ChromeDllLoader : public MainDllLoader { public: virtual std::wstring GetRegistryPath() { std::wstring key(google_update::kRegPathClients); BrowserDistribution* dist = BrowserDistribution::GetDistribution(); key.append(L"\\").append(dist->GetAppGuid()); return key; } virtual void OnBeforeLaunch(const std::wstring& dll_path) { RecordDidRun(dll_path); } virtual int OnBeforeExit(int return_code, const std::wstring& dll_path) { // NORMAL_EXIT_CANCEL is used for experiments when the user cancels // so we need to reset the did_run signal so omaha does not count // this run as active usage. if (content::RESULT_CODE_NORMAL_EXIT_CANCEL == return_code) { ClearDidRun(dll_path); } return return_code; } }; //============================================================================= class ChromiumDllLoader : public MainDllLoader { public: virtual std::wstring GetRegistryPath() { BrowserDistribution* dist = BrowserDistribution::GetDistribution(); return dist->GetVersionKey(); } }; MainDllLoader* MakeMainDllLoader() { #if defined(GOOGLE_CHROME_BUILD) return new ChromeDllLoader(); #else return new ChromiumDllLoader(); #endif } <commit_msg>Build fix ... missed a file.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <windows.h> #include <shlwapi.h> #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/environment.h" #include "base/file_util.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/win/registry.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "base/version.h" #include "chrome/app/breakpad_win.h" #include "chrome/app/client_util.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_result_codes.h" #include "chrome/common/chrome_switches.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/channel_info.h" #include "chrome/installer/util/install_util.h" #include "chrome/installer/util/google_update_constants.h" #include "chrome/installer/util/google_update_settings.h" #include "chrome/installer/util/util_constants.h" namespace { // The entry point signature of chrome.dll. typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*, wchar_t*); typedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)(); // Gets chrome version according to the load path. |exe_path| must be the // backslash terminated directory of the current chrome.exe. bool GetVersion(const wchar_t* exe_path, const wchar_t* key_path, std::wstring* version) { HKEY reg_root = InstallUtil::IsPerUserInstall(exe_path) ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE; bool success = false; base::win::RegKey key(reg_root, key_path, KEY_QUERY_VALUE); if (key.Valid()) { // If 'new_chrome.exe' is present it means chrome was auto-updated while // running. We need to consult the opv value so we can load the old dll. // TODO(cpu) : This is solving the same problem as the environment variable // so one of them will eventually be deprecated. std::wstring new_chrome_exe(exe_path); new_chrome_exe.append(installer::kChromeNewExe); if (::PathFileExistsW(new_chrome_exe.c_str()) && key.ReadValue(google_update::kRegOldVersionField, version) == ERROR_SUCCESS) { success = true; } else { success = (key.ReadValue(google_update::kRegVersionField, version) == ERROR_SUCCESS); } } return success; } // Gets the path of the current exe with a trailing backslash. std::wstring GetExecutablePath() { wchar_t path[MAX_PATH]; ::GetModuleFileNameW(NULL, path, MAX_PATH); if (!::PathRemoveFileSpecW(path)) return std::wstring(); std::wstring exe_path(path); return exe_path.append(L"\\"); } // Not generic, we only handle strings up to 128 chars. bool EnvQueryStr(const wchar_t* key_name, std::wstring* value) { wchar_t out[128]; DWORD count = sizeof(out)/sizeof(out[0]); DWORD rv = ::GetEnvironmentVariableW(key_name, out, count); if ((rv == 0) || (rv >= count)) return false; *value = out; return true; } // Expects that |dir| has a trailing backslash. |dir| is modified so it // contains the full path that was tried. Caller must check for the return // value not being null to determine if this path contains a valid dll. HMODULE LoadChromeWithDirectory(std::wstring* dir) { ::SetCurrentDirectoryW(dir->c_str()); const CommandLine& cmd_line = *CommandLine::ForCurrentProcess(); #ifdef _WIN64 if ((cmd_line.GetSwitchValueASCII(switches::kProcessType) == switches::kNaClBrokerProcess) || (cmd_line.GetSwitchValueASCII(switches::kProcessType) == switches::kNaClLoaderProcess)) { // Load the 64-bit DLL when running in a 64-bit process. dir->append(installer::kChromeNaCl64Dll); } else { // Only NaCl broker and loader can be launched as Win64 processes. NOTREACHED(); return NULL; } #else dir->append(installer::kChromeDll); #endif #ifdef NDEBUG // Experimental pre-reading optimization // The idea is to pre read significant portion of chrome.dll in advance // so that subsequent hard page faults are avoided. if (!cmd_line.HasSwitch(switches::kProcessType)) { // The kernel brings in 8 pages for the code section at a time and 4 pages // for other sections. We can skip over these pages to avoid a soft page // fault which may not occur during code execution. However skipping 4K at // a time still has better performance over 32K and 16K according to data. // TODO(ananta) // Investigate this and tune. const size_t kStepSize = 4 * 1024; DWORD pre_read_size = 0; DWORD pre_read_step_size = kStepSize; DWORD pre_read = 1; base::win::RegKey key(HKEY_CURRENT_USER, L"Software\\Google\\ChromeFrame", KEY_QUERY_VALUE); if (key.Valid()) { key.ReadValueDW(L"PreReadSize", &pre_read_size); key.ReadValueDW(L"PreReadStepSize", &pre_read_step_size); key.ReadValueDW(L"PreRead", &pre_read); key.Close(); } if (pre_read) { TRACE_EVENT_BEGIN_ETW("PreReadImage", 0, ""); file_util::PreReadImage(dir->c_str(), pre_read_size, pre_read_step_size); TRACE_EVENT_END_ETW("PreReadImage", 0, ""); } } #endif // NDEBUG return ::LoadLibraryExW(dir->c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH); } void RecordDidRun(const std::wstring& dll_path) { bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str()); GoogleUpdateSettings::UpdateDidRunState(true, system_level); } void ClearDidRun(const std::wstring& dll_path) { bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str()); GoogleUpdateSettings::UpdateDidRunState(false, system_level); } } //============================================================================= MainDllLoader::MainDllLoader() : dll_(NULL) { } MainDllLoader::~MainDllLoader() { #ifdef PURIFY // We should never unload the dll. There is only risk and no gain from // doing so. The singleton dtors have been already run by AtExitManager. ::FreeLibrary(dll_); #endif } // Loading chrome is an interesting affair. First we try loading from the // current directory to support run-what-you-compile and other development // scenarios. // If that fails then we look at the --chrome-version command line flag followed // by the 'CHROME_VERSION' env variable to determine if we should stick with an // older dll version even if a new one is available to support upgrade-in-place // scenarios. // If that fails then finally we look at the registry which should point us // to the latest version. This is the expected path for the first chrome.exe // browser instance in an installed build. HMODULE MainDllLoader::Load(std::wstring* out_version, std::wstring* out_file) { std::wstring dir(GetExecutablePath()); *out_file = dir; HMODULE dll = LoadChromeWithDirectory(out_file); if (dll) return dll; std::wstring version_string; scoped_ptr<Version> version; const CommandLine& cmd_line = *CommandLine::ForCurrentProcess(); if (cmd_line.HasSwitch(switches::kChromeVersion)) { version_string = cmd_line.GetSwitchValueNative(switches::kChromeVersion); version.reset(Version::GetVersionFromString(WideToASCII(version_string))); if (!version.get()) { // If a bogus command line flag was given, then abort. LOG(ERROR) << "Invalid version string received on command line: " << version_string; return NULL; } } if (!version.get()) { if (EnvQueryStr(ASCIIToWide(chrome::kChromeVersionEnvVar).c_str(), &version_string)) { version.reset(Version::GetVersionFromString(WideToASCII(version_string))); } } if (!version.get()) { std::wstring reg_path(GetRegistryPath()); // Look into the registry to find the latest version. We don't validate // this by building a Version object to avoid harming normal case startup // time. version_string.clear(); GetVersion(dir.c_str(), reg_path.c_str(), &version_string); } if (version.get() || !version_string.empty()) { *out_file = dir; *out_version = version_string; out_file->append(*out_version).append(L"\\"); dll = LoadChromeWithDirectory(out_file); if (!dll) { LOG(ERROR) << "Failed to load Chrome DLL from " << out_file; } return dll; } else { LOG(ERROR) << "Could not get Chrome DLL version."; return NULL; } } // Launching is a matter of loading the right dll, setting the CHROME_VERSION // environment variable and just calling the entry point. Derived classes can // add custom code in the OnBeforeLaunch callback. int MainDllLoader::Launch(HINSTANCE instance, sandbox::SandboxInterfaceInfo* sbox_info) { std::wstring version; std::wstring file; dll_ = Load(&version, &file); if (!dll_) return chrome::RESULT_CODE_MISSING_DATA; scoped_ptr<base::Environment> env(base::Environment::Create()); env->SetVar(chrome::kChromeVersionEnvVar, WideToUTF8(version)); InitCrashReporterWithDllPath(file); OnBeforeLaunch(file); DLL_MAIN entry_point = reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, "ChromeMain")); if (!entry_point) return chrome::RESULT_CODE_BAD_PROCESS_TYPE; int rc = entry_point(instance, sbox_info, ::GetCommandLineW()); return OnBeforeExit(rc, file); } void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() { RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function = reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>( ::GetProcAddress(dll_, "RelaunchChromeBrowserWithNewCommandLineIfNeeded")); if (!relaunch_function) { LOG(ERROR) << "Could not find exported function " << "RelaunchChromeBrowserWithNewCommandLineIfNeeded"; } else { relaunch_function(); } } //============================================================================= class ChromeDllLoader : public MainDllLoader { public: virtual std::wstring GetRegistryPath() { std::wstring key(google_update::kRegPathClients); BrowserDistribution* dist = BrowserDistribution::GetDistribution(); key.append(L"\\").append(dist->GetAppGuid()); return key; } virtual void OnBeforeLaunch(const std::wstring& dll_path) { RecordDidRun(dll_path); } virtual int OnBeforeExit(int return_code, const std::wstring& dll_path) { // NORMAL_EXIT_CANCEL is used for experiments when the user cancels // so we need to reset the did_run signal so omaha does not count // this run as active usage. if (chrome::RESULT_CODE_NORMAL_EXIT_CANCEL == return_code) { ClearDidRun(dll_path); } return return_code; } }; //============================================================================= class ChromiumDllLoader : public MainDllLoader { public: virtual std::wstring GetRegistryPath() { BrowserDistribution* dist = BrowserDistribution::GetDistribution(); return dist->GetVersionKey(); } }; MainDllLoader* MakeMainDllLoader() { #if defined(GOOGLE_CHROME_BUILD) return new ChromeDllLoader(); #else return new ChromiumDllLoader(); #endif } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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. // // This code glues the RLZ library DLL with Chrome. It allows Chrome to work // with or without the DLL being present. If the DLL is not present the // functions do nothing and just return false. #include "chrome/browser/rlz/rlz.h" #include <windows.h> #include <process.h> #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/task.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/profile_manager.h" #include "chrome/browser/template_url_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/env_vars.h" #include "chrome/installer/util/google_update_settings.h" //#include "chrome/common/pref_names.h" //#include "chrome/common/pref_service.h" namespace { // The maximum length of an access points RLZ in wide chars. const DWORD kMaxRlzLength = 64; // The RLZ is a DLL that might not be present in the system. We load it // as needed but never unload it. volatile HMODULE rlz_dll = NULL; enum { ACCESS_VALUES_STALE, // Possibly new values available. ACCESS_VALUES_FRESH // The cached values are current. }; // Tracks if we have tried and succeeded sending the ping. This helps us // decide if we need to refresh the some cached strings. volatile int access_values_state = ACCESS_VALUES_STALE; extern "C" { typedef bool (*RecordProductEventFn)(RLZTracker::Product product, RLZTracker::AccessPoint point, RLZTracker::Event event_id, void* reserved); typedef bool (*GetAccessPointRlzFn)(RLZTracker::AccessPoint point, wchar_t* rlz, DWORD rlz_size, void* reserved); typedef bool (*ClearAllProductEventsFn)(RLZTracker::Product product, void* reserved); typedef bool (*SendFinancialPingFn)(RLZTracker::Product product, RLZTracker::AccessPoint* access_points, const WCHAR* product_signature, const WCHAR* product_brand, const WCHAR* product_id, const WCHAR* product_lang, void* reserved); } // extern "C" RecordProductEventFn record_event = NULL; GetAccessPointRlzFn get_access_point = NULL; ClearAllProductEventsFn clear_all_events = NULL; SendFinancialPingFn send_ping = NULL; template <typename FuncT> FuncT WireExport(HMODULE module, const char* export_name) { void* entry_point = ::GetProcAddress(module, export_name); return (module)? reinterpret_cast<FuncT>(entry_point) : NULL; } HMODULE LoadRLZLibraryInternal(int directory_key) { std::wstring rlz_path; if (!PathService::Get(directory_key, &rlz_path)) return NULL; file_util::AppendToPath(&rlz_path, L"rlz.dll"); return ::LoadLibraryW(rlz_path.c_str()); } bool LoadRLZLibrary(int directory_key) { rlz_dll = LoadRLZLibraryInternal(directory_key); if (!rlz_dll) { // As a last resort we can try the EXE directory. if (directory_key != base::DIR_EXE) rlz_dll = LoadRLZLibraryInternal(base::DIR_EXE); } if (rlz_dll) { record_event = WireExport<RecordProductEventFn>(rlz_dll, "RecordProductEvent"); get_access_point = WireExport<GetAccessPointRlzFn>(rlz_dll, "GetAccessPointRlz"); clear_all_events = WireExport<ClearAllProductEventsFn>(rlz_dll, "ClearAllProductEvents"); send_ping = WireExport<SendFinancialPingFn>(rlz_dll, "SendFinancialPing"); return (record_event && get_access_point && clear_all_events && send_ping); } return false; } class DailyPingTask : public Task { public: virtual ~DailyPingTask() { } virtual void Run() { // We use a transient thread because we have no guarantees about // how long the RLZ lib can block us. _beginthread(PingNow, 0, NULL); } private: // Causes a ping to the server using WinInet. There is logic inside RLZ dll // that throttles it to a maximum of one ping per day. static void _cdecl PingNow(void*) { std::wstring lang; GoogleUpdateSettings::GetLanguage(&lang); if (lang.empty()) lang = L"en"; std::wstring brand; GoogleUpdateSettings::GetBrand(&brand); if (brand.empty()) brand = L"GGLD"; if (RLZTracker::SendFinancialPing(RLZTracker::CHROME, L"chrome", brand.c_str(), NULL, lang.c_str())) { access_values_state = ACCESS_VALUES_STALE; } } }; // Performs late RLZ initialization and RLZ event recording for chrome. // This task needs to run on the UI thread. class DelayedInitTask : public Task { public: explicit DelayedInitTask(int directory_key, bool first_run) : directory_key_(directory_key), first_run_(first_run) { } virtual ~DelayedInitTask() { } virtual void Run() { // For non-interactive tests we don't do the rest of the initialization // because sometimes the very act of loading the dll causes QEMU to crash. if (::GetEnvironmentVariableW(env_vars::kHeadless, NULL, 0)) return; if (!LoadRLZLibrary(directory_key_)) return; // Do the initial event recording if is the first run or if we have an // empty rlz which means we haven't got a chance to do it. std::wstring omnibox_rlz; RLZTracker::GetAccessPointRlz(RLZTracker::CHROME_OMNIBOX, &omnibox_rlz); if (first_run_ || omnibox_rlz.empty()) { // Record the installation of chrome. RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::INSTALL); RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_HOME_PAGE, RLZTracker::INSTALL); // Record if google is the initial search provider. if (IsGoogleDefaultSearch()) { RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::SET_TO_GOOGLE); } } // Schedule the daily RLZ ping. base::Thread* thread = g_browser_process->file_thread(); if (thread) thread->message_loop()->PostTask(FROM_HERE, new DailyPingTask()); } private: bool IsGoogleDefaultSearch() { if (!g_browser_process) return false; std::wstring user_data_dir; if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) return false; ProfileManager* profile_manager = g_browser_process->profile_manager(); Profile* profile = profile_manager->GetDefaultProfile(user_data_dir); if (!profile) return false; const TemplateURL* url_template = profile->GetTemplateURLModel()->GetDefaultSearchProvider(); if (!url_template) return false; return url_template->url()->HasGoogleBaseURLs(); } int directory_key_; bool first_run_; DISALLOW_IMPLICIT_CONSTRUCTORS(DelayedInitTask); }; } // namespace bool RLZTracker::InitRlz(int directory_key) { return LoadRLZLibrary(directory_key); } bool RLZTracker::InitRlzDelayed(int directory_key, bool first_run) { // Schedule the delayed init items. const int kTwentySeconds = 20 * 1000; MessageLoop::current()->PostDelayedTask(FROM_HERE, new DelayedInitTask(directory_key, first_run), kTwentySeconds); return true; } bool RLZTracker::RecordProductEvent(Product product, AccessPoint point, Event event) { return (record_event) ? record_event(product, point, event, NULL) : false; } bool RLZTracker::ClearAllProductEvents(Product product) { return (clear_all_events) ? clear_all_events(product, NULL) : false; } // We implement caching of the answer of get_access_point() if the request // is for CHROME_OMNIBOX. If we had a successful ping, then we update the // cached value. bool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) { static std::wstring cached_ommibox_rlz; if (!get_access_point) return false; if ((CHROME_OMNIBOX == point) && (access_values_state == ACCESS_VALUES_FRESH)) { *rlz = cached_ommibox_rlz; return true; } wchar_t str_rlz[kMaxRlzLength]; if (!get_access_point(point, str_rlz, kMaxRlzLength, NULL)) return false; if (CHROME_OMNIBOX == point) { access_values_state = ACCESS_VALUES_FRESH; cached_ommibox_rlz.assign(str_rlz); } *rlz = str_rlz; return true; } bool RLZTracker::SendFinancialPing(Product product, const wchar_t* product_signature, const wchar_t* product_brand, const wchar_t* product_id, const wchar_t* product_lang) { AccessPoint points[] = {CHROME_OMNIBOX, CHROME_HOME_PAGE, NO_ACCESS_POINT}; return (send_ping) ? send_ping(product, points, product_signature, product_brand, product_id, product_lang, NULL) : false; } <commit_msg>New default brandcode.<commit_after>// Copyright (c) 2006-2008 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. // // This code glues the RLZ library DLL with Chrome. It allows Chrome to work // with or without the DLL being present. If the DLL is not present the // functions do nothing and just return false. #include "chrome/browser/rlz/rlz.h" #include <windows.h> #include <process.h> #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/task.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/profile_manager.h" #include "chrome/browser/template_url_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/env_vars.h" #include "chrome/installer/util/google_update_settings.h" //#include "chrome/common/pref_names.h" //#include "chrome/common/pref_service.h" namespace { // The maximum length of an access points RLZ in wide chars. const DWORD kMaxRlzLength = 64; // The RLZ is a DLL that might not be present in the system. We load it // as needed but never unload it. volatile HMODULE rlz_dll = NULL; enum { ACCESS_VALUES_STALE, // Possibly new values available. ACCESS_VALUES_FRESH // The cached values are current. }; // Tracks if we have tried and succeeded sending the ping. This helps us // decide if we need to refresh the some cached strings. volatile int access_values_state = ACCESS_VALUES_STALE; extern "C" { typedef bool (*RecordProductEventFn)(RLZTracker::Product product, RLZTracker::AccessPoint point, RLZTracker::Event event_id, void* reserved); typedef bool (*GetAccessPointRlzFn)(RLZTracker::AccessPoint point, wchar_t* rlz, DWORD rlz_size, void* reserved); typedef bool (*ClearAllProductEventsFn)(RLZTracker::Product product, void* reserved); typedef bool (*SendFinancialPingFn)(RLZTracker::Product product, RLZTracker::AccessPoint* access_points, const WCHAR* product_signature, const WCHAR* product_brand, const WCHAR* product_id, const WCHAR* product_lang, void* reserved); } // extern "C" RecordProductEventFn record_event = NULL; GetAccessPointRlzFn get_access_point = NULL; ClearAllProductEventsFn clear_all_events = NULL; SendFinancialPingFn send_ping = NULL; template <typename FuncT> FuncT WireExport(HMODULE module, const char* export_name) { void* entry_point = ::GetProcAddress(module, export_name); return (module)? reinterpret_cast<FuncT>(entry_point) : NULL; } HMODULE LoadRLZLibraryInternal(int directory_key) { std::wstring rlz_path; if (!PathService::Get(directory_key, &rlz_path)) return NULL; file_util::AppendToPath(&rlz_path, L"rlz.dll"); return ::LoadLibraryW(rlz_path.c_str()); } bool LoadRLZLibrary(int directory_key) { rlz_dll = LoadRLZLibraryInternal(directory_key); if (!rlz_dll) { // As a last resort we can try the EXE directory. if (directory_key != base::DIR_EXE) rlz_dll = LoadRLZLibraryInternal(base::DIR_EXE); } if (rlz_dll) { record_event = WireExport<RecordProductEventFn>(rlz_dll, "RecordProductEvent"); get_access_point = WireExport<GetAccessPointRlzFn>(rlz_dll, "GetAccessPointRlz"); clear_all_events = WireExport<ClearAllProductEventsFn>(rlz_dll, "ClearAllProductEvents"); send_ping = WireExport<SendFinancialPingFn>(rlz_dll, "SendFinancialPing"); return (record_event && get_access_point && clear_all_events && send_ping); } return false; } class DailyPingTask : public Task { public: virtual ~DailyPingTask() { } virtual void Run() { // We use a transient thread because we have no guarantees about // how long the RLZ lib can block us. _beginthread(PingNow, 0, NULL); } private: // Causes a ping to the server using WinInet. There is logic inside RLZ dll // that throttles it to a maximum of one ping per day. static void _cdecl PingNow(void*) { std::wstring lang; GoogleUpdateSettings::GetLanguage(&lang); if (lang.empty()) lang = L"en"; std::wstring brand; GoogleUpdateSettings::GetBrand(&brand); if (brand.empty()) brand = L"GGCM"; if (RLZTracker::SendFinancialPing(RLZTracker::CHROME, L"chrome", brand.c_str(), NULL, lang.c_str())) { access_values_state = ACCESS_VALUES_STALE; } } }; // Performs late RLZ initialization and RLZ event recording for chrome. // This task needs to run on the UI thread. class DelayedInitTask : public Task { public: explicit DelayedInitTask(int directory_key, bool first_run) : directory_key_(directory_key), first_run_(first_run) { } virtual ~DelayedInitTask() { } virtual void Run() { // For non-interactive tests we don't do the rest of the initialization // because sometimes the very act of loading the dll causes QEMU to crash. if (::GetEnvironmentVariableW(env_vars::kHeadless, NULL, 0)) return; if (!LoadRLZLibrary(directory_key_)) return; // Do the initial event recording if is the first run or if we have an // empty rlz which means we haven't got a chance to do it. std::wstring omnibox_rlz; RLZTracker::GetAccessPointRlz(RLZTracker::CHROME_OMNIBOX, &omnibox_rlz); if (first_run_ || omnibox_rlz.empty()) { // Record the installation of chrome. RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::INSTALL); RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_HOME_PAGE, RLZTracker::INSTALL); // Record if google is the initial search provider. if (IsGoogleDefaultSearch()) { RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::SET_TO_GOOGLE); } } // Schedule the daily RLZ ping. base::Thread* thread = g_browser_process->file_thread(); if (thread) thread->message_loop()->PostTask(FROM_HERE, new DailyPingTask()); } private: bool IsGoogleDefaultSearch() { if (!g_browser_process) return false; std::wstring user_data_dir; if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) return false; ProfileManager* profile_manager = g_browser_process->profile_manager(); Profile* profile = profile_manager->GetDefaultProfile(user_data_dir); if (!profile) return false; const TemplateURL* url_template = profile->GetTemplateURLModel()->GetDefaultSearchProvider(); if (!url_template) return false; return url_template->url()->HasGoogleBaseURLs(); } int directory_key_; bool first_run_; DISALLOW_IMPLICIT_CONSTRUCTORS(DelayedInitTask); }; } // namespace bool RLZTracker::InitRlz(int directory_key) { return LoadRLZLibrary(directory_key); } bool RLZTracker::InitRlzDelayed(int directory_key, bool first_run) { // Schedule the delayed init items. const int kTwentySeconds = 20 * 1000; MessageLoop::current()->PostDelayedTask(FROM_HERE, new DelayedInitTask(directory_key, first_run), kTwentySeconds); return true; } bool RLZTracker::RecordProductEvent(Product product, AccessPoint point, Event event) { return (record_event) ? record_event(product, point, event, NULL) : false; } bool RLZTracker::ClearAllProductEvents(Product product) { return (clear_all_events) ? clear_all_events(product, NULL) : false; } // We implement caching of the answer of get_access_point() if the request // is for CHROME_OMNIBOX. If we had a successful ping, then we update the // cached value. bool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) { static std::wstring cached_ommibox_rlz; if (!get_access_point) return false; if ((CHROME_OMNIBOX == point) && (access_values_state == ACCESS_VALUES_FRESH)) { *rlz = cached_ommibox_rlz; return true; } wchar_t str_rlz[kMaxRlzLength]; if (!get_access_point(point, str_rlz, kMaxRlzLength, NULL)) return false; if (CHROME_OMNIBOX == point) { access_values_state = ACCESS_VALUES_FRESH; cached_ommibox_rlz.assign(str_rlz); } *rlz = str_rlz; return true; } bool RLZTracker::SendFinancialPing(Product product, const wchar_t* product_signature, const wchar_t* product_brand, const wchar_t* product_id, const wchar_t* product_lang) { AccessPoint points[] = {CHROME_OMNIBOX, CHROME_HOME_PAGE, NO_ACCESS_POINT}; return (send_ping) ? send_ping(product, points, product_signature, product_brand, product_id, product_lang, NULL) : false; } <|endoftext|>
<commit_before>/* This file is part of the clang-lazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com Author: Sérgio Martins <sergio.martins@kdab.com> Copyright (C) 2015 Sergio Martins <smartins@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. */ #include "checkmanager.h" #include "detachingtemporary.h" #include "Utils.h" #include "StringUtils.h" #include <clang/AST/DeclCXX.h> #include <clang/AST/Expr.h> #include <clang/AST/ExprCXX.h> using namespace clang; using namespace std; DetachingTemporary::DetachingTemporary(const std::string &name) : DetachingBase(name) { // Extra stuff that isn't really related to detachments but doesn't make sense to call on temporaries m_writeMethodsByType["QString"] = {"push_back", "push_front", "clear", "chop"}; m_writeMethodsByType["QList"] = {"takeAt", "takeFirst", "takeLast", "removeOne", "removeAll", "erase"}; m_writeMethodsByType["QVector"] = { "fill", "insert"}; m_writeMethodsByType["QMap"] = { "erase", "insert", "insertMulti", "remove", "take", "unite" }; m_writeMethodsByType["QHash"] = { "erase", "insert", "insertMulti", "remove", "take", "unite"}; m_writeMethodsByType["QMultiHash"] = m_writeMethodsByType["QHash"]; m_writeMethodsByType["QMultiMap"] = m_writeMethodsByType["QMap"]; m_writeMethodsByType["QLinkedList"] = {"takeFirst", "takeLast", "removeOne", "removeAll", "erase"}; m_writeMethodsByType["QSet"] = {"erase", "insert", "intersect", "unite", "subtract"}; m_writeMethodsByType["QStack"] = {"push", "swap"}; m_writeMethodsByType["QQueue"] = {"enqueue", "swap"}; m_writeMethodsByType["QListSpecialMethods"] = {"sort", "replaceInStrings", "removeDuplicates"}; m_writeMethodsByType["QStringList"] = m_writeMethodsByType["QListSpecialMethods"]; } bool isAllowedChainedClass(const std::string &className) { static const vector<string> allowed = {"QString", "QByteArray", "QVariant"}; return find(allowed.cbegin(), allowed.cend(), className) != allowed.cend(); } bool isAllowedChainedMethod(const std::string &methodName) { static const vector<string> allowed = {"QMap::keys", "QMap::values", "QHash::keys", "QMap::values", "QApplication::topLevelWidgets", "QAbstractItemView::selectedIndexes", "QListWidget::selectedItems", "QFile::encodeName", "QFile::decodeName", "QItemSelectionModel::selectedRows", "QTreeWidget::selectedItems", "QTableWidget::selectedItems", "QNetworkReply::rawHeaderList", "Mailbox::address", "QItemSelection::indexes", "QItemSelectionModel::selectedIndexes", "QMimeData::formats", "i18n"}; return find(allowed.cbegin(), allowed.cend(), methodName) != allowed.cend(); } void DetachingTemporary::VisitStmt(clang::Stmt *stm) { CallExpr *callExpr = dyn_cast<CallExpr>(stm); if (!callExpr) return; // For a chain like getList().first(), returns {first(), getList()} vector<CallExpr *> callExprs = Utils::callListForChain(callExpr); if (callExprs.size() < 2) return; CallExpr *firstCallToBeEvaluated = callExprs.at(callExprs.size() - 1); // This is the call to getList() FunctionDecl *firstFunc = firstCallToBeEvaluated->getDirectCallee(); if (!firstFunc) return; QualType qt = firstFunc->getReturnType(); const Type *firstFuncReturnType = qt.getTypePtrOrNull(); if (!firstFuncReturnType) return; if (firstFuncReturnType->isReferenceType() || firstFuncReturnType->isPointerType()) return; if (qt.isConstQualified()) { return; // const doesn't detach } CXXMethodDecl *firstMethod = dyn_cast<CXXMethodDecl>(firstFunc); if (isAllowedChainedMethod(StringUtils::qualifiedMethodName(firstFunc))) { return; } if (firstMethod && isAllowedChainedClass(firstMethod->getParent()->getNameAsString())) { return; } // Check if this is a QGlobalStatic if (firstMethod && firstMethod->getParent()->getNameAsString() == "QGlobalStatic") { return; } CallExpr *secondCallToBeEvaluated = callExprs.at(callExprs.size() - 2); // This is the call to first() FunctionDecl *detachingFunc = secondCallToBeEvaluated->getDirectCallee(); CXXMethodDecl *detachingMethod = detachingFunc ? dyn_cast<CXXMethodDecl>(detachingFunc) : nullptr; const Type *detachingMethodReturnType = detachingMethod ? detachingMethod->getReturnType().getTypePtrOrNull() : nullptr; if (!detachingMethod || !detachingMethodReturnType) return; // Check if it's one of the implicit shared classes CXXRecordDecl *classDecl = detachingMethod->getParent(); const std::string className = classDecl->getNameAsString(); auto it = m_methodsByType.find(className); auto it2 = m_writeMethodsByType.find(className); std::vector<std::string> allowedFunctions; std::vector<std::string> allowedWriteFunctions; if (it != m_methodsByType.end()) { allowedFunctions = it->second; } if (it2 != m_writeMethodsByType.end()) { allowedWriteFunctions = it2->second; } // Check if it's one of the detaching methods const std::string functionName = detachingMethod->getNameAsString(); string error; const bool isReadFunction = std::find(allowedFunctions.cbegin(), allowedFunctions.cend(), functionName) != allowedFunctions.cend(); const bool isWriteFunction = std::find(allowedWriteFunctions.cbegin(), allowedWriteFunctions.cend(), functionName) != allowedWriteFunctions.cend(); if (isReadFunction || isWriteFunction) { bool returnTypeIsIterator = false; CXXRecordDecl *returnRecord = detachingMethodReturnType->getAsCXXRecordDecl(); if (returnRecord) { returnTypeIsIterator = returnRecord->getNameAsString() == "iterator"; } if (isWriteFunction && (detachingMethodReturnType->isVoidType() || returnTypeIsIterator)) { error = std::string("Modifying temporary container is pointless and it also detaches"); } else { error = std::string("Don't call ") + StringUtils::qualifiedMethodName(detachingMethod) + std::string("() on temporary"); } } if (!error.empty()) emitWarning(stm->getLocStart(), error.c_str()); } bool DetachingTemporary::isDetachingMethod(CXXMethodDecl *method) const { if (!method) return false; CXXRecordDecl *record = method->getParent(); if (!record) return false; if (DetachingBase::isDetachingMethod(method)) return true; const string className = record->getNameAsString(); auto it = m_writeMethodsByType.find(className); if (it != m_writeMethodsByType.cend()) { const auto &methods = it->second; auto it2 = find(methods.cbegin(), methods.cend(), method->getNameAsString()); if (it2 != methods.cend()) return true; } return false; } REGISTER_CHECK_WITH_FLAGS("detaching-temporary", DetachingTemporary, CheckLevel1) <commit_msg>detaching-temporary: Blacklist++<commit_after>/* This file is part of the clang-lazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com Author: Sérgio Martins <sergio.martins@kdab.com> Copyright (C) 2015 Sergio Martins <smartins@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. */ #include "checkmanager.h" #include "detachingtemporary.h" #include "Utils.h" #include "StringUtils.h" #include <clang/AST/DeclCXX.h> #include <clang/AST/Expr.h> #include <clang/AST/ExprCXX.h> using namespace clang; using namespace std; DetachingTemporary::DetachingTemporary(const std::string &name) : DetachingBase(name) { // Extra stuff that isn't really related to detachments but doesn't make sense to call on temporaries m_writeMethodsByType["QString"] = {"push_back", "push_front", "clear", "chop"}; m_writeMethodsByType["QList"] = {"takeAt", "takeFirst", "takeLast", "removeOne", "removeAll", "erase"}; m_writeMethodsByType["QVector"] = { "fill", "insert"}; m_writeMethodsByType["QMap"] = { "erase", "insert", "insertMulti", "remove", "take", "unite" }; m_writeMethodsByType["QHash"] = { "erase", "insert", "insertMulti", "remove", "take", "unite"}; m_writeMethodsByType["QMultiHash"] = m_writeMethodsByType["QHash"]; m_writeMethodsByType["QMultiMap"] = m_writeMethodsByType["QMap"]; m_writeMethodsByType["QLinkedList"] = {"takeFirst", "takeLast", "removeOne", "removeAll", "erase"}; m_writeMethodsByType["QSet"] = {"erase", "insert", "intersect", "unite", "subtract"}; m_writeMethodsByType["QStack"] = {"push", "swap"}; m_writeMethodsByType["QQueue"] = {"enqueue", "swap"}; m_writeMethodsByType["QListSpecialMethods"] = {"sort", "replaceInStrings", "removeDuplicates"}; m_writeMethodsByType["QStringList"] = m_writeMethodsByType["QListSpecialMethods"]; } bool isAllowedChainedClass(const std::string &className) { static const vector<string> allowed = {"QString", "QByteArray", "QVariant"}; return find(allowed.cbegin(), allowed.cend(), className) != allowed.cend(); } bool isAllowedChainedMethod(const std::string &methodName) { static const vector<string> allowed = {"QMap::keys", "QMap::values", "QHash::keys", "QMap::values", "QApplication::topLevelWidgets", "QAbstractItemView::selectedIndexes", "QListWidget::selectedItems", "QFile::encodeName", "QFile::decodeName", "QItemSelectionModel::selectedRows", "QTreeWidget::selectedItems", "QTableWidget::selectedItems", "QNetworkReply::rawHeaderList", "Mailbox::address", "QItemSelection::indexes", "QItemSelectionModel::selectedIndexes", "QMimeData::formats", "i18n", "QAbstractTransition::targetStates"}; return find(allowed.cbegin(), allowed.cend(), methodName) != allowed.cend(); } void DetachingTemporary::VisitStmt(clang::Stmt *stm) { CallExpr *callExpr = dyn_cast<CallExpr>(stm); if (!callExpr) return; // For a chain like getList().first(), returns {first(), getList()} vector<CallExpr *> callExprs = Utils::callListForChain(callExpr); if (callExprs.size() < 2) return; CallExpr *firstCallToBeEvaluated = callExprs.at(callExprs.size() - 1); // This is the call to getList() FunctionDecl *firstFunc = firstCallToBeEvaluated->getDirectCallee(); if (!firstFunc) return; QualType qt = firstFunc->getReturnType(); const Type *firstFuncReturnType = qt.getTypePtrOrNull(); if (!firstFuncReturnType) return; if (firstFuncReturnType->isReferenceType() || firstFuncReturnType->isPointerType()) return; if (qt.isConstQualified()) { return; // const doesn't detach } CXXMethodDecl *firstMethod = dyn_cast<CXXMethodDecl>(firstFunc); if (isAllowedChainedMethod(StringUtils::qualifiedMethodName(firstFunc))) { return; } if (firstMethod && isAllowedChainedClass(firstMethod->getParent()->getNameAsString())) { return; } // Check if this is a QGlobalStatic if (firstMethod && firstMethod->getParent()->getNameAsString() == "QGlobalStatic") { return; } CallExpr *secondCallToBeEvaluated = callExprs.at(callExprs.size() - 2); // This is the call to first() FunctionDecl *detachingFunc = secondCallToBeEvaluated->getDirectCallee(); CXXMethodDecl *detachingMethod = detachingFunc ? dyn_cast<CXXMethodDecl>(detachingFunc) : nullptr; const Type *detachingMethodReturnType = detachingMethod ? detachingMethod->getReturnType().getTypePtrOrNull() : nullptr; if (!detachingMethod || !detachingMethodReturnType) return; // Check if it's one of the implicit shared classes CXXRecordDecl *classDecl = detachingMethod->getParent(); const std::string className = classDecl->getNameAsString(); auto it = m_methodsByType.find(className); auto it2 = m_writeMethodsByType.find(className); std::vector<std::string> allowedFunctions; std::vector<std::string> allowedWriteFunctions; if (it != m_methodsByType.end()) { allowedFunctions = it->second; } if (it2 != m_writeMethodsByType.end()) { allowedWriteFunctions = it2->second; } // Check if it's one of the detaching methods const std::string functionName = detachingMethod->getNameAsString(); string error; const bool isReadFunction = std::find(allowedFunctions.cbegin(), allowedFunctions.cend(), functionName) != allowedFunctions.cend(); const bool isWriteFunction = std::find(allowedWriteFunctions.cbegin(), allowedWriteFunctions.cend(), functionName) != allowedWriteFunctions.cend(); if (isReadFunction || isWriteFunction) { bool returnTypeIsIterator = false; CXXRecordDecl *returnRecord = detachingMethodReturnType->getAsCXXRecordDecl(); if (returnRecord) { returnTypeIsIterator = returnRecord->getNameAsString() == "iterator"; } if (isWriteFunction && (detachingMethodReturnType->isVoidType() || returnTypeIsIterator)) { error = std::string("Modifying temporary container is pointless and it also detaches"); } else { error = std::string("Don't call ") + StringUtils::qualifiedMethodName(detachingMethod) + std::string("() on temporary"); } } if (!error.empty()) emitWarning(stm->getLocStart(), error.c_str()); } bool DetachingTemporary::isDetachingMethod(CXXMethodDecl *method) const { if (!method) return false; CXXRecordDecl *record = method->getParent(); if (!record) return false; if (DetachingBase::isDetachingMethod(method)) return true; const string className = record->getNameAsString(); auto it = m_writeMethodsByType.find(className); if (it != m_writeMethodsByType.cend()) { const auto &methods = it->second; auto it2 = find(methods.cbegin(), methods.cend(), method->getNameAsString()); if (it2 != methods.cend()) return true; } return false; } REGISTER_CHECK_WITH_FLAGS("detaching-temporary", DetachingTemporary, CheckLevel1) <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fwkutil.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: jl $ $Date: 2004-05-18 12:50:34 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #if !defined INCLUDED_JVMFWK_FWKUTIL_HXX #define INCLUDED_JVMFWK_FWKUTIL_HXX #include "osl/mutex.hxx" #include "osl/module.hxx" #include "rtl/byteseq.hxx" #include "libxml/parser.h" #include "libxml/xpath.h" #define ENVIRONMENT_VAR_JRE_PATH "JAVA_HOME" namespace jfw { osl::Mutex * getFwkMutex(); rtl::ByteSequence encodeBase16(const rtl::ByteSequence& rawData); rtl::ByteSequence decodeBase16(const rtl::ByteSequence& data); rtl::OUString getPlatform(); /** //Todo Gets the directory where the user data is written Can have these values: - ~/.StarOffice/user/config (used in office) - arbitrary directory determined by environment variable - tmp directory (running out of office, e.g. regcomp) @return File URL of the directory */ rtl::OUString getJavaSettingsDirectory(); enum JFW_MODE { /** The mode is unknown. */ JFW_MODE_INDETERMINED, /** This library is loaded in an office process. */ JFW_MODE_OFFICE, /** We are NOT in an office process. The javavendors.xml is located next to the jvmfwk.dll, the javasettings.xml is NEIHER created, NOR read or written. As class path the environment variable CLASSPATH is used. The JRE, which is to be used is determined by the environment variable JAVA_HOME. It must contain a file URL to the JRE. */ JFW_MODE_ENV_SIMPLE }; JFW_MODE getMode(); /** Get the file URL to the javasettings.xml */ rtl::OUString getUserSettingsURL(); rtl::OString getUserSettingsPath(); /** returns .../javasettings_wnt_x86.xml. Or other platform suffixes */ rtl::OUString getSharedSettingsURL(); rtl::OString getSharedSettingsPath(); /** returns .../javasettings.xml. */ rtl::OUString getSharedSettingsURLNoPlatformSuffix(); rtl::OString getSharedSettingsPathNoPlatformSuffix(); rtl::OUString getBaseInstallation(); rtl::OUString getVendorSettingsURL(); rtl::OString getVendorSettingsPath(); rtl::OUString getDirFromFile(const rtl::OUString& usFilePath); rtl::OUString getFileFromURL(const rtl::OUString& sFileURL); rtl::OUString searchFileNextToThisLib(const rtl::OUString & sFile); class CNodeJava; /** creates the -Djava.class.path option with the complete classpath. If param mode is JFW_MODE_ENV_SIMPLE then the param javaSettings is ignored. */ javaFrameworkError makeClassPathOption( JFW_MODE mode, CNodeJava & javaSettings, /*out*/rtl::OString & sOption); struct PluginLibrary; class VersionInfo; class CJavaInfo; javaFrameworkError getVendorPluginURLs( const xmlDocPtr doc, const xmlXPathContextPtr context, std::vector<PluginLibrary> * vecPlugins); bool isAccessibilitySupportDesired(); javaFrameworkError getVersionInformation( const xmlDocPtr doc, const xmlXPathContextPtr context, const rtl::OString & sVendor, VersionInfo *pVersionInfo); /** Gets the file URL to the plubin library for the currently selected Java. */ javaFrameworkError getPluginLibrary( const rtl::OUString & sVendor, rtl::OUString & sLibPathe); /** Called from writeJavaInfoData. It sets the process identifier. When java is to be started, then the current id is compared to the one set by this function. If they are identical then the Java was selected in the same process. If that Java needs a prepared environment, such as a LD_LIBRARY_PATH, then it must not be started in this process. */ void setJavaSelected(); /** Determines if the currently selected Java was set in this process. @see setProcessId() */ bool wasJavaSelectedInSameProcess(); /** @param pDoc must not be freed within the function. @param pJavaInfoNode must not be freed within the function. */ javaFrameworkError writeElementJavaInfo(xmlDoc* pDoc, xmlNode* pJavaInfoNode, const jfw::CJavaInfo & aInfo); javaFrameworkError buildClassPathFromDirectory(const rtl::OUString & relPath, rtl::OUString & sClassPath); rtl::OUString retrieveClassPath( ::rtl::OUString const & macro ); // class CProcessId // { // sal_uInt8 m_arId[16]; // bool m_bValid; // public: // CProcessId(); // /** // If the argument is NULL or the object is invalid then // false is returned. // */ // bool operator == (const sal_uInt8 * arId) const; // void set(); // bool isValid() const; // }; } #endif <commit_msg>INTEGRATION: CWS jl8 (1.8.4); FILE MERGED 2004/07/06 16:03:15 jl 1.8.4.2: #i30342# 2004/06/24 13:02:03 jl 1.8.4.1: #i30342#<commit_after>/************************************************************************* * * $RCSfile: fwkutil.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2004-07-23 11:55:20 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #if !defined INCLUDED_JVMFWK_FWKUTIL_HXX #define INCLUDED_JVMFWK_FWKUTIL_HXX #include "osl/mutex.hxx" #include "osl/module.hxx" #include "rtl/byteseq.hxx" #include "libxml/parser.h" #include "libxml/xpath.h" #define ENVIRONMENT_VAR_JRE_PATH "JAVA_HOME" namespace jfw { osl::Mutex * getFwkMutex(); rtl::ByteSequence encodeBase16(const rtl::ByteSequence& rawData); rtl::ByteSequence decodeBase16(const rtl::ByteSequence& data); rtl::OUString getPlatform(); /** //Todo Gets the directory where the user data is written Can have these values: - ~/.StarOffice/user/config (used in office) - arbitrary directory determined by environment variable - tmp directory (running out of office, e.g. regcomp) @return File URL of the directory */ rtl::OUString getJavaSettingsDirectory(); enum JFW_MODE { /** The mode is unknown. */ JFW_MODE_INDETERMINED, /** This library is loaded in an office process. */ JFW_MODE_OFFICE, /** We are NOT in an office process. The javavendors.xml is located next to the jvmfwk.dll, the javasettings.xml is NEIHER created, NOR read or written. As class path the environment variable CLASSPATH is used. The JRE, which is to be used is determined by the environment variable JAVA_HOME. It must contain a file URL to the JRE. */ JFW_MODE_ENV_SIMPLE }; JFW_MODE getMode(); /** Get the file URL to the javasettings.xml */ rtl::OUString getUserSettingsURL(); rtl::OString getUserSettingsPath(); /** returns .../javasettings_wnt_x86.xml. Or other platform suffixes */ rtl::OUString getSharedSettingsURL(); rtl::OString getSharedSettingsPath(); /** returns .../javasettings.xml. */ rtl::OUString getSharedSettingsURLNoPlatformSuffix(); rtl::OString getSharedSettingsPathNoPlatformSuffix(); rtl::OUString getBaseInstallation(); rtl::OUString getVendorSettingsURL(); rtl::OString getVendorSettingsPath(); rtl::OUString getDirFromFile(const rtl::OUString& usFilePath); rtl::OUString getFileFromURL(const rtl::OUString& sFileURL); rtl::OUString searchFileNextToThisLib(const rtl::OUString & sFile); class CNodeJava; /** creates the -Djava.class.path option with the complete classpath. If param mode is JFW_MODE_ENV_SIMPLE then the param javaSettings is ignored. */ javaFrameworkError makeClassPathOption( JFW_MODE mode, CNodeJava & javaSettings, /*out*/rtl::OString & sOption); struct PluginLibrary; class VersionInfo; class CJavaInfo; javaFrameworkError getVendorPluginURLs( const xmlDocPtr doc, const xmlXPathContextPtr context, std::vector<PluginLibrary> * vecPlugins); javaFrameworkError getSupportedVendors( const xmlDocPtr doc, const xmlXPathContextPtr context, std::vector<rtl::OUString> * vecVendors); bool isAccessibilitySupportDesired(); javaFrameworkError getVersionInformation( const xmlDocPtr doc, const xmlXPathContextPtr context, const rtl::OUString & sVendor, VersionInfo *pVersionInfo); /** Gets the file URL to the plubin library for the currently selected Java. */ javaFrameworkError getPluginLibrary( const rtl::OUString & sVendor, rtl::OUString & sLibPathe); /** Called from writeJavaInfoData. It sets the process identifier. When java is to be started, then the current id is compared to the one set by this function. If they are identical then the Java was selected in the same process. If that Java needs a prepared environment, such as a LD_LIBRARY_PATH, then it must not be started in this process. */ void setJavaSelected(); /** Determines if the currently selected Java was set in this process. @see setProcessId() */ bool wasJavaSelectedInSameProcess(); /** @param pDoc must not be freed within the function. @param pJavaInfoNode must not be freed within the function. */ javaFrameworkError writeElementJavaInfo(xmlDoc* pDoc, xmlNode* pJavaInfoNode, const jfw::CJavaInfo & aInfo); javaFrameworkError buildClassPathFromDirectory(const rtl::OUString & relPath, rtl::OUString & sClassPath); rtl::OUString retrieveClassPath( ::rtl::OUString const & macro ); // class CProcessId // { // sal_uInt8 m_arId[16]; // bool m_bValid; // public: // CProcessId(); // /** // If the argument is NULL or the object is invalid then // false is returned. // */ // bool operator == (const sal_uInt8 * arId) const; // void set(); // bool isValid() const; // }; } #endif <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2552 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1492088 by johtaylo@johtaylo-jtincrementor2-increment on 2017/12/08 03:00:14<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2553 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2788 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1716952 by chui@ocl-promo-incrementor on 2018/12/06 03:00:18<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2789 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2495 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1457669 by johtaylo@johtaylo-jtincrementor-increment on 2017/09/12 03:00:05<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2496 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2471 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1444919 by johtaylo@johtaylo-jtincrementor-increment on 2017/08/09 03:00:05<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2472 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2011 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1229676 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/01/21 03:00:11<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2012 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2333 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1361545 by johtaylo@johtaylo-jtincrementor-increment on 2017/01/13 03:00:03<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2334 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2279 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1343667 by johtaylo@johtaylo-jtincrementor-increment on 2016/11/19 03:00:04<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2280 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2126 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1273675 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/05/27 03:00:13<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2127 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Object.cpp // Test02 // // Created by Golden Compass on 9/17/14. // Copyright (c) 2014 Golden Compass. All rights reserved. // #include "Object.h" Sphere::Sphere(vec3 _center, float _radius) { center = _center; radius = _radius; } //bool Sphere::isIntersectByRay(const vec3& ray) //{ // // return false; //} Plane::Plane(float _a, float _b, float _c, float _d) { a = _a; b = _b; c = _c; d = _d; } // ax + by + cz + d = 0 Plane::Plane(vec3 point, vec3 normal) { a = normal.x; b = normal.y; c = normal.z; d = -(a*point.x) - (b*point.y) - (c*point.z); }<commit_msg>working copy…<commit_after>// // Object.cpp // Test02 // // Created by Golden Compass on 9/17/14. // Copyright (c) 2014 Golden Compass. All rights reserved. // #include "Object.h" Sphere::Sphere(vec3 _center, float _radius) { center = _center; radius = _radius; } //bool Sphere::isIntersectByRay(const vec3& ray) //{ // // return false; //} Plane::Plane(float _a, float _b, float _c, float _d) { a = _a; b = _b; c = _c; d = _d; } // ax + by + cz + d = 0 Plane::Plane(vec3 point, vec3 normal) { a = normal.x; b = normal.y; c = normal.z; d = -(a*point.x) - (b*point.y) - (c*point.z); }<|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2067 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1249106 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/03/19 03:00:11<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2068 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2097 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1258907 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/04/18 03:00:24<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2098 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2340 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1364218 by johtaylo@johtaylo-jtincrementor-increment on 2017/01/20 03:00:45<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2341 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 1620 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1070744 by gandryey@gera-ubuntu14 on 2014/08/27 13:47:50<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 1621 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>#include <future> #include <string> #include <vector> #include "firebase/firestore.h" #include "firebase_test_framework.h" #include "firestore_integration_test.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "util/bundle_builder.h" #include "util/event_accumulator.h" #include "util/future_test_util.h" // These test cases are in sync with native iOS client SDK test // Firestore/Example/Tests/Integration/API/FIRBundlesTests.mm // and native Android client SDK test // firebase_firestore/tests/integration_tests/src/com/google/firebase/firestore/BundleTest.java // The iOS test names start with the mandatory test prefix while Android test // names do not. Here we use the Android test names. namespace firebase { namespace firestore { namespace { // Query names from the testing bundle in bundle_builder.cc constexpr char kLimitQueryName[] = "limit"; constexpr char kLimitToLastQueryName[] = "limit-to-last"; MATCHER_P( InProgressWithLoadedDocuments, expected_documents, std::string("Is a valid InProgress update with documents_loaded() == ") + std::to_string(expected_documents)) { std::string state_string = arg.state() == LoadBundleTaskProgress::State::kInProgress ? "kInProgress" : (arg.state() == LoadBundleTaskProgress::State::kError ? "kError" : "kSuccess"); *result_listener << "progress state() is " << state_string << " documents_loaded() is: " << arg.documents_loaded() << " total_documents() is: " << arg.total_documents() << " bytes_loaded() is: " << arg.bytes_loaded() << " total_bytes() is: " << arg.total_bytes(); return arg.state() == LoadBundleTaskProgress::State::kInProgress && arg.documents_loaded() == expected_documents && arg.documents_loaded() <= arg.total_documents() && arg.bytes_loaded() <= arg.total_bytes(); } void VerifySuccessProgress(LoadBundleTaskProgress progress) { EXPECT_EQ(progress.state(), LoadBundleTaskProgress::State::kSuccess); EXPECT_EQ(progress.documents_loaded(), progress.total_documents()); EXPECT_EQ(progress.bytes_loaded(), progress.total_bytes()); } void VerifyErrorProgress(LoadBundleTaskProgress progress) { EXPECT_EQ(progress.state(), LoadBundleTaskProgress::State::kError); EXPECT_EQ(progress.documents_loaded(), 0); EXPECT_EQ(progress.bytes_loaded(), 0); } std::string CreateTestBundle(Firestore* db) { return CreateBundle(db->app()->options().project_id()); } class BundleTest : public FirestoreIntegrationTest { protected: void SetUp() override { FirestoreIntegrationTest::SetUp(); // Clear the storage to avoid tests interfering with each other, since they // will be loading the same bundle file. ASSERT_THAT(TestFirestore()->ClearPersistence(), FutureSucceeds()); } template <typename T> T AwaitResult(const Future<T>& future) { auto* ptr = Await(future); EXPECT_NE(ptr, nullptr); // Return default instance instead of crashing. if (ptr == nullptr) { return {}; } return *ptr; } void VerifyQueryResults(Firestore* db) { { auto snapshot = AwaitResult(db->Collection("coll-1").Get(Source::kCache)); EXPECT_THAT( QuerySnapshotToValues(snapshot), testing::ElementsAre(MapFieldValue{{"k", FieldValue::String("a")}, {"bar", FieldValue::Integer(1)}}, MapFieldValue{{"k", FieldValue::String("b")}, {"bar", FieldValue::Integer(2)}})); } { Query limit = AwaitResult(db->NamedQuery(kLimitQueryName)); auto limit_snapshot = AwaitResult(limit.Get(Source::kCache)); EXPECT_THAT( QuerySnapshotToValues(limit_snapshot), testing::ElementsAre(MapFieldValue{{"k", FieldValue::String("b")}, {"bar", FieldValue::Integer(2)}})); } { Query limit_to_last = AwaitResult(db->NamedQuery(kLimitToLastQueryName)); auto limit_to_last_snapshot = AwaitResult(limit_to_last.Get(Source::kCache)); EXPECT_THAT( QuerySnapshotToValues(limit_to_last_snapshot), testing::ElementsAre(MapFieldValue{{"k", FieldValue::String("a")}, {"bar", FieldValue::Integer(1)}})); } } }; TEST_F(BundleTest, CanLoadBundlesWithoutProgressUpdates) { Firestore* db = TestFirestore(); auto bundle = CreateTestBundle(db); Future<LoadBundleTaskProgress> result = db->LoadBundle(bundle); VerifySuccessProgress(AwaitResult(result)); VerifyQueryResults(db); } TEST_F(BundleTest, CanLoadBundlesWithProgressUpdates) { Firestore* db = TestFirestore(); auto bundle = CreateTestBundle(db); std::vector<LoadBundleTaskProgress> progresses; Future<LoadBundleTaskProgress> result = db->LoadBundle( bundle, [&progresses](const LoadBundleTaskProgress& progress) { progresses.push_back(progress); }); auto final_progress = AwaitResult(result); // 4 progresses will be reported: initial, document 1, document 2, final // success. ASSERT_EQ(progresses.size(), 4); EXPECT_THAT(progresses[0], InProgressWithLoadedDocuments(0)); EXPECT_THAT(progresses[1], InProgressWithLoadedDocuments(1)); EXPECT_THAT(progresses[2], InProgressWithLoadedDocuments(2)); VerifySuccessProgress(progresses[3]); EXPECT_EQ(progresses[3], final_progress); VerifyQueryResults(db); } TEST_F(BundleTest, CanDeleteFirestoreFromProgressUpdate) { Firestore* db = TestFirestore(); auto bundle = CreateTestBundle(db); std::promise<void> db_deleted; std::vector<LoadBundleTaskProgress> progresses; Future<LoadBundleTaskProgress> result = db->LoadBundle(bundle, [this, db, &progresses, &db_deleted]( const LoadBundleTaskProgress& progress) { progresses.push_back(progress); // Delete firestore before the final progress. if (progresses.size() == 3) { DeleteFirestore(db); db_deleted.set_value(); } }); // Wait for the notification that the instance is deleted before verifying. db_deleted.get_future().wait(); // This future is not completed, and returns back a nullptr for result when it // times out. EXPECT_EQ(Await(result), nullptr); // 3 progresses will be reported: initial, document 1, document 2. // Final progress update is missing because Firestore is deleted before that. ASSERT_EQ(progresses.size(), 3); EXPECT_THAT(progresses[0], InProgressWithLoadedDocuments(0)); EXPECT_THAT(progresses[1], InProgressWithLoadedDocuments(1)); EXPECT_THAT(progresses[2], InProgressWithLoadedDocuments(2)); } TEST_F(BundleTest, LoadBundlesForASecondTimeSkips) { // TODO(wuandy): This test fails on Windows CI, but // local run is fine. We need to figure out why and re-enable it. SKIP_TEST_ON_WINDOWS; Firestore* db = TestFirestore(); auto bundle = CreateTestBundle(db); LoadBundleTaskProgress first_load = AwaitResult(db->LoadBundle(bundle)); VerifySuccessProgress(first_load); std::vector<LoadBundleTaskProgress> progresses; LoadBundleTaskProgress second_load = AwaitResult(db->LoadBundle( bundle, [&progresses](const LoadBundleTaskProgress& progress) { progresses.push_back(progress); })); // There will be 4 progress updates if it does not skip loading. ASSERT_EQ(progresses.size(), 1); VerifySuccessProgress(progresses[0]); EXPECT_EQ(progresses[0], second_load); VerifyQueryResults(db); } TEST_F(BundleTest, LoadInvalidBundlesShouldFail) { // TODO(wuandy): This test fails on Windows CI, but // local run is fine. We need to figure out why and re-enable it. SKIP_TEST_ON_WINDOWS; Firestore* db = TestFirestore(); std::vector<std::string> invalid_bundles{ "invalid bundle obviously", "\"(╯°□°)╯︵ ┻━┻\"", "\xc3\x28" // random bytes }; for (const auto& bundle : invalid_bundles) { std::vector<LoadBundleTaskProgress> progresses; Future<LoadBundleTaskProgress> result = db->LoadBundle( bundle, [&progresses](const LoadBundleTaskProgress& progress) { progresses.push_back(progress); }); Await(result); EXPECT_NE(result.error(), Error::kErrorOk); ASSERT_EQ(progresses.size(), 1); VerifyErrorProgress(progresses[0]); } } TEST_F(BundleTest, LoadBundleWithDocumentsAlreadyPulledFromBackend) { Firestore* db = TestFirestore(); auto collection = db->Collection("coll-1"); WriteDocuments(collection, { {"a", {{"bar", FieldValue::String("newValueA")}}}, {"b", {{"bar", FieldValue::String("newValueB")}}}, }); EventAccumulator<QuerySnapshot> accumulator; ListenerRegistration limit_registration = accumulator.listener()->AttachTo(&collection); accumulator.AwaitRemoteEvent(); // The test bundle is holding ancient documents, so no events are generated as // a result. The case where a bundle has newer doc than cache can only be // tested in spec tests. accumulator.FailOnNextEvent(); auto bundle = CreateTestBundle(db); VerifySuccessProgress(AwaitResult(db->LoadBundle(bundle))); EXPECT_THAT(QuerySnapshotToValues(*Await(collection.Get(Source::kCache))), testing::ElementsAre( MapFieldValue{{"bar", FieldValue::String("newValueA")}}, MapFieldValue{{"bar", FieldValue::String("newValueB")}})); { Query limit = AwaitResult(db->NamedQuery(kLimitQueryName)); EXPECT_THAT(QuerySnapshotToValues(AwaitResult(limit.Get(Source::kCache))), testing::ElementsAre( MapFieldValue{{"bar", FieldValue::String("newValueB")}})); } { Query limit_to_last = AwaitResult(db->NamedQuery(kLimitToLastQueryName)); EXPECT_THAT( QuerySnapshotToValues(AwaitResult(limit_to_last.Get(Source::kCache))), testing::ElementsAre( MapFieldValue{{"bar", FieldValue::String("newValueA")}})); } } TEST_F(BundleTest, LoadedDocumentsShouldNotBeGarbageCollectedRightAway) { Firestore* db = TestFirestore(); // This test really only makes sense with memory persistence, as disk // persistence only ever lazily deletes data. auto new_settings = db->settings(); new_settings.set_persistence_enabled(false); db->set_settings(new_settings); auto bundle = CreateTestBundle(db); VerifySuccessProgress(AwaitResult(db->LoadBundle(bundle))); // Read a different collection. This will trigger GC. Await(db->Collection("coll-other").Get()); // Read the loaded documents, expecting them to exist in cache. With memory // GC, the documents would get GC-ed if we did not hold the document keys in // an "umbrella" target. See LocalStore for details. VerifyQueryResults(db); } TEST_F(BundleTest, LoadDocumentsFromOtherProjectsShouldFail) { Firestore* db = TestFirestore(); auto bundle = CreateBundle("other-project"); std::vector<LoadBundleTaskProgress> progresses; Future<LoadBundleTaskProgress> result = db->LoadBundle( bundle, [&progresses](const LoadBundleTaskProgress& progress) { progresses.push_back(progress); }); Await(result); EXPECT_NE(result.error(), Error::kErrorOk); ASSERT_EQ(progresses.size(), 2); EXPECT_THAT(progresses[0], InProgressWithLoadedDocuments(0)); VerifyErrorProgress(progresses[1]); } TEST_F(BundleTest, GetInvalidNamedQuery) { Firestore* db = TestFirestore(); { auto future = db->NamedQuery("DOES_NOT_EXIST"); Await(future); EXPECT_EQ(future.status(), FutureStatus::kFutureStatusComplete); EXPECT_EQ(future.error(), Error::kErrorNotFound); } { auto future = db->NamedQuery(""); Await(future); EXPECT_EQ(future.status(), FutureStatus::kFutureStatusComplete); EXPECT_EQ(future.error(), Error::kErrorNotFound); } { auto future = db->NamedQuery("\xc3\x28"); Await(future); EXPECT_EQ(future.status(), FutureStatus::kFutureStatusComplete); EXPECT_EQ(future.error(), Error::kErrorNotFound); } } } // namespace } // namespace firestore } // namespace firebase <commit_msg>Disable more bundles tests that fail in Windows CI (#440)<commit_after>#include <future> #include <string> #include <vector> #include "firebase/firestore.h" #include "firebase_test_framework.h" #include "firestore_integration_test.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "util/bundle_builder.h" #include "util/event_accumulator.h" #include "util/future_test_util.h" // These test cases are in sync with native iOS client SDK test // Firestore/Example/Tests/Integration/API/FIRBundlesTests.mm // and native Android client SDK test // firebase_firestore/tests/integration_tests/src/com/google/firebase/firestore/BundleTest.java // The iOS test names start with the mandatory test prefix while Android test // names do not. Here we use the Android test names. namespace firebase { namespace firestore { namespace { // Query names from the testing bundle in bundle_builder.cc constexpr char kLimitQueryName[] = "limit"; constexpr char kLimitToLastQueryName[] = "limit-to-last"; MATCHER_P( InProgressWithLoadedDocuments, expected_documents, std::string("Is a valid InProgress update with documents_loaded() == ") + std::to_string(expected_documents)) { std::string state_string = arg.state() == LoadBundleTaskProgress::State::kInProgress ? "kInProgress" : (arg.state() == LoadBundleTaskProgress::State::kError ? "kError" : "kSuccess"); *result_listener << "progress state() is " << state_string << " documents_loaded() is: " << arg.documents_loaded() << " total_documents() is: " << arg.total_documents() << " bytes_loaded() is: " << arg.bytes_loaded() << " total_bytes() is: " << arg.total_bytes(); return arg.state() == LoadBundleTaskProgress::State::kInProgress && arg.documents_loaded() == expected_documents && arg.documents_loaded() <= arg.total_documents() && arg.bytes_loaded() <= arg.total_bytes(); } void VerifySuccessProgress(LoadBundleTaskProgress progress) { EXPECT_EQ(progress.state(), LoadBundleTaskProgress::State::kSuccess); EXPECT_EQ(progress.documents_loaded(), progress.total_documents()); EXPECT_EQ(progress.bytes_loaded(), progress.total_bytes()); } void VerifyErrorProgress(LoadBundleTaskProgress progress) { EXPECT_EQ(progress.state(), LoadBundleTaskProgress::State::kError); EXPECT_EQ(progress.documents_loaded(), 0); EXPECT_EQ(progress.bytes_loaded(), 0); } std::string CreateTestBundle(Firestore* db) { return CreateBundle(db->app()->options().project_id()); } class BundleTest : public FirestoreIntegrationTest { protected: void SetUp() override { FirestoreIntegrationTest::SetUp(); // Clear the storage to avoid tests interfering with each other, since they // will be loading the same bundle file. ASSERT_THAT(TestFirestore()->ClearPersistence(), FutureSucceeds()); } template <typename T> T AwaitResult(const Future<T>& future) { auto* ptr = Await(future); EXPECT_NE(ptr, nullptr); // Return default instance instead of crashing. if (ptr == nullptr) { return {}; } return *ptr; } void VerifyQueryResults(Firestore* db) { { auto snapshot = AwaitResult(db->Collection("coll-1").Get(Source::kCache)); EXPECT_THAT( QuerySnapshotToValues(snapshot), testing::ElementsAre(MapFieldValue{{"k", FieldValue::String("a")}, {"bar", FieldValue::Integer(1)}}, MapFieldValue{{"k", FieldValue::String("b")}, {"bar", FieldValue::Integer(2)}})); } { Query limit = AwaitResult(db->NamedQuery(kLimitQueryName)); auto limit_snapshot = AwaitResult(limit.Get(Source::kCache)); EXPECT_THAT( QuerySnapshotToValues(limit_snapshot), testing::ElementsAre(MapFieldValue{{"k", FieldValue::String("b")}, {"bar", FieldValue::Integer(2)}})); } { Query limit_to_last = AwaitResult(db->NamedQuery(kLimitToLastQueryName)); auto limit_to_last_snapshot = AwaitResult(limit_to_last.Get(Source::kCache)); EXPECT_THAT( QuerySnapshotToValues(limit_to_last_snapshot), testing::ElementsAre(MapFieldValue{{"k", FieldValue::String("a")}, {"bar", FieldValue::Integer(1)}})); } } }; TEST_F(BundleTest, CanLoadBundlesWithoutProgressUpdates) { Firestore* db = TestFirestore(); auto bundle = CreateTestBundle(db); Future<LoadBundleTaskProgress> result = db->LoadBundle(bundle); VerifySuccessProgress(AwaitResult(result)); VerifyQueryResults(db); } TEST_F(BundleTest, CanLoadBundlesWithProgressUpdates) { Firestore* db = TestFirestore(); auto bundle = CreateTestBundle(db); std::vector<LoadBundleTaskProgress> progresses; Future<LoadBundleTaskProgress> result = db->LoadBundle( bundle, [&progresses](const LoadBundleTaskProgress& progress) { progresses.push_back(progress); }); auto final_progress = AwaitResult(result); // 4 progresses will be reported: initial, document 1, document 2, final // success. ASSERT_EQ(progresses.size(), 4); EXPECT_THAT(progresses[0], InProgressWithLoadedDocuments(0)); EXPECT_THAT(progresses[1], InProgressWithLoadedDocuments(1)); EXPECT_THAT(progresses[2], InProgressWithLoadedDocuments(2)); VerifySuccessProgress(progresses[3]); EXPECT_EQ(progresses[3], final_progress); VerifyQueryResults(db); } TEST_F(BundleTest, CanDeleteFirestoreFromProgressUpdate) { Firestore* db = TestFirestore(); auto bundle = CreateTestBundle(db); std::promise<void> db_deleted; std::vector<LoadBundleTaskProgress> progresses; Future<LoadBundleTaskProgress> result = db->LoadBundle(bundle, [this, db, &progresses, &db_deleted]( const LoadBundleTaskProgress& progress) { progresses.push_back(progress); // Delete firestore before the final progress. if (progresses.size() == 3) { DeleteFirestore(db); db_deleted.set_value(); } }); // Wait for the notification that the instance is deleted before verifying. db_deleted.get_future().wait(); // This future is not completed, and returns back a nullptr for result when it // times out. EXPECT_EQ(Await(result), nullptr); // 3 progresses will be reported: initial, document 1, document 2. // Final progress update is missing because Firestore is deleted before that. ASSERT_EQ(progresses.size(), 3); EXPECT_THAT(progresses[0], InProgressWithLoadedDocuments(0)); EXPECT_THAT(progresses[1], InProgressWithLoadedDocuments(1)); EXPECT_THAT(progresses[2], InProgressWithLoadedDocuments(2)); } TEST_F(BundleTest, LoadBundlesForASecondTimeSkips) { // TODO(wuandy): This test fails on Windows CI, but // local run is fine. We need to figure out why and re-enable it. SKIP_TEST_ON_WINDOWS; Firestore* db = TestFirestore(); auto bundle = CreateTestBundle(db); LoadBundleTaskProgress first_load = AwaitResult(db->LoadBundle(bundle)); VerifySuccessProgress(first_load); std::vector<LoadBundleTaskProgress> progresses; LoadBundleTaskProgress second_load = AwaitResult(db->LoadBundle( bundle, [&progresses](const LoadBundleTaskProgress& progress) { progresses.push_back(progress); })); // There will be 4 progress updates if it does not skip loading. ASSERT_EQ(progresses.size(), 1); VerifySuccessProgress(progresses[0]); EXPECT_EQ(progresses[0], second_load); VerifyQueryResults(db); } TEST_F(BundleTest, LoadInvalidBundlesShouldFail) { // TODO(wuandy): This test fails on Windows CI, but // local run is fine. We need to figure out why and re-enable it. SKIP_TEST_ON_WINDOWS; Firestore* db = TestFirestore(); std::vector<std::string> invalid_bundles{ "invalid bundle obviously", "\"(╯°□°)╯︵ ┻━┻\"", "\xc3\x28" // random bytes }; for (const auto& bundle : invalid_bundles) { std::vector<LoadBundleTaskProgress> progresses; Future<LoadBundleTaskProgress> result = db->LoadBundle( bundle, [&progresses](const LoadBundleTaskProgress& progress) { progresses.push_back(progress); }); Await(result); EXPECT_NE(result.error(), Error::kErrorOk); ASSERT_EQ(progresses.size(), 1); VerifyErrorProgress(progresses[0]); } } TEST_F(BundleTest, LoadBundleWithDocumentsAlreadyPulledFromBackend) { // TODO(wuandy, b/189477267): This test fails on Windows CI, but // local run is fine. We need to figure out why and re-enable it. SKIP_TEST_ON_WINDOWS; Firestore* db = TestFirestore(); auto collection = db->Collection("coll-1"); WriteDocuments(collection, { {"a", {{"bar", FieldValue::String("newValueA")}}}, {"b", {{"bar", FieldValue::String("newValueB")}}}, }); EventAccumulator<QuerySnapshot> accumulator; ListenerRegistration limit_registration = accumulator.listener()->AttachTo(&collection); accumulator.AwaitRemoteEvent(); // The test bundle is holding ancient documents, so no events are generated as // a result. The case where a bundle has newer doc than cache can only be // tested in spec tests. accumulator.FailOnNextEvent(); auto bundle = CreateTestBundle(db); VerifySuccessProgress(AwaitResult(db->LoadBundle(bundle))); EXPECT_THAT(QuerySnapshotToValues(*Await(collection.Get(Source::kCache))), testing::ElementsAre( MapFieldValue{{"bar", FieldValue::String("newValueA")}}, MapFieldValue{{"bar", FieldValue::String("newValueB")}})); { Query limit = AwaitResult(db->NamedQuery(kLimitQueryName)); EXPECT_THAT(QuerySnapshotToValues(AwaitResult(limit.Get(Source::kCache))), testing::ElementsAre( MapFieldValue{{"bar", FieldValue::String("newValueB")}})); } { Query limit_to_last = AwaitResult(db->NamedQuery(kLimitToLastQueryName)); EXPECT_THAT( QuerySnapshotToValues(AwaitResult(limit_to_last.Get(Source::kCache))), testing::ElementsAre( MapFieldValue{{"bar", FieldValue::String("newValueA")}})); } } TEST_F(BundleTest, LoadedDocumentsShouldNotBeGarbageCollectedRightAway) { // TODO(wuandy, b/189477267): This test fails on Windows CI, but // local run is fine. We need to figure out why and re-enable it. SKIP_TEST_ON_WINDOWS; Firestore* db = TestFirestore(); // This test really only makes sense with memory persistence, as disk // persistence only ever lazily deletes data. auto new_settings = db->settings(); new_settings.set_persistence_enabled(false); db->set_settings(new_settings); auto bundle = CreateTestBundle(db); VerifySuccessProgress(AwaitResult(db->LoadBundle(bundle))); // Read a different collection. This will trigger GC. Await(db->Collection("coll-other").Get()); // Read the loaded documents, expecting them to exist in cache. With memory // GC, the documents would get GC-ed if we did not hold the document keys in // an "umbrella" target. See LocalStore for details. VerifyQueryResults(db); } TEST_F(BundleTest, LoadDocumentsFromOtherProjectsShouldFail) { Firestore* db = TestFirestore(); auto bundle = CreateBundle("other-project"); std::vector<LoadBundleTaskProgress> progresses; Future<LoadBundleTaskProgress> result = db->LoadBundle( bundle, [&progresses](const LoadBundleTaskProgress& progress) { progresses.push_back(progress); }); Await(result); EXPECT_NE(result.error(), Error::kErrorOk); ASSERT_EQ(progresses.size(), 2); EXPECT_THAT(progresses[0], InProgressWithLoadedDocuments(0)); VerifyErrorProgress(progresses[1]); } TEST_F(BundleTest, GetInvalidNamedQuery) { Firestore* db = TestFirestore(); { auto future = db->NamedQuery("DOES_NOT_EXIST"); Await(future); EXPECT_EQ(future.status(), FutureStatus::kFutureStatusComplete); EXPECT_EQ(future.error(), Error::kErrorNotFound); } { auto future = db->NamedQuery(""); Await(future); EXPECT_EQ(future.status(), FutureStatus::kFutureStatusComplete); EXPECT_EQ(future.error(), Error::kErrorNotFound); } { auto future = db->NamedQuery("\xc3\x28"); Await(future); EXPECT_EQ(future.status(), FutureStatus::kFutureStatusComplete); EXPECT_EQ(future.error(), Error::kErrorNotFound); } } } // namespace } // namespace firestore } // namespace firebase <|endoftext|>
<commit_before>#include <gmock/gmock.h> #include <string> #include <utility> #include <vector> #include "action/action_service_impl.h" #include "action/mocks/action_mock.h" namespace { using testing::_; using testing::NiceMock; using testing::Return; using MockAction = NiceMock<dronecode_sdk::testing::MockAction>; using ActionServiceImpl = dronecode_sdk::backend::ActionServiceImpl<MockAction>; using ActionResult = dronecode_sdk::rpc::action::ActionResult; using InputPair = std::pair<std::string, dronecode_sdk::ActionResult>; static constexpr float ARBITRARY_ALTITUDE = 42.42f; static constexpr float ARBITRARY_SPEED = 8.24f; std::vector<InputPair> generateInputPairs(); std::string armAndGetTranslatedResult(dronecode_sdk::ActionResult arm_result); std::string disarmAndGetTranslatedResult(dronecode_sdk::ActionResult disarm_result); std::string takeoffAndGetTranslatedResult(dronecode_sdk::ActionResult takeoff_result); std::string landAndGetTranslatedResult(dronecode_sdk::ActionResult land_result); std::string killAndGetTranslatedResult(dronecode_sdk::ActionResult kill_result); std::string returnToLaunchAndGetTranslatedResult(dronecode_sdk::ActionResult rtl_result); std::string transitionToFWAndGetTranslatedResult(const dronecode_sdk::ActionResult transition_to_fw_result); std::string transitionToMCAndGetTranslatedResult(const dronecode_sdk::ActionResult transition_to_fw_result); class ActionServiceImplTest : public ::testing::TestWithParam<InputPair> {}; TEST_P(ActionServiceImplTest, armResultIsTranslatedCorrectly) { const auto rpc_result = armAndGetTranslatedResult(GetParam().second); EXPECT_EQ(rpc_result, GetParam().first); } std::string armAndGetTranslatedResult(const dronecode_sdk::ActionResult arm_result) { MockAction action; ON_CALL(action, arm()).WillByDefault(Return(arm_result)); ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::ArmResponse response; actionService.Arm(nullptr, nullptr, &response); return ActionResult::Result_Name(response.action_result().result()); } TEST_F(ActionServiceImplTest, armsEvenWhenArgsAreNull) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, arm()).Times(1); actionService.Arm(nullptr, nullptr, nullptr); } TEST_P(ActionServiceImplTest, disarmResultIsTranslatedCorrectly) { const auto rpc_result = disarmAndGetTranslatedResult(GetParam().second); EXPECT_EQ(rpc_result, GetParam().first); } std::string disarmAndGetTranslatedResult(dronecode_sdk::ActionResult disarm_result) { MockAction action; ON_CALL(action, disarm()).WillByDefault(Return(disarm_result)); ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::DisarmResponse response; actionService.Disarm(nullptr, nullptr, &response); return ActionResult::Result_Name(response.action_result().result()); } TEST_F(ActionServiceImplTest, disarmsEvenWhenArgsAreNull) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, disarm()).Times(1); actionService.Disarm(nullptr, nullptr, nullptr); } TEST_P(ActionServiceImplTest, takeoffResultIsTranslatedCorrectly) { const auto rpc_result = takeoffAndGetTranslatedResult(GetParam().second); EXPECT_EQ(rpc_result, GetParam().first); } std::string takeoffAndGetTranslatedResult(const dronecode_sdk::ActionResult takeoff_result) { MockAction action; ON_CALL(action, takeoff()).WillByDefault(Return(takeoff_result)); ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::TakeoffResponse response; actionService.Takeoff(nullptr, nullptr, &response); return ActionResult::Result_Name(response.action_result().result()); } TEST_F(ActionServiceImplTest, takeoffEvenWhenArgsAreNull) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, takeoff()).Times(1); actionService.Takeoff(nullptr, nullptr, nullptr); } TEST_P(ActionServiceImplTest, landResultIsTranslatedCorrectly) { const auto rpc_result = landAndGetTranslatedResult(GetParam().second); EXPECT_EQ(rpc_result, GetParam().first); } std::string landAndGetTranslatedResult(const dronecode_sdk::ActionResult land_result) { MockAction action; ON_CALL(action, land()).WillByDefault(Return(land_result)); ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::LandResponse response; actionService.Land(nullptr, nullptr, &response); return ActionResult::Result_Name(response.action_result().result()); } TEST_F(ActionServiceImplTest, landsEvenWhenArgsAreNull) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, land()).Times(1); actionService.Land(nullptr, nullptr, nullptr); } TEST_P(ActionServiceImplTest, killResultIsTranslatedCorrectly) { const auto rpc_result = killAndGetTranslatedResult(GetParam().second); EXPECT_EQ(rpc_result, GetParam().first); } std::string killAndGetTranslatedResult(const dronecode_sdk::ActionResult kill_result) { MockAction action; ON_CALL(action, kill()).WillByDefault(Return(kill_result)); ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::KillResponse response; actionService.Kill(nullptr, nullptr, &response); return ActionResult::Result_Name(response.action_result().result()); } TEST_F(ActionServiceImplTest, killsEvenWhenArgsAreNull) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, kill()).Times(1); actionService.Kill(nullptr, nullptr, nullptr); } TEST_P(ActionServiceImplTest, rtlResultIsTranslatedCorrectly) { const auto rpc_result = returnToLaunchAndGetTranslatedResult(GetParam().second); EXPECT_EQ(rpc_result, GetParam().first); } std::string returnToLaunchAndGetTranslatedResult(const dronecode_sdk::ActionResult rtl_result) { MockAction action; ON_CALL(action, return_to_launch()).WillByDefault(Return(rtl_result)); ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::ReturnToLaunchResponse response; actionService.ReturnToLaunch(nullptr, nullptr, &response); return ActionResult::Result_Name(response.action_result().result()); } TEST_F(ActionServiceImplTest, rtlsEvenWhenArgsAreNull) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, return_to_launch()).Times(1); actionService.ReturnToLaunch(nullptr, nullptr, nullptr); } TEST_P(ActionServiceImplTest, transition2fwResultIsTranslatedCorrectly) { const auto rpc_result = transitionToFWAndGetTranslatedResult(GetParam().second); EXPECT_EQ(rpc_result, GetParam().first); } std::string transitionToFWAndGetTranslatedResult(const dronecode_sdk::ActionResult transition_to_fw_result) { MockAction action; ON_CALL(action, transition_to_fixedwing()).WillByDefault(Return(transition_to_fw_result)); ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::TransitionToFixedWingResponse response; actionService.TransitionToFixedWing(nullptr, nullptr, &response); return ActionResult::Result_Name(response.action_result().result()); } TEST_F(ActionServiceImplTest, transitions2fwEvenWhenArgsAreNull) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, transition_to_fixedwing()).Times(1); actionService.TransitionToFixedWing(nullptr, nullptr, nullptr); } TEST_P(ActionServiceImplTest, transition2mcResultIsTranslatedCorrectly) { const auto rpc_result = transitionToMCAndGetTranslatedResult(GetParam().second); EXPECT_EQ(rpc_result, GetParam().first); } std::string transitionToMCAndGetTranslatedResult(const dronecode_sdk::ActionResult transition_to_mc_result) { MockAction action; ON_CALL(action, transition_to_multicopter()).WillByDefault(Return(transition_to_mc_result)); ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::TransitionToMulticopterResponse response; actionService.TransitionToMulticopter(nullptr, nullptr, &response); return ActionResult::Result_Name(response.action_result().result()); } TEST_F(ActionServiceImplTest, transitions2mcEvenWhenArgsAreNull) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, transition_to_multicopter()).Times(1); actionService.TransitionToMulticopter(nullptr, nullptr, nullptr); } TEST_F(ActionServiceImplTest, getTakeoffAltitudeCallsGetter) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, get_takeoff_altitude()).Times(1); dronecode_sdk::rpc::action::GetTakeoffAltitudeResponse response; actionService.GetTakeoffAltitude(nullptr, nullptr, &response); } TEST_P(ActionServiceImplTest, getsCorrectTakeoffAltitude) { MockAction action; ActionServiceImpl actionService(action); const auto expected_pair = std::make_pair<>(dronecode_sdk::ActionResult::SUCCESS, ARBITRARY_ALTITUDE); ON_CALL(action, get_takeoff_altitude()).WillByDefault(Return(expected_pair)); dronecode_sdk::rpc::action::GetTakeoffAltitudeResponse response; actionService.GetTakeoffAltitude(nullptr, nullptr, &response); EXPECT_EQ(GetParam().first, ActionResult::Result_Name(response.action_result().result())); EXPECT_EQ(expected_pair.second, response.altitude()); } TEST_F(ActionServiceImplTest, getTakeoffAltitudeDoesNotCrashWithNullResponse) { MockAction action; ActionServiceImpl actionService(action); actionService.GetTakeoffAltitude(nullptr, nullptr, nullptr); } TEST_F(ActionServiceImplTest, setTakeoffAltitudeDoesNotCrashWithNullRequest) { MockAction action; ActionServiceImpl actionService(action); actionService.SetTakeoffAltitude(nullptr, nullptr, nullptr); } TEST_F(ActionServiceImplTest, setTakeoffAltitudeCallsSetter) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, set_takeoff_altitude(_)).Times(1); dronecode_sdk::rpc::action::SetTakeoffAltitudeRequest request; actionService.SetTakeoffAltitude(nullptr, &request, nullptr); } TEST_P(ActionServiceImplTest, setTakeoffAltitudeSetsRightValue) { MockAction action; ActionServiceImpl actionService(action); float expected_altitude = ARBITRARY_ALTITUDE; EXPECT_CALL(action, set_takeoff_altitude(expected_altitude)).Times(1); dronecode_sdk::rpc::action::SetTakeoffAltitudeRequest request; request.set_altitude(expected_altitude); actionService.SetTakeoffAltitude(nullptr, &request, nullptr); } TEST_F(ActionServiceImplTest, getMaxSpeedDoesNotCrashWithNullResponse) { MockAction action; ActionServiceImpl actionService(action); actionService.GetMaximumSpeed(nullptr, nullptr, nullptr); } TEST_F(ActionServiceImplTest, getMaxSpeedCallsGetter) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, get_max_speed()).Times(1); dronecode_sdk::rpc::action::GetMaximumSpeedResponse response; actionService.GetMaximumSpeed(nullptr, nullptr, &response); } TEST_P(ActionServiceImplTest, getMaxSpeedGetsRightValue) { MockAction action; ActionServiceImpl actionService(action); const auto expected_pair = std::make_pair<>(dronecode_sdk::ActionResult::SUCCESS, ARBITRARY_SPEED); ON_CALL(action, get_max_speed()).WillByDefault(Return(expected_pair)); dronecode_sdk::rpc::action::GetMaximumSpeedResponse response; actionService.GetMaximumSpeed(nullptr, nullptr, &response); EXPECT_EQ(GetParam().first, ActionResult::Result_Name(response.action_result().result())); EXPECT_EQ(expected_pair.second, response.speed()); } TEST_F(ActionServiceImplTest, setMaxSpeedDoesNotCrashWithNullRequest) { MockAction action; ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::SetMaximumSpeedResponse response; actionService.SetMaximumSpeed(nullptr, nullptr, &response); } TEST_F(ActionServiceImplTest, setMaxSpeedDoesNotCrashWithNullResponse) { MockAction action; ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::SetMaximumSpeedRequest request; request.set_speed(ARBITRARY_SPEED); actionService.SetMaximumSpeed(nullptr, &request, nullptr); } TEST_F(ActionServiceImplTest, setMaxSpeedCallsSetter) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, set_max_speed(_)).Times(1); dronecode_sdk::rpc::action::SetMaximumSpeedRequest request; actionService.SetMaximumSpeed(nullptr, &request, nullptr); } TEST_F(ActionServiceImplTest, setMaxSpeedSetsRightValue) { MockAction action; ActionServiceImpl actionService(action); const auto expected_speed = ARBITRARY_SPEED; EXPECT_CALL(action, set_max_speed(expected_speed)).Times(1); dronecode_sdk::rpc::action::SetMaximumSpeedRequest request; request.set_speed(expected_speed); actionService.SetMaximumSpeed(nullptr, &request, nullptr); } INSTANTIATE_TEST_CASE_P(ActionResultCorrespondences, ActionServiceImplTest, ::testing::ValuesIn(generateInputPairs())); std::vector<InputPair> generateInputPairs() { std::vector<InputPair> input_pairs; input_pairs.push_back(std::make_pair("SUCCESS", dronecode_sdk::ActionResult::SUCCESS)); input_pairs.push_back(std::make_pair("NO_SYSTEM", dronecode_sdk::ActionResult::NO_SYSTEM)); input_pairs.push_back( std::make_pair("CONNECTION_ERROR", dronecode_sdk::ActionResult::CONNECTION_ERROR)); input_pairs.push_back(std::make_pair("BUSY", dronecode_sdk::ActionResult::BUSY)); input_pairs.push_back( std::make_pair("COMMAND_DENIED", dronecode_sdk::ActionResult::COMMAND_DENIED)); input_pairs.push_back( std::make_pair("COMMAND_DENIED_LANDED_STATE_UNKNOWN", dronecode_sdk::ActionResult::COMMAND_DENIED_LANDED_STATE_UNKNOWN)); input_pairs.push_back(std::make_pair("COMMAND_DENIED_NOT_LANDED", dronecode_sdk::ActionResult::COMMAND_DENIED_NOT_LANDED)); input_pairs.push_back(std::make_pair("TIMEOUT", dronecode_sdk::ActionResult::TIMEOUT)); input_pairs.push_back( std::make_pair("VTOL_TRANSITION_SUPPORT_UNKNOWN", dronecode_sdk::ActionResult::VTOL_TRANSITION_SUPPORT_UNKNOWN)); input_pairs.push_back(std::make_pair("NO_VTOL_TRANSITION_SUPPORT", dronecode_sdk::ActionResult::NO_VTOL_TRANSITION_SUPPORT)); input_pairs.push_back(std::make_pair("UNKNOWN", dronecode_sdk::ActionResult::UNKNOWN)); return input_pairs; } } // namespace <commit_msg>backend: fix getsCorrectTakeoffAltitude and getMaxSpeedGetsRightValue unit tests<commit_after>#include <gmock/gmock.h> #include <string> #include <utility> #include <vector> #include "action/action_service_impl.h" #include "action/mocks/action_mock.h" namespace { using testing::_; using testing::NiceMock; using testing::Return; using MockAction = NiceMock<dronecode_sdk::testing::MockAction>; using ActionServiceImpl = dronecode_sdk::backend::ActionServiceImpl<MockAction>; using ActionResult = dronecode_sdk::rpc::action::ActionResult; using InputPair = std::pair<std::string, dronecode_sdk::ActionResult>; static constexpr float ARBITRARY_ALTITUDE = 42.42f; static constexpr float ARBITRARY_SPEED = 8.24f; std::vector<InputPair> generateInputPairs(); std::string armAndGetTranslatedResult(dronecode_sdk::ActionResult arm_result); std::string disarmAndGetTranslatedResult(dronecode_sdk::ActionResult disarm_result); std::string takeoffAndGetTranslatedResult(dronecode_sdk::ActionResult takeoff_result); std::string landAndGetTranslatedResult(dronecode_sdk::ActionResult land_result); std::string killAndGetTranslatedResult(dronecode_sdk::ActionResult kill_result); std::string returnToLaunchAndGetTranslatedResult(dronecode_sdk::ActionResult rtl_result); std::string transitionToFWAndGetTranslatedResult(const dronecode_sdk::ActionResult transition_to_fw_result); std::string transitionToMCAndGetTranslatedResult(const dronecode_sdk::ActionResult transition_to_fw_result); class ActionServiceImplTest : public ::testing::TestWithParam<InputPair> {}; TEST_P(ActionServiceImplTest, armResultIsTranslatedCorrectly) { const auto rpc_result = armAndGetTranslatedResult(GetParam().second); EXPECT_EQ(rpc_result, GetParam().first); } std::string armAndGetTranslatedResult(const dronecode_sdk::ActionResult arm_result) { MockAction action; ON_CALL(action, arm()).WillByDefault(Return(arm_result)); ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::ArmResponse response; actionService.Arm(nullptr, nullptr, &response); return ActionResult::Result_Name(response.action_result().result()); } TEST_F(ActionServiceImplTest, armsEvenWhenArgsAreNull) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, arm()).Times(1); actionService.Arm(nullptr, nullptr, nullptr); } TEST_P(ActionServiceImplTest, disarmResultIsTranslatedCorrectly) { const auto rpc_result = disarmAndGetTranslatedResult(GetParam().second); EXPECT_EQ(rpc_result, GetParam().first); } std::string disarmAndGetTranslatedResult(dronecode_sdk::ActionResult disarm_result) { MockAction action; ON_CALL(action, disarm()).WillByDefault(Return(disarm_result)); ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::DisarmResponse response; actionService.Disarm(nullptr, nullptr, &response); return ActionResult::Result_Name(response.action_result().result()); } TEST_F(ActionServiceImplTest, disarmsEvenWhenArgsAreNull) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, disarm()).Times(1); actionService.Disarm(nullptr, nullptr, nullptr); } TEST_P(ActionServiceImplTest, takeoffResultIsTranslatedCorrectly) { const auto rpc_result = takeoffAndGetTranslatedResult(GetParam().second); EXPECT_EQ(rpc_result, GetParam().first); } std::string takeoffAndGetTranslatedResult(const dronecode_sdk::ActionResult takeoff_result) { MockAction action; ON_CALL(action, takeoff()).WillByDefault(Return(takeoff_result)); ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::TakeoffResponse response; actionService.Takeoff(nullptr, nullptr, &response); return ActionResult::Result_Name(response.action_result().result()); } TEST_F(ActionServiceImplTest, takeoffEvenWhenArgsAreNull) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, takeoff()).Times(1); actionService.Takeoff(nullptr, nullptr, nullptr); } TEST_P(ActionServiceImplTest, landResultIsTranslatedCorrectly) { const auto rpc_result = landAndGetTranslatedResult(GetParam().second); EXPECT_EQ(rpc_result, GetParam().first); } std::string landAndGetTranslatedResult(const dronecode_sdk::ActionResult land_result) { MockAction action; ON_CALL(action, land()).WillByDefault(Return(land_result)); ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::LandResponse response; actionService.Land(nullptr, nullptr, &response); return ActionResult::Result_Name(response.action_result().result()); } TEST_F(ActionServiceImplTest, landsEvenWhenArgsAreNull) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, land()).Times(1); actionService.Land(nullptr, nullptr, nullptr); } TEST_P(ActionServiceImplTest, killResultIsTranslatedCorrectly) { const auto rpc_result = killAndGetTranslatedResult(GetParam().second); EXPECT_EQ(rpc_result, GetParam().first); } std::string killAndGetTranslatedResult(const dronecode_sdk::ActionResult kill_result) { MockAction action; ON_CALL(action, kill()).WillByDefault(Return(kill_result)); ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::KillResponse response; actionService.Kill(nullptr, nullptr, &response); return ActionResult::Result_Name(response.action_result().result()); } TEST_F(ActionServiceImplTest, killsEvenWhenArgsAreNull) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, kill()).Times(1); actionService.Kill(nullptr, nullptr, nullptr); } TEST_P(ActionServiceImplTest, rtlResultIsTranslatedCorrectly) { const auto rpc_result = returnToLaunchAndGetTranslatedResult(GetParam().second); EXPECT_EQ(rpc_result, GetParam().first); } std::string returnToLaunchAndGetTranslatedResult(const dronecode_sdk::ActionResult rtl_result) { MockAction action; ON_CALL(action, return_to_launch()).WillByDefault(Return(rtl_result)); ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::ReturnToLaunchResponse response; actionService.ReturnToLaunch(nullptr, nullptr, &response); return ActionResult::Result_Name(response.action_result().result()); } TEST_F(ActionServiceImplTest, rtlsEvenWhenArgsAreNull) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, return_to_launch()).Times(1); actionService.ReturnToLaunch(nullptr, nullptr, nullptr); } TEST_P(ActionServiceImplTest, transition2fwResultIsTranslatedCorrectly) { const auto rpc_result = transitionToFWAndGetTranslatedResult(GetParam().second); EXPECT_EQ(rpc_result, GetParam().first); } std::string transitionToFWAndGetTranslatedResult(const dronecode_sdk::ActionResult transition_to_fw_result) { MockAction action; ON_CALL(action, transition_to_fixedwing()).WillByDefault(Return(transition_to_fw_result)); ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::TransitionToFixedWingResponse response; actionService.TransitionToFixedWing(nullptr, nullptr, &response); return ActionResult::Result_Name(response.action_result().result()); } TEST_F(ActionServiceImplTest, transitions2fwEvenWhenArgsAreNull) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, transition_to_fixedwing()).Times(1); actionService.TransitionToFixedWing(nullptr, nullptr, nullptr); } TEST_P(ActionServiceImplTest, transition2mcResultIsTranslatedCorrectly) { const auto rpc_result = transitionToMCAndGetTranslatedResult(GetParam().second); EXPECT_EQ(rpc_result, GetParam().first); } std::string transitionToMCAndGetTranslatedResult(const dronecode_sdk::ActionResult transition_to_mc_result) { MockAction action; ON_CALL(action, transition_to_multicopter()).WillByDefault(Return(transition_to_mc_result)); ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::TransitionToMulticopterResponse response; actionService.TransitionToMulticopter(nullptr, nullptr, &response); return ActionResult::Result_Name(response.action_result().result()); } TEST_F(ActionServiceImplTest, transitions2mcEvenWhenArgsAreNull) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, transition_to_multicopter()).Times(1); actionService.TransitionToMulticopter(nullptr, nullptr, nullptr); } TEST_F(ActionServiceImplTest, getTakeoffAltitudeCallsGetter) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, get_takeoff_altitude()).Times(1); dronecode_sdk::rpc::action::GetTakeoffAltitudeResponse response; actionService.GetTakeoffAltitude(nullptr, nullptr, &response); } TEST_P(ActionServiceImplTest, getsCorrectTakeoffAltitude) { MockAction action; ActionServiceImpl actionService(action); const auto expected_pair = std::make_pair<>(GetParam().second, ARBITRARY_ALTITUDE); ON_CALL(action, get_takeoff_altitude()).WillByDefault(Return(expected_pair)); dronecode_sdk::rpc::action::GetTakeoffAltitudeResponse response; actionService.GetTakeoffAltitude(nullptr, nullptr, &response); EXPECT_EQ(GetParam().first, ActionResult::Result_Name(response.action_result().result())); EXPECT_EQ(expected_pair.second, response.altitude()); } TEST_F(ActionServiceImplTest, getTakeoffAltitudeDoesNotCrashWithNullResponse) { MockAction action; ActionServiceImpl actionService(action); actionService.GetTakeoffAltitude(nullptr, nullptr, nullptr); } TEST_F(ActionServiceImplTest, setTakeoffAltitudeDoesNotCrashWithNullRequest) { MockAction action; ActionServiceImpl actionService(action); actionService.SetTakeoffAltitude(nullptr, nullptr, nullptr); } TEST_F(ActionServiceImplTest, setTakeoffAltitudeCallsSetter) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, set_takeoff_altitude(_)).Times(1); dronecode_sdk::rpc::action::SetTakeoffAltitudeRequest request; actionService.SetTakeoffAltitude(nullptr, &request, nullptr); } TEST_P(ActionServiceImplTest, setTakeoffAltitudeSetsRightValue) { MockAction action; ActionServiceImpl actionService(action); float expected_altitude = ARBITRARY_ALTITUDE; EXPECT_CALL(action, set_takeoff_altitude(expected_altitude)).Times(1); dronecode_sdk::rpc::action::SetTakeoffAltitudeRequest request; request.set_altitude(expected_altitude); actionService.SetTakeoffAltitude(nullptr, &request, nullptr); } TEST_F(ActionServiceImplTest, getMaxSpeedDoesNotCrashWithNullResponse) { MockAction action; ActionServiceImpl actionService(action); actionService.GetMaximumSpeed(nullptr, nullptr, nullptr); } TEST_F(ActionServiceImplTest, getMaxSpeedCallsGetter) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, get_max_speed()).Times(1); dronecode_sdk::rpc::action::GetMaximumSpeedResponse response; actionService.GetMaximumSpeed(nullptr, nullptr, &response); } TEST_P(ActionServiceImplTest, getMaxSpeedGetsRightValue) { MockAction action; ActionServiceImpl actionService(action); const auto expected_pair = std::make_pair<>(GetParam().second, ARBITRARY_SPEED); ON_CALL(action, get_max_speed()).WillByDefault(Return(expected_pair)); dronecode_sdk::rpc::action::GetMaximumSpeedResponse response; actionService.GetMaximumSpeed(nullptr, nullptr, &response); EXPECT_EQ(GetParam().first, ActionResult::Result_Name(response.action_result().result())); EXPECT_EQ(expected_pair.second, response.speed()); } TEST_F(ActionServiceImplTest, setMaxSpeedDoesNotCrashWithNullRequest) { MockAction action; ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::SetMaximumSpeedResponse response; actionService.SetMaximumSpeed(nullptr, nullptr, &response); } TEST_F(ActionServiceImplTest, setMaxSpeedDoesNotCrashWithNullResponse) { MockAction action; ActionServiceImpl actionService(action); dronecode_sdk::rpc::action::SetMaximumSpeedRequest request; request.set_speed(ARBITRARY_SPEED); actionService.SetMaximumSpeed(nullptr, &request, nullptr); } TEST_F(ActionServiceImplTest, setMaxSpeedCallsSetter) { MockAction action; ActionServiceImpl actionService(action); EXPECT_CALL(action, set_max_speed(_)).Times(1); dronecode_sdk::rpc::action::SetMaximumSpeedRequest request; actionService.SetMaximumSpeed(nullptr, &request, nullptr); } TEST_F(ActionServiceImplTest, setMaxSpeedSetsRightValue) { MockAction action; ActionServiceImpl actionService(action); const auto expected_speed = ARBITRARY_SPEED; EXPECT_CALL(action, set_max_speed(expected_speed)).Times(1); dronecode_sdk::rpc::action::SetMaximumSpeedRequest request; request.set_speed(expected_speed); actionService.SetMaximumSpeed(nullptr, &request, nullptr); } INSTANTIATE_TEST_CASE_P(ActionResultCorrespondences, ActionServiceImplTest, ::testing::ValuesIn(generateInputPairs())); std::vector<InputPair> generateInputPairs() { std::vector<InputPair> input_pairs; input_pairs.push_back(std::make_pair("SUCCESS", dronecode_sdk::ActionResult::SUCCESS)); input_pairs.push_back(std::make_pair("NO_SYSTEM", dronecode_sdk::ActionResult::NO_SYSTEM)); input_pairs.push_back( std::make_pair("CONNECTION_ERROR", dronecode_sdk::ActionResult::CONNECTION_ERROR)); input_pairs.push_back(std::make_pair("BUSY", dronecode_sdk::ActionResult::BUSY)); input_pairs.push_back( std::make_pair("COMMAND_DENIED", dronecode_sdk::ActionResult::COMMAND_DENIED)); input_pairs.push_back( std::make_pair("COMMAND_DENIED_LANDED_STATE_UNKNOWN", dronecode_sdk::ActionResult::COMMAND_DENIED_LANDED_STATE_UNKNOWN)); input_pairs.push_back(std::make_pair("COMMAND_DENIED_NOT_LANDED", dronecode_sdk::ActionResult::COMMAND_DENIED_NOT_LANDED)); input_pairs.push_back(std::make_pair("TIMEOUT", dronecode_sdk::ActionResult::TIMEOUT)); input_pairs.push_back( std::make_pair("VTOL_TRANSITION_SUPPORT_UNKNOWN", dronecode_sdk::ActionResult::VTOL_TRANSITION_SUPPORT_UNKNOWN)); input_pairs.push_back(std::make_pair("NO_VTOL_TRANSITION_SUPPORT", dronecode_sdk::ActionResult::NO_VTOL_TRANSITION_SUPPORT)); input_pairs.push_back(std::make_pair("UNKNOWN", dronecode_sdk::ActionResult::UNKNOWN)); return input_pairs; } } // namespace <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "precompiled_configmgr.hxx" #include "sal/config.h" #include <vector> #include "com/sun/star/container/XChild.hpp" #include "com/sun/star/lang/NoSupportException.hpp" #include "com/sun/star/lang/XUnoTunnel.hpp" #include "com/sun/star/uno/Any.hxx" #include "com/sun/star/uno/Reference.hxx" #include "com/sun/star/uno/RuntimeException.hpp" #include "com/sun/star/uno/Sequence.hxx" #include "com/sun/star/uno/Type.hxx" #include "com/sun/star/uno/XInterface.hpp" #include "cppu/unotype.hxx" #include "cppuhelper/queryinterface.hxx" #include "cppuhelper/weak.hxx" #include "osl/diagnose.h" #include "osl/mutex.hxx" #include "rtl/ref.hxx" #include "rtl/string.h" #include "rtl/ustrbuf.hxx" #include "rtl/ustring.h" #include "rtl/ustring.hxx" #include "rtl/uuid.h" #include "sal/types.h" #include "access.hxx" #include "childaccess.hxx" #include "components.hxx" #include "data.hxx" #include "groupnode.hxx" #include "localizedpropertynode.hxx" #include "localizedvaluenode.hxx" #include "lock.hxx" #include "modifications.hxx" #include "node.hxx" #include "path.hxx" #include "propertynode.hxx" #include "rootaccess.hxx" #include "setnode.hxx" #include "type.hxx" namespace configmgr { namespace { namespace css = com::sun::star; } css::uno::Sequence< sal_Int8 > ChildAccess::getTunnelId() { static css::uno::Sequence< sal_Int8 > id; if (id.getLength() == 0) { css::uno::Sequence< sal_Int8 > uuid(16); rtl_createUuid( reinterpret_cast< sal_uInt8 * >(uuid.getArray()), 0, false); id = uuid; } return id; } ChildAccess::ChildAccess( Components & components, rtl::Reference< RootAccess > const & root, rtl::Reference< Access > const & parent, rtl::OUString const & name, rtl::Reference< Node > const & node): Access(components), root_(root), parent_(parent), name_(name), node_(node), inTransaction_(false) { lock_ = lock(); OSL_ASSERT(root.is() && parent.is() && node.is()); } ChildAccess::ChildAccess( Components & components, rtl::Reference< RootAccess > const & root, rtl::Reference< Node > const & node): Access(components), root_(root), node_(node), inTransaction_(false) { lock_ = lock(); OSL_ASSERT(root.is() && node.is()); } Path ChildAccess::getAbsolutePath() { OSL_ASSERT(getParentAccess().is()); Path path(getParentAccess()->getAbsolutePath()); path.push_back(name_); return path; } Path ChildAccess::getRelativePath() { Path path; rtl::Reference< Access > parent(getParentAccess()); if (parent.is()) { path = parent->getRelativePath(); } path.push_back(name_); return path; } rtl::OUString ChildAccess::getRelativePathRepresentation() { rtl::OUStringBuffer path; rtl::Reference< Access > parent(getParentAccess()); if (parent.is()) { path.append(parent->getRelativePathRepresentation()); if (path.getLength() != 0) { path.append(sal_Unicode('/')); } } path.append(Data::createSegment(node_->getTemplateName(), name_)); return path.makeStringAndClear(); } rtl::Reference< Node > ChildAccess::getNode() { return node_; } bool ChildAccess::isFinalized() { return node_->getFinalized() != Data::NO_LAYER || (parent_.is() && parent_->isFinalized()); } rtl::OUString ChildAccess::getNameInternal() { return name_; } rtl::Reference< RootAccess > ChildAccess::getRootAccess() { return root_; } rtl::Reference< Access > ChildAccess::getParentAccess() { return parent_; } void ChildAccess::acquire() throw () { Access::acquire(); } void ChildAccess::release() throw () { Access::release(); } css::uno::Reference< css::uno::XInterface > ChildAccess::getParent() throw (css::uno::RuntimeException) { OSL_ASSERT(thisIs(IS_ANY)); osl::MutexGuard g(*lock_); checkLocalizedPropertyAccess(); return static_cast< cppu::OWeakObject * >(parent_.get()); } void ChildAccess::setParent(css::uno::Reference< css::uno::XInterface > const &) throw (css::lang::NoSupportException, css::uno::RuntimeException) { OSL_ASSERT(thisIs(IS_ANY)); osl::MutexGuard g(*lock_); checkLocalizedPropertyAccess(); throw css::lang::NoSupportException( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("setParent")), static_cast< cppu::OWeakObject * >(this)); } sal_Int64 ChildAccess::getSomething( css::uno::Sequence< sal_Int8 > const & aIdentifier) throw (css::uno::RuntimeException) { OSL_ASSERT(thisIs(IS_ANY)); osl::MutexGuard g(*lock_); checkLocalizedPropertyAccess(); return aIdentifier == getTunnelId() ? reinterpret_cast< sal_Int64 >(this) : 0; } void ChildAccess::bind( rtl::Reference< RootAccess > const & root, rtl::Reference< Access > const & parent, rtl::OUString const & name) throw () { OSL_ASSERT( !parent_.is() && root.is() && parent.is() && name.getLength() != 0); root_ = root; parent_ = parent; name_ = name; } void ChildAccess::unbind() throw () { OSL_ASSERT(parent_.is()); parent_->releaseChild(name_); parent_.clear(); inTransaction_ = true; } void ChildAccess::committed() { inTransaction_ = false; } void ChildAccess::setNode(rtl::Reference< Node > const & node) { node_ = node; } void ChildAccess::setProperty( css::uno::Any const & value, Modifications * localModifications) { OSL_ASSERT(localModifications != 0); Type type = TYPE_ERROR; bool nillable = false; switch (node_->kind()) { case Node::KIND_PROPERTY: { PropertyNode * prop = dynamic_cast< PropertyNode * >(node_.get()); type = prop->getStaticType(); nillable = prop->isNillable(); } break; case Node::KIND_LOCALIZED_PROPERTY: { rtl::OUString locale(getRootAccess()->getLocale()); if (!Components::allLocales(locale)) { rtl::Reference< ChildAccess > child(getChild(locale)); if (child.is()) { child->setProperty(value, localModifications); } else { insertLocalizedValueChild( locale, value, localModifications); } return; } } break; case Node::KIND_LOCALIZED_VALUE: { LocalizedPropertyNode * locprop = dynamic_cast< LocalizedPropertyNode * >(getParentNode().get()); type = locprop->getStaticType(); nillable = locprop->isNillable(); } break; default: break; } checkValue(value, type, nillable); getParentAccess()->markChildAsModified(this); changedValue_.reset(new css::uno::Any(value)); localModifications->add(getRelativePath()); } css::uno::Any ChildAccess::asValue() { if (changedValue_.get() != 0) { return *changedValue_; } switch (node_->kind()) { case Node::KIND_PROPERTY: return dynamic_cast< PropertyNode * >(node_.get())->getValue( getComponents()); case Node::KIND_LOCALIZED_PROPERTY: { rtl::OUString locale(getRootAccess()->getLocale()); if (!Components::allLocales(locale)) { // Find best match using an adaption of RFC 4647 lookup matching // rules, removing "-" or "_" delimited segments from the end; // defaults are the "en-US" locale, the "en" locale, the empty // string locale, the first child (if any), or a nil value (even // though it may be illegal for the given property), in that // order: rtl::Reference< ChildAccess > child; for (;;) { child = getChild(locale); if (child.is() || locale.getLength() == 0) { break; } sal_Int32 i = locale.getLength() - 1; while (i > 0 && locale[i] != '-' && locale[i] != '_') { --i; } if (i == 0) { break; } locale = locale.copy(0, i); } if (!child.is()) { child = getChild( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("en-US"))); if (!child.is()) { child = getChild( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("en"))); if (!child.is()) { child = getChild(rtl::OUString()); if (!child.is()) { std::vector< rtl::Reference< ChildAccess > > all(getAllChildren()); if (!all.empty()) { child = all.front(); } } } } } return child.is() ? child->asValue() : css::uno::Any(); } } break; case Node::KIND_LOCALIZED_VALUE: return dynamic_cast< LocalizedValueNode * >(node_.get())->getValue(); default: break; } return css::uno::makeAny( css::uno::Reference< css::uno::XInterface >( static_cast< cppu::OWeakObject * >(this))); } void ChildAccess::commitChanges(bool valid, Modifications * globalModifications) { OSL_ASSERT(globalModifications != 0); commitChildChanges(valid, globalModifications); if (valid && changedValue_.get() != 0) { Path path(getAbsolutePath()); getComponents().addModification(path); globalModifications->add(path); switch (node_->kind()) { case Node::KIND_PROPERTY: dynamic_cast< PropertyNode * >(node_.get())->setValue( Data::NO_LAYER, *changedValue_); break; case Node::KIND_LOCALIZED_VALUE: dynamic_cast< LocalizedValueNode * >(node_.get())->setValue( Data::NO_LAYER, *changedValue_); break; default: OSL_ASSERT(false); // this cannot happen break; } } changedValue_.reset(); } ChildAccess::~ChildAccess() { osl::MutexGuard g(*lock_); if (parent_.is()) { parent_->releaseChild(name_); } } void ChildAccess::addTypes(std::vector< css::uno::Type > * types) const { OSL_ASSERT(types != 0); types->push_back(cppu::UnoType< css::container::XChild >::get()); types->push_back(cppu::UnoType< css::lang::XUnoTunnel >::get()); } void ChildAccess::addSupportedServiceNames( std::vector< rtl::OUString > * services) { OSL_ASSERT(services != 0); services->push_back( getParentNode()->kind() == Node::KIND_GROUP ? rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.GroupElement")) : rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.SetElement"))); } css::uno::Any ChildAccess::queryInterface(css::uno::Type const & aType) throw (css::uno::RuntimeException) { OSL_ASSERT(thisIs(IS_ANY)); osl::MutexGuard g(*lock_); checkLocalizedPropertyAccess(); css::uno::Any res(Access::queryInterface(aType)); return res.hasValue() ? res : cppu::queryInterface( aType, static_cast< css::container::XChild * >(this), static_cast< css::lang::XUnoTunnel * >(this)); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Resolves: fdo#33638 add extra level of language tag matching<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "precompiled_configmgr.hxx" #include "sal/config.h" #include <vector> #include "com/sun/star/container/XChild.hpp" #include "com/sun/star/lang/NoSupportException.hpp" #include "com/sun/star/lang/XUnoTunnel.hpp" #include "com/sun/star/uno/Any.hxx" #include "com/sun/star/uno/Reference.hxx" #include "com/sun/star/uno/RuntimeException.hpp" #include "com/sun/star/uno/Sequence.hxx" #include "com/sun/star/uno/Type.hxx" #include "com/sun/star/uno/XInterface.hpp" #include "cppu/unotype.hxx" #include "cppuhelper/queryinterface.hxx" #include "cppuhelper/weak.hxx" #include "osl/diagnose.h" #include "osl/mutex.hxx" #include "rtl/ref.hxx" #include "rtl/string.h" #include "rtl/ustrbuf.hxx" #include "rtl/ustring.h" #include "rtl/ustring.hxx" #include "rtl/uuid.h" #include "sal/types.h" #include "access.hxx" #include "childaccess.hxx" #include "components.hxx" #include "data.hxx" #include "groupnode.hxx" #include "localizedpropertynode.hxx" #include "localizedvaluenode.hxx" #include "lock.hxx" #include "modifications.hxx" #include "node.hxx" #include "path.hxx" #include "propertynode.hxx" #include "rootaccess.hxx" #include "setnode.hxx" #include "type.hxx" namespace configmgr { namespace { namespace css = com::sun::star; } css::uno::Sequence< sal_Int8 > ChildAccess::getTunnelId() { static css::uno::Sequence< sal_Int8 > id; if (id.getLength() == 0) { css::uno::Sequence< sal_Int8 > uuid(16); rtl_createUuid( reinterpret_cast< sal_uInt8 * >(uuid.getArray()), 0, false); id = uuid; } return id; } ChildAccess::ChildAccess( Components & components, rtl::Reference< RootAccess > const & root, rtl::Reference< Access > const & parent, rtl::OUString const & name, rtl::Reference< Node > const & node): Access(components), root_(root), parent_(parent), name_(name), node_(node), inTransaction_(false) { lock_ = lock(); OSL_ASSERT(root.is() && parent.is() && node.is()); } ChildAccess::ChildAccess( Components & components, rtl::Reference< RootAccess > const & root, rtl::Reference< Node > const & node): Access(components), root_(root), node_(node), inTransaction_(false) { lock_ = lock(); OSL_ASSERT(root.is() && node.is()); } Path ChildAccess::getAbsolutePath() { OSL_ASSERT(getParentAccess().is()); Path path(getParentAccess()->getAbsolutePath()); path.push_back(name_); return path; } Path ChildAccess::getRelativePath() { Path path; rtl::Reference< Access > parent(getParentAccess()); if (parent.is()) { path = parent->getRelativePath(); } path.push_back(name_); return path; } rtl::OUString ChildAccess::getRelativePathRepresentation() { rtl::OUStringBuffer path; rtl::Reference< Access > parent(getParentAccess()); if (parent.is()) { path.append(parent->getRelativePathRepresentation()); if (path.getLength() != 0) { path.append(sal_Unicode('/')); } } path.append(Data::createSegment(node_->getTemplateName(), name_)); return path.makeStringAndClear(); } rtl::Reference< Node > ChildAccess::getNode() { return node_; } bool ChildAccess::isFinalized() { return node_->getFinalized() != Data::NO_LAYER || (parent_.is() && parent_->isFinalized()); } rtl::OUString ChildAccess::getNameInternal() { return name_; } rtl::Reference< RootAccess > ChildAccess::getRootAccess() { return root_; } rtl::Reference< Access > ChildAccess::getParentAccess() { return parent_; } void ChildAccess::acquire() throw () { Access::acquire(); } void ChildAccess::release() throw () { Access::release(); } css::uno::Reference< css::uno::XInterface > ChildAccess::getParent() throw (css::uno::RuntimeException) { OSL_ASSERT(thisIs(IS_ANY)); osl::MutexGuard g(*lock_); checkLocalizedPropertyAccess(); return static_cast< cppu::OWeakObject * >(parent_.get()); } void ChildAccess::setParent(css::uno::Reference< css::uno::XInterface > const &) throw (css::lang::NoSupportException, css::uno::RuntimeException) { OSL_ASSERT(thisIs(IS_ANY)); osl::MutexGuard g(*lock_); checkLocalizedPropertyAccess(); throw css::lang::NoSupportException( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("setParent")), static_cast< cppu::OWeakObject * >(this)); } sal_Int64 ChildAccess::getSomething( css::uno::Sequence< sal_Int8 > const & aIdentifier) throw (css::uno::RuntimeException) { OSL_ASSERT(thisIs(IS_ANY)); osl::MutexGuard g(*lock_); checkLocalizedPropertyAccess(); return aIdentifier == getTunnelId() ? reinterpret_cast< sal_Int64 >(this) : 0; } void ChildAccess::bind( rtl::Reference< RootAccess > const & root, rtl::Reference< Access > const & parent, rtl::OUString const & name) throw () { OSL_ASSERT( !parent_.is() && root.is() && parent.is() && name.getLength() != 0); root_ = root; parent_ = parent; name_ = name; } void ChildAccess::unbind() throw () { OSL_ASSERT(parent_.is()); parent_->releaseChild(name_); parent_.clear(); inTransaction_ = true; } void ChildAccess::committed() { inTransaction_ = false; } void ChildAccess::setNode(rtl::Reference< Node > const & node) { node_ = node; } void ChildAccess::setProperty( css::uno::Any const & value, Modifications * localModifications) { OSL_ASSERT(localModifications != 0); Type type = TYPE_ERROR; bool nillable = false; switch (node_->kind()) { case Node::KIND_PROPERTY: { PropertyNode * prop = dynamic_cast< PropertyNode * >(node_.get()); type = prop->getStaticType(); nillable = prop->isNillable(); } break; case Node::KIND_LOCALIZED_PROPERTY: { rtl::OUString locale(getRootAccess()->getLocale()); if (!Components::allLocales(locale)) { rtl::Reference< ChildAccess > child(getChild(locale)); if (child.is()) { child->setProperty(value, localModifications); } else { insertLocalizedValueChild( locale, value, localModifications); } return; } } break; case Node::KIND_LOCALIZED_VALUE: { LocalizedPropertyNode * locprop = dynamic_cast< LocalizedPropertyNode * >(getParentNode().get()); type = locprop->getStaticType(); nillable = locprop->isNillable(); } break; default: break; } checkValue(value, type, nillable); getParentAccess()->markChildAsModified(this); changedValue_.reset(new css::uno::Any(value)); localModifications->add(getRelativePath()); } namespace { rtl::OUString lcl_StripSegment(const rtl::OUString &rLocale) { sal_Int32 i = rLocale.getLength() ? rLocale.getLength() - 1 : 0; while (i > 0 && rLocale[i] != '-' && rLocale[i] != '_') --i; return rLocale.copy(0, i); } } css::uno::Any ChildAccess::asValue() { if (changedValue_.get() != 0) { return *changedValue_; } switch (node_->kind()) { case Node::KIND_PROPERTY: return dynamic_cast< PropertyNode * >(node_.get())->getValue( getComponents()); case Node::KIND_LOCALIZED_PROPERTY: { rtl::OUString sLocale(getRootAccess()->getLocale()); if (!Components::allLocales(sLocale)) { rtl::Reference< ChildAccess > child; // Find best match using an adaption of RFC 4647 lookup matching // rules, removing "-" or "_" delimited segments from the end while (1) { child = getChild(sLocale); if (child.is()) break; rtl::OUString sTmpLocale = lcl_StripSegment(sLocale); if (!sTmpLocale.getLength()) break; sLocale = sTmpLocale; } //Resolves: fdo#33638 Look for the first entry with the same //first segment as the requested language tag, before falling //back to en-US, etc. typedef std::vector< rtl::Reference< ChildAccess > > ChildVector; if (!child.is()) { const ChildVector &rAllChildren = getAllChildren(); for (ChildVector::const_iterator aI = rAllChildren.begin(), aEnd = rAllChildren.end(); aI != aEnd; ++aI) { rtl::OUString sLanguage = lcl_StripSegment((*aI)->getNameInternal()); if (sLocale == sLanguage) { child = *aI; break; } } } // defaults are the "en-US" locale, the "en" locale, the empty // string locale, the first child (if any), or a nil value (even // though it may be illegal for the given property), in that // order: if (!child.is()) { child = getChild( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("en-US"))); if (!child.is()) { child = getChild( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("en"))); if (!child.is()) { child = getChild(rtl::OUString()); if (!child.is()) { ChildVector all(getAllChildren()); if (!all.empty()) child = all.front(); } } } } return child.is() ? child->asValue() : css::uno::Any(); } } break; case Node::KIND_LOCALIZED_VALUE: return dynamic_cast< LocalizedValueNode * >(node_.get())->getValue(); default: break; } return css::uno::makeAny( css::uno::Reference< css::uno::XInterface >( static_cast< cppu::OWeakObject * >(this))); } void ChildAccess::commitChanges(bool valid, Modifications * globalModifications) { OSL_ASSERT(globalModifications != 0); commitChildChanges(valid, globalModifications); if (valid && changedValue_.get() != 0) { Path path(getAbsolutePath()); getComponents().addModification(path); globalModifications->add(path); switch (node_->kind()) { case Node::KIND_PROPERTY: dynamic_cast< PropertyNode * >(node_.get())->setValue( Data::NO_LAYER, *changedValue_); break; case Node::KIND_LOCALIZED_VALUE: dynamic_cast< LocalizedValueNode * >(node_.get())->setValue( Data::NO_LAYER, *changedValue_); break; default: OSL_ASSERT(false); // this cannot happen break; } } changedValue_.reset(); } ChildAccess::~ChildAccess() { osl::MutexGuard g(*lock_); if (parent_.is()) { parent_->releaseChild(name_); } } void ChildAccess::addTypes(std::vector< css::uno::Type > * types) const { OSL_ASSERT(types != 0); types->push_back(cppu::UnoType< css::container::XChild >::get()); types->push_back(cppu::UnoType< css::lang::XUnoTunnel >::get()); } void ChildAccess::addSupportedServiceNames( std::vector< rtl::OUString > * services) { OSL_ASSERT(services != 0); services->push_back( getParentNode()->kind() == Node::KIND_GROUP ? rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.GroupElement")) : rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.SetElement"))); } css::uno::Any ChildAccess::queryInterface(css::uno::Type const & aType) throw (css::uno::RuntimeException) { OSL_ASSERT(thisIs(IS_ANY)); osl::MutexGuard g(*lock_); checkLocalizedPropertyAccess(); css::uno::Any res(Access::queryInterface(aType)); return res.hasValue() ? res : cppu::queryInterface( aType, static_cast< css::container::XChild * >(this), static_cast< css::lang::XUnoTunnel * >(this)); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "BtuLinear.h" BtuLinear::BtuLinear(): m_depthPid(DEP_KC, DEP_KI, DEP_KD, PID_FREQ, DEPTH_MIN, DEPTH_MAX, VEL_MIN, VEL_MAX, 0), m_actA(PIN_ACTA_PWM, PIN_ACTA_DIR, PIN_ACTA_POT, PID_FREQ), m_actB(PIN_ACTB_PWM, PIN_ACTB_DIR, PIN_ACTB_POT, PID_FREQ), m_pressureSensor(PIN_IMU_SDA, PIN_IMU_SCL), m_dryRunPot(DRY_RUN_POT_PIN) { m_dryRun = false; }; BtuLinear::BtuLinear(bool dryRun): m_depthPid(DEP_K_C, DEP_TAU_I, DEP_TAU_D, PID_FREQ, DEPTH_MIN, DEPTH_MAX, VEL_MIN, VEL_MAX, 0), m_actA(PIN_ACTA_PWM, PIN_ACTA_DIR, PIN_ACTA_POT, PID_FREQ), m_actB(PIN_ACTB_PWM, PIN_ACTB_DIR, PIN_ACTB_POT, PID_FREQ), m_pressureSensor(PIN_IMU_SDA, PIN_IMU_SCL), m_dryRunPot(DRY_RUN_POT_PIN) { m_dryRun = dryRun; }; BtuLinear::~BtuLinear(){} void BtuLinear::init() { m_mode = DEFAULT_CTRL_MODE; // default gain values for depth controller m_kc = DEP_KC; m_kI = DEP_KI; m_kD = DEP_KD; // default gain values for position controller m_p_kc = POS_KC; m_p_kI = POS_KI; m_p_kD = POS_KD; // default gain values for velocity controller m_v_kc = VEL_KC; m_v_kI = VEL_KI; m_v_kD = VEL_KD; // initialize Pressure Sensor m_pressureSensor.MS5837Init(); m_pressureSensor.MS5837Start(); wait(0.1); // remnant from old BTU class TODO: check if can be removed // initialize the actuators m_actA.reset(); m_actB.reset(); // initialize the Windows for SMA to 0 // for(int i = 0; i < AVG_WINDOW_WIDTH; i++) { // m_avg_windowA[i] = 0; // m_avg_windowB[i] = 0; // } // initialize starting voltage for velocity control to 0 // m_currentVoltage = 0; } // return a pressure reading float BtuLinear::getPressure() { return m_pressureSensor.MS5837_Pressure(); } // resets values of the controllers void BtuLinear::stop() { m_depthPid.reset(); m_actA.reset(); m_actB.reset(); return; } // updates depth PID tunings void BtuLinear::updateDepthTunings(float kc, float kI, float kD) { m_kc = kc; m_kI = kI; m_kD = kD; m_depthPid.setTunings(kc, kI, kD); } // updates Position PID tunings void BtuLinear::updatePosTunings(float kc, float kI, float kD) { m_p_kc = kc; m_p_kI = kI; m_p_kD = kD; m_actA.setPosTunings(kc, kI, kD); m_actB.setPosTunings(kc, kI, kD); } // updates Velocity PID tunings void BtuLinear::updateVelTunings(float kc, float kI, float kD) { m_v_kc = kc; m_v_kI = kI; m_v_kD = kD; m_actA.setVelTunings(kc, kI, kD); m_actB.setVelTunings(kc, kI, kD); } // updates Mode. Resets most values if the mode has changed void BtuLinear::updateMode(int mode) { if(m_mode != mode) { stop(); m_mode = mode; } } // runs one cycle of the controller dictated by mode void BtuLinear::runCycle(float setVal) { switch (m_mode) { case VOLTAGE_CTRL_MODE: voltageControl(setVal); break; case VELOCITY_CTRL_MODE: velocityControl(setVal); break; case DEPTH_CTRL_MODE: depthControl(setVal); break; case POSITION_CTRL_MODE: positionControl(setVal); break; } } // convenience function, updates mode, then runs a cycle in the chosen mode void BtuLinear::updateAndRunCycle(int mode, float value) { updateMode(mode); runCycle(value); } // calls voltageControlHelper on both actuators void BtuLinear::voltageControl(float setDuty) { m_actA.runVoltControl(setDuty); m_actB.runVoltControl(setDuty); } // updates the SMA window with the current position reading /* void BtuLinear::updatePositionReadings() { float aPosition = m_actAPot; float bPosition = m_actBPot; float aOldPos = m_avg_windowA[m_avg_windowPtr]; float bOldPos = m_avg_windowB[m_avg_windowPtr]; m_avg_windowA[m_avg_windowPtr] = aPosition; m_avg_windowB[m_avg_windowPtr] = bPosition; m_avg_windowPtr = (m_avg_windowPtr+1) % AVG_WINDOW_WIDTH; if(m_avg_windowSize >= AVG_WINDOW_WIDTH) { // buffer is full m_currentAvgA = m_currentAvgA + (aPosition / AVG_WINDOW_WIDTH)- (aOldPos / AVG_WINDOW_WIDTH); m_currentAvgB = m_currentAvgB + (bPosition / AVG_WINDOW_WIDTH)- (bOldPos / AVG_WINDOW_WIDTH); } else { // buffer is still filling up m_avg_windowSize++; m_currentAvgA = 0; m_currentAvgB = 0; for(int i = 0; i < m_avg_windowSize; i++) { m_currentAvgA = (m_avg_windowA[i] / m_avg_windowSize); m_currentAvgB = (m_avg_windowB[i] / m_avg_windowSize); } } } */ // gets the current Actuator Position. No SMA, just reads and rescales the potentiometer float BtuLinear::getActPosition(int act) { if(act == ACT_A) { return m_actA.getPosition(); } else { return m_actB.getPosition(); } } // does velocity control on both actuators void BtuLinear::velocityControl(float setVel) { m_actA.runVelControl(setVel); m_actB.runVelControl(setVel); } // control position of both actuators void BtuLinear::positionControl(float setPos) { m_actA.runPosControl(setPos); m_actB.runPosControl(setPos); } // control depth via master-slave void BtuLinear::depthControlHelper(float cmdVoltage) { // control velocity on one actuator m_actA.runVoltControl(cmdVoltage); // have the second mirror the first m_actB.runPosControl(m_actA.getPosition()); } // do depth control void BtuLinear::depthControl(float setDepthMeters) { float curDepth = getDepth(); m_depthPid.setProcessValue(curDepth); m_depthPid.setSetPoint(setDepthMeters); float cmdVolt = m_depthPid.compute(); // extending the actuator increases buoyancy -> less depth // therefore the axis direction has to be reversed depthControlHelper( -1 * cmdVolt ); } // get a depth reading float BtuLinear::getDepth() { if(m_dryRun) { float pvDepth = m_dryRunPot * (DEPTH_MAX); return pvDepth; } float pvDepth = getPressure(); float pvDepthMeters = (pvDepth - P_ATMOS_MBAR) / P_WATER_SURFACE_MBAR; return pvDepthMeters; } <commit_msg>fixed more merge conflicts<commit_after>#include "BtuLinear.h" BtuLinear::BtuLinear(): m_depthPid(DEP_KC, DEP_KI, DEP_KD, PID_FREQ, DEPTH_MIN, DEPTH_MAX, VEL_MIN, VEL_MAX, 0), m_actA(PIN_ACTA_PWM, PIN_ACTA_DIR, PIN_ACTA_POT, PID_FREQ), m_actB(PIN_ACTB_PWM, PIN_ACTB_DIR, PIN_ACTB_POT, PID_FREQ), m_pressureSensor(PIN_IMU_SDA, PIN_IMU_SCL), m_dryRunPot(DRY_RUN_POT_PIN) { m_dryRun = false; }; BtuLinear::BtuLinear(bool dryRun): m_depthPid(DEP_K_C, DEP_TAU_I, DEP_TAU_D, PID_FREQ, DEPTH_MIN, DEPTH_MAX, VEL_MIN, VEL_MAX, 0), m_actA(PIN_ACTA_PWM, PIN_ACTA_DIR, PIN_ACTA_POT, PID_FREQ), m_actB(PIN_ACTB_PWM, PIN_ACTB_DIR, PIN_ACTB_POT, PID_FREQ), m_pressureSensor(PIN_IMU_SDA, PIN_IMU_SCL), m_dryRunPot(DRY_RUN_POT_PIN) { m_dryRun = dryRun; }; BtuLinear::~BtuLinear(){} void BtuLinear::init() { m_mode = DEFAULT_CTRL_MODE; // default gain values for depth controller m_kc = DEP_KC; m_kI = DEP_KI; m_kD = DEP_KD; // default gain values for position controller m_p_kc = POS_KC; m_p_kI = POS_KI; m_p_kD = POS_KD; // default gain values for velocity controller m_v_kc = VEL_KC; m_v_kI = VEL_KI; m_v_kD = VEL_KD; // initialize Pressure Sensor m_pressureSensor.MS5837Init(); m_pressureSensor.MS5837Start(); wait(0.1); // remnant from old BTU class TODO: check if can be removed // initialize the actuators m_actA.reset(); m_actB.reset(); // initialize the Windows for SMA to 0 // for(int i = 0; i < AVG_WINDOW_WIDTH; i++) { // m_avg_windowA[i] = 0; // m_avg_windowB[i] = 0; // } // initialize starting voltage for velocity control to 0 // m_currentVoltage = 0; } // return a pressure reading float BtuLinear::getPressure() { return m_pressureSensor.MS5837_Pressure(); } // resets values of the controllers void BtuLinear::stop() { m_depthPid.reset(); m_actA.reset(); m_actB.reset(); return; } // updates depth PID tunings void BtuLinear::updateDepthTunings(float kc, float kI, float kD) { m_kc = kc; m_kI = kI; m_kD = kD; m_depthPid.setTunings(kc, kI, kD); } // updates Position PID tunings void BtuLinear::updatePosTunings(float kc, float kI, float kD) { m_p_kc = kc; m_p_kI = kI; m_p_kD = kD; m_actA.setPosTunings(kc, kI, kD); m_actB.setPosTunings(kc, kI, kD); } // updates Velocity PID tunings void BtuLinear::updateVelTunings(float kc, float kI, float kD) { m_v_kc = kc; m_v_kI = kI; m_v_kD = kD; m_actA.setVelTunings(kc, kI, kD); m_actB.setVelTunings(kc, kI, kD); } // updates Mode. Resets most values if the mode has changed void BtuLinear::updateMode(int mode) { if(m_mode != mode) { stop(); m_mode = mode; } } // runs one cycle of the controller dictated by mode void BtuLinear::runCycle(float setVal) { switch (m_mode) { case VOLTAGE_CTRL_MODE: voltageControl(setVal); break; case VELOCITY_CTRL_MODE: velocityControl(setVal); break; case DEPTH_CTRL_MODE: depthControl(setVal); break; case POSITION_CTRL_MODE: positionControl(setVal); break; } } // convenience function, updates mode, then runs a cycle in the chosen mode void BtuLinear::updateAndRunCycle(int mode, float value) { updateMode(mode); runCycle(value); } // calls voltageControlHelper on both actuators void BtuLinear::voltageControl(float setDuty) { m_actA.runVoltControl(setDuty); m_actB.runVoltControl(setDuty); } // updates the SMA window with the current position reading /* void BtuLinear::updatePositionReadings() { float aPosition = m_actAPot; float bPosition = m_actBPot; float aOldPos = m_avg_windowA[m_avg_windowPtr]; float bOldPos = m_avg_windowB[m_avg_windowPtr]; m_avg_windowA[m_avg_windowPtr] = aPosition; m_avg_windowB[m_avg_windowPtr] = bPosition; m_avg_windowPtr = (m_avg_windowPtr+1) % AVG_WINDOW_WIDTH; if(m_avg_windowSize >= AVG_WINDOW_WIDTH) { // buffer is full m_currentAvgA = m_currentAvgA + (aPosition / AVG_WINDOW_WIDTH)- (aOldPos / AVG_WINDOW_WIDTH); m_currentAvgB = m_currentAvgB + (bPosition / AVG_WINDOW_WIDTH)- (bOldPos / AVG_WINDOW_WIDTH); } else { // buffer is still filling up m_avg_windowSize++; m_currentAvgA = 0; m_currentAvgB = 0; for(int i = 0; i < m_avg_windowSize; i++) { m_currentAvgA = (m_avg_windowA[i] / m_avg_windowSize); m_currentAvgB = (m_avg_windowB[i] / m_avg_windowSize); } } } */ // gets the current Actuator Position. No SMA, just reads and rescales the potentiometer float BtuLinear::getActPosition(int act) { if(act == ACT_A) { return m_actA.getPosition(); } else { return m_actB.getPosition(); } } // does velocity control on both actuators void BtuLinear::velocityControl(float setVel) { m_actA.runVelControl(setVel); m_actB.runVelControl(setVel); } // control position of both actuators void BtuLinear::positionControl(float setPos) { m_actA.runPosControl(setPos); m_actB.runPosControl(setPos); } // control depth via master-slave void BtuLinear::depthControlHelper(float cmdVoltage) { // control velocity on one actuator m_actA.runVoltControl(cmdVoltage); // have the second mirror the first m_actB.runPosControl(m_actA.getPosition()); } // do depth control void BtuLinear::depthControl(float setDepthMeters) { // Read Pressure Value and Convert into Depth in Meters float curDepth = getDepth(); // current depth becomes process variable for PID controller m_depthPid.setProcessValue(curDepth); // desired depth in meters becomes set point of PID controller m_depthPid.setSetPoint(setDepthMeters); // commanded voltage is calculated by PID controller float cmdVolt = m_depthPid.compute(); // extending the actuator increases buoyancy -> less depth // therefore the axis direction has to be reversed // and commanded voltage with opposite sign is therefore applied depthControlHelper( -1 * cmdVolt ); } // get a depth reading float BtuLinear::getDepth() { if(m_dryRun) { float pvDepth = m_dryRunPot * (DEPTH_MAX); return pvDepth; } // read out pressure in mbar float pvDepth = getPressure(); // convert pressure to meters float pvDepthMeters = (pvDepth - P_ATMOS_MBAR) / P_WATER_SURFACE_MBAR; return pvDepthMeters; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: cmtree.cxx,v $ * * $Revision: 1.16 $ * * last change: $Author: jb $ $Date: 2000-12-06 17:57:12 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ /* PLEASE DON'T DELETE ANY COMMENT LINES, ALSO IT'S UNNECESSARY. */ #include "cmtree.hxx" #include <stl/deque> #include <stl/vector> #include <iostream> #include <exception> #include <sal/types.h> #include <stl/set> #include <rtl/string.hxx> #include <rtl/ustring.hxx> #include <osl/diagnose.h> #include "confname.hxx" // Iterator for PathName scans #include "cmtreemodel.hxx" #include "treeactions.hxx" #include <com/sun/star/uno/Any.hxx> // WISDOM // !!Never write same code twice!! using namespace std; using namespace rtl; using namespace com::sun::star::uno; namespace configmgr { // ------------------------ ChildListSet implementations ------------------------ ChildListSet::ChildListSet(ChildListSet const& aSet) { for(ChildList::iterator it = aSet.GetSet().begin(); it != aSet.GetSet().end(); ++it) m_aChildList.insert(m_aChildList.end(), (*it)->clone()); } ChildListSet::~ChildListSet() { for(ChildList::iterator it = m_aChildList.begin(); it != m_aChildList.end(); ++it) delete *it; } // ---------------------------- Node implementation ---------------------------- INode::INode(configuration::Attributes _aAttr):m_aAttributes(_aAttr){} INode::INode(OUString const& aName, configuration::Attributes _aAttr) :m_aName(aName) ,m_aAttributes(_aAttr){} // CopyCTor will be create automatically INode::~INode() {} ISubtree* INode::asISubtree(){return NULL;} ISubtree const* INode::asISubtree() const {return NULL;} ValueNode* INode::asValueNode() {return NULL;} ValueNode const* INode::asValueNode() const {return NULL;} // ------------------------- SearchNode implementation ------------------------- SearchNode::SearchNode():INode(configuration::Attributes()){} SearchNode::SearchNode(OUString const& aName) :INode(aName, configuration::Attributes()){} INode* SearchNode::clone() const {return new SearchNode(*this);} SearchNode::~SearchNode(){} //========================================================================== //= OPropagateLevels //========================================================================== /** fills a subtree with the correct level informations */ struct OPropagateLevels : public NodeModification { protected: sal_Int32 nChildLevel; public: OPropagateLevels(sal_Int32 _nParentLevel) { nChildLevel = (ITreeProvider::ALL_LEVELS == _nParentLevel) ? ITreeProvider::ALL_LEVELS : _nParentLevel - 1; } virtual void handle(ValueNode&) { /* not interested in value nodes */ } virtual void handle(ISubtree& _rSubtree) { if ((ITreeProvider::ALL_LEVELS == nChildLevel) || nChildLevel > _rSubtree.getLevel()) _rSubtree.setLevel(nChildLevel); } }; // -------------------------- ISubtree implementation -------------------------- ISubtree* ISubtree::asISubtree() {return this;} ISubtree const* ISubtree::asISubtree() const {return this;} //-------------------------------------------------------------------------- void ISubtree::setLevel(sal_Int16 _nLevel) { m_nLevel = _nLevel; if (0 == _nLevel) // nothing more to do, this means "nothing known about any children" return; // forward the level number to any child subtrees we have OPropagateLevels aDeeperInto(_nLevel); aDeeperInto.applyToChildren(*this); } // --------------------------- Subtree implementation --------------------------- INode* Subtree::clone() const {return new Subtree(*this);} INode* Subtree::doGetChild(OUString const& aName) const { SearchNode searchObj(aName); #ifdef DEBUG for (ChildList::iterator it2 = m_aChildren.GetSet().begin(); it2 != m_aChildren.GetSet().end(); ++it2) { INode* pINode = *it2; OUString aName2 = pINode->getName(); volatile int dummy = 0; } #endif ChildList::iterator it = m_aChildren.GetSet().find(&searchObj); if (it == m_aChildren.GetSet().end()) return NULL; else return *it; } INode* Subtree::addChild(std::auto_ptr<INode> aNode) // takes ownership { OUString aName = aNode->getName(); std::pair<ChildList::iterator, bool> aInserted = m_aChildren.GetSet().insert(aNode.get()); if (aInserted.second) aNode.release(); return *aInserted.first; } ::std::auto_ptr<INode> Subtree::removeChild(OUString const& aName) { SearchNode searchObj(aName); ChildList::const_iterator it = m_aChildren.GetSet().find(&searchObj); ::std::auto_ptr<INode> aReturn; if (m_aChildren.GetSet().end() != it) { aReturn = ::std::auto_ptr<INode>(*it); m_aChildren.GetSet().erase(it); } return aReturn; } //========================================================================== //= OBuildChangeTree - historic //========================================================================== /** generates a change tree by comparing two trees */ /* struct OBuildChangeTree : public NodeModification { protected: SubtreeChange& m_rChangeList; INode* m_pCacheNode; public: OBuildChangeTree(SubtreeChange& rList, INode* pNode) :m_rChangeList(rList) ,m_pCacheNode(pNode) { } virtual void handle(ValueNode& _nNode) { OUString aNodeName = _nNode.getName(); ISubtree* pTree = m_pCacheNode->asISubtree(); OSL_ENSHURE(pTree, "OBuildChangeTree::handle : node must be a inner node!"); if (pTree) { INode* pChild = pTree->getChild(aNodeName); ValueNode* pValueNode = pChild ? pChild->asValueNode() : NULL; OSL_ENSHURE(pValueNode, "OBuildChangeTree::handle : node must be a value node!"); // if the values differ add a new change if (pValueNode && _nNode.getValue() != pValueNode->getValue()) { ValueChange* pChange = new ValueChange(_nNode.getValue(), *pValueNode); m_rChangeList.addChange(::std::auto_ptr<Change>(pChange)); } } } virtual void handle(ISubtree& _rSubtree) { OUString aNodeName = _rSubtree.getName(); ISubtree* pTree = m_pCacheNode->asISubtree(); OSL_ENSHURE(pTree, "OBuildChangeTree::handle : node must be a inner node!"); if (pTree) { INode* pChild = pTree->getChild(aNodeName); // node not in cache, so ignore it // later, when we get additions and removements within on transaction, then we have to care about if (pChild) { ISubtree* pSubTree = pChild->asISubtree(); OSL_ENSHURE(pSubTree, "OBuildChangeTree::handle : node must be a inner node!"); // generate a new change SubtreeChange* pChange = new SubtreeChange(_rSubtree); OBuildChangeTree aNextLevel(*pChange, pSubTree); aNextLevel.applyToChildren(_rSubtree); // now count if there are any changes OChangeCounter aCounter; pChange->dispatch(aCounter); if (aCounter.nCount != 0) m_rChangeList.addChange(::std::auto_ptr<Change>(pChange)); else delete pChange; } } } }; */ void Subtree::forEachChild(NodeAction& anAction) const { for(ChildList::const_iterator it = m_aChildren.GetSet().begin(); it != m_aChildren.GetSet().end(); ++it) (**it).dispatch(anAction); } void Subtree::forEachChild(NodeModification& anAction) { for(ChildList::iterator it = m_aChildren.GetSet().begin(); it != m_aChildren.GetSet().end(); ++it) (**it).dispatch(anAction); } // -------------------------- ValueNode implementation -------------------------- void ValueNode::check_init() // may throw in the future { if (m_aValue.hasValue()) { OSL_ASSERT(m_aType != ::getVoidCppuType()); OSL_ASSERT(m_aType == m_aValue.getValueType()); } else OSL_ASSERT(getVoidCppuType() == m_aValue.getValueType()); if (m_aDefaultValue.hasValue()) { OSL_ASSERT(m_aType != ::getVoidCppuType()); OSL_ASSERT(m_aType == m_aDefaultValue.getValueType()); } else OSL_ASSERT(getVoidCppuType() == m_aDefaultValue.getValueType()); } void ValueNode::init() { OSL_ASSERT(m_aType == ::getVoidCppuType()); if (m_aDefaultValue.hasValue()) { m_aType = m_aDefaultValue.getValueType(); OSL_ASSERT(m_aType != ::getVoidCppuType()); } else if (m_aValue.hasValue()) { m_aType = m_aValue.getValueType(); OSL_ASSERT(m_aType != ::getVoidCppuType()); } } void ValueNode::setValue(Any aValue) { m_aValue = aValue; // flip the type if necessary if ( (m_aType.getTypeClass() == TypeClass_ANY) && (aValue.getValueType().getTypeClass() != TypeClass_ANY) && (aValue.getValueType().getTypeClass() != TypeClass_VOID) ) m_aType = aValue.getValueType(); } void ValueNode::changeDefault(Any aValue) { m_aDefaultValue = aValue; // flip the type if necessary if ( (m_aType.getTypeClass() == TypeClass_ANY) && (aValue.getValueType().getTypeClass() != TypeClass_ANY) && (aValue.getValueType().getTypeClass() != TypeClass_VOID) ) m_aType = aValue.getValueType(); } void ValueNode::setDefault() { // PRE: ???? // POST: isDefault() == true m_aValue = Any(); } INode* ValueNode::clone() const { return new ValueNode(*this); } ValueNode* ValueNode::asValueNode() {return this;} ValueNode const* ValueNode::asValueNode() const {return this;} } // namespace configmgr <commit_msg>include stdio.h to compile under Solaris 8<commit_after>/************************************************************************* * * $RCSfile: cmtree.cxx,v $ * * $Revision: 1.17 $ * * last change: $Author: fs $ $Date: 2000-12-10 09:59:57 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <stdio.h> /* PLEASE DON'T DELETE ANY COMMENT LINES, ALSO IT'S UNNECESSARY. */ #include "cmtree.hxx" #include <stl/deque> #include <stl/vector> #include <iostream> #include <exception> #include <sal/types.h> #include <stl/set> #include <rtl/string.hxx> #include <rtl/ustring.hxx> #include <osl/diagnose.h> #include "confname.hxx" // Iterator for PathName scans #include "cmtreemodel.hxx" #include "treeactions.hxx" #include <com/sun/star/uno/Any.hxx> // WISDOM // !!Never write same code twice!! using namespace std; using namespace rtl; using namespace com::sun::star::uno; namespace configmgr { // ------------------------ ChildListSet implementations ------------------------ ChildListSet::ChildListSet(ChildListSet const& aSet) { for(ChildList::iterator it = aSet.GetSet().begin(); it != aSet.GetSet().end(); ++it) m_aChildList.insert(m_aChildList.end(), (*it)->clone()); } ChildListSet::~ChildListSet() { for(ChildList::iterator it = m_aChildList.begin(); it != m_aChildList.end(); ++it) delete *it; } // ---------------------------- Node implementation ---------------------------- INode::INode(configuration::Attributes _aAttr):m_aAttributes(_aAttr){} INode::INode(OUString const& aName, configuration::Attributes _aAttr) :m_aName(aName) ,m_aAttributes(_aAttr){} // CopyCTor will be create automatically INode::~INode() {} ISubtree* INode::asISubtree(){return NULL;} ISubtree const* INode::asISubtree() const {return NULL;} ValueNode* INode::asValueNode() {return NULL;} ValueNode const* INode::asValueNode() const {return NULL;} // ------------------------- SearchNode implementation ------------------------- SearchNode::SearchNode():INode(configuration::Attributes()){} SearchNode::SearchNode(OUString const& aName) :INode(aName, configuration::Attributes()){} INode* SearchNode::clone() const {return new SearchNode(*this);} SearchNode::~SearchNode(){} //========================================================================== //= OPropagateLevels //========================================================================== /** fills a subtree with the correct level informations */ struct OPropagateLevels : public NodeModification { protected: sal_Int32 nChildLevel; public: OPropagateLevels(sal_Int32 _nParentLevel) { nChildLevel = (ITreeProvider::ALL_LEVELS == _nParentLevel) ? ITreeProvider::ALL_LEVELS : _nParentLevel - 1; } virtual void handle(ValueNode&) { /* not interested in value nodes */ } virtual void handle(ISubtree& _rSubtree) { if ((ITreeProvider::ALL_LEVELS == nChildLevel) || nChildLevel > _rSubtree.getLevel()) _rSubtree.setLevel(nChildLevel); } }; // -------------------------- ISubtree implementation -------------------------- ISubtree* ISubtree::asISubtree() {return this;} ISubtree const* ISubtree::asISubtree() const {return this;} //-------------------------------------------------------------------------- void ISubtree::setLevel(sal_Int16 _nLevel) { m_nLevel = _nLevel; if (0 == _nLevel) // nothing more to do, this means "nothing known about any children" return; // forward the level number to any child subtrees we have OPropagateLevels aDeeperInto(_nLevel); aDeeperInto.applyToChildren(*this); } // --------------------------- Subtree implementation --------------------------- INode* Subtree::clone() const {return new Subtree(*this);} INode* Subtree::doGetChild(OUString const& aName) const { SearchNode searchObj(aName); #ifdef DEBUG for (ChildList::iterator it2 = m_aChildren.GetSet().begin(); it2 != m_aChildren.GetSet().end(); ++it2) { INode* pINode = *it2; OUString aName2 = pINode->getName(); volatile int dummy = 0; } #endif ChildList::iterator it = m_aChildren.GetSet().find(&searchObj); if (it == m_aChildren.GetSet().end()) return NULL; else return *it; } INode* Subtree::addChild(std::auto_ptr<INode> aNode) // takes ownership { OUString aName = aNode->getName(); std::pair<ChildList::iterator, bool> aInserted = m_aChildren.GetSet().insert(aNode.get()); if (aInserted.second) aNode.release(); return *aInserted.first; } ::std::auto_ptr<INode> Subtree::removeChild(OUString const& aName) { SearchNode searchObj(aName); ChildList::const_iterator it = m_aChildren.GetSet().find(&searchObj); ::std::auto_ptr<INode> aReturn; if (m_aChildren.GetSet().end() != it) { aReturn = ::std::auto_ptr<INode>(*it); m_aChildren.GetSet().erase(it); } return aReturn; } //========================================================================== //= OBuildChangeTree - historic //========================================================================== /** generates a change tree by comparing two trees */ /* struct OBuildChangeTree : public NodeModification { protected: SubtreeChange& m_rChangeList; INode* m_pCacheNode; public: OBuildChangeTree(SubtreeChange& rList, INode* pNode) :m_rChangeList(rList) ,m_pCacheNode(pNode) { } virtual void handle(ValueNode& _nNode) { OUString aNodeName = _nNode.getName(); ISubtree* pTree = m_pCacheNode->asISubtree(); OSL_ENSHURE(pTree, "OBuildChangeTree::handle : node must be a inner node!"); if (pTree) { INode* pChild = pTree->getChild(aNodeName); ValueNode* pValueNode = pChild ? pChild->asValueNode() : NULL; OSL_ENSHURE(pValueNode, "OBuildChangeTree::handle : node must be a value node!"); // if the values differ add a new change if (pValueNode && _nNode.getValue() != pValueNode->getValue()) { ValueChange* pChange = new ValueChange(_nNode.getValue(), *pValueNode); m_rChangeList.addChange(::std::auto_ptr<Change>(pChange)); } } } virtual void handle(ISubtree& _rSubtree) { OUString aNodeName = _rSubtree.getName(); ISubtree* pTree = m_pCacheNode->asISubtree(); OSL_ENSHURE(pTree, "OBuildChangeTree::handle : node must be a inner node!"); if (pTree) { INode* pChild = pTree->getChild(aNodeName); // node not in cache, so ignore it // later, when we get additions and removements within on transaction, then we have to care about if (pChild) { ISubtree* pSubTree = pChild->asISubtree(); OSL_ENSHURE(pSubTree, "OBuildChangeTree::handle : node must be a inner node!"); // generate a new change SubtreeChange* pChange = new SubtreeChange(_rSubtree); OBuildChangeTree aNextLevel(*pChange, pSubTree); aNextLevel.applyToChildren(_rSubtree); // now count if there are any changes OChangeCounter aCounter; pChange->dispatch(aCounter); if (aCounter.nCount != 0) m_rChangeList.addChange(::std::auto_ptr<Change>(pChange)); else delete pChange; } } } }; */ void Subtree::forEachChild(NodeAction& anAction) const { for(ChildList::const_iterator it = m_aChildren.GetSet().begin(); it != m_aChildren.GetSet().end(); ++it) (**it).dispatch(anAction); } void Subtree::forEachChild(NodeModification& anAction) { for(ChildList::iterator it = m_aChildren.GetSet().begin(); it != m_aChildren.GetSet().end(); ++it) (**it).dispatch(anAction); } // -------------------------- ValueNode implementation -------------------------- void ValueNode::check_init() // may throw in the future { if (m_aValue.hasValue()) { OSL_ASSERT(m_aType != ::getVoidCppuType()); OSL_ASSERT(m_aType == m_aValue.getValueType()); } else OSL_ASSERT(getVoidCppuType() == m_aValue.getValueType()); if (m_aDefaultValue.hasValue()) { OSL_ASSERT(m_aType != ::getVoidCppuType()); OSL_ASSERT(m_aType == m_aDefaultValue.getValueType()); } else OSL_ASSERT(getVoidCppuType() == m_aDefaultValue.getValueType()); } void ValueNode::init() { OSL_ASSERT(m_aType == ::getVoidCppuType()); if (m_aDefaultValue.hasValue()) { m_aType = m_aDefaultValue.getValueType(); OSL_ASSERT(m_aType != ::getVoidCppuType()); } else if (m_aValue.hasValue()) { m_aType = m_aValue.getValueType(); OSL_ASSERT(m_aType != ::getVoidCppuType()); } } void ValueNode::setValue(Any aValue) { m_aValue = aValue; // flip the type if necessary if ( (m_aType.getTypeClass() == TypeClass_ANY) && (aValue.getValueType().getTypeClass() != TypeClass_ANY) && (aValue.getValueType().getTypeClass() != TypeClass_VOID) ) m_aType = aValue.getValueType(); } void ValueNode::changeDefault(Any aValue) { m_aDefaultValue = aValue; // flip the type if necessary if ( (m_aType.getTypeClass() == TypeClass_ANY) && (aValue.getValueType().getTypeClass() != TypeClass_ANY) && (aValue.getValueType().getTypeClass() != TypeClass_VOID) ) m_aType = aValue.getValueType(); } void ValueNode::setDefault() { // PRE: ???? // POST: isDefault() == true m_aValue = Any(); } INode* ValueNode::clone() const { return new ValueNode(*this); } ValueNode* ValueNode::asValueNode() {return this;} ValueNode const* ValueNode::asValueNode() const {return this;} } // namespace configmgr <|endoftext|>
<commit_before>// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <windows.h> #include <psapi.h> #include "base/basictypes.h" #include "base/process_util.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_process_filter.h" #include "chrome/test/perf/mem_usage.h" bool GetMemoryInfo(uint32 process_id, size_t *peak_virtual_size, size_t *current_virtual_size, size_t *peak_working_set_size, size_t *current_working_set_size) { if (!peak_virtual_size || !current_virtual_size) return false; HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_id); if (!process_handle) return false; PROCESS_MEMORY_COUNTERS_EX pmc; bool result = false; if (GetProcessMemoryInfo(process_handle, reinterpret_cast<PPROCESS_MEMORY_COUNTERS>(&pmc), sizeof(pmc))) { *peak_virtual_size = pmc.PeakPagefileUsage; *current_virtual_size = pmc.PagefileUsage; *peak_working_set_size = pmc.PeakWorkingSetSize; *current_working_set_size = pmc.WorkingSetSize; result = true; } CloseHandle(process_handle); return result; } size_t GetSystemCommitCharge() { // Get the System Page Size. SYSTEM_INFO system_info; GetSystemInfo(&system_info); // TODO(mbelshe): This does not work on win2k. // PERFORMANCE_INFORMATION info; // if (GetPerformanceInfo(&info, sizeof(info))) // return info.CommitTotal * system_info.dwPageSize; return -1; } void PrintChromeMemoryUsageInfo() { printf("\n"); BrowserProcessFilter chrome_filter(L""); process_util::NamedProcessIterator chrome_process_itr(chrome::kBrowserProcessExecutableName, &chrome_filter); const PROCESSENTRY32* chrome_entry; while (chrome_entry = chrome_process_itr.NextProcessEntry()) { uint32 pid = chrome_entry->th32ProcessID; size_t peak_virtual_size; size_t current_virtual_size; size_t peak_working_set_size; size_t current_working_set_size; if (GetMemoryInfo(pid, &peak_virtual_size, &current_virtual_size, &peak_working_set_size, &current_working_set_size)) { if (pid == chrome_filter.browser_process_id()) { wprintf(L"browser_vm_peak = %d\n", peak_virtual_size); wprintf(L"browser_vm_current = %d\n", current_virtual_size); wprintf(L"browser_ws_peak = %d\n", peak_working_set_size); wprintf(L"browser_ws_final = %d\n", current_working_set_size); } else { wprintf(L"render_vm_peak = %d\n", peak_virtual_size); wprintf(L"render_vm_current = %d\n", current_virtual_size); wprintf(L"render_ws_peak = %d\n", peak_working_set_size); wprintf(L"render_ws_final = %d\n", current_working_set_size); } } }; } <commit_msg>Don't link directly against GetPerformanceInfo so that win2k can be happy.<commit_after>// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <windows.h> #include <psapi.h> #include "base/basictypes.h" #include "base/process_util.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_process_filter.h" #include "chrome/test/perf/mem_usage.h" bool GetMemoryInfo(uint32 process_id, size_t *peak_virtual_size, size_t *current_virtual_size, size_t *peak_working_set_size, size_t *current_working_set_size) { if (!peak_virtual_size || !current_virtual_size) return false; HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_id); if (!process_handle) return false; PROCESS_MEMORY_COUNTERS_EX pmc; bool result = false; if (GetProcessMemoryInfo(process_handle, reinterpret_cast<PPROCESS_MEMORY_COUNTERS>(&pmc), sizeof(pmc))) { *peak_virtual_size = pmc.PeakPagefileUsage; *current_virtual_size = pmc.PagefileUsage; *peak_working_set_size = pmc.PeakWorkingSetSize; *current_working_set_size = pmc.WorkingSetSize; result = true; } CloseHandle(process_handle); return result; } // GetPerformanceInfo is not available on WIN2K. So we'll // load it on-the-fly. const wchar_t kPsapiDllName[] = L"psapi.dll"; typedef BOOL (WINAPI *GetPerformanceInfoFunction) ( PPERFORMANCE_INFORMATION pPerformanceInformation, DWORD cb); static BOOL InternalGetPerformanceInfo( PPERFORMANCE_INFORMATION pPerformanceInformation, DWORD cb) { static GetPerformanceInfoFunction GetPerformanceInfo_func = NULL; if (!GetPerformanceInfo_func) { HMODULE psapi_dll = ::GetModuleHandle(kPsapiDllName); if (psapi_dll) GetPerformanceInfo_func = reinterpret_cast<GetPerformanceInfoFunction>( GetProcAddress(psapi_dll, "GetPerformanceInfo")); if (!GetPerformanceInfo_func) { // The function could be loaded! memset(pPerformanceInformation, 0, cb); return FALSE; } } return GetPerformanceInfo_func(pPerformanceInformation, cb); } size_t GetSystemCommitCharge() { // Get the System Page Size. SYSTEM_INFO system_info; GetSystemInfo(&system_info); PERFORMANCE_INFORMATION info; if (InternalGetPerformanceInfo(&info, sizeof(info))) return info.CommitTotal * system_info.dwPageSize; return -1; } void PrintChromeMemoryUsageInfo() { printf("\n"); BrowserProcessFilter chrome_filter(L""); process_util::NamedProcessIterator chrome_process_itr(chrome::kBrowserProcessExecutableName, &chrome_filter); const PROCESSENTRY32* chrome_entry; while (chrome_entry = chrome_process_itr.NextProcessEntry()) { uint32 pid = chrome_entry->th32ProcessID; size_t peak_virtual_size; size_t current_virtual_size; size_t peak_working_set_size; size_t current_working_set_size; if (GetMemoryInfo(pid, &peak_virtual_size, &current_virtual_size, &peak_working_set_size, &current_working_set_size)) { if (pid == chrome_filter.browser_process_id()) { wprintf(L"browser_vm_peak = %d\n", peak_virtual_size); wprintf(L"browser_vm_current = %d\n", current_virtual_size); wprintf(L"browser_ws_peak = %d\n", peak_working_set_size); wprintf(L"browser_ws_final = %d\n", current_working_set_size); } else { wprintf(L"render_vm_peak = %d\n", peak_virtual_size); wprintf(L"render_vm_current = %d\n", current_virtual_size); wprintf(L"render_ws_peak = %d\n", peak_working_set_size); wprintf(L"render_ws_final = %d\n", current_working_set_size); } } }; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: mediatypedetectionhelper.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:44:52 $ * * 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 * ************************************************************************/ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_SERVICES_MEDIATYPEDETECTIONHELPER_HXX_ #include <services/mediatypedetectionhelper.hxx> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif #ifndef _INETTYPE_HXX #include <svtools/inettype.hxx> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework { using namespace ::com::sun::star ; using namespace ::rtl ; //_________________________________________________________________________________________________________________ // declarations //_________________________________________________________________________________________________________________ //***************************************************************************************************************** // constructor //***************************************************************************************************************** MediaTypeDetectionHelper::MediaTypeDetectionHelper( const uno::Reference< lang::XMultiServiceFactory >& xFactory ) : m_xFactory( xFactory ) { } //***************************************************************************************************************** // destructor //***************************************************************************************************************** MediaTypeDetectionHelper::~MediaTypeDetectionHelper() { } //***************************************************************************************************************** // XInterface, XTypeProvider, XServiceInfo //***************************************************************************************************************** DEFINE_XINTERFACE_3 ( MediaTypeDetectionHelper , OWeakObject , DIRECT_INTERFACE( lang::XTypeProvider ) , DIRECT_INTERFACE( lang::XServiceInfo ) , DIRECT_INTERFACE( util::XStringMapping ) ) DEFINE_XTYPEPROVIDER_3 ( MediaTypeDetectionHelper , lang::XTypeProvider , lang::XServiceInfo , util::XStringMapping ) DEFINE_XSERVICEINFO_ONEINSTANCESERVICE ( MediaTypeDetectionHelper , ::cppu::OWeakObject , SERVICENAME_MEDIATYPEDETECTIONHELPER , IMPLEMENTATIONNAME_MEDIATYPEDETECTIONHELPER ) DEFINE_INIT_SERVICE ( MediaTypeDetectionHelper, { } ) //***************************************************************************************************************** // XStringMapping //***************************************************************************************************************** //virtual sal_Bool SAL_CALL MediaTypeDetectionHelper::mapStrings( uno::Sequence< OUString >& rSeq ) throw(uno::RuntimeException) { sal_Bool bModified = sal_False; for( sal_Int32 i = rSeq.getLength(); i--; ) { OUString& rUrl = rSeq[i]; INetContentType eType = INetContentTypes::GetContentTypeFromURL( rUrl ); UniString aType( INetContentTypes::GetContentType( eType ) ); if( aType.Len() ) { rUrl = aType; bModified = sal_True; } } return bModified; } } // namespace framework <commit_msg>INTEGRATION: CWS pchfix02 (1.7.202); FILE MERGED 2006/09/01 17:29:19 kaib 1.7.202.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: mediatypedetectionhelper.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2006-09-16 14:10:33 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_framework.hxx" //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_SERVICES_MEDIATYPEDETECTIONHELPER_HXX_ #include <services/mediatypedetectionhelper.hxx> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif #ifndef _INETTYPE_HXX #include <svtools/inettype.hxx> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework { using namespace ::com::sun::star ; using namespace ::rtl ; //_________________________________________________________________________________________________________________ // declarations //_________________________________________________________________________________________________________________ //***************************************************************************************************************** // constructor //***************************************************************************************************************** MediaTypeDetectionHelper::MediaTypeDetectionHelper( const uno::Reference< lang::XMultiServiceFactory >& xFactory ) : m_xFactory( xFactory ) { } //***************************************************************************************************************** // destructor //***************************************************************************************************************** MediaTypeDetectionHelper::~MediaTypeDetectionHelper() { } //***************************************************************************************************************** // XInterface, XTypeProvider, XServiceInfo //***************************************************************************************************************** DEFINE_XINTERFACE_3 ( MediaTypeDetectionHelper , OWeakObject , DIRECT_INTERFACE( lang::XTypeProvider ) , DIRECT_INTERFACE( lang::XServiceInfo ) , DIRECT_INTERFACE( util::XStringMapping ) ) DEFINE_XTYPEPROVIDER_3 ( MediaTypeDetectionHelper , lang::XTypeProvider , lang::XServiceInfo , util::XStringMapping ) DEFINE_XSERVICEINFO_ONEINSTANCESERVICE ( MediaTypeDetectionHelper , ::cppu::OWeakObject , SERVICENAME_MEDIATYPEDETECTIONHELPER , IMPLEMENTATIONNAME_MEDIATYPEDETECTIONHELPER ) DEFINE_INIT_SERVICE ( MediaTypeDetectionHelper, { } ) //***************************************************************************************************************** // XStringMapping //***************************************************************************************************************** //virtual sal_Bool SAL_CALL MediaTypeDetectionHelper::mapStrings( uno::Sequence< OUString >& rSeq ) throw(uno::RuntimeException) { sal_Bool bModified = sal_False; for( sal_Int32 i = rSeq.getLength(); i--; ) { OUString& rUrl = rSeq[i]; INetContentType eType = INetContentTypes::GetContentTypeFromURL( rUrl ); UniString aType( INetContentTypes::GetContentType( eType ) ); if( aType.Len() ) { rUrl = aType; bModified = sal_True; } } return bModified; } } // namespace framework <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef BITMAP_H #define BITMAP_H struct static_bitmap { typedef uint64_t data_type; static constexpr const size_t bits_per_word = sizeof(data_type) * 8; size_t words; data_type* data; template<typename Array> void init(Array& array){ words = array.size(); data = array.data(); } void init(size_t w, data_type* d){ words = w; data = d; } static constexpr size_t word_offset(size_t bit){ return bit / bits_per_word; } static constexpr size_t bit_offset(size_t bit){ return bit % bits_per_word; } static constexpr data_type bit_mask(size_t bit){ return static_cast<data_type>(1) << bit_offset(bit); } void clear_all(){ for(size_t i = 0; i < words; ++i){ data[i] = 0; } } void set_all(){ for(size_t i = 0; i < words; ++i){ data[i] = ~static_cast<data_type>(0); } } size_t free_bit() const { for(size_t w = 0; w < words; ++w){ if(data[w] > 0){ for(size_t b = 0; b < bits_per_word; ++b){ if(data[w] & bit_mask(b)){ return w * bits_per_word + b; } } } } //TODO Use an assert here return 0; } size_t free_word() const { for(size_t w = 0; w < words; ++w){ if(data[w] == ~static_cast<data_type>(0)){ return w * bits_per_word; } } //TODO Use an assert here return 0; } bool is_set(size_t bit) const { return data[word_offset(bit)] & bit_mask(bit); } void set(size_t bit){ data[word_offset(bit)] |= bit_mask(bit); } void unset(size_t bit){ data[word_offset(bit)] &= ~bit_mask(bit); } }; #endif <commit_msg>Add assertions<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef BITMAP_H #define BITMAP_H #include "assert.hpp" struct static_bitmap { typedef uint64_t data_type; static constexpr const size_t bits_per_word = sizeof(data_type) * 8; size_t words; data_type* data; template<typename Array> void init(Array& array){ words = array.size(); data = array.data(); } void init(size_t w, data_type* d){ words = w; data = d; } static constexpr size_t word_offset(size_t bit){ return bit / bits_per_word; } static constexpr size_t bit_offset(size_t bit){ return bit % bits_per_word; } static constexpr data_type bit_mask(size_t bit){ return static_cast<data_type>(1) << bit_offset(bit); } void clear_all(){ for(size_t i = 0; i < words; ++i){ data[i] = 0; } } void set_all(){ for(size_t i = 0; i < words; ++i){ data[i] = ~static_cast<data_type>(0); } } size_t free_bit() const { for(size_t w = 0; w < words; ++w){ if(data[w] > 0){ for(size_t b = 0; b < bits_per_word; ++b){ if(data[w] & bit_mask(b)){ return w * bits_per_word + b; } } } } thor_unreachable("static_bitmap has not free bit"); } size_t free_word() const { for(size_t w = 0; w < words; ++w){ if(data[w] == ~static_cast<data_type>(0)){ return w * bits_per_word; } } thor_unreachable("static_bitmap has no free word"); } bool is_set(size_t bit) const { return data[word_offset(bit)] & bit_mask(bit); } void set(size_t bit){ data[word_offset(bit)] |= bit_mask(bit); } void unset(size_t bit){ data[word_offset(bit)] &= ~bit_mask(bit); } }; #endif <|endoftext|>
<commit_before>/* * Main Menu-bar */ #include <stdint.h> #include <stdio.h> #include <vector> #include <SDL2/SDL.h> #include "imgui.h" extern "C" { #include "util.h" #include "snepulator.h" #include "config.h" #include "gamepad.h" #include "video/tms9928a.h" #include "video/sms_vdp.h" #include "cpu/z80.h" #include "sg-1000.h" #include "sms.h" #include "colecovision.h" extern Z80_Regs z80_regs; extern TMS9928A_Mode sms_vdp_mode_get (void); /* TODO: Access through a function instead of accessing the array */ extern Gamepad_Instance gamepad_list[128]; extern uint32_t gamepad_list_count; extern Snepulator_Gamepad gamepad_1; extern Snepulator_Gamepad gamepad_2; } #include "gui/input.h" #include "gui/menubar.h" #include "gui/open.h" extern Snepulator_State state; extern File_Open_State open_state; extern bool config_capture_events; /* TODO: Move into state */ void snepulator_load_rom (char *path); void snepulator_load_sms_bios (char *path); void snepulator_load_colecovision_bios (char *path); /* * Render the menubar. */ void snepulator_render_menubar (void) { bool open_modal = false; bool input_modal = false; if (ImGui::BeginMainMenuBar ()) { if (ImGui::BeginMenu ("File")) { if (ImGui::MenuItem ("Load ROM...", NULL)) { state.running = false; open_state.title = "Load ROM..."; snepulator_set_open_regex (".*\\.(bin|col|gg|sg|sms)$"); open_state.callback = snepulator_load_rom; open_modal = true; } if (ImGui::BeginMenu ("Load BIOS...")) { if (ImGui::MenuItem ("Master System", NULL)) { state.running = false; open_state.title = "Load Master System BIOS..."; snepulator_set_open_regex (".*\\.(bin|sms)$"); open_state.callback = snepulator_load_sms_bios; open_modal = true; } if (ImGui::MenuItem ("ColecoVision", NULL)) { state.running = false; open_state.title = "Load ColecoVision BIOS..."; snepulator_set_open_regex (".*\\.(col)$"); open_state.callback = snepulator_load_colecovision_bios; open_modal = true; } if (ImGui::BeginMenu ("Clear")) { if (ImGui::MenuItem ("Master System", NULL)) { config_entry_remove ("sms", "bios"); config_write (); if (state.sms_bios_filename != NULL) { free (state.sms_bios_filename); state.sms_bios_filename = NULL; } } if (ImGui::MenuItem ("ColecoVision", NULL)) { config_entry_remove ("colecovision", "bios"); config_write (); if (state.colecovision_bios_filename != NULL) { free (state.colecovision_bios_filename); state.colecovision_bios_filename = NULL; } } ImGui::EndMenu (); } ImGui::EndMenu (); } if (ImGui::MenuItem ("Pause", NULL, !state.running)) { if (state.ready) { if (state.running) { snepulator_pause (); } else { state.running = true; } } } ImGui::Separator (); if (ImGui::MenuItem ("Quit", NULL)) { state.abort = true; } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Audio")) { if (ImGui::BeginMenu ("Device")) { int count = SDL_GetNumAudioDevices (0); for (int i = 0; i < count; i++) { const char *audio_device_name = SDL_GetAudioDeviceName (i, 0); if (audio_device_name == NULL) audio_device_name = "Unknown Audio Device"; if (ImGui::MenuItem (audio_device_name, NULL)) { } } ImGui::EndMenu (); } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Video")) { if (ImGui::BeginMenu ("Filter")) { if (ImGui::MenuItem ("GL_NEAREST", NULL, state.video_filter == VIDEO_FILTER_NEAREST)) { state.video_filter = VIDEO_FILTER_NEAREST; config_string_set ("video", "filter", "GL_NEAREST"); config_write (); } if (ImGui::MenuItem ("GL_LINEAR", NULL, state.video_filter == VIDEO_FILTER_LINEAR)) { state.video_filter = VIDEO_FILTER_LINEAR; config_string_set ("video", "filter", "GL_LINEAR"); config_write (); } if (ImGui::MenuItem ("Scanlines", NULL, state.video_filter == VIDEO_FILTER_SCANLINES)) { state.video_filter = VIDEO_FILTER_SCANLINES; config_string_set ("video", "filter", "Scanlines"); config_write (); } ImGui::EndMenu (); } if (ImGui::BeginMenu ("3D Mode")) { if (ImGui::MenuItem ("Left image only", NULL, state.video_3d_mode == VIDEO_3D_LEFT_ONLY)) { state.video_3d_mode = VIDEO_3D_LEFT_ONLY; } if (ImGui::MenuItem ("Right image only", NULL, state.video_3d_mode == VIDEO_3D_RIGHT_ONLY)) { state.video_3d_mode = VIDEO_3D_RIGHT_ONLY; } if (ImGui::MenuItem ("Red-Cyan", NULL, state.video_3d_mode == VIDEO_3D_RED_CYAN)) { state.video_3d_mode = VIDEO_3D_RED_CYAN; } if (ImGui::MenuItem ("Red-Green", NULL, state.video_3d_mode == VIDEO_3D_RED_GREEN)) { state.video_3d_mode = VIDEO_3D_RED_GREEN; } if (ImGui::MenuItem ("Magenta-Green", NULL, state.video_3d_mode == VIDEO_3D_MAGENTA_GREEN)) { state.video_3d_mode = VIDEO_3D_MAGENTA_GREEN; } ImGui::Separator (); if (ImGui::BeginMenu ("Colour")) { if (ImGui::MenuItem ("Saturation 0%", NULL, state.video_3d_saturation == 0.0)) { state.video_3d_saturation = 0.0; } if (ImGui::MenuItem ("Saturation 25%", NULL, state.video_3d_saturation == 0.25)) { state.video_3d_saturation = 0.25; } if (ImGui::MenuItem ("Saturation 50%", NULL, state.video_3d_saturation == 0.50)) { state.video_3d_saturation = 0.50; } if (ImGui::MenuItem ("Saturation 75%", NULL, state.video_3d_saturation == 0.75)) { state.video_3d_saturation = 0.75; } if (ImGui::MenuItem ("Saturation 100%", NULL, state.video_3d_saturation == 1.0)) { state.video_3d_saturation = 1.0; } ImGui::EndMenu (); } ImGui::EndMenu (); } if (ImGui::MenuItem ("Take Screenshot")) { snepulator_take_screenshot (); } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Console")) { if (ImGui::MenuItem ("Hard Reset")) { system_init (); } ImGui::Separator (); if (ImGui::MenuItem ("World", NULL, state.region == REGION_WORLD)) { state.region = REGION_WORLD; config_string_set ("sms", "region", "World"); config_write (); } if (ImGui::MenuItem ("Japan", NULL, state.region == REGION_JAPAN)) { state.region = REGION_JAPAN; config_string_set ("sms", "region", "Japan"); config_write (); } ImGui::Separator (); if (ImGui::MenuItem ("Auto", NULL, state.format_auto)) { state.format_auto = true; config_string_set ("sms", "format", "Auto"); config_write (); } if (ImGui::MenuItem ("NTSC", NULL, state.format == VIDEO_FORMAT_NTSC)) { state.format = VIDEO_FORMAT_NTSC; state.format_auto = false; config_string_set ("sms", "format", "NTSC"); config_write (); } if (ImGui::MenuItem ("PAL", NULL, state.format == VIDEO_FORMAT_PAL)) { state.format = VIDEO_FORMAT_PAL; state.format_auto = false; config_string_set ("sms", "format", "PAL"); config_write (); } ImGui::Separator (); if (ImGui::BeginMenu ("Info")) { ImGui::Text ("CPU"); ImGui::Text ("PC : %04x SP : %04x", z80_regs.pc, z80_regs.sp); ImGui::Text ("AF : %04x BC : %04x", z80_regs.af, z80_regs.bc); ImGui::Text ("DE : %04x HL : %04x", z80_regs.de, z80_regs.hl); ImGui::Text ("IX : %04x IY : %04x", z80_regs.ix, z80_regs.iy); ImGui::Text ("IM : %d IFF: %d/%d", z80_regs.im, z80_regs.iff1, z80_regs.iff2); ImGui::Separator (); ImGui::Text ("Video"); ImGui::Text ("Mode : %s", tms9928a_mode_name_get (sms_vdp_mode_get ())); ImGui::EndMenu (); } if (ImGui::BeginMenu ("Statistics")) { ImGui::Text ("Video"); ImGui::Text ("Host: %.2f fps", state.host_framerate); ImGui::Text ("VDP: %.2f fps", state.vdp_framerate); ImGui::Separator (); ImGui::Text ("Audio"); ImGui::Text ("Ring buffer: %.2f%% full", state.audio_ring_utilisation * 100.0); ImGui::EndMenu (); } if (ImGui::MenuItem ("Time Five Minutes", NULL)) { uint32_t start_time; uint32_t end_time; state.running = false; start_time = SDL_GetTicks (); state.run (5 * 60000); /* Simulate five minutes */ end_time = SDL_GetTicks (); state.running = true; fprintf (stdout, "[DEBUG] Took %d ms to emulate five minutes. (%fx speed-up)\n", end_time - start_time, (5.0 * 60000.0) / (end_time - start_time)); } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Input")) { if (ImGui::BeginMenu ("Player 1")) { if (ImGui::BeginMenu ("Type")) { if (ImGui::MenuItem ("Auto", NULL, gamepad_1.type_auto)) { gamepad_1.type_auto = true; } if (ImGui::MenuItem ("SMS Gamepad", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS)) { gamepad_1.type = GAMEPAD_TYPE_SMS; gamepad_1.type_auto = false; } if (ImGui::MenuItem ("SMS Light Phaser", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS_PHASER)) { gamepad_1.type = GAMEPAD_TYPE_SMS_PHASER; gamepad_1.type_auto = false; } if (ImGui::MenuItem ("SMS Paddle", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS_PADDLE)) { gamepad_1.type = GAMEPAD_TYPE_SMS_PADDLE; gamepad_1.type_auto = false; } ImGui::EndMenu (); } ImGui::Separator (); for (int i = 0; i < gamepad_list_count; i++) { if (ImGui::MenuItem (gamepad_get_name (i), NULL, gamepad_list [i].instance_id == gamepad_1.instance_id)) { gamepad_change_device (1, i); } } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Player 2")) { for (int i = 0; i < gamepad_list_count; i++) { if (ImGui::MenuItem (gamepad_get_name (i), NULL, gamepad_list [i].instance_id == gamepad_2.instance_id)) { gamepad_change_device (2, i); } } ImGui::EndMenu (); } if (ImGui::MenuItem ("Configure...", NULL)) { input_start (); input_modal = true; } ImGui::EndMenu (); } ImGui::EndMainMenuBar (); } /* Open any popups requested */ if (open_modal) { ImGui::OpenPopup (open_state.title); } if (input_modal) { config_capture_events = true; ImGui::OpenPopup ("Configure device..."); } } <commit_msg>gui: Include console name in 'Info' menu<commit_after>/* * Main Menu-bar */ #include <stdint.h> #include <stdio.h> #include <vector> #include <SDL2/SDL.h> #include "imgui.h" extern "C" { #include "util.h" #include "snepulator.h" #include "config.h" #include "gamepad.h" #include "video/tms9928a.h" #include "video/sms_vdp.h" #include "cpu/z80.h" #include "sg-1000.h" #include "sms.h" #include "colecovision.h" extern Z80_Regs z80_regs; extern TMS9928A_Mode sms_vdp_mode_get (void); /* TODO: Access through a function instead of accessing the array */ extern Gamepad_Instance gamepad_list[128]; extern uint32_t gamepad_list_count; extern Snepulator_Gamepad gamepad_1; extern Snepulator_Gamepad gamepad_2; } #include "gui/input.h" #include "gui/menubar.h" #include "gui/open.h" extern Snepulator_State state; extern File_Open_State open_state; extern bool config_capture_events; /* TODO: Move into state */ void snepulator_load_rom (char *path); void snepulator_load_sms_bios (char *path); void snepulator_load_colecovision_bios (char *path); /* * Render the menubar. */ void snepulator_render_menubar (void) { bool open_modal = false; bool input_modal = false; if (ImGui::BeginMainMenuBar ()) { if (ImGui::BeginMenu ("File")) { if (ImGui::MenuItem ("Load ROM...", NULL)) { state.running = false; open_state.title = "Load ROM..."; snepulator_set_open_regex (".*\\.(bin|col|gg|sg|sms)$"); open_state.callback = snepulator_load_rom; open_modal = true; } if (ImGui::BeginMenu ("Load BIOS...")) { if (ImGui::MenuItem ("Master System", NULL)) { state.running = false; open_state.title = "Load Master System BIOS..."; snepulator_set_open_regex (".*\\.(bin|sms)$"); open_state.callback = snepulator_load_sms_bios; open_modal = true; } if (ImGui::MenuItem ("ColecoVision", NULL)) { state.running = false; open_state.title = "Load ColecoVision BIOS..."; snepulator_set_open_regex (".*\\.(col)$"); open_state.callback = snepulator_load_colecovision_bios; open_modal = true; } if (ImGui::BeginMenu ("Clear")) { if (ImGui::MenuItem ("Master System", NULL)) { config_entry_remove ("sms", "bios"); config_write (); if (state.sms_bios_filename != NULL) { free (state.sms_bios_filename); state.sms_bios_filename = NULL; } } if (ImGui::MenuItem ("ColecoVision", NULL)) { config_entry_remove ("colecovision", "bios"); config_write (); if (state.colecovision_bios_filename != NULL) { free (state.colecovision_bios_filename); state.colecovision_bios_filename = NULL; } } ImGui::EndMenu (); } ImGui::EndMenu (); } if (ImGui::MenuItem ("Pause", NULL, !state.running)) { if (state.ready) { if (state.running) { snepulator_pause (); } else { state.running = true; } } } ImGui::Separator (); if (ImGui::MenuItem ("Quit", NULL)) { state.abort = true; } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Audio")) { if (ImGui::BeginMenu ("Device")) { int count = SDL_GetNumAudioDevices (0); for (int i = 0; i < count; i++) { const char *audio_device_name = SDL_GetAudioDeviceName (i, 0); if (audio_device_name == NULL) audio_device_name = "Unknown Audio Device"; if (ImGui::MenuItem (audio_device_name, NULL)) { } } ImGui::EndMenu (); } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Video")) { if (ImGui::BeginMenu ("Filter")) { if (ImGui::MenuItem ("GL_NEAREST", NULL, state.video_filter == VIDEO_FILTER_NEAREST)) { state.video_filter = VIDEO_FILTER_NEAREST; config_string_set ("video", "filter", "GL_NEAREST"); config_write (); } if (ImGui::MenuItem ("GL_LINEAR", NULL, state.video_filter == VIDEO_FILTER_LINEAR)) { state.video_filter = VIDEO_FILTER_LINEAR; config_string_set ("video", "filter", "GL_LINEAR"); config_write (); } if (ImGui::MenuItem ("Scanlines", NULL, state.video_filter == VIDEO_FILTER_SCANLINES)) { state.video_filter = VIDEO_FILTER_SCANLINES; config_string_set ("video", "filter", "Scanlines"); config_write (); } ImGui::EndMenu (); } if (ImGui::BeginMenu ("3D Mode")) { if (ImGui::MenuItem ("Left image only", NULL, state.video_3d_mode == VIDEO_3D_LEFT_ONLY)) { state.video_3d_mode = VIDEO_3D_LEFT_ONLY; } if (ImGui::MenuItem ("Right image only", NULL, state.video_3d_mode == VIDEO_3D_RIGHT_ONLY)) { state.video_3d_mode = VIDEO_3D_RIGHT_ONLY; } if (ImGui::MenuItem ("Red-Cyan", NULL, state.video_3d_mode == VIDEO_3D_RED_CYAN)) { state.video_3d_mode = VIDEO_3D_RED_CYAN; } if (ImGui::MenuItem ("Red-Green", NULL, state.video_3d_mode == VIDEO_3D_RED_GREEN)) { state.video_3d_mode = VIDEO_3D_RED_GREEN; } if (ImGui::MenuItem ("Magenta-Green", NULL, state.video_3d_mode == VIDEO_3D_MAGENTA_GREEN)) { state.video_3d_mode = VIDEO_3D_MAGENTA_GREEN; } ImGui::Separator (); if (ImGui::BeginMenu ("Colour")) { if (ImGui::MenuItem ("Saturation 0%", NULL, state.video_3d_saturation == 0.0)) { state.video_3d_saturation = 0.0; } if (ImGui::MenuItem ("Saturation 25%", NULL, state.video_3d_saturation == 0.25)) { state.video_3d_saturation = 0.25; } if (ImGui::MenuItem ("Saturation 50%", NULL, state.video_3d_saturation == 0.50)) { state.video_3d_saturation = 0.50; } if (ImGui::MenuItem ("Saturation 75%", NULL, state.video_3d_saturation == 0.75)) { state.video_3d_saturation = 0.75; } if (ImGui::MenuItem ("Saturation 100%", NULL, state.video_3d_saturation == 1.0)) { state.video_3d_saturation = 1.0; } ImGui::EndMenu (); } ImGui::EndMenu (); } if (ImGui::MenuItem ("Take Screenshot")) { snepulator_take_screenshot (); } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Console")) { if (ImGui::MenuItem ("Hard Reset")) { system_init (); } ImGui::Separator (); if (ImGui::MenuItem ("World", NULL, state.region == REGION_WORLD)) { state.region = REGION_WORLD; config_string_set ("sms", "region", "World"); config_write (); } if (ImGui::MenuItem ("Japan", NULL, state.region == REGION_JAPAN)) { state.region = REGION_JAPAN; config_string_set ("sms", "region", "Japan"); config_write (); } ImGui::Separator (); if (ImGui::MenuItem ("Auto", NULL, state.format_auto)) { state.format_auto = true; config_string_set ("sms", "format", "Auto"); config_write (); } if (ImGui::MenuItem ("NTSC", NULL, state.format == VIDEO_FORMAT_NTSC)) { state.format = VIDEO_FORMAT_NTSC; state.format_auto = false; config_string_set ("sms", "format", "NTSC"); config_write (); } if (ImGui::MenuItem ("PAL", NULL, state.format == VIDEO_FORMAT_PAL)) { state.format = VIDEO_FORMAT_PAL; state.format_auto = false; config_string_set ("sms", "format", "PAL"); config_write (); } ImGui::Separator (); if (ImGui::BeginMenu ("Info")) { ImGui::Text ("%s", state.console == CONSOLE_MASTER_SYSTEM ? "Master System" : state.console == CONSOLE_GAME_GEAR ? "Game Gear" : state.console == CONSOLE_SG_1000 ? "SG-1000" : state.console == CONSOLE_COLECOVISION ? "ColecoVision" : "N/A"); ImGui::Separator (); ImGui::Text ("CPU"); ImGui::Text ("PC : %04x SP : %04x", z80_regs.pc, z80_regs.sp); ImGui::Text ("AF : %04x BC : %04x", z80_regs.af, z80_regs.bc); ImGui::Text ("DE : %04x HL : %04x", z80_regs.de, z80_regs.hl); ImGui::Text ("IX : %04x IY : %04x", z80_regs.ix, z80_regs.iy); ImGui::Text ("IM : %d IFF: %d/%d", z80_regs.im, z80_regs.iff1, z80_regs.iff2); ImGui::Separator (); ImGui::Text ("Video"); ImGui::Text ("Mode : %s", tms9928a_mode_name_get (sms_vdp_mode_get ())); ImGui::EndMenu (); } if (ImGui::BeginMenu ("Statistics")) { ImGui::Text ("Video"); ImGui::Text ("Host: %.2f fps", state.host_framerate); ImGui::Text ("VDP: %.2f fps", state.vdp_framerate); ImGui::Separator (); ImGui::Text ("Audio"); ImGui::Text ("Ring buffer: %.2f%% full", state.audio_ring_utilisation * 100.0); ImGui::EndMenu (); } if (ImGui::MenuItem ("Time Five Minutes", NULL)) { uint32_t start_time; uint32_t end_time; state.running = false; start_time = SDL_GetTicks (); state.run (5 * 60000); /* Simulate five minutes */ end_time = SDL_GetTicks (); state.running = true; fprintf (stdout, "[DEBUG] Took %d ms to emulate five minutes. (%fx speed-up)\n", end_time - start_time, (5.0 * 60000.0) / (end_time - start_time)); } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Input")) { if (ImGui::BeginMenu ("Player 1")) { if (ImGui::BeginMenu ("Type")) { if (ImGui::MenuItem ("Auto", NULL, gamepad_1.type_auto)) { gamepad_1.type_auto = true; } if (ImGui::MenuItem ("SMS Gamepad", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS)) { gamepad_1.type = GAMEPAD_TYPE_SMS; gamepad_1.type_auto = false; } if (ImGui::MenuItem ("SMS Light Phaser", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS_PHASER)) { gamepad_1.type = GAMEPAD_TYPE_SMS_PHASER; gamepad_1.type_auto = false; } if (ImGui::MenuItem ("SMS Paddle", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS_PADDLE)) { gamepad_1.type = GAMEPAD_TYPE_SMS_PADDLE; gamepad_1.type_auto = false; } ImGui::EndMenu (); } ImGui::Separator (); for (int i = 0; i < gamepad_list_count; i++) { if (ImGui::MenuItem (gamepad_get_name (i), NULL, gamepad_list [i].instance_id == gamepad_1.instance_id)) { gamepad_change_device (1, i); } } ImGui::EndMenu (); } if (ImGui::BeginMenu ("Player 2")) { for (int i = 0; i < gamepad_list_count; i++) { if (ImGui::MenuItem (gamepad_get_name (i), NULL, gamepad_list [i].instance_id == gamepad_2.instance_id)) { gamepad_change_device (2, i); } } ImGui::EndMenu (); } if (ImGui::MenuItem ("Configure...", NULL)) { input_start (); input_modal = true; } ImGui::EndMenu (); } ImGui::EndMainMenuBar (); } /* Open any popups requested */ if (open_modal) { ImGui::OpenPopup (open_state.title); } if (input_modal) { config_capture_events = true; ImGui::OpenPopup ("Configure device..."); } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include <services/mediatypedetectionhelper.hxx> #include <services.h> #include <svl/inettype.hxx> #include <tools/string.hxx> #include <rtl/logfile.hxx> namespace framework { using namespace ::com::sun::star ; using namespace ::rtl ; //***************************************************************************************************************** // constructor //***************************************************************************************************************** MediaTypeDetectionHelper::MediaTypeDetectionHelper( const uno::Reference< lang::XMultiServiceFactory >& xFactory ) : m_xFactory( xFactory ) { } //***************************************************************************************************************** // destructor //***************************************************************************************************************** MediaTypeDetectionHelper::~MediaTypeDetectionHelper() { } DEFINE_XSERVICEINFO_ONEINSTANCESERVICE ( MediaTypeDetectionHelper , ::cppu::OWeakObject , DECLARE_ASCII("com.sun.star.frame.MediaTypeDetectionHelper") , IMPLEMENTATIONNAME_MEDIATYPEDETECTIONHELPER ) DEFINE_INIT_SERVICE ( MediaTypeDetectionHelper, { } ) //***************************************************************************************************************** // XStringMapping //***************************************************************************************************************** sal_Bool SAL_CALL MediaTypeDetectionHelper::mapStrings( uno::Sequence< OUString >& rSeq ) throw(uno::RuntimeException) { sal_Bool bModified = sal_False; for( sal_Int32 i = rSeq.getLength(); i--; ) { OUString& rUrl = rSeq[i]; INetContentType eType = INetContentTypes::GetContentTypeFromURL( rUrl ); rtl::OUString aType( INetContentTypes::GetContentType( eType ) ); if (!aType.isEmpty()) { rUrl = aType; bModified = sal_True; } } return bModified; } } // namespace framework /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Improve previous commit slightly<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include <services/mediatypedetectionhelper.hxx> #include <services.h> #include <svl/inettype.hxx> #include <tools/string.hxx> #include <rtl/logfile.hxx> namespace framework { using namespace ::com::sun::star ; using namespace ::rtl ; //***************************************************************************************************************** // constructor //***************************************************************************************************************** MediaTypeDetectionHelper::MediaTypeDetectionHelper( const uno::Reference< lang::XMultiServiceFactory >& xFactory ) : m_xFactory( xFactory ) { } //***************************************************************************************************************** // destructor //***************************************************************************************************************** MediaTypeDetectionHelper::~MediaTypeDetectionHelper() { } DEFINE_XSERVICEINFO_ONEINSTANCESERVICE ( MediaTypeDetectionHelper , ::cppu::OWeakObject , "com.sun.star.frame.MediaTypeDetectionHelper" , IMPLEMENTATIONNAME_MEDIATYPEDETECTIONHELPER ) DEFINE_INIT_SERVICE ( MediaTypeDetectionHelper, { } ) //***************************************************************************************************************** // XStringMapping //***************************************************************************************************************** sal_Bool SAL_CALL MediaTypeDetectionHelper::mapStrings( uno::Sequence< OUString >& rSeq ) throw(uno::RuntimeException) { sal_Bool bModified = sal_False; for( sal_Int32 i = rSeq.getLength(); i--; ) { OUString& rUrl = rSeq[i]; INetContentType eType = INetContentTypes::GetContentTypeFromURL( rUrl ); rtl::OUString aType( INetContentTypes::GetContentType( eType ) ); if (!aType.isEmpty()) { rUrl = aType; bModified = sal_True; } } return bModified; } } // namespace framework /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#ifndef VECTOR_H #define VECTOR_H #include "types.hpp" template<typename T> class vector { public: typedef T value_type; typedef value_type* pointer_type; typedef uint64_t size_type; typedef value_type* iterator; typedef const value_type* const_iterator; private: T* data; uint64_t _size; uint64_t _capacity; public: vector() : data(nullptr), _size(0), _capacity(0) {} explicit vector(uint64_t c) : data(new T[c]), _size(0), _capacity(c) {} // Disable copy for now vector(const vector& rhs) = delete; vector& operator=(const vector& rhs) = delete; //Move constructors vector(vector&& rhs) : data(rhs.data), _size(rhs._size), _capacity(rhs._capacity) { rhs.data = nullptr; rhs._size = 0; rhs._capacity = 0; }; vector& operator=(vector&& rhs){ data = rhs.data; _size = rhs._size; _capacity = rhs._capacity; rhs.data = nullptr; rhs._size = 0; rhs._capacity = 0; return *this; } ~vector(){ if(data){ delete[] data; } } //Getters size_type size() const { return _size; } size_type capacity() const { return _capacity; } const value_type& operator[](size_type pos) const { return data[pos]; } value_type& operator[](size_type pos){ return data[pos]; } //Modifiers void push_back(value_type& element){ if(_capacity == 0){ _capacity = 1; data = new T[_capacity]; } else if(_capacity == _size){ _capacity= _capacity * 2; auto new_data = new T[_capacity]; for(size_type i = 0; i < _size; ++i){ new_data[i] = data[i]; } delete[] data; data = new_data; } data[_size++] = element; } //Iterators iterator begin(){ return iterator(&data[0]); } const_iterator begin() const { return const_iterator(&data[0]); } iterator end(){ return iterator(&data[_size]); } const_iterator end() const { return const_iterator(&data[_size]); } }; #endif <commit_msg>Add constexpr when possible<commit_after>#ifndef VECTOR_H #define VECTOR_H #include "types.hpp" template<typename T> class vector { public: typedef T value_type; typedef value_type* pointer_type; typedef uint64_t size_type; typedef value_type* iterator; typedef const value_type* const_iterator; private: T* data; uint64_t _size; uint64_t _capacity; public: vector() : data(nullptr), _size(0), _capacity(0) {} explicit vector(uint64_t c) : data(new T[c]), _size(0), _capacity(c) {} // Disable copy for now vector(const vector& rhs) = delete; vector& operator=(const vector& rhs) = delete; //Move constructors vector(vector&& rhs) : data(rhs.data), _size(rhs._size), _capacity(rhs._capacity) { rhs.data = nullptr; rhs._size = 0; rhs._capacity = 0; }; vector& operator=(vector&& rhs){ data = rhs.data; _size = rhs._size; _capacity = rhs._capacity; rhs.data = nullptr; rhs._size = 0; rhs._capacity = 0; return *this; } ~vector(){ if(data){ delete[] data; } } //Getters constexpr size_type size() const { return _size; } constexpr size_type capacity() const { return _capacity; } constexpr const value_type& operator[](size_type pos) const { return data[pos]; } value_type& operator[](size_type pos){ return data[pos]; } //Modifiers void push_back(value_type& element){ if(_capacity == 0){ _capacity = 1; data = new T[_capacity]; } else if(_capacity == _size){ _capacity= _capacity * 2; auto new_data = new T[_capacity]; for(size_type i = 0; i < _size; ++i){ new_data[i] = data[i]; } delete[] data; data = new_data; } data[_size++] = element; } //Iterators iterator begin(){ return iterator(&data[0]); } constexpr const_iterator begin() const { return const_iterator(&data[0]); } iterator end(){ return iterator(&data[_size]); } constexpr const_iterator end() const { return const_iterator(&data[_size]); } }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: canvastools.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2005-04-18 09:15:25 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _BGFX_TOOLS_CANVASTOOLS_HXX #define _BGFX_TOOLS_CANVASTOOLS_HXX #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif namespace com { namespace sun { namespace star { namespace geometry { struct AffineMatrix2D; struct RealPoint2D; struct RealSize2D; struct RealRectangle2D; struct IntegerPoint2D; struct IntegerSize2D; struct IntegerRectangle2D; struct RealBezierSegment2D; } } } } namespace com { namespace sun { namespace star { namespace rendering { class XGraphicDevice; class XPolyPolygon2D; } } } } namespace com { namespace sun { namespace star { namespace awt { struct Point; struct Size; struct Rectangle; } } } } namespace basegfx { class B2DHomMatrix; class B2DVector; class B2DPoint; class B2DRange; class B2IVector; class B2IPoint; class B2IRange; class B2DPolygon; class B2DPolyPolygon; namespace unotools { // Polygon conversions // =================================================================== ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D > xPolyPolygonFromB2DPolygon( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XGraphicDevice >& xGraphicDevice, const ::basegfx::B2DPolygon& rPoly ); ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D > xPolyPolygonFromB2DPolyPolygon( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XGraphicDevice >& xGraphicDevice, const ::basegfx::B2DPolyPolygon& rPolyPoly ); ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealBezierSegment2D > > bezierSequenceSequenceFromB2DPolyPolygon( const ::basegfx::B2DPolyPolygon& rPolyPoly ); ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealPoint2D > > pointSequenceSequenceFromB2DPolyPolygon( const ::basegfx::B2DPolyPolygon& rPolyPoly ); ::basegfx::B2DPolygon polygonFromPoint2DSequence( const ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealPoint2D >& rPoints ); ::basegfx::B2DPolyPolygon polyPolygonFromPoint2DSequenceSequence( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealPoint2D > >& rPoints ); ::basegfx::B2DPolygon polygonFromBezier2DSequence( const ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealBezierSegment2D >& rPoints ); ::basegfx::B2DPolyPolygon polyPolygonFromBezier2DSequenceSequence( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealBezierSegment2D > >& rPoints ); // Matrix conversions // =================================================================== ::com::sun::star::geometry::AffineMatrix2D& affineMatrixFromHomMatrix( ::com::sun::star::geometry::AffineMatrix2D& matrix, const ::basegfx::B2DHomMatrix& transform); ::basegfx::B2DHomMatrix& homMatrixFromAffineMatrix( ::basegfx::B2DHomMatrix& transform, const ::com::sun::star::geometry::AffineMatrix2D& matrix ); // Geometry conversions // =================================================================== ::com::sun::star::geometry::RealSize2D size2DFromB2DSize( const ::basegfx::B2DVector& ); ::com::sun::star::geometry::RealPoint2D point2DFromB2DPoint( const ::basegfx::B2DPoint& ); ::com::sun::star::geometry::RealRectangle2D rectangle2DFromB2DRectangle( const ::basegfx::B2DRange& ); ::basegfx::B2DVector b2DSizeFromRealSize2D( const ::com::sun::star::geometry::RealSize2D& ); ::basegfx::B2DPoint b2DPointFromRealPoint2D( const ::com::sun::star::geometry::RealPoint2D& ); ::basegfx::B2DRange b2DRectangleFromRealRectangle2D( const ::com::sun::star::geometry::RealRectangle2D& ); ::com::sun::star::geometry::IntegerSize2D integerSize2DFromB2ISize( const ::basegfx::B2IVector& ); ::com::sun::star::geometry::IntegerPoint2D integerPoint2DFromB2IPoint( const ::basegfx::B2IPoint& ); ::com::sun::star::geometry::IntegerRectangle2D integerRectangle2DFromB2IRectangle( const ::basegfx::B2IRange& ); ::basegfx::B2IVector b2ISizeFromIntegerSize2D( const ::com::sun::star::geometry::IntegerSize2D& ); ::basegfx::B2IPoint b2IPointFromIntegerPoint2D( const ::com::sun::star::geometry::IntegerPoint2D& ); ::basegfx::B2IRange b2IRectangleFromIntegerRectangle2D( const ::com::sun::star::geometry::IntegerRectangle2D& ); ::com::sun::star::awt::Size awtSizeFromB2ISize( const ::basegfx::B2IVector& ); ::com::sun::star::awt::Point awtPointFromB2IPoint( const ::basegfx::B2IPoint& ); ::com::sun::star::awt::Rectangle awtRectangleFromB2IRectangle( const ::basegfx::B2IRange& ); ::basegfx::B2IVector b2ISizeFromAwtSize( const ::com::sun::star::awt::Size& ); ::basegfx::B2IPoint b2IPointFromAwtPoint( const ::com::sun::star::awt::Point& ); ::basegfx::B2IRange b2IRectangleFromAwtRectangle( const ::com::sun::star::awt::Rectangle& ); } } #endif /* _BGFX_TOOLS_CANVASTOOLS_HXX */ <commit_msg>INTEGRATION: CWS ooo19126 (1.5.16); FILE MERGED 2005/09/05 17:38:29 rt 1.5.16.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: canvastools.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-07 20:35:18 $ * * 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 _BGFX_TOOLS_CANVASTOOLS_HXX #define _BGFX_TOOLS_CANVASTOOLS_HXX #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif namespace com { namespace sun { namespace star { namespace geometry { struct AffineMatrix2D; struct RealPoint2D; struct RealSize2D; struct RealRectangle2D; struct IntegerPoint2D; struct IntegerSize2D; struct IntegerRectangle2D; struct RealBezierSegment2D; } } } } namespace com { namespace sun { namespace star { namespace rendering { class XGraphicDevice; class XPolyPolygon2D; } } } } namespace com { namespace sun { namespace star { namespace awt { struct Point; struct Size; struct Rectangle; } } } } namespace basegfx { class B2DHomMatrix; class B2DVector; class B2DPoint; class B2DRange; class B2IVector; class B2IPoint; class B2IRange; class B2DPolygon; class B2DPolyPolygon; namespace unotools { // Polygon conversions // =================================================================== ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D > xPolyPolygonFromB2DPolygon( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XGraphicDevice >& xGraphicDevice, const ::basegfx::B2DPolygon& rPoly ); ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D > xPolyPolygonFromB2DPolyPolygon( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XGraphicDevice >& xGraphicDevice, const ::basegfx::B2DPolyPolygon& rPolyPoly ); ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealBezierSegment2D > > bezierSequenceSequenceFromB2DPolyPolygon( const ::basegfx::B2DPolyPolygon& rPolyPoly ); ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealPoint2D > > pointSequenceSequenceFromB2DPolyPolygon( const ::basegfx::B2DPolyPolygon& rPolyPoly ); ::basegfx::B2DPolygon polygonFromPoint2DSequence( const ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealPoint2D >& rPoints ); ::basegfx::B2DPolyPolygon polyPolygonFromPoint2DSequenceSequence( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealPoint2D > >& rPoints ); ::basegfx::B2DPolygon polygonFromBezier2DSequence( const ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealBezierSegment2D >& rPoints ); ::basegfx::B2DPolyPolygon polyPolygonFromBezier2DSequenceSequence( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealBezierSegment2D > >& rPoints ); // Matrix conversions // =================================================================== ::com::sun::star::geometry::AffineMatrix2D& affineMatrixFromHomMatrix( ::com::sun::star::geometry::AffineMatrix2D& matrix, const ::basegfx::B2DHomMatrix& transform); ::basegfx::B2DHomMatrix& homMatrixFromAffineMatrix( ::basegfx::B2DHomMatrix& transform, const ::com::sun::star::geometry::AffineMatrix2D& matrix ); // Geometry conversions // =================================================================== ::com::sun::star::geometry::RealSize2D size2DFromB2DSize( const ::basegfx::B2DVector& ); ::com::sun::star::geometry::RealPoint2D point2DFromB2DPoint( const ::basegfx::B2DPoint& ); ::com::sun::star::geometry::RealRectangle2D rectangle2DFromB2DRectangle( const ::basegfx::B2DRange& ); ::basegfx::B2DVector b2DSizeFromRealSize2D( const ::com::sun::star::geometry::RealSize2D& ); ::basegfx::B2DPoint b2DPointFromRealPoint2D( const ::com::sun::star::geometry::RealPoint2D& ); ::basegfx::B2DRange b2DRectangleFromRealRectangle2D( const ::com::sun::star::geometry::RealRectangle2D& ); ::com::sun::star::geometry::IntegerSize2D integerSize2DFromB2ISize( const ::basegfx::B2IVector& ); ::com::sun::star::geometry::IntegerPoint2D integerPoint2DFromB2IPoint( const ::basegfx::B2IPoint& ); ::com::sun::star::geometry::IntegerRectangle2D integerRectangle2DFromB2IRectangle( const ::basegfx::B2IRange& ); ::basegfx::B2IVector b2ISizeFromIntegerSize2D( const ::com::sun::star::geometry::IntegerSize2D& ); ::basegfx::B2IPoint b2IPointFromIntegerPoint2D( const ::com::sun::star::geometry::IntegerPoint2D& ); ::basegfx::B2IRange b2IRectangleFromIntegerRectangle2D( const ::com::sun::star::geometry::IntegerRectangle2D& ); ::com::sun::star::awt::Size awtSizeFromB2ISize( const ::basegfx::B2IVector& ); ::com::sun::star::awt::Point awtPointFromB2IPoint( const ::basegfx::B2IPoint& ); ::com::sun::star::awt::Rectangle awtRectangleFromB2IRectangle( const ::basegfx::B2IRange& ); ::basegfx::B2IVector b2ISizeFromAwtSize( const ::com::sun::star::awt::Size& ); ::basegfx::B2IPoint b2IPointFromAwtPoint( const ::com::sun::star::awt::Point& ); ::basegfx::B2IRange b2IRectangleFromAwtRectangle( const ::com::sun::star::awt::Rectangle& ); } } #endif /* _BGFX_TOOLS_CANVASTOOLS_HXX */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: graphicnameaccess.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2004-07-06 16:58:28 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_UICONFIGURATION_GRAPHICNAMEACCESS_HXX_ #include <uiconfiguration/graphicnameaccess.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #include <comphelper/sequence.hxx> using namespace ::com::sun::star; namespace framework { GraphicNameAccess::GraphicNameAccess() { } GraphicNameAccess::~GraphicNameAccess() { } void GraphicNameAccess::addElement( const rtl::OUString& rName, const uno::Reference< graphic::XGraphic >& rElement ) { m_aNameToElementMap.insert( NameGraphicHashMap::value_type( rName, rElement )); } sal_uInt32 GraphicNameAccess::size() const { return m_aNameToElementMap.size(); } // XNameAccess uno::Any SAL_CALL GraphicNameAccess::getByName( const ::rtl::OUString& aName ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException) { NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.find( aName ); if ( pIter != m_aNameToElementMap.end() ) return uno::makeAny( pIter->second ); else throw container::NoSuchElementException(); } uno::Sequence< ::rtl::OUString > SAL_CALL GraphicNameAccess::getElementNames() throw(::com::sun::star::uno::RuntimeException) { if ( m_aSeq.getLength() == 0 ) { uno::Sequence< rtl::OUString > aSeq( m_aNameToElementMap.size() ); NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.begin(); sal_Int32 i( 0); while ( pIter != m_aNameToElementMap.end()) { aSeq[i++] = pIter->first; ++pIter; } m_aSeq = aSeq; } return m_aSeq; } sal_Bool SAL_CALL GraphicNameAccess::hasByName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException) { NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.find( aName ); return ( pIter != m_aNameToElementMap.end() ); } // XElementAccess sal_Bool SAL_CALL GraphicNameAccess::hasElements() throw( uno::RuntimeException ) { return ( m_aNameToElementMap.size() > 0 ); } uno::Type SAL_CALL GraphicNameAccess::getElementType() throw( uno::RuntimeException ) { return ::getCppuType( (const uno::Reference< graphic::XGraphic > *)NULL ); } } // namespace framework <commit_msg>INTEGRATION: CWS ooo19126 (1.2.288); FILE MERGED 2005/09/05 13:07:02 rt 1.2.288.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: graphicnameaccess.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:49:39 $ * * 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 __FRAMEWORK_UICONFIGURATION_GRAPHICNAMEACCESS_HXX_ #include <uiconfiguration/graphicnameaccess.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #include <comphelper/sequence.hxx> using namespace ::com::sun::star; namespace framework { GraphicNameAccess::GraphicNameAccess() { } GraphicNameAccess::~GraphicNameAccess() { } void GraphicNameAccess::addElement( const rtl::OUString& rName, const uno::Reference< graphic::XGraphic >& rElement ) { m_aNameToElementMap.insert( NameGraphicHashMap::value_type( rName, rElement )); } sal_uInt32 GraphicNameAccess::size() const { return m_aNameToElementMap.size(); } // XNameAccess uno::Any SAL_CALL GraphicNameAccess::getByName( const ::rtl::OUString& aName ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException) { NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.find( aName ); if ( pIter != m_aNameToElementMap.end() ) return uno::makeAny( pIter->second ); else throw container::NoSuchElementException(); } uno::Sequence< ::rtl::OUString > SAL_CALL GraphicNameAccess::getElementNames() throw(::com::sun::star::uno::RuntimeException) { if ( m_aSeq.getLength() == 0 ) { uno::Sequence< rtl::OUString > aSeq( m_aNameToElementMap.size() ); NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.begin(); sal_Int32 i( 0); while ( pIter != m_aNameToElementMap.end()) { aSeq[i++] = pIter->first; ++pIter; } m_aSeq = aSeq; } return m_aSeq; } sal_Bool SAL_CALL GraphicNameAccess::hasByName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException) { NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.find( aName ); return ( pIter != m_aNameToElementMap.end() ); } // XElementAccess sal_Bool SAL_CALL GraphicNameAccess::hasElements() throw( uno::RuntimeException ) { return ( m_aNameToElementMap.size() > 0 ); } uno::Type SAL_CALL GraphicNameAccess::getElementType() throw( uno::RuntimeException ) { return ::getCppuType( (const uno::Reference< graphic::XGraphic > *)NULL ); } } // namespace framework <|endoftext|>
<commit_before>/* Copyright (c) 2010-2012 Delft University of Technology. * * This software is protected by national and international copyright. * Any unauthorized use, reproduction or modification is unlawful and * will be prosecuted. Commercial and non-private application of the * software in any form is strictly prohibited unless otherwise granted * by the authors. * * The code is provided without any warranty; without even the implied * warranty of merchantibility or fitness for a particular purpose. * * Changelog * YYMMDD Author Comment * 101203 E. Iorfida First creation of the code. * 101208 E. Iorfida Fulfillment of the code with the elliptical case. * 101208 E. Iorfida Modified punctuation. * 101215 E. Iorfida Added tolerance, added parabolic, circular and hyperbolic * cases. * 101217 E. Iorfida Added computeAbsoluteValue( ) in the errors computation, * modified punctuation. * 101219 J. Melman Put gravitational parameters in one place, changed first right * ascension to 15.0 * pi / 8.0, thereby exposing a possible * error. * 110107 E. Iorfida orbitalConversionBookExampleUnitTest.test added to this file, * to have a unique unit test file for the conversion code. Also * some punctuation modifications have been made. * 110109 J. Melman Included test for semi-latus rectum of circular case. Gave the * orbital angles less trivial values, and not almost exclusively * in the first quadrant. * 110111 E. Iorfida Updated to the new format of unitTest file and added hyperbolic * equatorial case. * 110204 K. Kumar Removed "vector" from naming. * 110216 K. Kumar Added unit tests for new orbital element conversion functions. * 110310 K. Kumar Changed right ascension of ascending node to longitude of * ascending node. * 110510 K. Kumar Updated to use new orbital element conversion functions and * removed dynamic memory allocation. * * References * http://www.astro.uu.nl/~strous/AA/en/reken/kepler.html, last accessed: 16th February, 2011. * Vallado, D. A., McClain, W. D. Fundamentals of astrodynamics and applications, 2nd Edition, * Kluwer Academic Publishers, The Netherlands, 2004. * Fortescue, P. W., et al. Spacecraft systems engineering, Third Edition, * Wiley, England, 2003. * */ // Temporary notes (move to class/function doxygen): // Test runs code and verifies result against expected value. // If the tested code is erroneous, the test function returns a boolean // true; if the code is correct, the function returns a boolean false. // #include <cmath> #include <iostream> #include <limits> #include <TudatCore/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h> #include <TudatCore/Astrodynamics/BasicAstrodynamics/unitConversions.h> #include "Tudat/Astrodynamics/BasicAstrodynamics/convertMeanAnomalyToEccentricAnomaly.h" #include "Tudat/Astrodynamics/BasicAstrodynamics/convertMeanAnomalyToHyperbolicEccentricAnomaly.h" #include "Tudat/Astrodynamics/Bodies/celestialBody.h" #include "Tudat/Astrodynamics/Bodies/planet.h" #include "Tudat/Astrodynamics/Gravitation/gravityFieldModel.h" #include "Tudat/Astrodynamics/Gravitation/sphericalHarmonicsGravityField.h" #include "Tudat/Mathematics/RootFindingMethods/newtonRaphson.h" //! Test orbital element conversion code. int main( ) { // Using declarations. using std::cerr; using std::endl; using std::fabs; using std::pow; using tudat::orbital_element_conversions::convertCartesianToKeplerianElements; using tudat::orbital_element_conversions::convertKeplerianToCartesianElements; using tudat::orbital_element_conversions::ConvertMeanAnomalyToEccentricAnomaly; using tudat::orbital_element_conversions::ConvertMeanAnomalyToHyperbolicEccentricAnomaly; using namespace tudat; // Test of orbital element conversion methods imeplemented in Tudat. // Test 1: Test of mean anomaly to eccentric anomaly conversion. // Initialize unit test result to false. bool isOrbitalElementConversionErroneous = false; // Test 1: Test of mean anomaly to eccentric anomaly conversion. // Source: ( Vallado, 2004 ). // Set tolerance for conversion. double toleranceOrbitalElementConversion = 1e-8; // Set eccentricity. double eccentricity = 0.01671; // Set mean anomaly. double meanAnomaly = unit_conversions::convertDegreesToRadians( 60.0 ); // Create Newton-Raphson object. NewtonRaphson newtonRaphson; // Create object for mean anomaly to eccentric anomaly conversion. orbital_element_conversions::ConvertMeanAnomalyToEccentricAnomaly convertMeanAnomalyToEccentricAnomaly( eccentricity, meanAnomaly, &newtonRaphson ); // Compute eccentric anomaly. double eccentricAnomaly = convertMeanAnomalyToEccentricAnomaly.convert( ); // Check if computed eccentric anomaly is equal to reference value. if ( fabs( eccentricAnomaly - 1.061789204 ) > toleranceOrbitalElementConversion ) { isOrbitalElementConversionErroneous = true; cerr << "The conversion of mean anomaly to eccentric anomaly is " << "erroneous as the computed eccentric anomaly after applying the conversion ( " << unit_conversions::convertRadiansToDegrees( eccentricAnomaly ) << " ) does not match the expected value of the eccentric anomaly ( " << unit_conversions::convertRadiansToDegrees( 1.061789204 ) << " ) " << endl; } // Return test result. // If test is successful return false; if test fails, return true. if ( isOrbitalElementConversionErroneous ) { cerr << "testOrbitalElementConversions failed!" << endl; } return isOrbitalElementConversionErroneous; } <commit_msg>Removed old (superfluous) orbital elements unit test (issue #409).<commit_after><|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 "GenericConstantRankTwoTensor.h" registerMooseObject("MooseApp", GenericConstantRankTwoTensor); registerMooseObject("MooseApp", ADGenericConstantRankTwoTensor); template <bool is_ad> InputParameters GenericConstantRankTwoTensorTempl<is_ad>::validParams() { InputParameters params = Material::validParams(); params.addClassDescription( "Object for declaring a constant rank two tensor as a material property."); params.addRequiredParam<std::vector<Real>>( "tensor_values", "Vector of values defining the constant rank two tensor"); params.addRequiredParam<MaterialPropertyName>( "tensor_name", "Name of the tensor material property to be created"); params.set<MooseEnum>("constant_on") = "SUBDOMAIN"; return params; } template <bool is_ad> GenericConstantRankTwoTensorTempl<is_ad>::GenericConstantRankTwoTensorTempl( const InputParameters & parameters) : Material(parameters), _prop( declareGenericProperty<RankTwoTensor, is_ad>(getParam<MaterialPropertyName>("tensor_name"))) { _tensor.fillFromInputVector(getParam<std::vector<Real>>("tensor_values")); } template <bool is_ad> void GenericConstantRankTwoTensorTempl<is_ad>::initQpStatefulProperties() { GenericConstantRankTwoTensorTempl<is_ad>::computeQpProperties(); } template <bool is_ad> void GenericConstantRankTwoTensorTempl<is_ad>::computeQpProperties() { _prop[_qp] = _tensor; } template class GenericConstantRankTwoTensorTempl<false>; template class GenericConstantRankTwoTensorTempl<true>;<commit_msg>This should resolve #22619. Added an extra empty line at the end<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 "GenericConstantRankTwoTensor.h" registerMooseObject("MooseApp", GenericConstantRankTwoTensor); registerMooseObject("MooseApp", ADGenericConstantRankTwoTensor); template <bool is_ad> InputParameters GenericConstantRankTwoTensorTempl<is_ad>::validParams() { InputParameters params = Material::validParams(); params.addClassDescription( "Object for declaring a constant rank two tensor as a material property."); params.addRequiredParam<std::vector<Real>>( "tensor_values", "Vector of values defining the constant rank two tensor"); params.addRequiredParam<MaterialPropertyName>( "tensor_name", "Name of the tensor material property to be created"); params.set<MooseEnum>("constant_on") = "SUBDOMAIN"; return params; } template <bool is_ad> GenericConstantRankTwoTensorTempl<is_ad>::GenericConstantRankTwoTensorTempl( const InputParameters & parameters) : Material(parameters), _prop( declareGenericProperty<RankTwoTensor, is_ad>(getParam<MaterialPropertyName>("tensor_name"))) { _tensor.fillFromInputVector(getParam<std::vector<Real>>("tensor_values")); } template <bool is_ad> void GenericConstantRankTwoTensorTempl<is_ad>::initQpStatefulProperties() { GenericConstantRankTwoTensorTempl<is_ad>::computeQpProperties(); } template <bool is_ad> void GenericConstantRankTwoTensorTempl<is_ad>::computeQpProperties() { _prop[_qp] = _tensor; } template class GenericConstantRankTwoTensorTempl<false>; template class GenericConstantRankTwoTensorTempl<true>; <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/initfiles/p10_nmmu_scom.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2019,2020 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p10_nmmu_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; fapi2::ReturnCode p10_nmmu_scom(const fapi2::Target<fapi2::TARGET_TYPE_NMMU>& TGT0, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT2) { { fapi2::ATTR_EC_Type l_chip_ec; fapi2::ATTR_NAME_Type l_chip_id; FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT1, l_chip_id)); FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT1, l_chip_ec)); fapi2::ATTR_PROC_FABRIC_BROADCAST_MODE_Type l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_BROADCAST_MODE, TGT2, l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE)); fapi2::buffer<uint64_t> l_scom_buffer; { FAPI_TRY(fapi2::getScom( TGT0, 0x2010c15ull, l_scom_buffer )); if ((l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE != fapi2::ENUM_ATTR_PROC_FABRIC_BROADCAST_MODE_1HOP_CHIP_IS_GROUP)) { constexpr auto l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_ON = 0x1; l_scom_buffer.insert<39, 1, 63, uint64_t>(l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_ON ); } else if ((l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_BROADCAST_MODE_1HOP_CHIP_IS_GROUP)) { constexpr auto l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_OFF = 0x0; l_scom_buffer.insert<39, 1, 63, uint64_t>(l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_OFF ); } FAPI_TRY(fapi2::putScom(TGT0, 0x2010c15ull, l_scom_buffer)); } }; fapi_try_exit: return fapi2::current_err; } <commit_msg>Enable epsilons in nmmu scom initfile<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/initfiles/p10_nmmu_scom.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2019,2020 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p10_nmmu_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; constexpr uint64_t literal_0 = 0; constexpr uint64_t literal_0x001 = 0x001; fapi2::ReturnCode p10_nmmu_scom(const fapi2::Target<fapi2::TARGET_TYPE_NMMU>& TGT0, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT2) { { fapi2::ATTR_EC_Type l_chip_ec; fapi2::ATTR_NAME_Type l_chip_id; FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT1, l_chip_id)); FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT1, l_chip_ec)); fapi2::ATTR_PROC_FABRIC_BROADCAST_MODE_Type l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_BROADCAST_MODE, TGT2, l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE)); fapi2::ATTR_PROC_EPS_WRITE_CYCLES_T1_Type l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T1; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_EPS_WRITE_CYCLES_T1, TGT2, l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T1)); fapi2::ATTR_PROC_EPS_WRITE_CYCLES_T2_Type l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T2; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_EPS_WRITE_CYCLES_T2, TGT2, l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T2)); fapi2::buffer<uint64_t> l_scom_buffer; { FAPI_TRY(fapi2::getScom( TGT0, 0x2010c15ull, l_scom_buffer )); if ((l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE != fapi2::ENUM_ATTR_PROC_FABRIC_BROADCAST_MODE_1HOP_CHIP_IS_GROUP)) { constexpr auto l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_ON = 0x1; l_scom_buffer.insert<39, 1, 63, uint64_t>(l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_ON ); } else if ((l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_BROADCAST_MODE_1HOP_CHIP_IS_GROUP)) { constexpr auto l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_OFF = 0x0; l_scom_buffer.insert<39, 1, 63, uint64_t>(l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_OFF ); } FAPI_TRY(fapi2::putScom(TGT0, 0x2010c15ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x2010c1dull, l_scom_buffer )); if ((l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T1 != literal_0)) { l_scom_buffer.insert<0, 12, 52, uint64_t>(l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T1 ); } else if ((l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T1 == literal_0)) { l_scom_buffer.insert<0, 12, 52, uint64_t>(literal_0x001 ); } if ((l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T2 != literal_0)) { l_scom_buffer.insert<16, 12, 52, uint64_t>(l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T2 ); } else if ((l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T2 == literal_0)) { l_scom_buffer.insert<16, 12, 52, uint64_t>(literal_0x001 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x2010c1dull, l_scom_buffer)); } }; fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>// Copyright 2014 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "scheduling/request-pool-service.h" #include <list> #include <string> #include "common/logging.h" #include "rpc/thrift-util.h" #include "util/jni-util.h" #include "util/parse-util.h" using namespace std; using namespace impala; DEFINE_string(fair_scheduler_allocation_path, "", "Path to the fair scheduler " "allocation file (fair-scheduler.xml)."); DEFINE_string(llama_site_path, "", "Path to the Llama configuration file " "(llama-site.xml). If set, fair_scheduler_allocation_path must also be set."); // The default_pool parameters are used if fair scheduler allocation and Llama // configuration files are not provided. DEFINE_int64(default_pool_max_requests, -1, "Maximum number of concurrent outstanding " "requests allowed to run before queueing incoming requests. A negative value " "indicates no limit. 0 indicates no requests will be admitted. Ignored if " "fair_scheduler_config_path and llama_site_path are set."); DEFINE_string(default_pool_mem_limit, "", "Maximum amount of memory that all " "outstanding requests in this pool may use before new requests to this pool" " are queued. Specified as a number of bytes ('<int>[bB]?'), megabytes " "('<float>[mM]'), gigabytes ('<float>[gG]'), or percentage of the physical memory " "('<int>%'). 0 or not setting indicates no limit. Defaults to bytes if no unit is " "given. Ignored if fair_scheduler_config_path and llama_site_path are set."); DEFINE_int64(default_pool_max_queued, 0, "Maximum number of requests allowed to be " "queued before rejecting requests. A negative value or 0 indicates requests " "will always be rejected once the maximum number of concurrent requests are " "executing. Ignored if fair_scheduler_config_path and " "llama_site_path are set."); // Flags to disable the pool limits for all pools. DEFINE_bool(disable_pool_mem_limits, false, "Disables all per-pool mem limits."); DEFINE_bool(disable_pool_max_requests, false, "Disables all per-pool limits on the " "maximum number of running requests."); DECLARE_bool(enable_rm); // Pool name used when the configuration files are not specified. const string DEFAULT_POOL_NAME = "default-pool"; RequestPoolService::RequestPoolService() { if (FLAGS_fair_scheduler_allocation_path.empty() && FLAGS_llama_site_path.empty()) { if (FLAGS_enable_rm) { LOG(ERROR) << "If resource management is enabled, -fair_scheduler_allocation_path " << "is required."; exit(1); } default_pool_only_ = true; bool is_percent; // not used int64_t bytes_limit = ParseUtil::ParseMemSpec(FLAGS_default_pool_mem_limit, &is_percent); // -1 indicates an error occurred if (bytes_limit < 0) { LOG(ERROR) << "Unable to parse default pool mem limit from '" << FLAGS_default_pool_mem_limit << "'."; exit(1); } // 0 indicates no limit or not set if (bytes_limit == 0) { default_pool_mem_limit_ = -1; } else { default_pool_mem_limit_ = bytes_limit; } return; } default_pool_only_ = false; jmethodID start_id; // RequestPoolService.start(), only called in this method. JniMethodDescriptor methods[] = { {"<init>", "(Ljava/lang/String;Ljava/lang/String;)V", &ctor_}, {"start", "()V", &start_id}, {"resolveRequestPool", "([B)[B", &resolve_request_pool_id_}, {"getPoolConfig", "([B)[B", &get_pool_config_id_}}; JNIEnv* jni_env = getJNIEnv(); request_pool_service_class_ = jni_env->FindClass("com/cloudera/impala/util/RequestPoolService"); EXIT_IF_EXC(jni_env); uint32_t num_methods = sizeof(methods) / sizeof(methods[0]); for (int i = 0; i < num_methods; ++i) { EXIT_IF_ERROR(JniUtil::LoadJniMethod(jni_env, request_pool_service_class_, &(methods[i]))); } jstring fair_scheduler_config_path = jni_env->NewStringUTF(FLAGS_fair_scheduler_allocation_path.c_str()); EXIT_IF_EXC(jni_env); jstring llama_site_path = jni_env->NewStringUTF(FLAGS_llama_site_path.c_str()); EXIT_IF_EXC(jni_env); jobject request_pool_service = jni_env->NewObject(request_pool_service_class_, ctor_, fair_scheduler_config_path, llama_site_path); EXIT_IF_EXC(jni_env); EXIT_IF_ERROR(JniUtil::LocalToGlobalRef(jni_env, request_pool_service, &request_pool_service_)); jni_env->CallObjectMethod(request_pool_service_, start_id); EXIT_IF_EXC(jni_env); } Status RequestPoolService::ResolveRequestPool(const string& requested_pool_name, const string& user, TResolveRequestPoolResult* resolved_pool) { if (default_pool_only_) { resolved_pool->__set_resolved_pool(DEFAULT_POOL_NAME); resolved_pool->__set_has_access(true); return Status::OK; } TResolveRequestPoolParams params; params.__set_user(user); params.__set_requested_pool(requested_pool_name); return JniUtil::CallJniMethod(request_pool_service_, resolve_request_pool_id_, params, resolved_pool); } Status RequestPoolService::GetPoolConfig(const string& pool_name, TPoolConfigResult* pool_config) { if (default_pool_only_) { pool_config->__set_max_requests( FLAGS_disable_pool_max_requests ? -1 : FLAGS_default_pool_max_requests); pool_config->__set_mem_limit( FLAGS_disable_pool_mem_limits ? -1 : default_pool_mem_limit_); pool_config->__set_max_queued(FLAGS_default_pool_max_queued); return Status::OK; } TPoolConfigParams params; params.__set_pool(pool_name); RETURN_IF_ERROR(JniUtil::CallJniMethod( request_pool_service_, get_pool_config_id_, params, pool_config)); if (FLAGS_disable_pool_max_requests) pool_config->__set_max_requests(-1); if (FLAGS_disable_pool_mem_limits) pool_config->__set_mem_limit(-1); return Status::OK; } <commit_msg>Admission controller: Change default values for the "default pool"<commit_after>// Copyright 2014 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "scheduling/request-pool-service.h" #include <list> #include <string> #include "common/logging.h" #include "rpc/thrift-util.h" #include "util/jni-util.h" #include "util/parse-util.h" using namespace std; using namespace impala; DEFINE_string(fair_scheduler_allocation_path, "", "Path to the fair scheduler " "allocation file (fair-scheduler.xml)."); DEFINE_string(llama_site_path, "", "Path to the Llama configuration file " "(llama-site.xml). If set, fair_scheduler_allocation_path must also be set."); // The default_pool parameters are used if fair scheduler allocation and Llama // configuration files are not provided. The default values for this 'default pool' // are the same as the default values for pools defined via the fair scheduler // allocation file and Llama configurations. DEFINE_int64(default_pool_max_requests, 20, "Maximum number of concurrent outstanding " "requests allowed to run before queueing incoming requests. A negative value " "indicates no limit. 0 indicates no requests will be admitted. Ignored if " "fair_scheduler_config_path and llama_site_path are set."); DEFINE_string(default_pool_mem_limit, "", "Maximum amount of memory that all " "outstanding requests in this pool may use before new requests to this pool" " are queued. Specified as a number of bytes ('<int>[bB]?'), megabytes " "('<float>[mM]'), gigabytes ('<float>[gG]'), or percentage of the physical memory " "('<int>%'). 0 or not setting indicates no limit. Defaults to bytes if no unit is " "given. Ignored if fair_scheduler_config_path and llama_site_path are set."); DEFINE_int64(default_pool_max_queued, 50, "Maximum number of requests allowed to be " "queued before rejecting requests. A negative value or 0 indicates requests " "will always be rejected once the maximum number of concurrent requests are " "executing. Ignored if fair_scheduler_config_path and " "llama_site_path are set."); // Flags to disable the pool limits for all pools. DEFINE_bool(disable_pool_mem_limits, false, "Disables all per-pool mem limits."); DEFINE_bool(disable_pool_max_requests, false, "Disables all per-pool limits on the " "maximum number of running requests."); DECLARE_bool(enable_rm); // Pool name used when the configuration files are not specified. const string DEFAULT_POOL_NAME = "default-pool"; RequestPoolService::RequestPoolService() { if (FLAGS_fair_scheduler_allocation_path.empty() && FLAGS_llama_site_path.empty()) { if (FLAGS_enable_rm) { LOG(ERROR) << "If resource management is enabled, -fair_scheduler_allocation_path " << "is required."; exit(1); } default_pool_only_ = true; bool is_percent; // not used int64_t bytes_limit = ParseUtil::ParseMemSpec(FLAGS_default_pool_mem_limit, &is_percent); // -1 indicates an error occurred if (bytes_limit < 0) { LOG(ERROR) << "Unable to parse default pool mem limit from '" << FLAGS_default_pool_mem_limit << "'."; exit(1); } // 0 indicates no limit or not set if (bytes_limit == 0) { default_pool_mem_limit_ = -1; } else { default_pool_mem_limit_ = bytes_limit; } return; } default_pool_only_ = false; jmethodID start_id; // RequestPoolService.start(), only called in this method. JniMethodDescriptor methods[] = { {"<init>", "(Ljava/lang/String;Ljava/lang/String;)V", &ctor_}, {"start", "()V", &start_id}, {"resolveRequestPool", "([B)[B", &resolve_request_pool_id_}, {"getPoolConfig", "([B)[B", &get_pool_config_id_}}; JNIEnv* jni_env = getJNIEnv(); request_pool_service_class_ = jni_env->FindClass("com/cloudera/impala/util/RequestPoolService"); EXIT_IF_EXC(jni_env); uint32_t num_methods = sizeof(methods) / sizeof(methods[0]); for (int i = 0; i < num_methods; ++i) { EXIT_IF_ERROR(JniUtil::LoadJniMethod(jni_env, request_pool_service_class_, &(methods[i]))); } jstring fair_scheduler_config_path = jni_env->NewStringUTF(FLAGS_fair_scheduler_allocation_path.c_str()); EXIT_IF_EXC(jni_env); jstring llama_site_path = jni_env->NewStringUTF(FLAGS_llama_site_path.c_str()); EXIT_IF_EXC(jni_env); jobject request_pool_service = jni_env->NewObject(request_pool_service_class_, ctor_, fair_scheduler_config_path, llama_site_path); EXIT_IF_EXC(jni_env); EXIT_IF_ERROR(JniUtil::LocalToGlobalRef(jni_env, request_pool_service, &request_pool_service_)); jni_env->CallObjectMethod(request_pool_service_, start_id); EXIT_IF_EXC(jni_env); } Status RequestPoolService::ResolveRequestPool(const string& requested_pool_name, const string& user, TResolveRequestPoolResult* resolved_pool) { if (default_pool_only_) { resolved_pool->__set_resolved_pool(DEFAULT_POOL_NAME); resolved_pool->__set_has_access(true); return Status::OK; } TResolveRequestPoolParams params; params.__set_user(user); params.__set_requested_pool(requested_pool_name); return JniUtil::CallJniMethod(request_pool_service_, resolve_request_pool_id_, params, resolved_pool); } Status RequestPoolService::GetPoolConfig(const string& pool_name, TPoolConfigResult* pool_config) { if (default_pool_only_) { pool_config->__set_max_requests( FLAGS_disable_pool_max_requests ? -1 : FLAGS_default_pool_max_requests); pool_config->__set_mem_limit( FLAGS_disable_pool_mem_limits ? -1 : default_pool_mem_limit_); pool_config->__set_max_queued(FLAGS_default_pool_max_queued); return Status::OK; } TPoolConfigParams params; params.__set_pool(pool_name); RETURN_IF_ERROR(JniUtil::CallJniMethod( request_pool_service_, get_pool_config_id_, params, pool_config)); if (FLAGS_disable_pool_max_requests) pool_config->__set_max_requests(-1); if (FLAGS_disable_pool_mem_limits) pool_config->__set_mem_limit(-1); return Status::OK; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: scdll.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: nn $ $Date: 2000-10-19 18:32:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop #include <svx/eeitem.hxx> #define ITEMID_FIELD EE_FEATURE_FIELD #include "scitems.hxx" // fuer tbxctrls etc. #include "scmod.hxx" #include "scresid.hxx" #include "sc.hrc" #include "cfgids.hxx" //! die Registrierung wird wegen CLOOKs in ein eigenes File wandern muessen... // Interface-Registrierung #include "docsh.hxx" #include "tabvwsh.hxx" #include "prevwsh.hxx" #include "drawsh.hxx" #include "drformsh.hxx" #include "drtxtob.hxx" #include "editsh.hxx" #include "pivotsh.hxx" #include "auditsh.hxx" #include "cellsh.hxx" #include "oleobjsh.hxx" #include "chartsh.hxx" #include "graphsh.hxx" #include "pgbrksh.hxx" #include "docpool.hxx" #include "appoptio.hxx" // Controls #include <svx/tbxalign.hxx> #include <svx/tbxctl.hxx> #include <svx/fillctrl.hxx> #include <svx/linectrl.hxx> #include <svx/tbcontrl.hxx> #include <svx/selctrl.hxx> #include <svx/insctrl.hxx> #include <svx/zoomctrl.hxx> #include <svx/flditem.hxx> #include <svx/modctrl.hxx> #include <svx/pszctrl.hxx> #include <svx/fntctl.hxx> #include <svx/fntszctl.hxx> #include "tbinsert.hxx" // Child-Windows #include "reffact.hxx" #include "navipi.hxx" #include "inputwin.hxx" #include <svx/fontwork.hxx> #include <svx/srchdlg.hxx> #include <offmgr/hyprlink.hxx> #include <svx/imapdlg.hxx> #include "editutil.hxx" #include <svx/svdfield.hxx> // SdrRegisterFieldClasses #include "dwfunctr.hxx" #include "acredlin.hxx" //------------------------------------------------------------------ ScResId::ScResId( USHORT nId ) : ResId( nId, SC_MOD()->GetResMgr() ) { } //------------------------------------------------------------------ void ScDLL::Init() { // called directly after loading the DLL // do whatever you want, you may use Sxx-DLL too ScDocumentPool::InitVersionMaps(); // wird im ScModule ctor gebraucht // the ScModule must be created ScModuleDummy **ppShlPtr = (ScModuleDummy**) GetAppData(SHL_CALC); #ifndef SO3 SvFactory *pFact = (*ppShlPtr)->pScDocShellFactory; #else SvFactory *pFact = (SvFactory*)(*ppShlPtr)->pScDocShellFactory; #endif ScLibSignalFunc pFunc = (*ppShlPtr)->pSignalFunc; delete (*ppShlPtr); ScModule* pMod = new ScModule((SfxObjectFactory*)pFact); (*ppShlPtr) = pMod; (*ppShlPtr)->pScDocShellFactory = pFact; (*ppShlPtr)->pSignalFunc = pFunc; ScGlobal::Init(); // erst wenn der ResManager initialisiert ist // erst nach ScGlobal::Init duerfen die App-Optionen // initialisiert werden // register your view-factories here ScTabViewShell ::RegisterFactory(1); ScPreviewShell ::RegisterFactory(2); // register your shell-interfaces here ScModule ::RegisterInterface(pMod); ScDocShell ::RegisterInterface(pMod); ScTabViewShell ::RegisterInterface(pMod); ScPreviewShell ::RegisterInterface(pMod); ScDrawShell ::RegisterInterface(pMod); ScDrawFormShell ::RegisterInterface(pMod); ScDrawTextObjectBar ::RegisterInterface(pMod); ScEditShell ::RegisterInterface(pMod); ScPivotShell ::RegisterInterface(pMod); ScAuditingShell ::RegisterInterface(pMod); ScFormatShell ::RegisterInterface(pMod); ScCellShell ::RegisterInterface(pMod); ScOleObjectShell ::RegisterInterface(pMod); ScChartShell ::RegisterInterface(pMod); ScGraphicShell ::RegisterInterface(pMod); ScPageBreakShell ::RegisterInterface(pMod); // register your controllers here ScDocShell::Factory().RegisterMenuBar( ScResId(SCCFG_MENUBAR) ); ScDocShell::Factory().RegisterPluginMenuBar( ScResId(SCCFG_PLUGINMENU) ); ScDocShell::Factory().RegisterAccel( ScResId(SCCFG_ACCELERATOR) ); // eigene Controller ScTbxInsertCtrl ::RegisterControl(SID_TBXCTL_INSERT, pMod); ScTbxInsertCtrl ::RegisterControl(SID_TBXCTL_INSCELLS, pMod); ScTbxInsertCtrl ::RegisterControl(SID_TBXCTL_INSOBJ, pMod); // Svx-Toolbox-Controller SvxTbxCtlDraw ::RegisterControl(SID_INSERT_DRAW, pMod); SvxTbxCtlAlign ::RegisterControl(SID_OBJECT_ALIGN, pMod); SvxFillToolBoxControl ::RegisterControl(0, pMod); SvxLineStyleToolBoxControl ::RegisterControl(0, pMod); SvxLineWidthToolBoxControl ::RegisterControl(0, pMod); SvxLineColorToolBoxControl ::RegisterControl(0, pMod); SvxLineEndToolBoxControl ::RegisterControl(SID_ATTR_LINEEND_STYLE, pMod); SvxStyleToolBoxControl ::RegisterControl(SID_STYLE_APPLY, pMod); SvxFontNameToolBoxControl ::RegisterControl(SID_ATTR_CHAR_FONT, pMod); SvxFontHeightToolBoxControl ::RegisterControl(SID_ATTR_CHAR_FONTHEIGHT, pMod); SvxFontColorToolBoxControl ::RegisterControl(SID_ATTR_CHAR_COLOR, pMod); SvxColorToolBoxControl ::RegisterControl(SID_BACKGROUND_COLOR, pMod); SvxFrameToolBoxControl ::RegisterControl(SID_ATTR_BORDER, pMod); SvxFrameLineStyleToolBoxControl ::RegisterControl(SID_FRAME_LINESTYLE, pMod); SvxFrameLineColorToolBoxControl ::RegisterControl(SID_FRAME_LINECOLOR, pMod); // Svx-StatusBar-Controller SvxInsertStatusBarControl ::RegisterControl(SID_ATTR_INSERT, pMod); SvxSelectionModeControl ::RegisterControl(SID_STATUS_SELMODE, pMod); SvxZoomStatusBarControl ::RegisterControl(SID_ATTR_ZOOM, pMod); SvxModifyControl ::RegisterControl(SID_DOC_MODIFIED, pMod); SvxPosSizeStatusBarControl ::RegisterControl(SID_ATTR_SIZE, pMod); // Svx-Menue-Controller SvxFontMenuControl ::RegisterControl(SID_ATTR_CHAR_FONT, pMod); SvxFontSizeMenuControl ::RegisterControl(SID_ATTR_CHAR_FONTHEIGHT, pMod); // Child-Windows // Hack: Eingabezeile mit 42 registrieren, damit sie im PlugIn immer sichtbar ist ScInputWindowWrapper ::RegisterChildWindow(42, pMod, SFX_CHILDWIN_TASK); ScNavigatorDialogWrapper ::RegisterChildWindowContext(pMod); ScSolverDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScNameDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScPivotLayoutWrapper ::RegisterChildWindow(FALSE, pMod); ScTabOpDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScFilterDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScSpecialFilterDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScDbNameDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScConsolidateDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScChartDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScPrintAreasDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScCondFormatDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScColRowNameRangesDlgWrapper::RegisterChildWindow(FALSE, pMod); ScFormulaDlgWrapper ::RegisterChildWindow(FALSE, pMod); // First docking Window for Calc ScFunctionChildWindow ::RegisterChildWindow(FALSE, pMod); // Redlining- Window ScAcceptChgDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScSimpleRefDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScHighlightChgDlgWrapper ::RegisterChildWindow(FALSE, pMod); SvxFontWorkChildWindow ::RegisterChildWindow(FALSE, pMod); SvxHyperlinkDlgWrapper ::RegisterChildWindow(FALSE, pMod); SvxIMapDlgChildWindow ::RegisterChildWindow(FALSE, pMod); // Edit-Engine-Felder, soweit nicht schon in OfficeApplication::Init SvClassManager& rClassManager = SvxFieldItem::GetClassManager(); // rClassManager.SV_CLASS_REGISTER( SvxURLField ); // rClassManager.SV_CLASS_REGISTER( SvxDateField ); // rClassManager.SV_CLASS_REGISTER( SvxPageField ); rClassManager.SV_CLASS_REGISTER( SvxPagesField ); // rClassManager.SV_CLASS_REGISTER( SvxTimeField ); rClassManager.SV_CLASS_REGISTER( SvxFileField ); // rClassManager.SV_CLASS_REGISTER( SvxExtFileField ); rClassManager.SV_CLASS_REGISTER( SvxTableField ); SdrRegisterFieldClasses(); // SvDraw-Felder registrieren pMod->PutItem( SfxUInt16Item( SID_ATTR_METRIC, pMod->GetAppOptions().GetAppMetric() ) ); // StarOne Services are now handled in the registry } void ScDLL::Exit() { // called directly befor unloading the DLL // do whatever you want, Sxx-DLL is accessible // the SxxModule must be destroyed ScModuleDummy **ppShlPtr = (ScModuleDummy**) GetAppData(SHL_CALC); delete (*ppShlPtr); (*ppShlPtr) = NULL; // auf keinen Fall ein neues ScModuleDummy anlegen, weil dessen vtable sonst // in der DLL waere und das Loeschen im LibExit schiefgehen wuerde // ScGlobal::Clear ist schon im Module-dtor } //------------------------------------------------------------------ // Statusbar //------------------------------------------------------------------ #define TEXT_WIDTH(s) rStatusBar.GetTextWidth((s)) void ScDLL::FillStatusBar(StatusBar &rStatusBar) { // Dokumentposition (Tabelle x / y) rStatusBar.InsertItem( SID_STATUS_DOCPOS, TEXT_WIDTH( String().Fill( 10, 'X' ) ), SIB_LEFT|SIB_AUTOSIZE ); // Seitenvorlage rStatusBar.InsertItem( SID_STATUS_PAGESTYLE, TEXT_WIDTH( String().Fill( 15, 'X' ) ), SIB_LEFT|SIB_AUTOSIZE ); // Ma"sstab rStatusBar.InsertItem( SID_ATTR_ZOOM, SvxZoomStatusBarControl::GetDefItemWidth(rStatusBar), SIB_CENTER ); // Einfuege-/Ueberschreibmodus rStatusBar.InsertItem( SID_ATTR_INSERT, SvxInsertStatusBarControl::GetDefItemWidth(rStatusBar), SIB_CENTER ); // Selektionsmodus rStatusBar.InsertItem( SID_STATUS_SELMODE, SvxSelectionModeControl::GetDefItemWidth(rStatusBar), SIB_CENTER ); // Dokument geaendert rStatusBar.InsertItem( SID_DOC_MODIFIED, SvxModifyControl::GetDefItemWidth(rStatusBar)); // Mail rStatusBar.InsertItem( SID_MAIL_NOTIFY, TEXT_WIDTH( String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("Mail")) ), SIB_CENTER ); // den aktuellen Kontext anzeigen Uhrzeit / FramePos / TabellenInfo / Errors rStatusBar.InsertItem( SID_ATTR_SIZE, SvxPosSizeStatusBarControl::GetDefItemWidth(rStatusBar), SIB_AUTOSIZE|SIB_LEFT|SIB_USERDRAW); } #undef TEXT_WIDTH <commit_msg>register graphic toolbox controller<commit_after>/************************************************************************* * * $RCSfile: scdll.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: nn $ $Date: 2000-10-20 18:23:17 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop #include <svx/eeitem.hxx> #define ITEMID_FIELD EE_FEATURE_FIELD #include "scitems.hxx" // fuer tbxctrls etc. #include "scmod.hxx" #include "scresid.hxx" #include "sc.hrc" #include "cfgids.hxx" //! die Registrierung wird wegen CLOOKs in ein eigenes File wandern muessen... // Interface-Registrierung #include "docsh.hxx" #include "tabvwsh.hxx" #include "prevwsh.hxx" #include "drawsh.hxx" #include "drformsh.hxx" #include "drtxtob.hxx" #include "editsh.hxx" #include "pivotsh.hxx" #include "auditsh.hxx" #include "cellsh.hxx" #include "oleobjsh.hxx" #include "chartsh.hxx" #include "graphsh.hxx" #include "pgbrksh.hxx" #include "docpool.hxx" #include "appoptio.hxx" // Controls #include <svx/tbxalign.hxx> #include <svx/tbxctl.hxx> #include <svx/fillctrl.hxx> #include <svx/linectrl.hxx> #include <svx/tbcontrl.hxx> #include <svx/selctrl.hxx> #include <svx/insctrl.hxx> #include <svx/zoomctrl.hxx> #include <svx/flditem.hxx> #include <svx/modctrl.hxx> #include <svx/pszctrl.hxx> #include <svx/fntctl.hxx> #include <svx/fntszctl.hxx> #include <svx/grafctrl.hxx> #include "tbinsert.hxx" // Child-Windows #include "reffact.hxx" #include "navipi.hxx" #include "inputwin.hxx" #include <svx/fontwork.hxx> #include <svx/srchdlg.hxx> #include <offmgr/hyprlink.hxx> #include <svx/imapdlg.hxx> #include "editutil.hxx" #include <svx/svdfield.hxx> // SdrRegisterFieldClasses #include "dwfunctr.hxx" #include "acredlin.hxx" //------------------------------------------------------------------ ScResId::ScResId( USHORT nId ) : ResId( nId, SC_MOD()->GetResMgr() ) { } //------------------------------------------------------------------ void ScDLL::Init() { // called directly after loading the DLL // do whatever you want, you may use Sxx-DLL too ScDocumentPool::InitVersionMaps(); // wird im ScModule ctor gebraucht // the ScModule must be created ScModuleDummy **ppShlPtr = (ScModuleDummy**) GetAppData(SHL_CALC); #ifndef SO3 SvFactory *pFact = (*ppShlPtr)->pScDocShellFactory; #else SvFactory *pFact = (SvFactory*)(*ppShlPtr)->pScDocShellFactory; #endif ScLibSignalFunc pFunc = (*ppShlPtr)->pSignalFunc; delete (*ppShlPtr); ScModule* pMod = new ScModule((SfxObjectFactory*)pFact); (*ppShlPtr) = pMod; (*ppShlPtr)->pScDocShellFactory = pFact; (*ppShlPtr)->pSignalFunc = pFunc; ScGlobal::Init(); // erst wenn der ResManager initialisiert ist // erst nach ScGlobal::Init duerfen die App-Optionen // initialisiert werden // register your view-factories here ScTabViewShell ::RegisterFactory(1); ScPreviewShell ::RegisterFactory(2); // register your shell-interfaces here ScModule ::RegisterInterface(pMod); ScDocShell ::RegisterInterface(pMod); ScTabViewShell ::RegisterInterface(pMod); ScPreviewShell ::RegisterInterface(pMod); ScDrawShell ::RegisterInterface(pMod); ScDrawFormShell ::RegisterInterface(pMod); ScDrawTextObjectBar ::RegisterInterface(pMod); ScEditShell ::RegisterInterface(pMod); ScPivotShell ::RegisterInterface(pMod); ScAuditingShell ::RegisterInterface(pMod); ScFormatShell ::RegisterInterface(pMod); ScCellShell ::RegisterInterface(pMod); ScOleObjectShell ::RegisterInterface(pMod); ScChartShell ::RegisterInterface(pMod); ScGraphicShell ::RegisterInterface(pMod); ScPageBreakShell ::RegisterInterface(pMod); // register your controllers here ScDocShell::Factory().RegisterMenuBar( ScResId(SCCFG_MENUBAR) ); ScDocShell::Factory().RegisterPluginMenuBar( ScResId(SCCFG_PLUGINMENU) ); ScDocShell::Factory().RegisterAccel( ScResId(SCCFG_ACCELERATOR) ); // eigene Controller ScTbxInsertCtrl ::RegisterControl(SID_TBXCTL_INSERT, pMod); ScTbxInsertCtrl ::RegisterControl(SID_TBXCTL_INSCELLS, pMod); ScTbxInsertCtrl ::RegisterControl(SID_TBXCTL_INSOBJ, pMod); // Svx-Toolbox-Controller SvxTbxCtlDraw ::RegisterControl(SID_INSERT_DRAW, pMod); SvxTbxCtlAlign ::RegisterControl(SID_OBJECT_ALIGN, pMod); SvxFillToolBoxControl ::RegisterControl(0, pMod); SvxLineStyleToolBoxControl ::RegisterControl(0, pMod); SvxLineWidthToolBoxControl ::RegisterControl(0, pMod); SvxLineColorToolBoxControl ::RegisterControl(0, pMod); SvxLineEndToolBoxControl ::RegisterControl(SID_ATTR_LINEEND_STYLE, pMod); SvxStyleToolBoxControl ::RegisterControl(SID_STYLE_APPLY, pMod); SvxFontNameToolBoxControl ::RegisterControl(SID_ATTR_CHAR_FONT, pMod); SvxFontHeightToolBoxControl ::RegisterControl(SID_ATTR_CHAR_FONTHEIGHT, pMod); SvxFontColorToolBoxControl ::RegisterControl(SID_ATTR_CHAR_COLOR, pMod); SvxColorToolBoxControl ::RegisterControl(SID_BACKGROUND_COLOR, pMod); SvxFrameToolBoxControl ::RegisterControl(SID_ATTR_BORDER, pMod); SvxFrameLineStyleToolBoxControl ::RegisterControl(SID_FRAME_LINESTYLE, pMod); SvxFrameLineColorToolBoxControl ::RegisterControl(SID_FRAME_LINECOLOR, pMod); SvxGrafModeToolBoxControl ::RegisterControl(SID_ATTR_GRAF_MODE, pMod); SvxGrafRedToolBoxControl ::RegisterControl(SID_ATTR_GRAF_RED, pMod); SvxGrafGreenToolBoxControl ::RegisterControl(SID_ATTR_GRAF_GREEN, pMod); SvxGrafBlueToolBoxControl ::RegisterControl(SID_ATTR_GRAF_BLUE, pMod); SvxGrafLuminanceToolBoxControl ::RegisterControl(SID_ATTR_GRAF_LUMINANCE, pMod); SvxGrafContrastToolBoxControl ::RegisterControl(SID_ATTR_GRAF_CONTRAST, pMod); SvxGrafGammaToolBoxControl ::RegisterControl(SID_ATTR_GRAF_GAMMA, pMod); SvxGrafTransparenceToolBoxControl::RegisterControl(SID_ATTR_GRAF_TRANSPARENCE, pMod); // Svx-StatusBar-Controller SvxInsertStatusBarControl ::RegisterControl(SID_ATTR_INSERT, pMod); SvxSelectionModeControl ::RegisterControl(SID_STATUS_SELMODE, pMod); SvxZoomStatusBarControl ::RegisterControl(SID_ATTR_ZOOM, pMod); SvxModifyControl ::RegisterControl(SID_DOC_MODIFIED, pMod); SvxPosSizeStatusBarControl ::RegisterControl(SID_ATTR_SIZE, pMod); // Svx-Menue-Controller SvxFontMenuControl ::RegisterControl(SID_ATTR_CHAR_FONT, pMod); SvxFontSizeMenuControl ::RegisterControl(SID_ATTR_CHAR_FONTHEIGHT, pMod); // Child-Windows // Hack: Eingabezeile mit 42 registrieren, damit sie im PlugIn immer sichtbar ist ScInputWindowWrapper ::RegisterChildWindow(42, pMod, SFX_CHILDWIN_TASK); ScNavigatorDialogWrapper ::RegisterChildWindowContext(pMod); ScSolverDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScNameDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScPivotLayoutWrapper ::RegisterChildWindow(FALSE, pMod); ScTabOpDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScFilterDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScSpecialFilterDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScDbNameDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScConsolidateDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScChartDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScPrintAreasDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScCondFormatDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScColRowNameRangesDlgWrapper::RegisterChildWindow(FALSE, pMod); ScFormulaDlgWrapper ::RegisterChildWindow(FALSE, pMod); // First docking Window for Calc ScFunctionChildWindow ::RegisterChildWindow(FALSE, pMod); // Redlining- Window ScAcceptChgDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScSimpleRefDlgWrapper ::RegisterChildWindow(FALSE, pMod); ScHighlightChgDlgWrapper ::RegisterChildWindow(FALSE, pMod); SvxFontWorkChildWindow ::RegisterChildWindow(FALSE, pMod); SvxHyperlinkDlgWrapper ::RegisterChildWindow(FALSE, pMod); SvxIMapDlgChildWindow ::RegisterChildWindow(FALSE, pMod); // Edit-Engine-Felder, soweit nicht schon in OfficeApplication::Init SvClassManager& rClassManager = SvxFieldItem::GetClassManager(); // rClassManager.SV_CLASS_REGISTER( SvxURLField ); // rClassManager.SV_CLASS_REGISTER( SvxDateField ); // rClassManager.SV_CLASS_REGISTER( SvxPageField ); rClassManager.SV_CLASS_REGISTER( SvxPagesField ); // rClassManager.SV_CLASS_REGISTER( SvxTimeField ); rClassManager.SV_CLASS_REGISTER( SvxFileField ); // rClassManager.SV_CLASS_REGISTER( SvxExtFileField ); rClassManager.SV_CLASS_REGISTER( SvxTableField ); SdrRegisterFieldClasses(); // SvDraw-Felder registrieren pMod->PutItem( SfxUInt16Item( SID_ATTR_METRIC, pMod->GetAppOptions().GetAppMetric() ) ); // StarOne Services are now handled in the registry } void ScDLL::Exit() { // called directly befor unloading the DLL // do whatever you want, Sxx-DLL is accessible // the SxxModule must be destroyed ScModuleDummy **ppShlPtr = (ScModuleDummy**) GetAppData(SHL_CALC); delete (*ppShlPtr); (*ppShlPtr) = NULL; // auf keinen Fall ein neues ScModuleDummy anlegen, weil dessen vtable sonst // in der DLL waere und das Loeschen im LibExit schiefgehen wuerde // ScGlobal::Clear ist schon im Module-dtor } //------------------------------------------------------------------ // Statusbar //------------------------------------------------------------------ #define TEXT_WIDTH(s) rStatusBar.GetTextWidth((s)) void ScDLL::FillStatusBar(StatusBar &rStatusBar) { // Dokumentposition (Tabelle x / y) rStatusBar.InsertItem( SID_STATUS_DOCPOS, TEXT_WIDTH( String().Fill( 10, 'X' ) ), SIB_LEFT|SIB_AUTOSIZE ); // Seitenvorlage rStatusBar.InsertItem( SID_STATUS_PAGESTYLE, TEXT_WIDTH( String().Fill( 15, 'X' ) ), SIB_LEFT|SIB_AUTOSIZE ); // Ma"sstab rStatusBar.InsertItem( SID_ATTR_ZOOM, SvxZoomStatusBarControl::GetDefItemWidth(rStatusBar), SIB_CENTER ); // Einfuege-/Ueberschreibmodus rStatusBar.InsertItem( SID_ATTR_INSERT, SvxInsertStatusBarControl::GetDefItemWidth(rStatusBar), SIB_CENTER ); // Selektionsmodus rStatusBar.InsertItem( SID_STATUS_SELMODE, SvxSelectionModeControl::GetDefItemWidth(rStatusBar), SIB_CENTER ); // Dokument geaendert rStatusBar.InsertItem( SID_DOC_MODIFIED, SvxModifyControl::GetDefItemWidth(rStatusBar)); // Mail rStatusBar.InsertItem( SID_MAIL_NOTIFY, TEXT_WIDTH( String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("Mail")) ), SIB_CENTER ); // den aktuellen Kontext anzeigen Uhrzeit / FramePos / TabellenInfo / Errors rStatusBar.InsertItem( SID_ATTR_SIZE, SvxPosSizeStatusBarControl::GetDefItemWidth(rStatusBar), SIB_AUTOSIZE|SIB_LEFT|SIB_USERDRAW); } #undef TEXT_WIDTH <|endoftext|>
<commit_before>/* * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "BitmapImage.h" #if PLATFORM(CG) #include "AffineTransform.h" #include "FloatConversion.h" #include "FloatRect.h" #include "GraphicsContext.h" #include "ImageObserver.h" #include "PDFDocumentImage.h" #include "PlatformString.h" #include <ApplicationServices/ApplicationServices.h> #include "WebCoreSystemInterface.h" #if PLATFORM(WIN) #include <WebKitSystemInterface/WebKitSystemInterface.h> #endif namespace WebCore { void FrameData::clear() { if (m_frame) { CGImageRelease(m_frame); m_frame = 0; m_duration = 0.0f; m_hasAlpha = true; } } // ================================================ // Image Class // ================================================ // Drawing Routines void BitmapImage::checkForSolidColor() { if (frameCount() > 1) m_isSolidColor = false; else { CGImageRef image = frameAtIndex(0); // Currently we only check for solid color in the important special case of a 1x1 image. if (image && CGImageGetWidth(image) == 1 && CGImageGetHeight(image) == 1) { unsigned char pixel[4]; // RGBA CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB(); CGContextRef bmap = CGBitmapContextCreate(pixel, 1, 1, 8, sizeof(pixel), space, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); if (bmap) { GraphicsContext(bmap).setCompositeOperation(CompositeCopy); CGRect dst = { {0, 0}, {1, 1} }; CGContextDrawImage(bmap, dst, image); if (pixel[3] == 0) m_solidColor = Color(0, 0, 0, 0); else m_solidColor = Color(pixel[0] * 255 / pixel[3], pixel[1] * 255 / pixel[3], pixel[2] * 255 / pixel[3], pixel[3]); m_isSolidColor = true; CFRelease(bmap); } CFRelease(space); } } } CGImageRef BitmapImage::getCGImageRef() { return frameAtIndex(0); } void BitmapImage::draw(GraphicsContext* ctxt, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp) { if (!m_source.initialized()) return; CGRect fr = ctxt->roundToDevicePixels(srcRect); CGRect ir = ctxt->roundToDevicePixels(dstRect); CGImageRef image = frameAtIndex(m_currentFrame); if (!image) // If it's too early we won't have an image yet. return; if (mayFillWithSolidColor()) { fillWithSolidColor(ctxt, ir, solidColor(), compositeOp); return; } CGContextRef context = ctxt->platformContext(); ctxt->save(); // Get the height (in adjusted, i.e. scaled, coords) of the portion of the image // that is currently decoded. This could be less that the actual height. CGSize selfSize = size(); // full image size, in pixels float curHeight = CGImageGetHeight(image); // height of loaded portion, in pixels CGSize adjustedSize = selfSize; if (curHeight < selfSize.height) { adjustedSize.height *= curHeight / selfSize.height; // Is the amount of available bands less than what we need to draw? If so, // we may have to clip 'fr' if it goes outside the available bounds. if (CGRectGetMaxY(fr) > adjustedSize.height) { float frHeight = adjustedSize.height - fr.origin.y; // clip fr to available bounds if (frHeight <= 0) return; // clipped out entirely ir.size.height *= (frHeight / fr.size.height); // scale ir proportionally to fr fr.size.height = frHeight; } } // Flip the coords. ctxt->setCompositeOperation(compositeOp); CGContextTranslateCTM(context, ir.origin.x, ir.origin.y); CGContextScaleCTM(context, 1, -1); CGContextTranslateCTM(context, 0, -ir.size.height); // Translated to origin, now draw at 0,0. ir.origin.x = ir.origin.y = 0; // If we're drawing a sub portion of the image then create // a image for the sub portion and draw that. // Test using example site at http://www.meyerweb.com/eric/css/edge/complexspiral/demo.html if (fr.size.width != adjustedSize.width || fr.size.height != adjustedSize.height) { // Convert ft to image pixel coords: float xscale = adjustedSize.width / selfSize.width; float yscale = adjustedSize.height / curHeight; // yes, curHeight, not selfSize.height! fr.origin.x /= xscale; fr.origin.y /= yscale; fr.size.width /= xscale; fr.size.height /= yscale; image = CGImageCreateWithImageInRect(image, fr); if (image) { CGContextDrawImage(context, ir, image); CFRelease(image); } } else // Draw the whole image. CGContextDrawImage(context, ir, image); ctxt->restore(); startAnimation(); if (imageObserver()) imageObserver()->didDraw(this); } struct ImageInfo { ImageInfo(const FloatPoint& point, Image* i) : tilePoint(point) , image(i) {} FloatPoint tilePoint; Image* image; }; void Image::drawPatternCallback(void* info, CGContextRef context) { ImageInfo* data = (ImageInfo*)info; CGImageRef image = data->image->nativeImageForCurrentFrame(); CGContextDrawImage(context, GraphicsContext(context).roundToDevicePixels(FloatRect(data->tilePoint.x(), data->tilePoint.y(), CGImageGetWidth(image), CGImageGetHeight(image))), image); } void Image::drawPattern(GraphicsContext* ctxt, const FloatRect& tileRect, const AffineTransform& patternTransform, const FloatPoint& phase, CompositeOperator op, const FloatRect& destRect) { CGContextRef context = ctxt->platformContext(); ctxt->save(); CGContextClipToRect(context, destRect); ctxt->setCompositeOperation(op); CGContextTranslateCTM(context, destRect.x(), destRect.y()); CGContextScaleCTM(context, 1, -1); CGContextTranslateCTM(context, 0, -destRect.height()); // Compute the scaled tile size. float scaledTileHeight = tileRect.height() * narrowPrecisionToFloat(patternTransform.d()); // We have to adjust the phase to deal with the fact we're in Cartesian space now (with the bottom left corner of destRect being // the origin). float adjustedX = phase.x() - destRect.x() + tileRect.x() * narrowPrecisionToFloat(patternTransform.a()); // We translated the context so that destRect.x() is the origin, so subtract it out. float adjustedY = destRect.height() - (phase.y() - destRect.y() + tileRect.y() * narrowPrecisionToFloat(patternTransform.d()) + scaledTileHeight); CGImageRef tileImage = nativeImageForCurrentFrame(); float h = CGImageGetHeight(tileImage); #ifndef BUILDING_ON_TIGER // Leopard has an optimized call for the tiling of image patterns, but we can only use it if the image has been decoded enough that // its buffer is the same size as the overall image. Because a partially decoded CGImageRef with a smaller width or height than the // overall image buffer needs to tile with "gaps", we can't use the optimized tiling call in that case. We also avoid this optimization // when tiling portions of an image, since until we can actually cache the subimage we want to tile, this code won't be any faster. // FIXME: Could create WebKitSystemInterface SPI for CGCreatePatternWithImage2 and probably make Tiger tile faster as well. float scaledTileWidth = tileRect.width() * narrowPrecisionToFloat(patternTransform.a()); float w = CGImageGetWidth(tileImage); if (w == size().width() && h == size().height() && tileRect.size() == size()) CGContextDrawTiledImage(context, FloatRect(adjustedX, adjustedY, scaledTileWidth, scaledTileHeight), tileImage); else { #endif // On Leopard, this code now only runs for partially decoded images whose buffers do not yet match the overall size of the image or for // tiling a portion of an image (i.e., a subimage like the ones used by CSS border-image). // On Tiger this code runs all the time. This code is suboptimal because the pattern does not reference the image directly, and the // pattern is destroyed before exiting the function. This means any decoding the pattern does doesn't end up cached anywhere, so we // redecode every time we paint. static const CGPatternCallbacks patternCallbacks = { 0, drawPatternCallback, NULL }; CGAffineTransform matrix = CGAffineTransformMake(narrowPrecisionToCGFloat(patternTransform.a()), 0, 0, narrowPrecisionToCGFloat(patternTransform.d()), adjustedX, adjustedY); matrix = CGAffineTransformConcat(matrix, CGContextGetCTM(context)); // If we're painting a subimage, store the offset to the image. ImageInfo info(FloatPoint(-tileRect.x(), tileRect.y() + tileRect.height() - h), this); CGPatternRef pattern = CGPatternCreate(&info, CGRectMake(0, 0, tileRect.width(), tileRect.height()), matrix, tileRect.width(), tileRect.height(), kCGPatternTilingConstantSpacing, true, &patternCallbacks); if (pattern == NULL) { ctxt->restore(); return; } CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL); CGFloat alpha = 1; CGColorRef color = CGColorCreateWithPattern(patternSpace, pattern, &alpha); CGContextSetFillColorSpace(context, patternSpace); CGColorSpaceRelease(patternSpace); CGPatternRelease(pattern); // FIXME: Really want a public API for this. It is just CGContextSetBaseCTM(context, CGAffineTransformIdentiy). wkSetPatternBaseCTM(context, CGAffineTransformIdentity); CGContextSetPatternPhase(context, CGSizeZero); CGContextSetFillColorWithColor(context, color); CGContextFillRect(context, CGContextGetClipBoundingBox(context)); CGColorRelease(color); ctxt->restore(); #ifndef BUILDING_ON_TIGER } #endif if (imageObserver()) imageObserver()->didDraw(this); } } #endif // PLATFORM(CG) <commit_msg>Fix unbalanced save/restore on Leopard only.<commit_after>/* * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "BitmapImage.h" #if PLATFORM(CG) #include "AffineTransform.h" #include "FloatConversion.h" #include "FloatRect.h" #include "GraphicsContext.h" #include "ImageObserver.h" #include "PDFDocumentImage.h" #include "PlatformString.h" #include <ApplicationServices/ApplicationServices.h> #include "WebCoreSystemInterface.h" #if PLATFORM(WIN) #include <WebKitSystemInterface/WebKitSystemInterface.h> #endif namespace WebCore { void FrameData::clear() { if (m_frame) { CGImageRelease(m_frame); m_frame = 0; m_duration = 0.0f; m_hasAlpha = true; } } // ================================================ // Image Class // ================================================ // Drawing Routines void BitmapImage::checkForSolidColor() { if (frameCount() > 1) m_isSolidColor = false; else { CGImageRef image = frameAtIndex(0); // Currently we only check for solid color in the important special case of a 1x1 image. if (image && CGImageGetWidth(image) == 1 && CGImageGetHeight(image) == 1) { unsigned char pixel[4]; // RGBA CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB(); CGContextRef bmap = CGBitmapContextCreate(pixel, 1, 1, 8, sizeof(pixel), space, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); if (bmap) { GraphicsContext(bmap).setCompositeOperation(CompositeCopy); CGRect dst = { {0, 0}, {1, 1} }; CGContextDrawImage(bmap, dst, image); if (pixel[3] == 0) m_solidColor = Color(0, 0, 0, 0); else m_solidColor = Color(pixel[0] * 255 / pixel[3], pixel[1] * 255 / pixel[3], pixel[2] * 255 / pixel[3], pixel[3]); m_isSolidColor = true; CFRelease(bmap); } CFRelease(space); } } } CGImageRef BitmapImage::getCGImageRef() { return frameAtIndex(0); } void BitmapImage::draw(GraphicsContext* ctxt, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp) { if (!m_source.initialized()) return; CGRect fr = ctxt->roundToDevicePixels(srcRect); CGRect ir = ctxt->roundToDevicePixels(dstRect); CGImageRef image = frameAtIndex(m_currentFrame); if (!image) // If it's too early we won't have an image yet. return; if (mayFillWithSolidColor()) { fillWithSolidColor(ctxt, ir, solidColor(), compositeOp); return; } CGContextRef context = ctxt->platformContext(); ctxt->save(); // Get the height (in adjusted, i.e. scaled, coords) of the portion of the image // that is currently decoded. This could be less that the actual height. CGSize selfSize = size(); // full image size, in pixels float curHeight = CGImageGetHeight(image); // height of loaded portion, in pixels CGSize adjustedSize = selfSize; if (curHeight < selfSize.height) { adjustedSize.height *= curHeight / selfSize.height; // Is the amount of available bands less than what we need to draw? If so, // we may have to clip 'fr' if it goes outside the available bounds. if (CGRectGetMaxY(fr) > adjustedSize.height) { float frHeight = adjustedSize.height - fr.origin.y; // clip fr to available bounds if (frHeight <= 0) return; // clipped out entirely ir.size.height *= (frHeight / fr.size.height); // scale ir proportionally to fr fr.size.height = frHeight; } } // Flip the coords. ctxt->setCompositeOperation(compositeOp); CGContextTranslateCTM(context, ir.origin.x, ir.origin.y); CGContextScaleCTM(context, 1, -1); CGContextTranslateCTM(context, 0, -ir.size.height); // Translated to origin, now draw at 0,0. ir.origin.x = ir.origin.y = 0; // If we're drawing a sub portion of the image then create // a image for the sub portion and draw that. // Test using example site at http://www.meyerweb.com/eric/css/edge/complexspiral/demo.html if (fr.size.width != adjustedSize.width || fr.size.height != adjustedSize.height) { // Convert ft to image pixel coords: float xscale = adjustedSize.width / selfSize.width; float yscale = adjustedSize.height / curHeight; // yes, curHeight, not selfSize.height! fr.origin.x /= xscale; fr.origin.y /= yscale; fr.size.width /= xscale; fr.size.height /= yscale; image = CGImageCreateWithImageInRect(image, fr); if (image) { CGContextDrawImage(context, ir, image); CFRelease(image); } } else // Draw the whole image. CGContextDrawImage(context, ir, image); ctxt->restore(); startAnimation(); if (imageObserver()) imageObserver()->didDraw(this); } struct ImageInfo { ImageInfo(const FloatPoint& point, Image* i) : tilePoint(point) , image(i) {} FloatPoint tilePoint; Image* image; }; void Image::drawPatternCallback(void* info, CGContextRef context) { ImageInfo* data = (ImageInfo*)info; CGImageRef image = data->image->nativeImageForCurrentFrame(); CGContextDrawImage(context, GraphicsContext(context).roundToDevicePixels(FloatRect(data->tilePoint.x(), data->tilePoint.y(), CGImageGetWidth(image), CGImageGetHeight(image))), image); } void Image::drawPattern(GraphicsContext* ctxt, const FloatRect& tileRect, const AffineTransform& patternTransform, const FloatPoint& phase, CompositeOperator op, const FloatRect& destRect) { CGContextRef context = ctxt->platformContext(); ctxt->save(); CGContextClipToRect(context, destRect); ctxt->setCompositeOperation(op); CGContextTranslateCTM(context, destRect.x(), destRect.y()); CGContextScaleCTM(context, 1, -1); CGContextTranslateCTM(context, 0, -destRect.height()); // Compute the scaled tile size. float scaledTileHeight = tileRect.height() * narrowPrecisionToFloat(patternTransform.d()); // We have to adjust the phase to deal with the fact we're in Cartesian space now (with the bottom left corner of destRect being // the origin). float adjustedX = phase.x() - destRect.x() + tileRect.x() * narrowPrecisionToFloat(patternTransform.a()); // We translated the context so that destRect.x() is the origin, so subtract it out. float adjustedY = destRect.height() - (phase.y() - destRect.y() + tileRect.y() * narrowPrecisionToFloat(patternTransform.d()) + scaledTileHeight); CGImageRef tileImage = nativeImageForCurrentFrame(); float h = CGImageGetHeight(tileImage); #ifndef BUILDING_ON_TIGER // Leopard has an optimized call for the tiling of image patterns, but we can only use it if the image has been decoded enough that // its buffer is the same size as the overall image. Because a partially decoded CGImageRef with a smaller width or height than the // overall image buffer needs to tile with "gaps", we can't use the optimized tiling call in that case. We also avoid this optimization // when tiling portions of an image, since until we can actually cache the subimage we want to tile, this code won't be any faster. // FIXME: Could create WebKitSystemInterface SPI for CGCreatePatternWithImage2 and probably make Tiger tile faster as well. float scaledTileWidth = tileRect.width() * narrowPrecisionToFloat(patternTransform.a()); float w = CGImageGetWidth(tileImage); if (w == size().width() && h == size().height() && tileRect.size() == size()) CGContextDrawTiledImage(context, FloatRect(adjustedX, adjustedY, scaledTileWidth, scaledTileHeight), tileImage); else { #endif // On Leopard, this code now only runs for partially decoded images whose buffers do not yet match the overall size of the image or for // tiling a portion of an image (i.e., a subimage like the ones used by CSS border-image). // On Tiger this code runs all the time. This code is suboptimal because the pattern does not reference the image directly, and the // pattern is destroyed before exiting the function. This means any decoding the pattern does doesn't end up cached anywhere, so we // redecode every time we paint. static const CGPatternCallbacks patternCallbacks = { 0, drawPatternCallback, NULL }; CGAffineTransform matrix = CGAffineTransformMake(narrowPrecisionToCGFloat(patternTransform.a()), 0, 0, narrowPrecisionToCGFloat(patternTransform.d()), adjustedX, adjustedY); matrix = CGAffineTransformConcat(matrix, CGContextGetCTM(context)); // If we're painting a subimage, store the offset to the image. ImageInfo info(FloatPoint(-tileRect.x(), tileRect.y() + tileRect.height() - h), this); CGPatternRef pattern = CGPatternCreate(&info, CGRectMake(0, 0, tileRect.width(), tileRect.height()), matrix, tileRect.width(), tileRect.height(), kCGPatternTilingConstantSpacing, true, &patternCallbacks); if (pattern == NULL) { ctxt->restore(); return; } CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL); CGFloat alpha = 1; CGColorRef color = CGColorCreateWithPattern(patternSpace, pattern, &alpha); CGContextSetFillColorSpace(context, patternSpace); CGColorSpaceRelease(patternSpace); CGPatternRelease(pattern); // FIXME: Really want a public API for this. It is just CGContextSetBaseCTM(context, CGAffineTransformIdentiy). wkSetPatternBaseCTM(context, CGAffineTransformIdentity); CGContextSetPatternPhase(context, CGSizeZero); CGContextSetFillColorWithColor(context, color); CGContextFillRect(context, CGContextGetClipBoundingBox(context)); CGColorRelease(color); #ifndef BUILDING_ON_TIGER } #endif ctxt->restore(); if (imageObserver()) imageObserver()->didDraw(this); } } #endif // PLATFORM(CG) <|endoftext|>
<commit_before>#include "dsa/network.h" #include "dsa/requester.h" #include "dsa/responder.h" #include "dsa/stream.h" #include <chrono> #include <ctime> #include <iostream> #include "core/client.h" #include "module/logger.h" #include "network/tcp/tcp_server.h" #include "util/date_time.h" #include <atomic> #include <boost/program_options.hpp> using high_resolution_clock = std::chrono::high_resolution_clock; using time_point = std::chrono::high_resolution_clock::time_point; namespace opts = boost::program_options; using namespace dsa; namespace broker_benchmark { class BenchmarkNodeValue : public NodeModel { public: explicit BenchmarkNodeValue(LinkStrandRef strand) : NodeModel(std::move(strand)){}; }; class BenchmarkNodeRoot : public NodeModel { public: explicit BenchmarkNodeRoot(LinkStrandRef strand, int num_point) : NodeModel(std::move(strand)) { for (int i = 0; i < num_point; ++i) { add_list_child("v" + std::to_string(i), make_ref_<BenchmarkNodeValue>(_strand)); } }; int64_t sub_value = 0; void new_value() { sub_value++; auto msg = make_ref_<SubscribeResponseMessage>(); msg->set_value(MessageValue(Var(sub_value), DateTime::get_ts())); for (auto it : _list_children) { it.second->set_subscribe_response(msg->get_ref()); } } }; } WrapperStrand get_client_wrapper_strand(shared_ptr_<App>& app, const string_& dsid_prefix) { WrapperStrand client_strand; client_strand.tcp_host = "127.0.0.1"; client_strand.tcp_port = 4120; client_strand.strand = EditableStrand::make_default(app); client_strand.client_connection_maker = [ dsid_prefix = dsid_prefix, tcp_host = client_strand.tcp_host, tcp_port = client_strand.tcp_port ](LinkStrandRef & strand, const string_& previous_session_id, int32_t last_ack_id) ->shared_ptr_<Connection> { return make_shared_<TcpClientConnection>(strand, dsid_prefix, tcp_host, tcp_port); }; return std::move(client_strand); } int main(int argc, const char* argv[]) { typedef broker_benchmark::BenchmarkNodeRoot BenchmarkNodeRoot; opts::options_description desc{"Options"}; desc.add_options()("help,h", "Help screen") // ("client,c", opts::value<int>()->default_value(2), "Number of Clients") // ("point,p", opts::value<int>()->default_value(2), "Number of Points per Client") // ("num-message,n", opts::value<int>()->default_value(100), "Message per second per Point") // ("encode-value,e", opts::bool_switch(), "Encode value before sending") // ("decode-value,d", opts::bool_switch(), "Decode value after receiving") // ; opts::variables_map variables; opts::store(opts::parse_command_line(argc, argv, desc), variables); opts::notify(variables); if (variables.count("help")) { std::cout << desc << '\n'; return 0; } int client_count = variables["client"].as<int>(); int point_count = variables["point"].as<int>(); int num_message = variables["num-message"].as<int>(); bool encode_value = variables["encode-value"].as<bool>(); bool decode_value = variables["decode-value"].as<bool>(); auto app = std::make_shared<App>(8); std::vector<shared_ptr_<Client>> clients; std::vector<ref_<EditableStrand>> strands; std::vector<ref_<BenchmarkNodeRoot>> root_nodes; std::vector<int64_t> message_receive_count; clients.reserve(client_count); message_receive_count.reserve(client_count); for (int i = 0; i < client_count; ++i) { message_receive_count.emplace_back(0); WrapperStrand strand = get_client_wrapper_strand(app, "benchmark" + std::to_string(i)); auto client = make_shared_<Client>(strand); auto root_node = make_ref_<BenchmarkNodeRoot>(strand.strand, point_count); root_nodes.emplace_back(root_node); strand.strand->set_responder_model(std::move(root_node)); clients.emplace_back(client); client->connect([ =, &count = message_receive_count[i], &client = clients[i] ](const shared_ptr_<Connection>&) { SubscribeOptions options; options.qos = QosLevel::_1; for (int a = 0; a < client_count; ++a) { string_ node_path = "downstream/benchmark" + std::to_string(a); for (int b = 0; b < point_count; ++b) { string_ point_path = node_path + "/v" + std::to_string(b); client->get_session().requester.subscribe( point_path, [&count](IncomingSubscribeStream&, ref_<const SubscribeResponseMessage>&&) { ++count; }, options); } } }); strands.emplace_back(strand.strand); } int interval_ms = 5; int msg_per_interval = num_message * interval_ms / 1000; if (msg_per_interval == 0) { msg_per_interval = 1; interval_ms = 1000 / num_message; } boost::posix_time::milliseconds interval(interval_ms); boost::asio::deadline_timer timer(app->io_service(), interval); int64_t last_count = 0; int64_t last_time = DateTime::time_since_epoch(); std::function<void(const boost::system::error_code&)> timer_callback = [&](const boost::system::error_code& error) { try { int64_t current_time = DateTime::time_since_epoch(); int64_t count = 0; for (int i = 0; i < client_count; ++i) { count += message_receive_count[i]; } if (current_time - last_time > 1000) { std::cout << std::endl << "per second: " << (count - last_count) * 1000 / (current_time - last_time) << " total: " << count; last_time = current_time; last_count = count; } for (int i = 0; i < client_count; ++i) { strands[i]->dispatch([&,i]() { auto& node = root_nodes[i]; for (int j = 0; j < msg_per_interval; ++j) { node->new_value(); } }); } } catch (std::exception& e) { std::cout << std::endl << e.what(); } timer.expires_from_now(interval); timer.async_wait(timer_callback); }; timer.async_wait(timer_callback); app->wait(); } <commit_msg>fix broker_throughput<commit_after>#include "dsa/network.h" #include "dsa/requester.h" #include "dsa/responder.h" #include "dsa/stream.h" #include <chrono> #include <ctime> #include <iostream> #include "core/client.h" #include "module/logger.h" #include "network/tcp/tcp_server.h" #include "util/date_time.h" #include <math.h> #include <atomic> #include <boost/program_options.hpp> using high_resolution_clock = std::chrono::high_resolution_clock; using time_point = std::chrono::high_resolution_clock::time_point; namespace opts = boost::program_options; using namespace dsa; namespace broker_benchmark { class BenchmarkNodeValue : public NodeModel { public: explicit BenchmarkNodeValue(LinkStrandRef strand) : NodeModel(std::move(strand)) { update_property("$type", Var("number")); }; }; class BenchmarkNodeRoot : public NodeModel { public: explicit BenchmarkNodeRoot(LinkStrandRef strand, int num_point) : NodeModel(std::move(strand)) { for (int i = 0; i < num_point; ++i) { add_list_child("v" + std::to_string(i), make_ref_<BenchmarkNodeValue>(_strand)); } }; int64_t sub_value = 0; void new_value() { sub_value++; auto msg = make_ref_<SubscribeResponseMessage>(); msg->set_value(MessageValue(Var(sub_value), DateTime::get_ts())); for (auto it : _list_children) { it.second->set_subscribe_response(msg->get_ref()); } } }; } WrapperStrand get_client_wrapper_strand(shared_ptr_<App>& app, const string_& dsid_prefix) { WrapperStrand client_strand; client_strand.tcp_host = "127.0.0.1"; client_strand.tcp_port = 4120; client_strand.strand = EditableStrand::make_default(app); client_strand.client_connection_maker = [ dsid_prefix = dsid_prefix, tcp_host = client_strand.tcp_host, tcp_port = client_strand.tcp_port ](LinkStrandRef & strand, const string_& previous_session_id, int32_t last_ack_id) ->shared_ptr_<Connection> { return make_shared_<TcpClientConnection>(strand, dsid_prefix, tcp_host, tcp_port); }; return std::move(client_strand); } int main(int argc, const char* argv[]) { typedef broker_benchmark::BenchmarkNodeRoot BenchmarkNodeRoot; opts::options_description desc{"Options"}; desc.add_options()("help,h", "Help screen") // ("client,c", opts::value<int>()->default_value(1), "Number of Clients") // ("point,p", opts::value<int>()->default_value(1), "Number of Points per Client") // ("num-message,n", opts::value<int>()->default_value(1), "Message per second per Point") // ("encode-value,e", opts::bool_switch(), "Encode value before sending") // ("decode-value,d", opts::bool_switch(), "Decode value after receiving") // ; opts::variables_map variables; opts::store(opts::parse_command_line(argc, argv, desc), variables); opts::notify(variables); if (variables.count("help")) { std::cout << desc << '\n'; return 0; } int client_count = variables["client"].as<int>(); int point_count = variables["point"].as<int>(); int num_message = variables["num-message"].as<int>(); bool encode_value = variables["encode-value"].as<bool>(); bool decode_value = variables["decode-value"].as<bool>(); auto app = std::make_shared<App>(8); std::vector<shared_ptr_<Client>> clients; std::vector<ref_<EditableStrand>> strands; std::vector<ref_<BenchmarkNodeRoot>> root_nodes; std::vector<int64_t> message_receive_count; clients.reserve(client_count); message_receive_count.reserve(client_count); for (int i = 0; i < client_count; ++i) { message_receive_count.emplace_back(0); WrapperStrand strand = get_client_wrapper_strand(app, "benchmark" + std::to_string(i)); auto client = make_shared_<Client>(strand); auto root_node = make_ref_<BenchmarkNodeRoot>(strand.strand, point_count); root_nodes.emplace_back(root_node); strand.strand->set_responder_model(std::move(root_node)); clients.emplace_back(client); client->connect([ =, &count = message_receive_count[i], &client = clients[i] ](const shared_ptr_<Connection>&) { SubscribeOptions options; options.qos = QosLevel::_1; for (int a = 0; a < client_count; ++a) { string_ node_path = "downstream/benchmark" + std::to_string(a); for (int b = 0; b < point_count; ++b) { string_ point_path = node_path + "/v" + std::to_string(b); client->get_session().requester.subscribe( point_path, [&count](IncomingSubscribeStream&, ref_<const SubscribeResponseMessage>&&) { ++count; }, options); } } }); strands.emplace_back(strand.strand); } int interval_ms = 5; int msg_per_interval = num_message * interval_ms / 1000; if (msg_per_interval == 0) { msg_per_interval = 1; interval_ms = 1000 / num_message; } boost::posix_time::milliseconds interval(interval_ms); boost::asio::deadline_timer timer(app->io_service(), interval); int64_t last_count = 0; int64_t last_time = DateTime::time_since_epoch(); std::function<void(const boost::system::error_code&)> timer_callback = [&](const boost::system::error_code& error) { try { int64_t current_time = DateTime::time_since_epoch(); int64_t count = 0; for (int i = 0; i < client_count; ++i) { count += message_receive_count[i]; } if (current_time - last_time > 1000) { std::cout << std::endl << "per second: " << ceil((count - last_count) * 1000.0 / (current_time - last_time)) << " total: " << count; last_time = current_time; last_count = count; } for (int i = 0; i < client_count; ++i) { strands[i]->dispatch([&, i]() { auto& node = root_nodes[i]; for (int j = 0; j < msg_per_interval; ++j) { node->new_value(); } }); } } catch (std::exception& e) { std::cout << std::endl << e.what(); } timer.expires_from_now(interval); timer.async_wait(timer_callback); }; timer.async_wait(timer_callback); app->wait(); } <|endoftext|>
<commit_before>// Copyright (c) 2016 IBM Corporation. #include "string-extern.h" #include "std/core.h" #include "std/listdef.h" #include "strutils.h" #include <regex> using namespace tosca; StringTerm& AfterFirst(Context& ctx, StringTerm& string, StringTerm& sep) { const tosca::string& ustring = string.Unbox(); const tosca::string& usep = sep.Unbox(); tosca::string::size_type idx = ustring.find(usep); StringTerm& result = newStringTerm(ctx, (idx == tosca::string::npos) ? "" : ustring.substr(idx + 1).c_str()); string.Release(); sep.Release(); return result; } StringTerm& BeforeFirst(Context& ctx, StringTerm& string, StringTerm& sep) { const tosca::string& ustring = string.Unbox(); const tosca::string& usep = sep.Unbox(); tosca::string::size_type idx = ustring.find(usep); StringTerm& result = newStringTerm(ctx, (idx == tosca::string::npos) ? ustring : ustring.substr(0, idx).c_str()); string.Release(); sep.Release(); return result; } Bool& StringEqual(Context& ctx, StringTerm& str1, StringTerm& str2) { const tosca::string& ustr1 = str1.Unbox(); const tosca::string& ustr2 = str2.Unbox(); Bool& result = ustr1 == ustr2 ? newTRUE(ctx) : newFALSE(ctx); str1.Release(); str2.Release(); return result; } StringTerm& Escape(Context& ctx, StringTerm& str) { StringTerm& result = newStringTerm(ctx, makeEscaped(str.Unbox())); str.Release(); return result; } DoubleTerm& Length(Context& ctx, StringTerm& str) { DoubleTerm& result = newDoubleTerm(ctx, str.Unbox().size()); str.Release(); return result; } StringTerm& Mangle(Context& ctx, StringTerm& str) { StringTerm& result = newStringTerm(ctx, makeMangle(str.Unbox())); str.Release(); return result; } StringTerm& UpCase(Context& ctx, StringTerm& str) { tosca::string upper(str.Unbox()); for (tosca::string::iterator it= upper.begin(); it != upper.end(); ++it) *it = toupper(*it); str.Release(); return newStringTerm(ctx, upper.c_str()); } StringTerm& DownCase(Context& ctx, StringTerm& str) { tosca::string lower(str.Unbox()); for (tosca::string::iterator it= lower.begin(); it != lower.end(); ++it) *it = tolower(*it); str.Release(); return newStringTerm(ctx, lower.c_str()); } StringTerm& Replace(Context& ctx, StringTerm& str, StringTerm& oldStr, StringTerm& newStr) { if (oldStr.Unbox().empty()) { oldStr.Release(); newStr.Release(); return str; } tosca::string result(str.Unbox()); const tosca::string& uoldStr = oldStr.Unbox(); const tosca::string& unewStr = newStr.Unbox(); size_t pos = 0; while ((pos = result.find(uoldStr, pos)) != tosca::string::npos) { result.replace(pos, uoldStr.length(), unewStr); pos += unewStr.length(); } str.Release(); oldStr.Release(); newStr.Release(); return newStringTerm(ctx, result.c_str()); } Bool& Contains(Context& ctx, StringTerm& str1, StringTerm& str2) { const tosca::string& ustr1 = str1.Unbox(); const tosca::string& ustr2 = str2.Unbox(); Bool& result = ustr1.find(ustr2) != tosca::string::npos ? newTRUE(ctx) : newFALSE(ctx); str1.Release(); str2.Release(); return result; } StringTerm& Substring(Context& ctx, StringTerm& str, DoubleTerm& from, DoubleTerm& to) { const tosca::string& ustr = str.Unbox(); tosca::string::size_type pos = static_cast<tosca::string::size_type>(from.Unbox()); tosca::string::size_type end = static_cast<tosca::string::size_type>(to.Unbox()); tosca::string::size_type count = end > pos ? end - pos : 0; StringTerm& result = newStringTerm(ctx, ustr.substr(pos, count).c_str()); str.Release(); from.Release(); return result; } StringTerm& Substring2(Context& ctx, StringTerm& str, DoubleTerm& from) { const tosca::string& ustr = str.Unbox(); tosca::string::size_type pos = static_cast<tosca::string::size_type>(from.Unbox()); StringTerm& result = newStringTerm(ctx, ustr.substr(pos).c_str()); str.Release(); from.Release(); return result; } #ifdef STD_REGEX Bool& MatchRegex(Context& ctx, StringTerm& pattern, StringTerm& str) { std::regex regex(pattern.Unbox()); Bool& result = std::regex_match(str.Unbox(), regex) ? newTRUE(ctx) : newFALSE(ctx); pattern.Release(); str.Release(); return result; } #endif Bool& StartsWith(Context& ctx, StringTerm& str, StringTerm& prefix) { const tosca::string& ustr = str.Unbox(); const tosca::string& uprefix = prefix.Unbox(); Bool& result = (!ustr.compare(0, uprefix.size(), uprefix)) ? newTRUE(ctx) : newFALSE(ctx); str.Release(); prefix.Release(); return result; } Bool& EndsWith(tosca::Context& ctx, tosca::StringTerm& str, tosca::StringTerm& suffix) { const tosca::string& ustr = str.Unbox(); const tosca::string& usuffix = suffix.Unbox(); Bool& result = (ustr.size() >= usuffix.size() && !ustr.compare(ustr.size() - usuffix.size(), usuffix.size(), usuffix)) ? newTRUE(ctx) : newFALSE(ctx); str.Release(); suffix.Release(); return result; } tosca::StringTerm& Trim(tosca::Context& ctx, tosca::StringTerm& str) { const tosca::string& ustr = str.Unbox(); if (ustr.empty()) return str; tosca::string::size_type first = ustr.find_first_not_of(" \t\f\n\r\b"); if (first == tosca::string::npos) { // All whitespace characters. str.Release(); return newStringTerm(ctx, ""); } size_t last = ustr.find_last_not_of(" \t\f\n\r\b"); StringTerm& result = newStringTerm(ctx, ustr.substr(first, (last-first+1)).c_str()); str.Release(); return result; } List<tosca::StringTerm>& Split(tosca::Context& ctx, tosca::StringTerm& str, tosca::StringTerm& sep) { const tosca::string& ustr = str.Unbox(); if (ustr.empty()) { str.Release(); sep.Release(); return newNil<tosca::StringTerm>(ctx); } const tosca::string& usep = sep.Unbox(); List<tosca::StringTerm>* result = 0; List<tosca::StringTerm>* last = 0; tosca::string::size_type spos = 0; tosca::string::size_type pos = 0; int trailings = 0; // to discard empty trailing strings while ((pos = ustr.find(usep, spos)) != tosca::string::npos) { tosca::string::size_type count = pos - spos; if (count == 0) { trailings ++; spos += usep.length(); continue; } for (; trailings > 0; trailings--) { List<tosca::StringTerm>& cons = dynamic_cast<List<tosca::StringTerm>&>(_CCons<tosca::StringTerm>::Make(ctx)); cons.SetSub(0, newStringTerm(ctx, "")); if (last) last->SetSub(1, cons); last = &cons; if (!result) result = last; } List<tosca::StringTerm>& cons = dynamic_cast<List<tosca::StringTerm>&>(_CCons<tosca::StringTerm>::Make(ctx)); cons.SetSub(0, newStringTerm(ctx, ustr.substr(spos, count).c_str())); if (last) last->SetSub(1, cons); last = &cons; if (!result) result = last; spos = pos + usep.length(); } if (spos < ustr.length()) { List<tosca::StringTerm>& cons = dynamic_cast<List<tosca::StringTerm>&>(_CCons<tosca::StringTerm>::Make(ctx)); cons.SetSub(0, newStringTerm(ctx, ustr.substr(spos).c_str())); if (last) last->SetSub(1, cons); last = &cons; if (!result) result = last; } if (last) { last->SetSub(1, newNil<tosca::StringTerm>(ctx)); str.Release(); } else { // sep was not found or only trailing empty strings. Just return the original string, even when empty result = &newCons(ctx, str, newNil<tosca::StringTerm>(ctx)); } sep.Release(); return *result; } tosca::StringTerm& Squash(tosca::Context& ctx, tosca::StringTerm& str) { tosca::string squashed; bool wasspace = false; for (auto iter = str.Unbox().begin(); iter != str.Unbox().end(); iter++) { if (isspace(*iter)) { if (!wasspace) { wasspace=true; squashed += ' '; } } else { squashed += *iter; wasspace = false; } } str.Release(); return newStringTerm(ctx, squashed.c_str()); } tosca::DoubleTerm& Index(tosca::Context& ctx, tosca::StringTerm& string, tosca::StringTerm& pattern) { auto search = string.Unbox().find(pattern.Unbox()); tosca::DoubleTerm& result = newDoubleTerm(ctx, search == tosca::string::npos ? -1 : search); string.Release(); pattern.Release(); return result; } <commit_msg>Attempt to eliminate leak #43<commit_after>// Copyright (c) 2016 IBM Corporation. #include "string-extern.h" #include "std/core.h" #include "std/listdef.h" #include "strutils.h" #include <regex> using namespace tosca; StringTerm& AfterFirst(Context& ctx, StringTerm& string, StringTerm& sep) { const tosca::string& ustring = string.Unbox(); const tosca::string& usep = sep.Unbox(); tosca::string::size_type idx = ustring.find(usep); StringTerm& result = newStringTerm(ctx, (idx == tosca::string::npos) ? "" : ustring.substr(idx + 1).c_str()); string.Release(); sep.Release(); return result; } StringTerm& BeforeFirst(Context& ctx, StringTerm& string, StringTerm& sep) { const tosca::string& ustring = string.Unbox(); const tosca::string& usep = sep.Unbox(); tosca::string::size_type idx = ustring.find(usep); StringTerm& result = newStringTerm(ctx, (idx == tosca::string::npos) ? ustring : ustring.substr(0, idx)); string.Release(); sep.Release(); return result; } Bool& StringEqual(Context& ctx, StringTerm& str1, StringTerm& str2) { const tosca::string& ustr1 = str1.Unbox(); const tosca::string& ustr2 = str2.Unbox(); Bool& result = ustr1 == ustr2 ? newTRUE(ctx) : newFALSE(ctx); str1.Release(); str2.Release(); return result; } StringTerm& Escape(Context& ctx, StringTerm& str) { StringTerm& result = newStringTerm(ctx, makeEscaped(str.Unbox())); str.Release(); return result; } DoubleTerm& Length(Context& ctx, StringTerm& str) { DoubleTerm& result = newDoubleTerm(ctx, str.Unbox().size()); str.Release(); return result; } StringTerm& Mangle(Context& ctx, StringTerm& str) { StringTerm& result = newStringTerm(ctx, makeMangle(str.Unbox())); str.Release(); return result; } StringTerm& UpCase(Context& ctx, StringTerm& str) { tosca::string upper(str.Unbox()); for (tosca::string::iterator it= upper.begin(); it != upper.end(); ++it) *it = toupper(*it); str.Release(); return newStringTerm(ctx, upper.c_str()); } StringTerm& DownCase(Context& ctx, StringTerm& str) { tosca::string lower(str.Unbox()); for (tosca::string::iterator it= lower.begin(); it != lower.end(); ++it) *it = tolower(*it); str.Release(); return newStringTerm(ctx, lower.c_str()); } StringTerm& Replace(Context& ctx, StringTerm& str, StringTerm& oldStr, StringTerm& newStr) { if (oldStr.Unbox().empty()) { oldStr.Release(); newStr.Release(); return str; } tosca::string result(str.Unbox()); const tosca::string& uoldStr = oldStr.Unbox(); const tosca::string& unewStr = newStr.Unbox(); size_t pos = 0; while ((pos = result.find(uoldStr, pos)) != tosca::string::npos) { result.replace(pos, uoldStr.length(), unewStr); pos += unewStr.length(); } str.Release(); oldStr.Release(); newStr.Release(); return newStringTerm(ctx, result.c_str()); } Bool& Contains(Context& ctx, StringTerm& str1, StringTerm& str2) { const tosca::string& ustr1 = str1.Unbox(); const tosca::string& ustr2 = str2.Unbox(); Bool& result = ustr1.find(ustr2) != tosca::string::npos ? newTRUE(ctx) : newFALSE(ctx); str1.Release(); str2.Release(); return result; } StringTerm& Substring(Context& ctx, StringTerm& str, DoubleTerm& from, DoubleTerm& to) { const tosca::string& ustr = str.Unbox(); tosca::string::size_type pos = static_cast<tosca::string::size_type>(from.Unbox()); tosca::string::size_type end = static_cast<tosca::string::size_type>(to.Unbox()); tosca::string::size_type count = end > pos ? end - pos : 0; StringTerm& result = newStringTerm(ctx, ustr.substr(pos, count).c_str()); str.Release(); from.Release(); return result; } StringTerm& Substring2(Context& ctx, StringTerm& str, DoubleTerm& from) { const tosca::string& ustr = str.Unbox(); tosca::string::size_type pos = static_cast<tosca::string::size_type>(from.Unbox()); StringTerm& result = newStringTerm(ctx, ustr.substr(pos).c_str()); str.Release(); from.Release(); return result; } #ifdef STD_REGEX Bool& MatchRegex(Context& ctx, StringTerm& pattern, StringTerm& str) { std::regex regex(pattern.Unbox()); Bool& result = std::regex_match(str.Unbox(), regex) ? newTRUE(ctx) : newFALSE(ctx); pattern.Release(); str.Release(); return result; } #endif Bool& StartsWith(Context& ctx, StringTerm& str, StringTerm& prefix) { const tosca::string& ustr = str.Unbox(); const tosca::string& uprefix = prefix.Unbox(); Bool& result = (!ustr.compare(0, uprefix.size(), uprefix)) ? newTRUE(ctx) : newFALSE(ctx); str.Release(); prefix.Release(); return result; } Bool& EndsWith(tosca::Context& ctx, tosca::StringTerm& str, tosca::StringTerm& suffix) { const tosca::string& ustr = str.Unbox(); const tosca::string& usuffix = suffix.Unbox(); Bool& result = (ustr.size() >= usuffix.size() && !ustr.compare(ustr.size() - usuffix.size(), usuffix.size(), usuffix)) ? newTRUE(ctx) : newFALSE(ctx); str.Release(); suffix.Release(); return result; } tosca::StringTerm& Trim(tosca::Context& ctx, tosca::StringTerm& str) { const tosca::string& ustr = str.Unbox(); if (ustr.empty()) return str; tosca::string::size_type first = ustr.find_first_not_of(" \t\f\n\r\b"); if (first == tosca::string::npos) { // All whitespace characters. str.Release(); return newStringTerm(ctx, ""); } size_t last = ustr.find_last_not_of(" \t\f\n\r\b"); StringTerm& result = newStringTerm(ctx, ustr.substr(first, (last-first+1)).c_str()); str.Release(); return result; } List<tosca::StringTerm>& Split(tosca::Context& ctx, tosca::StringTerm& str, tosca::StringTerm& sep) { const tosca::string& ustr = str.Unbox(); if (ustr.empty()) { str.Release(); sep.Release(); return newNil<tosca::StringTerm>(ctx); } const tosca::string& usep = sep.Unbox(); List<tosca::StringTerm>* result = 0; List<tosca::StringTerm>* last = 0; tosca::string::size_type spos = 0; tosca::string::size_type pos = 0; int trailings = 0; // to discard empty trailing strings while ((pos = ustr.find(usep, spos)) != tosca::string::npos) { tosca::string::size_type count = pos - spos; if (count == 0) { trailings ++; spos += usep.length(); continue; } for (; trailings > 0; trailings--) { List<tosca::StringTerm>& cons = dynamic_cast<List<tosca::StringTerm>&>(_CCons<tosca::StringTerm>::Make(ctx)); cons.SetSub(0, newStringTerm(ctx, "")); if (last) last->SetSub(1, cons); last = &cons; if (!result) result = last; } List<tosca::StringTerm>& cons = dynamic_cast<List<tosca::StringTerm>&>(_CCons<tosca::StringTerm>::Make(ctx)); cons.SetSub(0, newStringTerm(ctx, ustr.substr(spos, count).c_str())); if (last) last->SetSub(1, cons); last = &cons; if (!result) result = last; spos = pos + usep.length(); } if (spos < ustr.length()) { List<tosca::StringTerm>& cons = dynamic_cast<List<tosca::StringTerm>&>(_CCons<tosca::StringTerm>::Make(ctx)); cons.SetSub(0, newStringTerm(ctx, ustr.substr(spos).c_str())); if (last) last->SetSub(1, cons); last = &cons; if (!result) result = last; } if (last) { last->SetSub(1, newNil<tosca::StringTerm>(ctx)); str.Release(); } else { // sep was not found or only trailing empty strings. Just return the original string, even when empty result = &newCons(ctx, str, newNil<tosca::StringTerm>(ctx)); } sep.Release(); return *result; } tosca::StringTerm& Squash(tosca::Context& ctx, tosca::StringTerm& str) { tosca::string squashed; bool wasspace = false; for (auto iter = str.Unbox().begin(); iter != str.Unbox().end(); iter++) { if (isspace(*iter)) { if (!wasspace) { wasspace=true; squashed += ' '; } } else { squashed += *iter; wasspace = false; } } str.Release(); return newStringTerm(ctx, squashed.c_str()); } tosca::DoubleTerm& Index(tosca::Context& ctx, tosca::StringTerm& string, tosca::StringTerm& pattern) { auto search = string.Unbox().find(pattern.Unbox()); tosca::DoubleTerm& result = newDoubleTerm(ctx, search == tosca::string::npos ? -1 : search); string.Release(); pattern.Release(); return result; } <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/conditional_simplifier.h" #include <string> #include <utility> #include <vector> #include "tensorflow/compiler/xla/literal_util.h" #include "tensorflow/compiler/xla/service/call_inliner.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" namespace xla { // Tries to replace a conditional with a call operation of the corresponding // computation. If the given conditional has a constant predicate, tries to // replace it with a call to its true/false computation as appropirate and then // inline that computation. // // Returns true if it made a change to the graph. static StatusOr<bool> TryRemoveConditional(HloInstruction* conditional) { CHECK_EQ(conditional->opcode(), HloOpcode::kConditional); // Do not remove conditionals that contain side-effecting instructions or // have control predecessors/successors in either true/false computation. if (!conditional->parent()->IsRemovable(conditional) || conditional->HasSideEffect()) { VLOG(2) << "Not attempting to remove conditional as it is not removable or " "has side effect: " << conditional->ToShortString(); return false; } if (conditional->operand(0)->opcode() != HloOpcode::kConstant) { VLOG(2) << "Not attempting to remove conditional as its predicate is not a " "compile-time constant: " << conditional->ToShortString(); return false; } auto computation = conditional->parent(); HloInstruction* call_op; if (conditional->operand(0)->literal().Get<bool>({})) { call_op = computation->AddInstruction(HloInstruction::CreateCall( conditional->shape(), {conditional->mutable_operand(1)}, conditional->true_computation())); } else { call_op = computation->AddInstruction(HloInstruction::CreateCall( conditional->shape(), {conditional->mutable_operand(2)}, conditional->false_computation())); } TF_RETURN_IF_ERROR(computation->ReplaceInstruction(conditional, call_op)); TF_RETURN_IF_ERROR(CallInliner::Inline(call_op).status()); return true; } StatusOr<bool> ConditionalSimplifier::Run(HloModule* module) { XLA_VLOG_LINES( 3, "ConditionalSimplifier::Run(), before:\n" + module->ToString()); bool changed = false; // Gather all the conditional ops in our module. We do this ahead of time so // we don't have to worry about mutating the lists of computations or // instructions as we iterate. std::vector<HloInstruction*> conditional_ops; for (auto* comp : module->computations()) { for (auto* instr : comp->instructions()) { if (instr->opcode() == HloOpcode::kConditional) { conditional_ops.push_back(instr); } } } for (HloInstruction* conditional_op : conditional_ops) { TF_ASSIGN_OR_RETURN(bool result, TryRemoveConditional(conditional_op)); changed |= result; } XLA_VLOG_LINES(3, "ConditionalSimplifier::Run(), after:\n" + module->ToString()); return changed; } } // namespace xla <commit_msg>Teach the conditinal simplifier about sharding.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/conditional_simplifier.h" #include <string> #include <utility> #include <vector> #include "tensorflow/compiler/xla/literal_util.h" #include "tensorflow/compiler/xla/service/call_inliner.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" namespace xla { // Tries to replace a conditional with a call operation of the corresponding // computation. If the given conditional has a constant predicate, tries to // replace it with a call to its true/false computation as appropirate and then // inline that computation. // // Returns true if it made a change to the graph. static StatusOr<bool> TryRemoveConditional(HloInstruction* conditional) { CHECK_EQ(conditional->opcode(), HloOpcode::kConditional); // Do not remove conditionals that contain side-effecting instructions or // have control predecessors/successors in either true/false computation. if (!conditional->parent()->IsRemovable(conditional) || conditional->HasSideEffect()) { VLOG(2) << "Not attempting to remove conditional as it is not removable or " "has side effect: " << conditional->ToShortString(); return false; } if (conditional->operand(0)->opcode() != HloOpcode::kConstant) { VLOG(2) << "Not attempting to remove conditional as its predicate is not a " "compile-time constant: " << conditional->ToShortString(); return false; } auto computation = conditional->parent(); HloInstruction* call_op; if (conditional->operand(0)->literal().Get<bool>({})) { call_op = computation->AddInstruction(HloInstruction::CreateCall( conditional->shape(), {conditional->mutable_operand(1)}, conditional->true_computation())); } else { call_op = computation->AddInstruction(HloInstruction::CreateCall( conditional->shape(), {conditional->mutable_operand(2)}, conditional->false_computation())); } conditional->SetupDerivedInstruction(call_op); TF_RETURN_IF_ERROR(computation->ReplaceInstruction(conditional, call_op)); TF_RETURN_IF_ERROR(CallInliner::Inline(call_op).status()); return true; } StatusOr<bool> ConditionalSimplifier::Run(HloModule* module) { XLA_VLOG_LINES( 3, "ConditionalSimplifier::Run(), before:\n" + module->ToString()); bool changed = false; // Gather all the conditional ops in our module. We do this ahead of time so // we don't have to worry about mutating the lists of computations or // instructions as we iterate. std::vector<HloInstruction*> conditional_ops; for (auto* comp : module->computations()) { for (auto* instr : comp->instructions()) { if (instr->opcode() == HloOpcode::kConditional) { conditional_ops.push_back(instr); } } } for (HloInstruction* conditional_op : conditional_ops) { TF_ASSIGN_OR_RETURN(bool result, TryRemoveConditional(conditional_op)); changed |= result; } XLA_VLOG_LINES(3, "ConditionalSimplifier::Run(), after:\n" + module->ToString()); return changed; } } // namespace xla <|endoftext|>
<commit_before>// kmreadermainwin // (c) 2002 Don Sanders <sanders@kde.org> // License: GPL // // A toplevel KMainWindow derived class for displaying // single messages or single message parts. // // Could be extended to include support for normal main window // widgets like a toolbar. #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <qaccel.h> #include <kapplication.h> #include <klocale.h> #include <kstdaccel.h> #include <kwin.h> #include <kaction.h> #include <kiconloader.h> #include "kmcommands.h" #include "kmenubar.h" #include "kpopupmenu.h" #include "kmreaderwin.h" #include "kmfolder.h" #include "kmreadermainwin.h" #include "kmreadermainwin.moc" KMReaderMainWin::KMReaderMainWin( bool htmlOverride, char *name ) : KMail::SecondaryWindow( name ), mMsg( 0 ) { KWin::setIcons(winId(), kapp->icon(), kapp->miniIcon()); mReaderWin = new KMReaderWin( this, this, actionCollection() ); //mReaderWin->setShowCompleteMessage( true ); mReaderWin->setAutoDelete( true ); mReaderWin->setHtmlOverride( htmlOverride ); setCentralWidget( mReaderWin ); setupAccel(); connect( kmkernel, SIGNAL( configChanged() ), this, SLOT( slotConfigChanged() ) ); } KMReaderMainWin::KMReaderMainWin( char *name ) : KMail::SecondaryWindow( name ), mMsg( 0 ) { mReaderWin = new KMReaderWin( this, this, actionCollection() ); mReaderWin->setAutoDelete( true ); setCentralWidget( mReaderWin ); setupAccel(); connect( kmkernel, SIGNAL( configChanged() ), this, SLOT( slotConfigChanged() ) ); } KMReaderMainWin::KMReaderMainWin(KMMessagePart* aMsgPart, bool aHTML, const QString& aFileName, const QString& pname, const QTextCodec *codec, char *name ) : KMail::SecondaryWindow( name ), mMsg( 0 ) { resize( 550, 600 ); mReaderWin = new KMReaderWin( this, this, actionCollection() ); //new reader mReaderWin->setOverrideCodec( codec ); mReaderWin->setMsgPart( aMsgPart, aHTML, aFileName, pname ); setCentralWidget( mReaderWin ); setupAccel(); connect( kmkernel, SIGNAL( configChanged() ), this, SLOT( slotConfigChanged() ) ); } KMReaderMainWin::~KMReaderMainWin() { saveMainWindowSettings(KMKernel::config(), "Separate Reader Window"); } void KMReaderMainWin::showMsg( const QTextCodec *codec, KMMessage *msg ) { mReaderWin->setOverrideCodec( codec ); mReaderWin->setMsg( msg, true ); setCaption( msg->subject() ); mMsg = msg; } //----------------------------------------------------------------------------- void KMReaderMainWin::slotPrintMsg() { KMCommand *command = new KMPrintCommand( this, mReaderWin->message(), mReaderWin->htmlOverride() ); command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotReplyToMsg() { KMCommand *command = new KMReplyToCommand( this, mReaderWin->message(), mReaderWin->copyText() ); command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotReplyAuthorToMsg() { KMCommand *command = new KMReplyAuthorCommand( this, mReaderWin->message(), mReaderWin->copyText() ); command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotReplyAllToMsg() { KMCommand *command = new KMReplyToAllCommand( this, mReaderWin->message(), mReaderWin->copyText() ); command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotReplyListToMsg() { KMCommand *command = new KMReplyListCommand( this, mReaderWin->message(), mReaderWin->copyText() ); command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotForwardMsg() { KMCommand *command = 0; if ( mReaderWin->message()->parent() ) { command = new KMForwardCommand( this, mReaderWin->message(), mReaderWin->message()->parent()->identity() ); } else { command = new KMForwardCommand( this, mReaderWin->message() ); } command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotForwardAttachedMsg() { KMCommand *command = 0; if ( mReaderWin->message()->parent() ) { command = new KMForwardAttachedCommand( this, mReaderWin->message(), mReaderWin->message()->parent()->identity() ); } else { command = new KMForwardAttachedCommand( this, mReaderWin->message() ); } command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotRedirectMsg() { KMCommand *command = new KMRedirectCommand( this, mReaderWin->message() ); command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotBounceMsg() { KMCommand *command = new KMBounceCommand( this, mReaderWin->message() ); command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotConfigChanged() { //readConfig(); } void KMReaderMainWin::setupAccel() { if (kmkernel->xmlGuiInstance()) setInstance( kmkernel->xmlGuiInstance() ); KStdAction::close( this, SLOT( close() ), actionCollection() ); applyMainWindowSettings(KMKernel::config(), "Separate Reader Window"); QAccel *accel = new QAccel(mReaderWin, "showMsg()"); accel->connectItem(accel->insertItem(Key_Up), mReaderWin, SLOT(slotScrollUp())); accel->connectItem(accel->insertItem(Key_Down), mReaderWin, SLOT(slotScrollDown())); accel->connectItem(accel->insertItem(Key_Prior), mReaderWin, SLOT(slotScrollPrior())); accel->connectItem(accel->insertItem(Key_Next), mReaderWin, SLOT(slotScrollNext())); accel->connectItem(accel->insertItem(KStdAccel::shortcut(KStdAccel::Copy)), mReaderWin, SLOT(slotCopySelectedText())); connect( mReaderWin, SIGNAL(popupMenu(KMMessage&,const KURL&,const QPoint&)), this, SLOT(slotMsgPopup(KMMessage&,const KURL&,const QPoint&))); connect(mReaderWin, SIGNAL(urlClicked(const KURL&,int)), mReaderWin, SLOT(slotUrlClicked())); mForwardActionMenu = new KActionMenu( i18n("Message->","&Forward"), "mail_forward", actionCollection(), "message_forward" ); mForwardAction = new KAction( i18n("&Inline..."), "mail_forward", SHIFT+Key_F, this, SLOT(slotForwardMsg()), actionCollection(), "message_forward" ); mForwardActionMenu->insert( mForwardAction ); mForwardAttachedAction = new KAction( i18n("Message->Forward->","As &Attachment..."), "mail_forward", Key_F, this, SLOT(slotForwardAttachedMsg()), actionCollection(), "message_forward_as_attachment" ); mForwardActionMenu->insert( mForwardAttachedAction ); mRedirectAction = new KAction( i18n("Message->Forward->","&Redirect..."), Key_E, this, SLOT(slotRedirectMsg()), actionCollection(), "message_forward_redirect" ); mForwardActionMenu->insert( mRedirectAction ); mBounceAction = new KAction( i18n("&Bounce..."), 0, this, SLOT(slotBounceMsg()), actionCollection(), "bounce" ); mReplyActionMenu = new KActionMenu( i18n("Message->","&Reply"), "mail_reply", actionCollection(), "message_reply_menu" ); connect( mReplyActionMenu, SIGNAL(activated()), this, SLOT(slotReplyToMsg()) ); mReplyAction = new KAction( i18n("&Reply..."), "mail_reply", Key_R, this, SLOT(slotReplyToMsg()), actionCollection(), "reply" ); mReplyActionMenu->insert( mReplyAction ); mReplyAuthorAction = new KAction( i18n("Reply to A&uthor..."), "mail_reply", SHIFT+Key_A, this, SLOT(slotReplyAuthorToMsg()), actionCollection(), "reply_author" ); mReplyActionMenu->insert( mReplyAuthorAction ); mReplyAllAction = new KAction( i18n("Reply to &All..."), "mail_replyall", Key_A, this, SLOT(slotReplyAllToMsg()), actionCollection(), "reply_all" ); mReplyActionMenu->insert( mReplyAllAction ); mReplyListAction = new KAction( i18n("Reply to Mailing-&List..."), "mail_replylist", Key_L, this, SLOT(slotReplyListToMsg()), actionCollection(), "reply_list" ); mReplyActionMenu->insert( mReplyListAction ); mPrintAction = KStdAction::print (this, SLOT(slotPrintMsg()), actionCollection()); createGUI( "kmreadermainwin.rc" ); menuBar()->hide(); } void KMReaderMainWin::slotMsgPopup(KMMessage &aMsg, const KURL &aUrl, const QPoint& aPoint) { KPopupMenu * menu = new KPopupMenu; mUrl = aUrl; mMsg = &aMsg; if (!aUrl.isEmpty()) { if (aUrl.protocol() == "mailto") { // popup on a mailto URL mReaderWin->mailToComposeAction()->plug( menu ); if ( mMsg ) { mReaderWin->mailToReplyAction()->plug( menu ); mReaderWin->mailToForwardAction()->plug( menu ); menu->insertSeparator(); } mReaderWin->addAddrBookAction()->plug( menu ); mReaderWin->openAddrBookAction()->plug( menu ); mReaderWin->copyAction()->plug( menu ); } else { // popup on a not-mailto URL mReaderWin->urlOpenAction()->plug( menu ); mReaderWin->urlSaveAsAction()->plug( menu ); mReaderWin->copyURLAction()->plug( menu ); mReaderWin->addBookmarksAction()->plug( menu ); } } else { // popup somewhere else (i.e., not a URL) on the message if (!mMsg) // no message { delete menu; return; } mReplyAction->plug( menu ); mReplyAllAction->plug( menu ); mReplyAuthorAction->plug( menu ); mReplyListAction->plug( menu ); mForwardActionMenu->plug( menu ); mBounceAction->plug( menu ); menu->insertSeparator(); QPopupMenu* copyMenu = new QPopupMenu(menu); KMMenuCommand::folderToPopupMenu( false, this, &mMenuToFolder, copyMenu ); menu->insertItem( i18n("&Copy To" ), copyMenu ); menu->insertSeparator(); mReaderWin->toggleFixFontAction()->plug( menu ); mReaderWin->viewSourceAction()->plug( menu ); mPrintAction->plug( menu ); menu->insertItem( SmallIcon("filesaveas"), i18n( "Save &As..." ), mReaderWin, SLOT( slotSaveMsg() ) ); menu->insertItem( i18n("Save Attachments..."), mReaderWin, SLOT(slotSaveAttachments()) ); } menu->exec(aPoint, 0); delete menu; } void KMReaderMainWin::copySelectedToFolder( int menuId ) { if (!mMenuToFolder[menuId]) return; KMCommand *command = new KMCopyCommand( mMenuToFolder[menuId], mMsg ); command->start(); } <commit_msg>Don't show the toolbar when the external message window is abused as an attachment viewer. Enable it when a message is set for the window. Fixeѕ a crash with trying to forward a 0 mail.<commit_after>// kmreadermainwin // (c) 2002 Don Sanders <sanders@kde.org> // License: GPL // // A toplevel KMainWindow derived class for displaying // single messages or single message parts. // // Could be extended to include support for normal main window // widgets like a toolbar. #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <qaccel.h> #include <kapplication.h> #include <klocale.h> #include <kstdaccel.h> #include <kwin.h> #include <kaction.h> #include <kiconloader.h> #include "kmcommands.h" #include "kmenubar.h" #include "kpopupmenu.h" #include "kmreaderwin.h" #include "kmfolder.h" #include "kmreadermainwin.h" #include "kmreadermainwin.moc" KMReaderMainWin::KMReaderMainWin( bool htmlOverride, char *name ) : KMail::SecondaryWindow( name ), mMsg( 0 ) { KWin::setIcons(winId(), kapp->icon(), kapp->miniIcon()); mReaderWin = new KMReaderWin( this, this, actionCollection() ); //mReaderWin->setShowCompleteMessage( true ); mReaderWin->setAutoDelete( true ); mReaderWin->setHtmlOverride( htmlOverride ); setCentralWidget( mReaderWin ); setupAccel(); connect( kmkernel, SIGNAL( configChanged() ), this, SLOT( slotConfigChanged() ) ); } KMReaderMainWin::KMReaderMainWin( char *name ) : KMail::SecondaryWindow( name ), mMsg( 0 ) { mReaderWin = new KMReaderWin( this, this, actionCollection() ); mReaderWin->setAutoDelete( true ); setCentralWidget( mReaderWin ); setupAccel(); connect( kmkernel, SIGNAL( configChanged() ), this, SLOT( slotConfigChanged() ) ); } KMReaderMainWin::KMReaderMainWin(KMMessagePart* aMsgPart, bool aHTML, const QString& aFileName, const QString& pname, const QTextCodec *codec, char *name ) : KMail::SecondaryWindow( name ), mMsg( 0 ) { resize( 550, 600 ); mReaderWin = new KMReaderWin( this, this, actionCollection() ); //new reader mReaderWin->setOverrideCodec( codec ); mReaderWin->setMsgPart( aMsgPart, aHTML, aFileName, pname ); setCentralWidget( mReaderWin ); setupAccel(); connect( kmkernel, SIGNAL( configChanged() ), this, SLOT( slotConfigChanged() ) ); } KMReaderMainWin::~KMReaderMainWin() { saveMainWindowSettings(KMKernel::config(), "Separate Reader Window"); } void KMReaderMainWin::showMsg( const QTextCodec *codec, KMMessage *msg ) { mReaderWin->setOverrideCodec( codec ); mReaderWin->setMsg( msg, true ); setCaption( msg->subject() ); mMsg = msg; toolBar( "mainToolBar" )->show(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotPrintMsg() { KMCommand *command = new KMPrintCommand( this, mReaderWin->message(), mReaderWin->htmlOverride() ); command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotReplyToMsg() { KMCommand *command = new KMReplyToCommand( this, mReaderWin->message(), mReaderWin->copyText() ); command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotReplyAuthorToMsg() { KMCommand *command = new KMReplyAuthorCommand( this, mReaderWin->message(), mReaderWin->copyText() ); command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotReplyAllToMsg() { KMCommand *command = new KMReplyToAllCommand( this, mReaderWin->message(), mReaderWin->copyText() ); command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotReplyListToMsg() { KMCommand *command = new KMReplyListCommand( this, mReaderWin->message(), mReaderWin->copyText() ); command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotForwardMsg() { KMCommand *command = 0; if ( mReaderWin->message()->parent() ) { command = new KMForwardCommand( this, mReaderWin->message(), mReaderWin->message()->parent()->identity() ); } else { command = new KMForwardCommand( this, mReaderWin->message() ); } command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotForwardAttachedMsg() { KMCommand *command = 0; if ( mReaderWin->message()->parent() ) { command = new KMForwardAttachedCommand( this, mReaderWin->message(), mReaderWin->message()->parent()->identity() ); } else { command = new KMForwardAttachedCommand( this, mReaderWin->message() ); } command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotRedirectMsg() { KMCommand *command = new KMRedirectCommand( this, mReaderWin->message() ); command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotBounceMsg() { KMCommand *command = new KMBounceCommand( this, mReaderWin->message() ); command->start(); } //----------------------------------------------------------------------------- void KMReaderMainWin::slotConfigChanged() { //readConfig(); } void KMReaderMainWin::setupAccel() { if (kmkernel->xmlGuiInstance()) setInstance( kmkernel->xmlGuiInstance() ); KStdAction::close( this, SLOT( close() ), actionCollection() ); applyMainWindowSettings(KMKernel::config(), "Separate Reader Window"); QAccel *accel = new QAccel(mReaderWin, "showMsg()"); accel->connectItem(accel->insertItem(Key_Up), mReaderWin, SLOT(slotScrollUp())); accel->connectItem(accel->insertItem(Key_Down), mReaderWin, SLOT(slotScrollDown())); accel->connectItem(accel->insertItem(Key_Prior), mReaderWin, SLOT(slotScrollPrior())); accel->connectItem(accel->insertItem(Key_Next), mReaderWin, SLOT(slotScrollNext())); accel->connectItem(accel->insertItem(KStdAccel::shortcut(KStdAccel::Copy)), mReaderWin, SLOT(slotCopySelectedText())); connect( mReaderWin, SIGNAL(popupMenu(KMMessage&,const KURL&,const QPoint&)), this, SLOT(slotMsgPopup(KMMessage&,const KURL&,const QPoint&))); connect(mReaderWin, SIGNAL(urlClicked(const KURL&,int)), mReaderWin, SLOT(slotUrlClicked())); mForwardActionMenu = new KActionMenu( i18n("Message->","&Forward"), "mail_forward", actionCollection(), "message_forward" ); mForwardAction = new KAction( i18n("&Inline..."), "mail_forward", SHIFT+Key_F, this, SLOT(slotForwardMsg()), actionCollection(), "message_forward" ); mForwardActionMenu->insert( mForwardAction ); mForwardAttachedAction = new KAction( i18n("Message->Forward->","As &Attachment..."), "mail_forward", Key_F, this, SLOT(slotForwardAttachedMsg()), actionCollection(), "message_forward_as_attachment" ); mForwardActionMenu->insert( mForwardAttachedAction ); mRedirectAction = new KAction( i18n("Message->Forward->","&Redirect..."), Key_E, this, SLOT(slotRedirectMsg()), actionCollection(), "message_forward_redirect" ); mForwardActionMenu->insert( mRedirectAction ); mBounceAction = new KAction( i18n("&Bounce..."), 0, this, SLOT(slotBounceMsg()), actionCollection(), "bounce" ); mReplyActionMenu = new KActionMenu( i18n("Message->","&Reply"), "mail_reply", actionCollection(), "message_reply_menu" ); connect( mReplyActionMenu, SIGNAL(activated()), this, SLOT(slotReplyToMsg()) ); mReplyAction = new KAction( i18n("&Reply..."), "mail_reply", Key_R, this, SLOT(slotReplyToMsg()), actionCollection(), "reply" ); mReplyActionMenu->insert( mReplyAction ); mReplyAuthorAction = new KAction( i18n("Reply to A&uthor..."), "mail_reply", SHIFT+Key_A, this, SLOT(slotReplyAuthorToMsg()), actionCollection(), "reply_author" ); mReplyActionMenu->insert( mReplyAuthorAction ); mReplyAllAction = new KAction( i18n("Reply to &All..."), "mail_replyall", Key_A, this, SLOT(slotReplyAllToMsg()), actionCollection(), "reply_all" ); mReplyActionMenu->insert( mReplyAllAction ); mReplyListAction = new KAction( i18n("Reply to Mailing-&List..."), "mail_replylist", Key_L, this, SLOT(slotReplyListToMsg()), actionCollection(), "reply_list" ); mReplyActionMenu->insert( mReplyListAction ); mPrintAction = KStdAction::print (this, SLOT(slotPrintMsg()), actionCollection()); createGUI( "kmreadermainwin.rc" ); menuBar()->hide(); toolBar( "mainToolBar" )->hide(); } void KMReaderMainWin::slotMsgPopup(KMMessage &aMsg, const KURL &aUrl, const QPoint& aPoint) { KPopupMenu * menu = new KPopupMenu; mUrl = aUrl; mMsg = &aMsg; if (!aUrl.isEmpty()) { if (aUrl.protocol() == "mailto") { // popup on a mailto URL mReaderWin->mailToComposeAction()->plug( menu ); if ( mMsg ) { mReaderWin->mailToReplyAction()->plug( menu ); mReaderWin->mailToForwardAction()->plug( menu ); menu->insertSeparator(); } mReaderWin->addAddrBookAction()->plug( menu ); mReaderWin->openAddrBookAction()->plug( menu ); mReaderWin->copyAction()->plug( menu ); } else { // popup on a not-mailto URL mReaderWin->urlOpenAction()->plug( menu ); mReaderWin->urlSaveAsAction()->plug( menu ); mReaderWin->copyURLAction()->plug( menu ); mReaderWin->addBookmarksAction()->plug( menu ); } } else { // popup somewhere else (i.e., not a URL) on the message if (!mMsg) // no message { delete menu; return; } mReplyAction->plug( menu ); mReplyAllAction->plug( menu ); mReplyAuthorAction->plug( menu ); mReplyListAction->plug( menu ); mForwardActionMenu->plug( menu ); mBounceAction->plug( menu ); menu->insertSeparator(); QPopupMenu* copyMenu = new QPopupMenu(menu); KMMenuCommand::folderToPopupMenu( false, this, &mMenuToFolder, copyMenu ); menu->insertItem( i18n("&Copy To" ), copyMenu ); menu->insertSeparator(); mReaderWin->toggleFixFontAction()->plug( menu ); mReaderWin->viewSourceAction()->plug( menu ); mPrintAction->plug( menu ); menu->insertItem( SmallIcon("filesaveas"), i18n( "Save &As..." ), mReaderWin, SLOT( slotSaveMsg() ) ); menu->insertItem( i18n("Save Attachments..."), mReaderWin, SLOT(slotSaveAttachments()) ); } menu->exec(aPoint, 0); delete menu; } void KMReaderMainWin::copySelectedToFolder( int menuId ) { if (!mMenuToFolder[menuId]) return; KMCommand *command = new KMCopyCommand( mMenuToFolder[menuId], mMsg ); command->start(); } <|endoftext|>
<commit_before>/*************************************************************************** knarticlewindow.cpp - description ------------------- copyright : (C) 2000 by Christian Thurner email : cthurner@freepage.de ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include <kstdaction.h> #include <klocale.h> #include <kedittoolbar.h> #include <kkeydialog.h> #include <khtml_part.h> #include "kngroup.h" #include "knsavedarticle.h" #include "knfetcharticle.h" #include "knarticlewidget.h" #include "knsavedarticlemanager.h" #include "utilities.h" #include "knglobals.h" #include "knode.h" #include "knarticlewindow.h" KNArticleWindow::KNArticleWindow(KNArticle *art, KNArticleCollection *col, const char *name ) : KMainWindow(0, name) { if(art) setCaption(art->subject()); //setIcon(UserIcon("posting")); artW=new KNArticleWidget(this); artW->setData(art, col); setCentralWidget(artW); connect(artW, SIGNAL(articleLoaded()), SLOT(slotArticleLoaded())); *actionCollection() += artW->actions(); // include the actions of the article widget // file menu KStdAction::close(this, SLOT(slotFileClose()),actionCollection()); // article menu actPostReply = new KAction(i18n("Post &reply"),"reply", Key_R , this, SLOT(slotArtReply()), actionCollection(), "article_postReply"); actPostReply->setEnabled(false); actMailReply = new KAction(i18n("&Mail reply"),"mail_reply", Key_A , this, SLOT(slotArtRemail()), actionCollection(), "article_mailReply"); actMailReply->setEnabled(false); actForward = new KAction(i18n("&Forward"), "mail_forward", Key_F , this, SLOT(slotArtForward()), actionCollection(), "article_forward"); actForward->setEnabled(false); actCancel = new KAction(i18n("article","&Cancel"), 0 , this, SLOT(slotArtCancel()), actionCollection(), "article_cancel"); actCancel->setEnabled(false); actSupersede = new KAction(i18n("&Supersede"), 0 , this, SLOT(slotArtSupersede()), actionCollection(), "article_supersede"); actSupersede->setEnabled(false); // settings menu KStdAction::showToolbar(this, SLOT(slotToggleToolBar()), actionCollection()); KStdAction::keyBindings(this, SLOT(slotConfKeys()), actionCollection()); KStdAction::configureToolbars(this, SLOT(slotConfToolbar()), actionCollection()); KStdAction::preferences(knGlobals.top, SLOT(slotSettings()), actionCollection()); createGUI("knreaderui.rc"); restoreWindowSize("reader", this, QSize(500,400)); } KNArticleWindow::~KNArticleWindow() { saveWindowSize("reader", size()); } void KNArticleWindow::slotArticleLoaded() { actPostReply->setEnabled(true); actMailReply->setEnabled(true); actForward->setEnabled(true); actCancel->setEnabled(true); actSupersede->setEnabled(true); } void KNArticleWindow::slotFileClose() { close(); } void KNArticleWindow::slotArtReply() { knGlobals.sArtManager->reply(artW->article(),static_cast<KNGroup*>(artW->collection())); } void KNArticleWindow::slotArtRemail() { knGlobals.sArtManager->reply(artW->article(), 0); } void KNArticleWindow::slotArtForward() { knGlobals.sArtManager->forward(artW->article()); } void KNArticleWindow::slotArtCancel() { knGlobals.sArtManager->cancel(static_cast<KNFetchArticle*>(artW->article()),static_cast<KNGroup*>(artW->collection())); } void KNArticleWindow::slotArtSupersede() { knGlobals.sArtManager->supersede(static_cast<KNFetchArticle*>(artW->article()),static_cast<KNGroup*>(artW->collection())); } void KNArticleWindow::slotToggleToolBar() { if(toolBar("mainToolBar")->isVisible()) toolBar("mainToolBar")->hide(); else toolBar("mainToolBar")->show(); } void KNArticleWindow::slotConfKeys() { KKeyDialog::configureKeys(actionCollection(), xmlFile(), true, this); } void KNArticleWindow::slotConfToolbar() { KEditToolbar *dlg = new KEditToolbar(guiFactory(),this); if (dlg->exec()) { //guiFactory()->removeClient(artW->part()); createGUI("knreaderui.rc",false); //guiFactory()->addClient(artW->part()); conserveMemory(); } delete dlg; } //-------------------------------- #include "knarticlewindow.moc" <commit_msg>- actPostReply = new KAction(i18n("Post &reply"),"reply", Key_R , this, SLOT(slotArtReply()), + actPostReply = new KAction(i18n("Post &reply"),"message_reply", Key_R , this, SLOT(slotArtReply()),<commit_after>/*************************************************************************** knarticlewindow.cpp - description ------------------- copyright : (C) 2000 by Christian Thurner email : cthurner@freepage.de ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include <kstdaction.h> #include <klocale.h> #include <kedittoolbar.h> #include <kkeydialog.h> #include <khtml_part.h> #include "kngroup.h" #include "knsavedarticle.h" #include "knfetcharticle.h" #include "knarticlewidget.h" #include "knsavedarticlemanager.h" #include "utilities.h" #include "knglobals.h" #include "knode.h" #include "knarticlewindow.h" KNArticleWindow::KNArticleWindow(KNArticle *art, KNArticleCollection *col, const char *name ) : KMainWindow(0, name) { if(art) setCaption(art->subject()); //setIcon(UserIcon("posting")); artW=new KNArticleWidget(this); artW->setData(art, col); setCentralWidget(artW); connect(artW, SIGNAL(articleLoaded()), SLOT(slotArticleLoaded())); *actionCollection() += artW->actions(); // include the actions of the article widget // file menu KStdAction::close(this, SLOT(slotFileClose()),actionCollection()); // article menu actPostReply = new KAction(i18n("Post &reply"),"message_reply", Key_R , this, SLOT(slotArtReply()), actionCollection(), "article_postReply"); actPostReply->setEnabled(false); actMailReply = new KAction(i18n("&Mail reply"),"mail_reply", Key_A , this, SLOT(slotArtRemail()), actionCollection(), "article_mailReply"); actMailReply->setEnabled(false); actForward = new KAction(i18n("&Forward"), "mail_forward", Key_F , this, SLOT(slotArtForward()), actionCollection(), "article_forward"); actForward->setEnabled(false); actCancel = new KAction(i18n("article","&Cancel"), 0 , this, SLOT(slotArtCancel()), actionCollection(), "article_cancel"); actCancel->setEnabled(false); actSupersede = new KAction(i18n("&Supersede"), 0 , this, SLOT(slotArtSupersede()), actionCollection(), "article_supersede"); actSupersede->setEnabled(false); // settings menu KStdAction::showToolbar(this, SLOT(slotToggleToolBar()), actionCollection()); KStdAction::keyBindings(this, SLOT(slotConfKeys()), actionCollection()); KStdAction::configureToolbars(this, SLOT(slotConfToolbar()), actionCollection()); KStdAction::preferences(knGlobals.top, SLOT(slotSettings()), actionCollection()); createGUI("knreaderui.rc"); restoreWindowSize("reader", this, QSize(500,400)); } KNArticleWindow::~KNArticleWindow() { saveWindowSize("reader", size()); } void KNArticleWindow::slotArticleLoaded() { actPostReply->setEnabled(true); actMailReply->setEnabled(true); actForward->setEnabled(true); actCancel->setEnabled(true); actSupersede->setEnabled(true); } void KNArticleWindow::slotFileClose() { close(); } void KNArticleWindow::slotArtReply() { knGlobals.sArtManager->reply(artW->article(),static_cast<KNGroup*>(artW->collection())); } void KNArticleWindow::slotArtRemail() { knGlobals.sArtManager->reply(artW->article(), 0); } void KNArticleWindow::slotArtForward() { knGlobals.sArtManager->forward(artW->article()); } void KNArticleWindow::slotArtCancel() { knGlobals.sArtManager->cancel(static_cast<KNFetchArticle*>(artW->article()),static_cast<KNGroup*>(artW->collection())); } void KNArticleWindow::slotArtSupersede() { knGlobals.sArtManager->supersede(static_cast<KNFetchArticle*>(artW->article()),static_cast<KNGroup*>(artW->collection())); } void KNArticleWindow::slotToggleToolBar() { if(toolBar("mainToolBar")->isVisible()) toolBar("mainToolBar")->hide(); else toolBar("mainToolBar")->show(); } void KNArticleWindow::slotConfKeys() { KKeyDialog::configureKeys(actionCollection(), xmlFile(), true, this); } void KNArticleWindow::slotConfToolbar() { KEditToolbar *dlg = new KEditToolbar(guiFactory(),this); if (dlg->exec()) { //guiFactory()->removeClient(artW->part()); createGUI("knreaderui.rc",false); //guiFactory()->addClient(artW->part()); conserveMemory(); } delete dlg; } //-------------------------------- #include "knarticlewindow.moc" <|endoftext|>
<commit_before>/* KNode, the KDE newsreader Copyright (c) 1999-2005 the KNode authors. See file AUTHORS for details 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. 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, US */ #include <kdebug.h> #include "knmemorymanager.h" #include "knfolder.h" #include "knglobals.h" #include "knconfigmanager.h" #include "knarticlemanager.h" #include "kngroupmanager.h" #include "knfoldermanager.h" KNMemoryManager::KNMemoryManager() : c_ollCacheSize(0), a_rtCacheSize(0) { } KNMemoryManager::~KNMemoryManager() { for ( QValueList<CollectionItem*>::Iterator it = mColList.begin(); it != mColList.end(); ++it ) delete (*it); for ( QValueList<ArticleItem*>::Iterator it = mArtList.begin(); it != mArtList.end(); ++it ) delete (*it); } void KNMemoryManager::updateCacheEntry(KNArticleCollection *c) { CollectionItem *ci; int oldSize=0; if( (ci=findCacheEntry(c, true)) ) { // item is taken from the list oldSize=ci->storageSize; ci->sync(); kdDebug(5003) << "KNMemoryManager::updateCacheEntry() : collection (" << c->name() << ") updated" << endl; } else { ci=new CollectionItem(c); kdDebug(5003) << "KNMemoryManager::updateCacheEntry() : collection (" << c->name() << ") added" << endl; } mColList.append(ci); c_ollCacheSize += (ci->storageSize - oldSize); checkMemoryUsageCollections(); } void KNMemoryManager::removeCacheEntry(KNArticleCollection *c) { CollectionItem *ci; ci=findCacheEntry(c, true); if(ci) { c_ollCacheSize -= ci->storageSize; delete ci; kdDebug(5003) << "KNMemoryManager::removeCacheEntry() : collection removed (" << c->name() << "), " << mColList.count() << " collections left in cache" << endl; } } void KNMemoryManager::prepareLoad(KNArticleCollection *c) { CollectionItem ci(c); c_ollCacheSize += ci.storageSize; checkMemoryUsageCollections(); c_ollCacheSize -= ci.storageSize; } void KNMemoryManager::updateCacheEntry(KNArticle *a) { ArticleItem *ai; int oldSize=0; if( (ai=findCacheEntry(a, true)) ) { oldSize=ai->storageSize; ai->sync(); kdDebug(5003) << "KNMemoryManager::updateCacheEntry() : article updated" << endl; } else { ai=new ArticleItem(a); kdDebug(5003) << "KNMemoryManager::updateCacheEntry() : article added" << endl; } mArtList.append(ai); a_rtCacheSize += (ai->storageSize - oldSize); checkMemoryUsageArticles(); } void KNMemoryManager::removeCacheEntry(KNArticle *a) { ArticleItem *ai; if( (ai=findCacheEntry(a, true)) ) { a_rtCacheSize -= ai->storageSize; delete ai; kdDebug(5003) << "KNMemoryManager::removeCacheEntry() : article removed, " << mArtList.count() << " articles left in cache" << endl; } } KNMemoryManager::CollectionItem* KNMemoryManager::findCacheEntry(KNArticleCollection *c, bool take) { for ( QValueList<CollectionItem*>::Iterator it = mColList.begin(); it != mColList.end(); ++it ) { if ( (*it)->col == c ) { if ( take ) mColList.remove( it ); return (*it); } } return 0; } KNMemoryManager::ArticleItem* KNMemoryManager::findCacheEntry(KNArticle *a, bool take) { for ( QValueList<ArticleItem*>::Iterator it = mArtList.begin(); it != mArtList.end(); ++it ) { if ( (*it)->art == a ) { if ( take ) mArtList.remove( it ); return (*it); } } return 0; } void KNMemoryManager::checkMemoryUsageCollections() { int maxSize = knGlobals.configManager()->readNewsGeneral()->collCacheSize() * 1024; KNArticleCollection *c=0; if (c_ollCacheSize > maxSize) { QValueList<CollectionItem*> tempList( mColList ); // work on a copy, KNGroup-/Foldermanager will // modify the original list for ( QValueList<CollectionItem*>::Iterator it = tempList.begin(); it != tempList.end(); ) { if ( c_ollCacheSize <= maxSize ) break; // unloadHeaders() will remove the cache entry and thus invalidate the iterator! c = (*it)->col; ++it; if (c->type() == KNCollection::CTgroup) knGlobals.groupManager()->unloadHeaders(static_cast<KNGroup*>(c), false); // *try* to unload else if (c->type() == KNCollection::CTfolder) knGlobals.folderManager()->unloadHeaders(static_cast<KNFolder*>(c), false); // *try* to unload } } kdDebug(5003) << "KNMemoryManager::checkMemoryUsageCollections() : " << mColList.count() << " collections in cache => Usage : " << ( c_ollCacheSize*100.0 / maxSize ) << "%" << endl; } void KNMemoryManager::checkMemoryUsageArticles() { int maxSize = knGlobals.configManager()->readNewsGeneral()->artCacheSize() * 1024; if (a_rtCacheSize > maxSize) { QValueList<ArticleItem*> tempList( mArtList ); // work on a copy, KNArticlemanager will // modify the original list for ( QValueList<ArticleItem*>::Iterator it = mArtList.begin(); it != mArtList.end(); ) { if ( a_rtCacheSize <= maxSize ) break; // unloadArticle() will remove the cache entry and thus invalidate the iterator! KNArticle *art = (*it)->art; ++it; knGlobals.articleManager()->unloadArticle( art, false ); // *try* to unload } } kdDebug(5003) << "KNMemoryManager::checkMemoryUsageArticles() : " << mArtList.count() << " articles in cache => Usage : " << ( a_rtCacheSize*100.0 / maxSize ) << "%" << endl; } void KNMemoryManager::ArticleItem::sync() { storageSize=art->storageSize(); } void KNMemoryManager::CollectionItem::sync() { storageSize=col->length()*1024; // rule of thumb : ~1k per header } <commit_msg>Fix crash.<commit_after>/* KNode, the KDE newsreader Copyright (c) 1999-2005 the KNode authors. See file AUTHORS for details 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. 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, US */ #include <kdebug.h> #include "knmemorymanager.h" #include "knfolder.h" #include "knglobals.h" #include "knconfigmanager.h" #include "knarticlemanager.h" #include "kngroupmanager.h" #include "knfoldermanager.h" KNMemoryManager::KNMemoryManager() : c_ollCacheSize(0), a_rtCacheSize(0) { } KNMemoryManager::~KNMemoryManager() { for ( QValueList<CollectionItem*>::Iterator it = mColList.begin(); it != mColList.end(); ++it ) delete (*it); for ( QValueList<ArticleItem*>::Iterator it = mArtList.begin(); it != mArtList.end(); ++it ) delete (*it); } void KNMemoryManager::updateCacheEntry(KNArticleCollection *c) { CollectionItem *ci; int oldSize=0; if( (ci=findCacheEntry(c, true)) ) { // item is taken from the list oldSize=ci->storageSize; ci->sync(); kdDebug(5003) << "KNMemoryManager::updateCacheEntry() : collection (" << c->name() << ") updated" << endl; } else { ci=new CollectionItem(c); kdDebug(5003) << "KNMemoryManager::updateCacheEntry() : collection (" << c->name() << ") added" << endl; } mColList.append(ci); c_ollCacheSize += (ci->storageSize - oldSize); checkMemoryUsageCollections(); } void KNMemoryManager::removeCacheEntry(KNArticleCollection *c) { CollectionItem *ci; ci=findCacheEntry(c, true); if(ci) { c_ollCacheSize -= ci->storageSize; delete ci; kdDebug(5003) << "KNMemoryManager::removeCacheEntry() : collection removed (" << c->name() << "), " << mColList.count() << " collections left in cache" << endl; } } void KNMemoryManager::prepareLoad(KNArticleCollection *c) { CollectionItem ci(c); c_ollCacheSize += ci.storageSize; checkMemoryUsageCollections(); c_ollCacheSize -= ci.storageSize; } void KNMemoryManager::updateCacheEntry(KNArticle *a) { ArticleItem *ai; int oldSize=0; if( (ai=findCacheEntry(a, true)) ) { oldSize=ai->storageSize; ai->sync(); kdDebug(5003) << "KNMemoryManager::updateCacheEntry() : article updated" << endl; } else { ai=new ArticleItem(a); kdDebug(5003) << "KNMemoryManager::updateCacheEntry() : article added" << endl; } mArtList.append(ai); a_rtCacheSize += (ai->storageSize - oldSize); checkMemoryUsageArticles(); } void KNMemoryManager::removeCacheEntry(KNArticle *a) { ArticleItem *ai; if( (ai=findCacheEntry(a, true)) ) { a_rtCacheSize -= ai->storageSize; delete ai; kdDebug(5003) << "KNMemoryManager::removeCacheEntry() : article removed, " << mArtList.count() << " articles left in cache" << endl; } } KNMemoryManager::CollectionItem* KNMemoryManager::findCacheEntry(KNArticleCollection *c, bool take) { for ( QValueList<CollectionItem*>::Iterator it = mColList.begin(); it != mColList.end(); ++it ) { if ( (*it)->col == c ) { CollectionItem *ret = (*it); if ( take ) mColList.remove( it ); return ret; } } return 0; } KNMemoryManager::ArticleItem* KNMemoryManager::findCacheEntry(KNArticle *a, bool take) { for ( QValueList<ArticleItem*>::Iterator it = mArtList.begin(); it != mArtList.end(); ++it ) { if ( (*it)->art == a ) { ArticleItem *ret = (*it); if ( take ) mArtList.remove( it ); return ret; } } return 0; } void KNMemoryManager::checkMemoryUsageCollections() { int maxSize = knGlobals.configManager()->readNewsGeneral()->collCacheSize() * 1024; KNArticleCollection *c=0; if (c_ollCacheSize > maxSize) { QValueList<CollectionItem*> tempList( mColList ); // work on a copy, KNGroup-/Foldermanager will // modify the original list for ( QValueList<CollectionItem*>::Iterator it = tempList.begin(); it != tempList.end(); ) { if ( c_ollCacheSize <= maxSize ) break; // unloadHeaders() will remove the cache entry and thus invalidate the iterator! c = (*it)->col; ++it; if (c->type() == KNCollection::CTgroup) knGlobals.groupManager()->unloadHeaders(static_cast<KNGroup*>(c), false); // *try* to unload else if (c->type() == KNCollection::CTfolder) knGlobals.folderManager()->unloadHeaders(static_cast<KNFolder*>(c), false); // *try* to unload } } kdDebug(5003) << "KNMemoryManager::checkMemoryUsageCollections() : " << mColList.count() << " collections in cache => Usage : " << ( c_ollCacheSize*100.0 / maxSize ) << "%" << endl; } void KNMemoryManager::checkMemoryUsageArticles() { int maxSize = knGlobals.configManager()->readNewsGeneral()->artCacheSize() * 1024; if (a_rtCacheSize > maxSize) { QValueList<ArticleItem*> tempList( mArtList ); // work on a copy, KNArticlemanager will // modify the original list for ( QValueList<ArticleItem*>::Iterator it = mArtList.begin(); it != mArtList.end(); ) { if ( a_rtCacheSize <= maxSize ) break; // unloadArticle() will remove the cache entry and thus invalidate the iterator! KNArticle *art = (*it)->art; ++it; knGlobals.articleManager()->unloadArticle( art, false ); // *try* to unload } } kdDebug(5003) << "KNMemoryManager::checkMemoryUsageArticles() : " << mArtList.count() << " articles in cache => Usage : " << ( a_rtCacheSize*100.0 / maxSize ) << "%" << endl; } void KNMemoryManager::ArticleItem::sync() { storageSize=art->storageSize(); } void KNMemoryManager::CollectionItem::sync() { storageSize=col->length()*1024; // rule of thumb : ~1k per header } <|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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. */ #include "urihandler.h" #ifndef KORG_NODCOP #include <dcopclient.h> #include "kmailIface_stub.h" #endif #include <kiconloader.h> #include <krun.h> #include <kapplication.h> #include <kprocess.h> #include <kdebug.h> bool UriHandler::process( const QString &uri ) { kdDebug(5850) << "UriHandler::process(): " << uri << endl; #ifndef KORG_NODCOP if ( uri.startsWith( "kmail:" ) ) { // make sure kmail is running or the part is shown kapp->startServiceByDesktopPath("kmail"); // parse string, show int start = uri.find( ':' ) + 1; int delimiter = uri.find( '/', start ); QString serialNumberStr = uri.mid( start, delimiter-start ); Q_UINT32 serialNumber = serialNumberStr.toUInt(); QString messageId = uri.mid( delimiter+1 ); kdDebug(5850) << "SERIALNUMBERSTR: " << serialNumberStr << " MESSAGEID: " << messageId << endl; KMailIface_stub kmailIface( "kmail", "KMailIface" ); kmailIface.showMail( serialNumber, messageId ); return true; } else if ( uri.startsWith( "mailto:" ) ) { KApplication::kApplication()->invokeMailer( uri.mid(7), QString::null ); return true; } else if ( uri.startsWith( "uid:" ) ) { DCOPClient *client = KApplication::kApplication()->dcopClient(); const QByteArray noParamData; const QByteArray paramData; QByteArray replyData; QCString replyTypeStr; bool foundAbbrowser = client->call( "kaddressbook", "KAddressBookIface", "interfaces()", noParamData, replyTypeStr, replyData ); if ( foundAbbrowser ) { //KAddressbook is already running, so just DCOP to it to bring up the contact editor //client->send("kaddressbook","KAddressBookIface", QDataStream arg( paramData, IO_WriteOnly ); arg << uri.mid( 6 ); #if KDE_IS_VERSION( 3, 2, 90 ) kapp->updateRemoteUserTimestamp("kaddressbook"); #endif client->send( "kaddressbook", "KAddressBookIface", "showContactEditor( QString )", paramData ); return true; } else { /* KaddressBook is not already running. Pass it the UID of the contact via the command line while starting it - its neater. We start it without its main interface */ KIconLoader *iconLoader = new KIconLoader(); QString iconPath = iconLoader->iconPath( "go", KIcon::Small ); QString tmpStr = "kaddressbook --editor-only --uid "; tmpStr += KProcess::quote( uri.mid( 6 ) ); KRun::runCommand( tmpStr, "KAddressBook", iconPath ); return true; } } else { // no special URI, let KDE handle it new KRun(KURL( uri )); } #endif return false; } <commit_msg>Backport fix for failing DCOP call<commit_after>/* This file is part of KOrganizer. Copyright (c) 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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. */ #include "urihandler.h" #ifndef KORG_NODCOP #include <dcopclient.h> #include "kmailIface_stub.h" #endif #include <kiconloader.h> #include <krun.h> #include <kapplication.h> #include <kprocess.h> #include <kdebug.h> bool UriHandler::process( const QString &uri ) { kdDebug(5850) << "UriHandler::process(): " << uri << endl; #ifndef KORG_NODCOP if ( uri.startsWith( "kmail:" ) ) { // make sure kmail is running or the part is shown kapp->startServiceByDesktopPath("kmail"); // parse string, show int start = uri.find( ':' ) + 1; int delimiter = uri.find( '/', start ); QString serialNumberStr = uri.mid( start, delimiter-start ); Q_UINT32 serialNumber = serialNumberStr.toUInt(); QString messageId = uri.mid( delimiter+1 ); kdDebug(5850) << "SERIALNUMBERSTR: " << serialNumberStr << " MESSAGEID: " << messageId << endl; KMailIface_stub kmailIface( "kmail", "KMailIface" ); kmailIface.showMail( serialNumber, messageId ); return true; } else if ( uri.startsWith( "mailto:" ) ) { KApplication::kApplication()->invokeMailer( uri.mid(7), QString::null ); return true; } else if ( uri.startsWith( "uid:" ) ) { DCOPClient *client = KApplication::kApplication()->dcopClient(); const QByteArray noParamData; const QByteArray paramData; QByteArray replyData; QCString replyTypeStr; bool foundAbbrowser = client->call( "kaddressbook", "KAddressBookIface", "interfaces()", noParamData, replyTypeStr, replyData ); if ( foundAbbrowser ) { //KAddressbook is already running, so just DCOP to it to bring up the contact editor #if KDE_IS_VERSION( 3, 2, 90 ) kapp->updateRemoteUserTimestamp("kaddressbook"); #endif DCOPRef kaddressbook( "kaddressbook", "KAddressBookIface" ); kaddressbook.send( "showContactEditor", uri.mid( 6 ) ); return true; } else { /* KaddressBook is not already running. Pass it the UID of the contact via the command line while starting it - its neater. We start it without its main interface */ KIconLoader *iconLoader = new KIconLoader(); QString iconPath = iconLoader->iconPath( "go", KIcon::Small ); QString tmpStr = "kaddressbook --editor-only --uid "; tmpStr += KProcess::quote( uri.mid( 6 ) ); KRun::runCommand( tmpStr, "KAddressBook", iconPath ); return true; } } else { // no special URI, let KDE handle it new KRun(KURL( uri )); } #endif return false; } <|endoftext|>
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "open_spiel/bots/human/human_bot.h" #include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <string> #include <unordered_map> #include <utility> namespace open_spiel { namespace { const int kMaxWidth = 80; const int kPadding = 2; void PrintColumns(const std::vector<std::string>& strings) { std::string padding_string(kPadding, ' '); int longest_string_length = 0; for (const std::string& string : strings) { if (string.length() > longest_string_length) { longest_string_length = string.length(); } } int max_columns = (kMaxWidth - 1) / (longest_string_length + 2 * kPadding); int rows = ceil((float) strings.size() / (float) max_columns); int columns = ceil((float) strings.size() / (float) rows); for (int row = 0; row < rows; ++row) { for (int column = 0; column < columns; ++column) { int index = row + column * rows; if (index < strings.size()) { std::cout << std::left << std::setw(longest_string_length + kPadding) << padding_string << strings[index]; } } std::cout << "\n"; } } } // namespace Action HumanBot::Step(const State& state) { std::vector<Action> legal_actions = state.LegalActions(state.CurrentPlayer()); if (legal_actions.empty()) { return kInvalidAction; } std::unordered_map<std::string, Action> action_map; for (Action legal_action : legal_actions) { action_map[state.ActionToString(legal_action)] = legal_action; } while (true) { Action action; std::string action_string = ""; std::cout << "Choose an action (empty to print legal actions): "; std::getline(std::cin, action_string); // Print the legal actions if no action is given. if (action_string.empty()) { std::cout << "Legal action(s):\n"; std::vector<std::string> legal_action_strings; std::vector<std::pair<std::string, Action>> sorted_action_map( action_map.begin(), action_map.end()); std::sort(sorted_action_map.begin(), sorted_action_map.end(), [](const auto& left, const auto& right) { return left.first.compare(right.first); }); int longest_action_length = 0; for (const Action& legal_action : legal_actions) { int action_length = std::to_string(legal_action).length(); if (action_length > longest_action_length) { longest_action_length = action_length; } } for (const auto& string_action_pair : sorted_action_map) { std::string action_string = string_action_pair.first; std::string action_int_string = std::to_string(string_action_pair.second); std::string action_padding( longest_action_length - action_int_string.length(), ' '); legal_action_strings.push_back(absl::StrCat( action_padding, action_int_string, ": ", action_string)); } PrintColumns(legal_action_strings); continue; } // Return the action if a valid string is given. if (action_map.find(action_string) != action_map.end()) { return action_map[action_string]; } // Return the action if a valid integer is given. try { action = std::stoi(action_string); } catch (const std::exception& e) { std::cout << "Could not parse the action: " << action_string << "\n"; continue; } for (Action legal_action : legal_actions) { if (action == legal_action) { return action; } } // The input was not valid. std::cout << "Illegal action selected: " << action_string << "\n"; } } } // namespace open_spiel <commit_msg>Flush output in human bot<commit_after>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "open_spiel/bots/human/human_bot.h" #include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <string> #include <unordered_map> #include <utility> namespace open_spiel { namespace { const int kMaxWidth = 80; const int kPadding = 2; void PrintColumns(const std::vector<std::string>& strings) { std::string padding_string(kPadding, ' '); int longest_string_length = 0; for (const std::string& string : strings) { if (string.length() > longest_string_length) { longest_string_length = string.length(); } } int max_columns = (kMaxWidth - 1) / (longest_string_length + 2 * kPadding); int rows = ceil((float) strings.size() / (float) max_columns); int columns = ceil((float) strings.size() / (float) rows); for (int row = 0; row < rows; ++row) { for (int column = 0; column < columns; ++column) { int index = row + column * rows; if (index < strings.size()) { std::cout << std::left << std::setw(longest_string_length + kPadding) << padding_string << strings[index]; } } std::cout << std::endl; } } } // namespace Action HumanBot::Step(const State& state) { std::vector<Action> legal_actions = state.LegalActions(state.CurrentPlayer()); if (legal_actions.empty()) { return kInvalidAction; } std::unordered_map<std::string, Action> action_map; for (Action legal_action : legal_actions) { action_map[state.ActionToString(legal_action)] = legal_action; } while (true) { Action action; std::string action_string = ""; std::cout << "Choose an action (empty to print legal actions): "; std::getline(std::cin, action_string); // Print the legal actions if no action is given. if (action_string.empty()) { std::cout << "Legal action(s):" << std::endl; std::vector<std::string> legal_action_strings; std::vector<std::pair<std::string, Action>> sorted_action_map( action_map.begin(), action_map.end()); std::sort(sorted_action_map.begin(), sorted_action_map.end(), [](const auto& left, const auto& right) { return left.first.compare(right.first); }); int longest_action_length = 0; for (const Action& legal_action : legal_actions) { int action_length = std::to_string(legal_action).length(); if (action_length > longest_action_length) { longest_action_length = action_length; } } for (const auto& string_action_pair : sorted_action_map) { std::string action_string = string_action_pair.first; std::string action_int_string = std::to_string(string_action_pair.second); std::string action_padding( longest_action_length - action_int_string.length(), ' '); legal_action_strings.push_back(absl::StrCat( action_padding, action_int_string, ": ", action_string)); } PrintColumns(legal_action_strings); continue; } // Return the action if a valid string is given. if (action_map.find(action_string) != action_map.end()) { return action_map[action_string]; } // Return the action if a valid integer is given. try { action = std::stoi(action_string); } catch (const std::exception& e) { std::cout << "Could not parse the action: " << action_string << std::endl; continue; } for (Action legal_action : legal_actions) { if (action == legal_action) { return action; } } // The input was not valid. std::cout << "Illegal action selected: " << action_string << std::endl; } } } // namespace open_spiel <|endoftext|>
<commit_before>//===- CXComment.cpp - libclang APIs for manipulating CXComments ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines all libclang APIs related to walking comment AST. // //===----------------------------------------------------------------------===// #include "clang-c/Index.h" #include "CXComment.h" #include "CXCursor.h" #include "CXString.h" #include "clang/AST/Decl.h" #include "clang/Index/CommentToXML.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/ErrorHandling.h" #include <climits> using namespace clang; using namespace clang::comments; using namespace clang::cxcomment; extern "C" { enum CXCommentKind clang_Comment_getKind(CXComment CXC) { const Comment *C = getASTNode(CXC); if (!C) return CXComment_Null; switch (C->getCommentKind()) { case Comment::NoCommentKind: return CXComment_Null; case Comment::TextCommentKind: return CXComment_Text; case Comment::InlineCommandCommentKind: return CXComment_InlineCommand; case Comment::HTMLStartTagCommentKind: return CXComment_HTMLStartTag; case Comment::HTMLEndTagCommentKind: return CXComment_HTMLEndTag; case Comment::ParagraphCommentKind: return CXComment_Paragraph; case Comment::BlockCommandCommentKind: return CXComment_BlockCommand; case Comment::ParamCommandCommentKind: return CXComment_ParamCommand; case Comment::TParamCommandCommentKind: return CXComment_TParamCommand; case Comment::VerbatimBlockCommentKind: return CXComment_VerbatimBlockCommand; case Comment::VerbatimBlockLineCommentKind: return CXComment_VerbatimBlockLine; case Comment::VerbatimLineCommentKind: return CXComment_VerbatimLine; case Comment::FullCommentKind: return CXComment_FullComment; } llvm_unreachable("unknown CommentKind"); } unsigned clang_Comment_getNumChildren(CXComment CXC) { const Comment *C = getASTNode(CXC); if (!C) return 0; return C->child_count(); } CXComment clang_Comment_getChild(CXComment CXC, unsigned ChildIdx) { const Comment *C = getASTNode(CXC); if (!C || ChildIdx >= C->child_count()) return createCXComment(NULL, NULL); return createCXComment(*(C->child_begin() + ChildIdx), CXC.TranslationUnit); } unsigned clang_Comment_isWhitespace(CXComment CXC) { const Comment *C = getASTNode(CXC); if (!C) return false; if (const TextComment *TC = dyn_cast<TextComment>(C)) return TC->isWhitespace(); if (const ParagraphComment *PC = dyn_cast<ParagraphComment>(C)) return PC->isWhitespace(); return false; } unsigned clang_InlineContentComment_hasTrailingNewline(CXComment CXC) { const InlineContentComment *ICC = getASTNodeAs<InlineContentComment>(CXC); if (!ICC) return false; return ICC->hasTrailingNewline(); } CXString clang_TextComment_getText(CXComment CXC) { const TextComment *TC = getASTNodeAs<TextComment>(CXC); if (!TC) return cxstring::createNull(); return cxstring::createRef(TC->getText()); } CXString clang_InlineCommandComment_getCommandName(CXComment CXC) { const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC); if (!ICC) return cxstring::createNull(); const CommandTraits &Traits = getCommandTraits(CXC); return cxstring::createRef(ICC->getCommandName(Traits)); } enum CXCommentInlineCommandRenderKind clang_InlineCommandComment_getRenderKind(CXComment CXC) { const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC); if (!ICC) return CXCommentInlineCommandRenderKind_Normal; switch (ICC->getRenderKind()) { case InlineCommandComment::RenderNormal: return CXCommentInlineCommandRenderKind_Normal; case InlineCommandComment::RenderBold: return CXCommentInlineCommandRenderKind_Bold; case InlineCommandComment::RenderMonospaced: return CXCommentInlineCommandRenderKind_Monospaced; case InlineCommandComment::RenderEmphasized: return CXCommentInlineCommandRenderKind_Emphasized; } llvm_unreachable("unknown InlineCommandComment::RenderKind"); } unsigned clang_InlineCommandComment_getNumArgs(CXComment CXC) { const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC); if (!ICC) return 0; return ICC->getNumArgs(); } CXString clang_InlineCommandComment_getArgText(CXComment CXC, unsigned ArgIdx) { const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC); if (!ICC || ArgIdx >= ICC->getNumArgs()) return cxstring::createNull(); return cxstring::createRef(ICC->getArgText(ArgIdx)); } CXString clang_HTMLTagComment_getTagName(CXComment CXC) { const HTMLTagComment *HTC = getASTNodeAs<HTMLTagComment>(CXC); if (!HTC) return cxstring::createNull(); return cxstring::createRef(HTC->getTagName()); } unsigned clang_HTMLStartTagComment_isSelfClosing(CXComment CXC) { const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC); if (!HST) return false; return HST->isSelfClosing(); } unsigned clang_HTMLStartTag_getNumAttrs(CXComment CXC) { const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC); if (!HST) return 0; return HST->getNumAttrs(); } CXString clang_HTMLStartTag_getAttrName(CXComment CXC, unsigned AttrIdx) { const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC); if (!HST || AttrIdx >= HST->getNumAttrs()) return cxstring::createNull(); return cxstring::createRef(HST->getAttr(AttrIdx).Name); } CXString clang_HTMLStartTag_getAttrValue(CXComment CXC, unsigned AttrIdx) { const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC); if (!HST || AttrIdx >= HST->getNumAttrs()) return cxstring::createNull(); return cxstring::createRef(HST->getAttr(AttrIdx).Value); } CXString clang_BlockCommandComment_getCommandName(CXComment CXC) { const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC); if (!BCC) return cxstring::createNull(); const CommandTraits &Traits = getCommandTraits(CXC); return cxstring::createRef(BCC->getCommandName(Traits)); } unsigned clang_BlockCommandComment_getNumArgs(CXComment CXC) { const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC); if (!BCC) return 0; return BCC->getNumArgs(); } CXString clang_BlockCommandComment_getArgText(CXComment CXC, unsigned ArgIdx) { const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC); if (!BCC || ArgIdx >= BCC->getNumArgs()) return cxstring::createNull(); return cxstring::createRef(BCC->getArgText(ArgIdx)); } CXComment clang_BlockCommandComment_getParagraph(CXComment CXC) { const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC); if (!BCC) return createCXComment(NULL, NULL); return createCXComment(BCC->getParagraph(), CXC.TranslationUnit); } CXString clang_ParamCommandComment_getParamName(CXComment CXC) { const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC); if (!PCC || !PCC->hasParamName()) return cxstring::createNull(); return cxstring::createRef(PCC->getParamNameAsWritten()); } unsigned clang_ParamCommandComment_isParamIndexValid(CXComment CXC) { const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC); if (!PCC) return false; return PCC->isParamIndexValid(); } unsigned clang_ParamCommandComment_getParamIndex(CXComment CXC) { const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC); if (!PCC || !PCC->isParamIndexValid() || PCC->isVarArgParam()) return ParamCommandComment::InvalidParamIndex; return PCC->getParamIndex(); } unsigned clang_ParamCommandComment_isDirectionExplicit(CXComment CXC) { const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC); if (!PCC) return false; return PCC->isDirectionExplicit(); } enum CXCommentParamPassDirection clang_ParamCommandComment_getDirection( CXComment CXC) { const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC); if (!PCC) return CXCommentParamPassDirection_In; switch (PCC->getDirection()) { case ParamCommandComment::In: return CXCommentParamPassDirection_In; case ParamCommandComment::Out: return CXCommentParamPassDirection_Out; case ParamCommandComment::InOut: return CXCommentParamPassDirection_InOut; } llvm_unreachable("unknown ParamCommandComment::PassDirection"); } CXString clang_TParamCommandComment_getParamName(CXComment CXC) { const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC); if (!TPCC || !TPCC->hasParamName()) return cxstring::createNull(); return cxstring::createRef(TPCC->getParamNameAsWritten()); } unsigned clang_TParamCommandComment_isParamPositionValid(CXComment CXC) { const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC); if (!TPCC) return false; return TPCC->isPositionValid(); } unsigned clang_TParamCommandComment_getDepth(CXComment CXC) { const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC); if (!TPCC || !TPCC->isPositionValid()) return 0; return TPCC->getDepth(); } unsigned clang_TParamCommandComment_getIndex(CXComment CXC, unsigned Depth) { const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC); if (!TPCC || !TPCC->isPositionValid() || Depth >= TPCC->getDepth()) return 0; return TPCC->getIndex(Depth); } CXString clang_VerbatimBlockLineComment_getText(CXComment CXC) { const VerbatimBlockLineComment *VBL = getASTNodeAs<VerbatimBlockLineComment>(CXC); if (!VBL) return cxstring::createNull(); return cxstring::createRef(VBL->getText()); } CXString clang_VerbatimLineComment_getText(CXComment CXC) { const VerbatimLineComment *VLC = getASTNodeAs<VerbatimLineComment>(CXC); if (!VLC) return cxstring::createNull(); return cxstring::createRef(VLC->getText()); } //===----------------------------------------------------------------------===// // Converting comments to XML. //===----------------------------------------------------------------------===// CXString clang_HTMLTagComment_getAsString(CXComment CXC) { const HTMLTagComment *HTC = getASTNodeAs<HTMLTagComment>(CXC); if (!HTC) return cxstring::createNull(); CXTranslationUnit TU = CXC.TranslationUnit; if (!TU->CommentToXML) TU->CommentToXML = new index::CommentToXMLConverter(); SmallString<128> Text; TU->CommentToXML->convertHTMLTagNodeToText( HTC, Text, cxtu::getASTUnit(TU)->getASTContext()); return cxstring::createDup(Text.str()); } CXString clang_FullComment_getAsHTML(CXComment CXC) { const FullComment *FC = getASTNodeAs<FullComment>(CXC); if (!FC) return cxstring::createNull(); CXTranslationUnit TU = CXC.TranslationUnit; if (!TU->CommentToXML) TU->CommentToXML = new index::CommentToXMLConverter(); SmallString<1024> HTML; TU->CommentToXML ->convertCommentToHTML(FC, HTML, cxtu::getASTUnit(TU)->getASTContext()); return cxstring::createDup(HTML.str()); } CXString clang_FullComment_getAsXML(CXComment CXC) { const FullComment *FC = getASTNodeAs<FullComment>(CXC); if (!FC) return cxstring::createNull(); CXTranslationUnit TU = CXC.TranslationUnit; if (!TU->CommentToXML) TU->CommentToXML = new index::CommentToXMLConverter(); SmallString<1024> XML; TU->CommentToXML ->convertCommentToXML(FC, XML, cxtu::getASTUnit(TU)->getASTContext()); return cxstring::createDup(XML.str()); } } // end extern "C" <commit_msg>Work around a bug in old gcc on the FreeBSD bot, which complains about ambiguity between index() function and clang::index namespace.<commit_after>//===- CXComment.cpp - libclang APIs for manipulating CXComments ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines all libclang APIs related to walking comment AST. // //===----------------------------------------------------------------------===// #include "clang-c/Index.h" #include "CXComment.h" #include "CXCursor.h" #include "CXString.h" #include "clang/AST/Decl.h" #include "clang/Index/CommentToXML.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/ErrorHandling.h" #include <climits> using namespace clang; using namespace clang::comments; using namespace clang::cxcomment; extern "C" { enum CXCommentKind clang_Comment_getKind(CXComment CXC) { const Comment *C = getASTNode(CXC); if (!C) return CXComment_Null; switch (C->getCommentKind()) { case Comment::NoCommentKind: return CXComment_Null; case Comment::TextCommentKind: return CXComment_Text; case Comment::InlineCommandCommentKind: return CXComment_InlineCommand; case Comment::HTMLStartTagCommentKind: return CXComment_HTMLStartTag; case Comment::HTMLEndTagCommentKind: return CXComment_HTMLEndTag; case Comment::ParagraphCommentKind: return CXComment_Paragraph; case Comment::BlockCommandCommentKind: return CXComment_BlockCommand; case Comment::ParamCommandCommentKind: return CXComment_ParamCommand; case Comment::TParamCommandCommentKind: return CXComment_TParamCommand; case Comment::VerbatimBlockCommentKind: return CXComment_VerbatimBlockCommand; case Comment::VerbatimBlockLineCommentKind: return CXComment_VerbatimBlockLine; case Comment::VerbatimLineCommentKind: return CXComment_VerbatimLine; case Comment::FullCommentKind: return CXComment_FullComment; } llvm_unreachable("unknown CommentKind"); } unsigned clang_Comment_getNumChildren(CXComment CXC) { const Comment *C = getASTNode(CXC); if (!C) return 0; return C->child_count(); } CXComment clang_Comment_getChild(CXComment CXC, unsigned ChildIdx) { const Comment *C = getASTNode(CXC); if (!C || ChildIdx >= C->child_count()) return createCXComment(NULL, NULL); return createCXComment(*(C->child_begin() + ChildIdx), CXC.TranslationUnit); } unsigned clang_Comment_isWhitespace(CXComment CXC) { const Comment *C = getASTNode(CXC); if (!C) return false; if (const TextComment *TC = dyn_cast<TextComment>(C)) return TC->isWhitespace(); if (const ParagraphComment *PC = dyn_cast<ParagraphComment>(C)) return PC->isWhitespace(); return false; } unsigned clang_InlineContentComment_hasTrailingNewline(CXComment CXC) { const InlineContentComment *ICC = getASTNodeAs<InlineContentComment>(CXC); if (!ICC) return false; return ICC->hasTrailingNewline(); } CXString clang_TextComment_getText(CXComment CXC) { const TextComment *TC = getASTNodeAs<TextComment>(CXC); if (!TC) return cxstring::createNull(); return cxstring::createRef(TC->getText()); } CXString clang_InlineCommandComment_getCommandName(CXComment CXC) { const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC); if (!ICC) return cxstring::createNull(); const CommandTraits &Traits = getCommandTraits(CXC); return cxstring::createRef(ICC->getCommandName(Traits)); } enum CXCommentInlineCommandRenderKind clang_InlineCommandComment_getRenderKind(CXComment CXC) { const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC); if (!ICC) return CXCommentInlineCommandRenderKind_Normal; switch (ICC->getRenderKind()) { case InlineCommandComment::RenderNormal: return CXCommentInlineCommandRenderKind_Normal; case InlineCommandComment::RenderBold: return CXCommentInlineCommandRenderKind_Bold; case InlineCommandComment::RenderMonospaced: return CXCommentInlineCommandRenderKind_Monospaced; case InlineCommandComment::RenderEmphasized: return CXCommentInlineCommandRenderKind_Emphasized; } llvm_unreachable("unknown InlineCommandComment::RenderKind"); } unsigned clang_InlineCommandComment_getNumArgs(CXComment CXC) { const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC); if (!ICC) return 0; return ICC->getNumArgs(); } CXString clang_InlineCommandComment_getArgText(CXComment CXC, unsigned ArgIdx) { const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC); if (!ICC || ArgIdx >= ICC->getNumArgs()) return cxstring::createNull(); return cxstring::createRef(ICC->getArgText(ArgIdx)); } CXString clang_HTMLTagComment_getTagName(CXComment CXC) { const HTMLTagComment *HTC = getASTNodeAs<HTMLTagComment>(CXC); if (!HTC) return cxstring::createNull(); return cxstring::createRef(HTC->getTagName()); } unsigned clang_HTMLStartTagComment_isSelfClosing(CXComment CXC) { const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC); if (!HST) return false; return HST->isSelfClosing(); } unsigned clang_HTMLStartTag_getNumAttrs(CXComment CXC) { const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC); if (!HST) return 0; return HST->getNumAttrs(); } CXString clang_HTMLStartTag_getAttrName(CXComment CXC, unsigned AttrIdx) { const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC); if (!HST || AttrIdx >= HST->getNumAttrs()) return cxstring::createNull(); return cxstring::createRef(HST->getAttr(AttrIdx).Name); } CXString clang_HTMLStartTag_getAttrValue(CXComment CXC, unsigned AttrIdx) { const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC); if (!HST || AttrIdx >= HST->getNumAttrs()) return cxstring::createNull(); return cxstring::createRef(HST->getAttr(AttrIdx).Value); } CXString clang_BlockCommandComment_getCommandName(CXComment CXC) { const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC); if (!BCC) return cxstring::createNull(); const CommandTraits &Traits = getCommandTraits(CXC); return cxstring::createRef(BCC->getCommandName(Traits)); } unsigned clang_BlockCommandComment_getNumArgs(CXComment CXC) { const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC); if (!BCC) return 0; return BCC->getNumArgs(); } CXString clang_BlockCommandComment_getArgText(CXComment CXC, unsigned ArgIdx) { const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC); if (!BCC || ArgIdx >= BCC->getNumArgs()) return cxstring::createNull(); return cxstring::createRef(BCC->getArgText(ArgIdx)); } CXComment clang_BlockCommandComment_getParagraph(CXComment CXC) { const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC); if (!BCC) return createCXComment(NULL, NULL); return createCXComment(BCC->getParagraph(), CXC.TranslationUnit); } CXString clang_ParamCommandComment_getParamName(CXComment CXC) { const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC); if (!PCC || !PCC->hasParamName()) return cxstring::createNull(); return cxstring::createRef(PCC->getParamNameAsWritten()); } unsigned clang_ParamCommandComment_isParamIndexValid(CXComment CXC) { const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC); if (!PCC) return false; return PCC->isParamIndexValid(); } unsigned clang_ParamCommandComment_getParamIndex(CXComment CXC) { const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC); if (!PCC || !PCC->isParamIndexValid() || PCC->isVarArgParam()) return ParamCommandComment::InvalidParamIndex; return PCC->getParamIndex(); } unsigned clang_ParamCommandComment_isDirectionExplicit(CXComment CXC) { const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC); if (!PCC) return false; return PCC->isDirectionExplicit(); } enum CXCommentParamPassDirection clang_ParamCommandComment_getDirection( CXComment CXC) { const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC); if (!PCC) return CXCommentParamPassDirection_In; switch (PCC->getDirection()) { case ParamCommandComment::In: return CXCommentParamPassDirection_In; case ParamCommandComment::Out: return CXCommentParamPassDirection_Out; case ParamCommandComment::InOut: return CXCommentParamPassDirection_InOut; } llvm_unreachable("unknown ParamCommandComment::PassDirection"); } CXString clang_TParamCommandComment_getParamName(CXComment CXC) { const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC); if (!TPCC || !TPCC->hasParamName()) return cxstring::createNull(); return cxstring::createRef(TPCC->getParamNameAsWritten()); } unsigned clang_TParamCommandComment_isParamPositionValid(CXComment CXC) { const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC); if (!TPCC) return false; return TPCC->isPositionValid(); } unsigned clang_TParamCommandComment_getDepth(CXComment CXC) { const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC); if (!TPCC || !TPCC->isPositionValid()) return 0; return TPCC->getDepth(); } unsigned clang_TParamCommandComment_getIndex(CXComment CXC, unsigned Depth) { const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC); if (!TPCC || !TPCC->isPositionValid() || Depth >= TPCC->getDepth()) return 0; return TPCC->getIndex(Depth); } CXString clang_VerbatimBlockLineComment_getText(CXComment CXC) { const VerbatimBlockLineComment *VBL = getASTNodeAs<VerbatimBlockLineComment>(CXC); if (!VBL) return cxstring::createNull(); return cxstring::createRef(VBL->getText()); } CXString clang_VerbatimLineComment_getText(CXComment CXC) { const VerbatimLineComment *VLC = getASTNodeAs<VerbatimLineComment>(CXC); if (!VLC) return cxstring::createNull(); return cxstring::createRef(VLC->getText()); } //===----------------------------------------------------------------------===// // Converting comments to XML. //===----------------------------------------------------------------------===// CXString clang_HTMLTagComment_getAsString(CXComment CXC) { const HTMLTagComment *HTC = getASTNodeAs<HTMLTagComment>(CXC); if (!HTC) return cxstring::createNull(); CXTranslationUnit TU = CXC.TranslationUnit; if (!TU->CommentToXML) TU->CommentToXML = new clang::index::CommentToXMLConverter(); SmallString<128> Text; TU->CommentToXML->convertHTMLTagNodeToText( HTC, Text, cxtu::getASTUnit(TU)->getASTContext()); return cxstring::createDup(Text.str()); } CXString clang_FullComment_getAsHTML(CXComment CXC) { const FullComment *FC = getASTNodeAs<FullComment>(CXC); if (!FC) return cxstring::createNull(); CXTranslationUnit TU = CXC.TranslationUnit; if (!TU->CommentToXML) TU->CommentToXML = new clang::index::CommentToXMLConverter(); SmallString<1024> HTML; TU->CommentToXML ->convertCommentToHTML(FC, HTML, cxtu::getASTUnit(TU)->getASTContext()); return cxstring::createDup(HTML.str()); } CXString clang_FullComment_getAsXML(CXComment CXC) { const FullComment *FC = getASTNodeAs<FullComment>(CXC); if (!FC) return cxstring::createNull(); CXTranslationUnit TU = CXC.TranslationUnit; if (!TU->CommentToXML) TU->CommentToXML = new clang::index::CommentToXMLConverter(); SmallString<1024> XML; TU->CommentToXML ->convertCommentToXML(FC, XML, cxtu::getASTUnit(TU)->getASTContext()); return cxstring::createDup(XML.str()); } } // end extern "C" <|endoftext|>
<commit_before>/// @file /// @author uentity /// @date 22.09.2017 /// @brief BS tree Python bindings /// @copyright /// This Source Code Form is subject to the terms of the Mozilla Public License, /// v. 2.0. If a copy of the MPL was not distributed with this file, /// You can obtain one at https://mozilla.org/MPL/2.0/ #include <bs/bs.h> #include <bs/link.h> #include <bs/node.h> #include <boost/uuid/uuid_io.hpp> #include <boost/uuid/string_generator.hpp> #include <string> #include <iostream> NAMESPACE_BEGIN(blue_sky) NAMESPACE_BEGIN(python) using namespace tree; namespace { template<typename Link = link> class py_link : public Link { public: using Link::Link; sp_link clone() const override { PYBIND11_OVERLOAD_PURE(sp_link, Link, clone, ); } sp_obj data() const override { PYBIND11_OVERLOAD_PURE(sp_obj, Link, data, ); } std::string type_id() const override { PYBIND11_OVERLOAD_PURE(std::string, Link, type_id, ); } std::string oid() const override { PYBIND11_OVERLOAD_PURE(std::string, Link, oid, ); } std::string obj_type_id() const override { PYBIND11_OVERLOAD_PURE(std::string, Link, obj_type_id, ); } sp_node data_node() const override { PYBIND11_OVERLOAD_PURE(sp_node, Link, data_node, ); } }; static boost::uuids::string_generator uuid_from_str; void print_link(const sp_link& l, int level = 0) { static const auto dumplnk = [](const sp_link& l_) { std::cout << l_->name() << " -> (" << l_->obj_type_id() << ", " << l_->oid() << ")" << std::endl; }; const std::string loffs(level*2, ' '); // print link itself std::cout << loffs; dumplnk(l); if(auto n = l->data_node()) { // print leafs for(const auto &leaf : *n) print_link(leaf, level+1); } } } void py_bind_tree(py::module& m) { py::class_<inode>(m, "inode") .def(py::init<std::string, std::string>()) .def_readonly("owner", &inode::owner) .def_readonly("group", &inode::group) .def_property_readonly("suid", [](const inode& i) { return i.suid; }) .def_property_readonly("sgid", [](const inode& i) { return i.sgid; }) .def_property_readonly("sticky", [](const inode& i) { return i.sticky; }) .def_property_readonly("u", [](const inode& i) { return i.u; }) .def_property_readonly("g", [](const inode& i) { return i.g; }) .def_property_readonly("o", [](const inode& i) { return i.o; }) ; py::class_<link, py_link<>, std::shared_ptr<link>> link_pyface(m, "link"); link_pyface .def(py::init<std::string>()) .def("clone", &link::clone) .def("data", &link::data) .def("type_id", &link::type_id) .def("oid", &link::oid) .def("obj_type_id", &link::obj_type_id) .def("data_node", &link::data_node) .def_property_readonly("id", [](const link& L) { return boost::uuids::to_string(L.id()); }) .def_property_readonly("name", &link::name) .def_property("inode", py::overload_cast<>(&link::get_inode, py::const_), py::overload_cast<>(&link::get_inode) ) .def_property_readonly("owner", &link::owner) ; py::class_<hard_link, link, py_link<hard_link>, std::shared_ptr<hard_link>>(m, "hard_link") .def(py::init<std::string, sp_obj>()) ; py::class_<weak_link, link, py_link<weak_link>, std::shared_ptr<weak_link>>(m, "weak_link") .def(py::init<std::string, const sp_obj&>()) ; // forward define node py::class_<node, objbase, std::shared_ptr<node>> node_pyface(m, "node"); // export node's Key enum py::enum_<node::Key>(node_pyface, "Key") .value("ID", node::Key::ID) .value("OID", node::Key::OID) .value("Name", node::Key::Name) .value("Type", node::Key::Type) ; // export node's insert policy py::enum_<node::InsertPolicy>(node_pyface, "InsertPolicy") .value("AllowDupNames", node::InsertPolicy::AllowDupNames) .value("DenyDupNames", node::InsertPolicy::DenyDupNames) .value("RenameDup", node::InsertPolicy::RenameDup) .value("DenyDupOID", node::InsertPolicy::DenyDupOID) .value("Merge", node::InsertPolicy::Merge) .export_values(); ; // fill node with methods node_pyface BSPY_EXPORT_DEF(node) .def(py::init<>()) .def("__len__", &node::size) .def("__iter__", [](const node& N) { return py::make_iterator(N.begin(), N.end()); }, py::keep_alive<0, 1>() ) // check by link name or object instance (object's ID) .def("__contains__", [](const node& N, py::object key) { if(PyString_Check(key.ptr())) return N.find(py::cast<std::string>(key)) != N.end<>(); return N.find_oid(py::cast<sp_obj>(key)->id()) != N.end<>(); }) // check by link ID .def("contains_lid", [](const node& N, const std::string& lid) { return N.find(uuid_from_str(lid)) != N.end<>(); }, "LID", "Check if node contains link with given ID") // check by object ID .def("contains_oid", [](const node& N, const std::string& oid) { return N.find_oid(oid) != N.end<>(); }, "OID", "Check if node contains object with given ID") // check by object type .def("contains_type", [](const node& N, const std::string& type_id) { return N.equal_type(type_id).first != N.end<node::Key::Type>(); }, "obj_type_id", "Check if node contains objects with given type") // get item by int index .def("__getitem__", [](const node& N, const long idx) { // support for Pythonish indexing from both ends if(std::size_t(std::abs(idx)) > N.size()) throw py::key_error("Index out of bounds"); auto pos = idx < 0 ? N.end() : N.begin(); std::advance(pos, idx); if(pos == N.end()) throw py::key_error("Index out of bounds"); return *pos; }, py::return_value_policy::reference_internal, "link_idx"_a) // search by link name .def("__getitem__", [](const node& N, const std::string& link_name) { auto r = N.find(link_name); if(r != N.end<>()) return *r; throw py::key_error("Node doesn't contain link with name '" + link_name + "'"); }, py::return_value_policy::reference_internal, "link_name"_a) // search by object instance .def("__getitem__", [](const node& N, const sp_obj& obj) { auto r = N.find(obj->id()); if(r != N.end<>()) return *r; throw py::key_error("Node doesn't contain object with ID = " + obj->id()); }, py::return_value_policy::reference_internal, "object"_a) // search by object ID .def("find_oid", [](const node& N, const std::string& oid) { auto r = N.find_oid(oid); if(r != N.end<>()) return *r; throw py::key_error("Node doesn't contain object with ID - " + oid); }, py::return_value_policy::reference_internal, "OID"_a, "Find item by object ID") // search by link ID .def("find_lid", [](const node& N, const std::string& lid) { auto r = N.find(uuid_from_str(lid)); if(r != N.end<>()) return *r; throw py::key_error("Node doesn't contain link with ID - " + lid); }, py::return_value_policy::reference_internal, "LID"_a, "Find item by object link ID") // deep search by link name or object instance (OID) .def("deep_search", [](const node& N, py::object key) { if(PyString_Check(key.ptr())) return N.deep_search(py::cast<std::string>(key)); return N.deep_search_oid(py::cast<sp_obj>(key)->id()); }, "key"_a, "Deep search for link with given name or by object instance (OID)") .def("deep_search_lid", [](const node& N, const std::string& lid) { return N.deep_search(uuid_from_str(lid)); }, "LID"_a, "Deep search for link with given ID") // deep search by object ID .def("deep_search_oid", [](const node& N, const std::string& oid) { return N.deep_search_oid(oid); }, "OID"_a, "Deep search for object with given ID") .def("equal_range", [](const node& N, const std::string& link_name) { auto r = N.equal_range(link_name); return py::make_iterator(r.first, r.second); }, py::keep_alive<0, 1>(), "link_name"_a) .def("equal_range_oid", [](const node& N, const std::string& oid) { auto r = N.equal_range_oid(oid); return py::make_iterator(r.first, r.second); }, py::keep_alive<0, 1>(), "OID"_a) .def("equal_type", [](const node& N, const std::string& type_id) { auto r = N.equal_type(type_id); return py::make_iterator(r.first, r.second); }, py::keep_alive<0, 1>(), "obj_type_id"_a) // insert given link .def("insert", [](node& N, sp_link l, uint pol = node::AllowDupNames) { return N.insert(std::move(l)).second; }, "link"_a, "pol"_a = node::AllowDupNames, "Insert given link") // insert hard link to given object .def("insert", [](node& N, std::string name, sp_obj obj, uint pol = node::AllowDupNames) { return N.insert(std::move(name), std::move(obj), pol).second; }, "name"_a, "obj"_a, "pol"_a = node::AllowDupNames, "Insert hard link to given object") // erase by given index .def("__delitem__", [](node& N, const long idx) { // support for Pythonish indexing from both ends if(std::size_t(std::abs(idx)) > N.size()) throw py::key_error("Index out of bounds"); N.erase(idx < 0 ? N.size() + idx : idx); }) // erase by given link name or object instance (object's ID) .def("__delitem__", [](node& N, py::object key) { if(PyString_Check(key.ptr())) N.erase(py::cast<std::string>(key)); N.erase_oid(py::cast<sp_obj>(key)->id()); }) .def("erase", (void (node::*)(const std::string&))&node::erase, "link_name"_a, "Erase links with given name") .def("erase_oid", &node::erase_oid, "obj"_a, "Erase links to given object") .def("erase_lid", [](node& N, const std::string& key) { N.erase(uuid_from_str(key)); }, "lid"_a, "Erase link with given ID") .def("erase_type", [](node& N, const std::string& type_id) { N.erase_type(type_id); }, "obj_type_id"_a, "Erase all links pointing to objects with given type") // misc functions .def_property_readonly("size", &node::size) .def_property_readonly("empty", &node::empty) .def("clear", &node::clear, "Clears all node contents") .def("keys", [](const node& N, node::Key ktype = node::Key::Name) { if(ktype == node::Key::ID) { // convert UUIDs to string representation auto keys = N.keys<>(); std::vector<std::string> res; res.reserve(keys.size()); for(const auto& k : keys) res.emplace_back(boost::uuids::to_string(k)); return res; } else { switch(ktype) { default: case node::Key::Name : return N.keys<node::Key::Name>(); case node::Key::OID : return N.keys<node::Key::OID>(); case node::Key::Type : return N.keys<node::Key::Type>(); }; } }, "key_type"_a = node::Key::Name) ; m.def("print_link", [](const sp_link& l) { print_link(l, 0); }); m.def("print_link", [](const sp_node& n, std::string name = "/") { print_link(std::make_shared<tree::hard_link>(name, n), 0); }, "node"_a, "root_name"_a = "/"); } NAMESPACE_END(python) NAMESPACE_END(blue_sky) <commit_msg>node.python: make link's ID a 'default' key for misc operations, update and fix bindings<commit_after>/// @file /// @author uentity /// @date 22.09.2017 /// @brief BS tree Python bindings /// @copyright /// This Source Code Form is subject to the terms of the Mozilla Public License, /// v. 2.0. If a copy of the MPL was not distributed with this file, /// You can obtain one at https://mozilla.org/MPL/2.0/ #include <bs/bs.h> #include <bs/link.h> #include <bs/node.h> #include <boost/uuid/uuid_io.hpp> #include <boost/uuid/string_generator.hpp> #include <string> #include <iostream> NAMESPACE_BEGIN(blue_sky) NAMESPACE_BEGIN(python) using namespace tree; namespace { template<typename Link = link> class py_link : public Link { public: using Link::Link; sp_link clone() const override { PYBIND11_OVERLOAD_PURE(sp_link, Link, clone, ); } sp_obj data() const override { PYBIND11_OVERLOAD_PURE(sp_obj, Link, data, ); } std::string type_id() const override { PYBIND11_OVERLOAD_PURE(std::string, Link, type_id, ); } std::string oid() const override { PYBIND11_OVERLOAD_PURE(std::string, Link, oid, ); } std::string obj_type_id() const override { PYBIND11_OVERLOAD_PURE(std::string, Link, obj_type_id, ); } sp_node data_node() const override { PYBIND11_OVERLOAD_PURE(sp_node, Link, data_node, ); } }; static boost::uuids::string_generator uuid_from_str; void print_link(const sp_link& l, int level = 0) { static const auto dumplnk = [](const sp_link& l_) { std::cout << l_->name() << " -> (" << l_->obj_type_id() << ", " << l_->oid() << ")" << std::endl; }; const std::string loffs(level*2, ' '); // print link itself std::cout << loffs; dumplnk(l); if(auto n = l->data_node()) { // print leafs for(const auto &leaf : *n) print_link(leaf, level+1); } } } void py_bind_tree(py::module& m) { py::class_<inode>(m, "inode") .def(py::init<std::string, std::string>()) .def_readonly("owner", &inode::owner) .def_readonly("group", &inode::group) .def_property_readonly("suid", [](const inode& i) { return i.suid; }) .def_property_readonly("sgid", [](const inode& i) { return i.sgid; }) .def_property_readonly("sticky", [](const inode& i) { return i.sticky; }) .def_property_readonly("u", [](const inode& i) { return i.u; }) .def_property_readonly("g", [](const inode& i) { return i.g; }) .def_property_readonly("o", [](const inode& i) { return i.o; }) ; py::class_<link, py_link<>, std::shared_ptr<link>> link_pyface(m, "link"); link_pyface .def(py::init<std::string>()) .def("clone", &link::clone) .def("data", &link::data) .def("type_id", &link::type_id) .def("oid", &link::oid) .def("obj_type_id", &link::obj_type_id) .def("data_node", &link::data_node) .def_property_readonly("id", [](const link& L) { return boost::uuids::to_string(L.id()); }) .def_property_readonly("name", &link::name) .def_property("inode", py::overload_cast<>(&link::get_inode, py::const_), py::overload_cast<>(&link::get_inode) ) .def_property_readonly("owner", &link::owner) ; py::class_<hard_link, link, py_link<hard_link>, std::shared_ptr<hard_link>>(m, "hard_link") .def(py::init<std::string, sp_obj>()) ; py::class_<weak_link, link, py_link<weak_link>, std::shared_ptr<weak_link>>(m, "weak_link") .def(py::init<std::string, const sp_obj&>()) ; // forward define node py::class_<node, objbase, std::shared_ptr<node>> node_pyface(m, "node"); // export node's Key enum py::enum_<node::Key>(node_pyface, "Key") .value("ID", node::Key::ID) .value("OID", node::Key::OID) .value("Name", node::Key::Name) .value("Type", node::Key::Type) .value("AnyOrder", node::Key::AnyOrder) ; // export node's insert policy py::enum_<node::InsertPolicy>(node_pyface, "InsertPolicy") .value("AllowDupNames", node::InsertPolicy::AllowDupNames) .value("DenyDupNames", node::InsertPolicy::DenyDupNames) .value("RenameDup", node::InsertPolicy::RenameDup) .value("DenyDupOID", node::InsertPolicy::DenyDupOID) .value("Merge", node::InsertPolicy::Merge) .export_values(); ; // fill node with methods node_pyface BSPY_EXPORT_DEF(node) .def(py::init<>()) .def("__len__", &node::size) .def("__iter__", [](const node& N) { return py::make_iterator(N.begin(), N.end()); }, py::keep_alive<0, 1>() ) // check by link ID or object object's ID .def("__contains__", [](const node& N, py::object key) { if(PyString_Check(key.ptr())) return N.find(uuid_from_str(py::cast<std::string>(key))) != N.end<>(); return N.find_oid(py::cast<sp_obj>(key)->id()) != N.end<>(); }) // check by link name .def("contains_name", [](const node& N, const std::string& lname) { return N.find(lname) != N.end<>(); }, "link_name", "Check if node contains link with given name") // check by object ID .def("contains_oid", [](const node& N, const std::string& oid) { return N.find_oid(oid) != N.end<>(); }, "oid", "Check if node contains link to object with given ID") // check by object type .def("contains_type", [](const node& N, const std::string& type_id) { return N.equal_type(type_id).first != N.end<node::Key::Type>(); }, "obj_type_id", "Check if node contain links to objects with given type") // get item by int index .def("__getitem__", [](const node& N, const long idx) { // support for Pythonish indexing from both ends if(std::size_t(std::abs(idx)) > N.size()) throw py::key_error("Index out of bounds"); auto pos = idx < 0 ? N.end() : N.begin(); std::advance(pos, idx); if(pos == N.end()) throw py::key_error("Index out of bounds"); return *pos; }, "link_idx"_a) // search by link name .def("__getitem__", [](const node& N, const std::string& lid) { auto r = N.find(uuid_from_str(lid)); if(r != N.end<>()) return *r; throw py::key_error("Node doesn't contain link with ID " + lid); }, "link_name"_a) // search by object instance .def("__getitem__", [](const node& N, const sp_obj& obj) { auto r = N.find(obj->id()); if(r != N.end<>()) return *r; throw py::key_error("Node doesn't contain links to object with ID = " + obj->id()); }, "object"_a) // search by object ID .def("find_oid", [](const node& N, const std::string& oid) { auto r = N.find_oid(oid); if(r != N.end<>()) return *r; throw py::key_error("Node doesn't contain links to object with ID - " + oid); }, "oid"_a, "Find link by object ID") // search by link name .def("find_name", [](const node& N, const std::string& lname) { auto r = N.find(lname); if(r != N.end<>()) return *r; throw py::key_error("Node doesn't contain link with name '" + lname + "'"); }, "link_name"_a, "Find link by name") // obtain index in custom order from link .def("index", [](const node& N, const std::string& lid) { return N.index(uuid_from_str(lid)); }, "lid"_a, "Find index of link with given ID") .def("index", [](const node& N, const sp_link& l) { return N.index(l->id()); }, "link"_a, "Find index of given link") // deep search by link ID or object ID .def("deep_search", [](const node& N, py::object key) { if(PyString_Check(key.ptr())) return N.deep_search(uuid_from_str(py::cast<std::string>(key))); return N.deep_search_oid(py::cast<sp_obj>(key)->id()); }, "key"_a, "Deep search for link with given ID or by object instance (OID)") .def("deep_search_name", [](const node& N, const std::string& lname) { return N.deep_search(lname); }, "link_name"_a, "Deep search for link with given name") // deep search by object ID .def("deep_search_oid", [](const node& N, const std::string& oid) { return N.deep_search_oid(oid); }, "oid"_a, "Deep search for link to object with given ID") .def("equal_range", [](const node& N, const std::string& link_name) { auto r = N.equal_range(link_name); return py::make_iterator(r.first, r.second); }, py::keep_alive<0, 1>(), "link_name"_a) .def("equal_range_oid", [](const node& N, const std::string& oid) { auto r = N.equal_range_oid(oid); return py::make_iterator(r.first, r.second); }, py::keep_alive<0, 1>(), "OID"_a) .def("equal_type", [](const node& N, const std::string& type_id) { auto r = N.equal_type(type_id); return py::make_iterator(r.first, r.second); }, py::keep_alive<0, 1>(), "obj_type_id"_a) // insert given link .def("insert", [](node& N, sp_link l, uint pol = node::AllowDupNames) { return N.insert(std::move(l)).second; }, "link"_a, "pol"_a = node::AllowDupNames, "Insert given link") // insert hard link to given object .def("insert", [](node& N, std::string name, sp_obj obj, uint pol = node::AllowDupNames) { return N.insert(std::move(name), std::move(obj), pol).second; }, "name"_a, "obj"_a, "pol"_a = node::AllowDupNames, "Insert hard link to given object") // erase by given index .def("__delitem__", [](node& N, const long idx) { // support for Pythonish indexing from both ends if(std::size_t(std::abs(idx)) > N.size()) throw py::key_error("Index out of bounds"); N.erase(idx < 0 ? N.size() + idx : idx); }) // erase by given link ID or object instance (object's ID) .def("__delitem__", [](node& N, py::object key) { if(PyString_Check(key.ptr())) N.erase(uuid_from_str(py::cast<std::string>(key))); else N.erase_oid(py::cast<sp_obj>(key)->id()); }) .def("erase", [](node& N, const std::string& key) { N.erase(uuid_from_str(key)); }, "lid"_a, "Erase link with given ID") .def("erase_name", (void (node::*)(const std::string&))&node::erase, "link_name"_a, "Erase links with given name") .def("erase_oid", &node::erase_oid, "obj"_a, "Erase links to given object") .def("erase_type", [](node& N, const std::string& type_id) { N.erase_type(type_id); }, "obj_type_id"_a, "Erase all links pointing to objects with given type") // misc functions .def_property_readonly("size", &node::size) .def_property_readonly("empty", &node::empty) .def("clear", &node::clear, "Clears all node contents") .def("keys", [](const node& N, node::Key ktype = node::Key::Name) { if(ktype == node::Key::ID) { // convert UUIDs to string representation auto keys = N.keys<>(); std::vector<std::string> res; res.reserve(keys.size()); for(const auto& k : keys) res.emplace_back(boost::uuids::to_string(k)); return res; } else { switch(ktype) { default: case node::Key::Name : return N.keys<node::Key::Name>(); case node::Key::OID : return N.keys<node::Key::OID>(); case node::Key::Type : return N.keys<node::Key::Type>(); }; } }, "key_type"_a = node::Key::Name) ; m.def("print_link", [](const sp_link& l) { print_link(l, 0); }); m.def("print_link", [](const sp_node& n, std::string name = "/") { print_link(std::make_shared<tree::hard_link>(name, n), 0); }, "node"_a, "root_name"_a = "/"); } NAMESPACE_END(python) NAMESPACE_END(blue_sky) <|endoftext|>
<commit_before>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQMathMatrixWidget.cpp,v $ // $Revision: 1.1 $ // $Name: $ // $Author: ssahle $ // $Date: 2007/02/09 16:49:41 $ // End CVS Header // Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. //#include <qpushbutton.h> #include <qlayout.h> #include <qlineedit.h> #include <qlabel.h> #include <qtable.h> #include "copasi.h" #include "CQMathMatrixWidget.h" #include "qtUtilities.h" //#include "sensitivities/CSensTask.h" //#include "sensitivities/CSensProblem.h" #include "CopasiDataModel/CCopasiDataModel.h" //#include "utilities/CCopasiVector.h" #include "model/CModel.h" #include <qtabwidget.h> /** * Constructs a CQMathMatrixWidget which is a child of 'parent', with the * name 'name' and widget flags set to 'f'. */ CQMathMatrixWidget::CQMathMatrixWidget(QWidget* parent, const char* name, WFlags fl) : CopasiWidget(parent, name, fl) { if (!name) setName("CQMathMatrixWidget"); setCaption("CQMathMatrixWidget"); mWidgetLayout = new QGridLayout(this, 1, 1, 11, 6, "CQMathMatrixWidgetLayout"); // ********** Label ************** mLabelTitle = new QLabel(this, "SensLabel"); mLabelTitle->setText("Sensitivities"); mLabelTitle->setAlignment(int(QLabel::AlignVCenter | QLabel::AlignLeft)); mLabelTitle->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); mWidgetLayout->addWidget(mLabelTitle, 0, 0); // tab widget mpTab = new QTabWidget(this, "TabWidget"); mWidgetLayout->addMultiCellWidget(mpTab, 1, 2, 0, 2); // 1 mArrayWidget1 = new CQArrayAnnotationsWidget(mpTab, "ArrayWidget1"); //mArrayWidget1->setColorCoding(new CColorScale1()); //CColorScaleAverage * tcs = new CColorScaleAverage(); CColorScaleBiLog * tcs = new CColorScaleBiLog(); mArrayWidget1->setColorCoding(tcs); //tcs->setMinMax(-1,1); //tcs->setSymmetric(true); //tcs->setFactor(3.0); mArrayWidget1->setColorScalingAutomatic(true); mpTab->addTab(mArrayWidget1, "Stoichiometry Matrix"); // 2 mArrayWidget2 = new CQArrayAnnotationsWidget(mpTab, "ArrayWidget2"); //mArrayWidge2->setColorCoding(new CColorScale1()); tcs = new CColorScaleBiLog(); mArrayWidget2->setColorCoding(tcs); //tcs2->setMinMax(-1,1); //tcs2->setSymmetric(true); //tcs2->setFactor(3.0); mArrayWidget2->setColorScalingAutomatic(true); mpTab->addTab(mArrayWidget2, "Reduced Stoichiometry Matrix"); // 3 mArrayWidget3 = new CQArrayAnnotationsWidget(mpTab, "ArrayWidget3"); //mArrayWidge2->setColorCoding(new CColorScale1()); tcs = new CColorScaleBiLog(); mArrayWidget3->setColorCoding(tcs); //tcs2->setMinMax(-1,1); //tcs2->setSymmetric(true); //tcs2->setFactor(3.0); mArrayWidget3->setColorScalingAutomatic(true); mpTab->addTab(mArrayWidget3, "Link Matrix"); } /* * Destroys the object and frees any allocated resources */ CQMathMatrixWidget::~CQMathMatrixWidget() {} void CQMathMatrixWidget::loadMatrices() { // CSensTask * pTask = // dynamic_cast<CSensTask*>((*CCopasiDataModel::Global->getTaskList())["Sensitivities"]); // if (!pTask) // { // clearArrays(); // return; //} // // CSensProblem * pProblem = dynamic_cast< CSensProblem * >(pTask->getProblem()); // if (!pProblem) // { // clearArrays(); // return; //} const CModel* pModel = CCopasiDataModel::Global->getModel(); //mpResult = pProblem->getResultAnnotated(); //mpScaledResult = pProblem->getScaledResultAnnotated(); const CArrayAnnotation * tmp; tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Stoichiometry(ann)"))); mArrayWidget1->setArrayAnnotation(tmp); tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Reduced stoichiometry(ann)"))); mArrayWidget2->setArrayAnnotation(tmp); tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Link matrix(ann)"))); mArrayWidget3->setArrayAnnotation(tmp); } void CQMathMatrixWidget::clearArrays() { mArrayWidget1->setArrayAnnotation(NULL); mArrayWidget2->setArrayAnnotation(NULL); mArrayWidget3->setArrayAnnotation(NULL); } //************************************* bool CQMathMatrixWidget::update(ListViews::ObjectType C_UNUSED(objectType), ListViews::Action C_UNUSED(action), const std::string & C_UNUSED(key)) { /* if (this->isShown()) return loadFromBackend(); else return true;*/ return true; } bool CQMathMatrixWidget::leave() { return true; } bool CQMathMatrixWidget::enter(const std::string & C_UNUSED(key)) { //clear the widget if the pointer to the result has changed /* CSensTask * pTask = dynamic_cast<CSensTask*>((*CCopasiDataModel::Global->getTaskList())["Sensitivities"]); if (!pTask) { clearArrays(); return false; } CSensProblem * pProblem = dynamic_cast< CSensProblem * >(pTask->getProblem()); if (!pProblem) { clearArrays(); return false; } if (mpResult != pProblem->getResultAnnotated()) { clearArrays(); return false; } */ loadMatrices(); return true; } <commit_msg>improvement in color scaling<commit_after>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQMathMatrixWidget.cpp,v $ // $Revision: 1.2 $ // $Name: $ // $Author: ssahle $ // $Date: 2007/02/12 00:04:23 $ // End CVS Header // Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. //#include <qpushbutton.h> #include <qlayout.h> #include <qlineedit.h> #include <qlabel.h> #include <qtable.h> #include "copasi.h" #include "CQMathMatrixWidget.h" #include "qtUtilities.h" //#include "sensitivities/CSensTask.h" //#include "sensitivities/CSensProblem.h" #include "CopasiDataModel/CCopasiDataModel.h" //#include "utilities/CCopasiVector.h" #include "model/CModel.h" #include <qtabwidget.h> /** * Constructs a CQMathMatrixWidget which is a child of 'parent', with the * name 'name' and widget flags set to 'f'. */ CQMathMatrixWidget::CQMathMatrixWidget(QWidget* parent, const char* name, WFlags fl) : CopasiWidget(parent, name, fl) { if (!name) setName("CQMathMatrixWidget"); setCaption("CQMathMatrixWidget"); mWidgetLayout = new QGridLayout(this, 1, 1, 11, 6, "CQMathMatrixWidgetLayout"); // ********** Label ************** mLabelTitle = new QLabel(this, "SensLabel"); mLabelTitle->setText("Sensitivities"); mLabelTitle->setAlignment(int(QLabel::AlignVCenter | QLabel::AlignLeft)); mLabelTitle->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); mWidgetLayout->addWidget(mLabelTitle, 0, 0); // tab widget mpTab = new QTabWidget(this, "TabWidget"); mWidgetLayout->addMultiCellWidget(mpTab, 1, 2, 0, 2); // 1 mArrayWidget1 = new CQArrayAnnotationsWidget(mpTab, "ArrayWidget1"); //mArrayWidget1->setColorCoding(new CColorScale1()); //CColorScaleAverage * tcs = new CColorScaleAverage(); CColorScaleSimple * tcs = new CColorScaleSimple(); mArrayWidget1->setColorCoding(tcs); tcs->setMinMax(-1.5, 1.5); //tcs->setMinMax(-1,1); //tcs->setSymmetric(true); //tcs->setFactor(3.0); mArrayWidget1->setColorScalingAutomatic(false); mpTab->addTab(mArrayWidget1, "Stoichiometry Matrix"); // 2 mArrayWidget2 = new CQArrayAnnotationsWidget(mpTab, "ArrayWidget2"); //mArrayWidge2->setColorCoding(new CColorScale1()); tcs = new CColorScaleSimple(); mArrayWidget2->setColorCoding(tcs); tcs->setMinMax(-1.5, 1.5); //tcs2->setMinMax(-1,1); //tcs2->setSymmetric(true); //tcs2->setFactor(3.0); mArrayWidget2->setColorScalingAutomatic(false); mpTab->addTab(mArrayWidget2, "Reduced Stoichiometry Matrix"); // 3 mArrayWidget3 = new CQArrayAnnotationsWidget(mpTab, "ArrayWidget3"); //mArrayWidge2->setColorCoding(new CColorScale1()); tcs = new CColorScaleSimple(); mArrayWidget3->setColorCoding(tcs); tcs->setMinMax(-1.5, 1.5); //tcs2->setMinMax(-1,1); //tcs2->setSymmetric(true); //tcs2->setFactor(3.0); mArrayWidget3->setColorScalingAutomatic(false); mpTab->addTab(mArrayWidget3, "Link Matrix"); } /* * Destroys the object and frees any allocated resources */ CQMathMatrixWidget::~CQMathMatrixWidget() {} void CQMathMatrixWidget::loadMatrices() { // CSensTask * pTask = // dynamic_cast<CSensTask*>((*CCopasiDataModel::Global->getTaskList())["Sensitivities"]); // if (!pTask) // { // clearArrays(); // return; //} // // CSensProblem * pProblem = dynamic_cast< CSensProblem * >(pTask->getProblem()); // if (!pProblem) // { // clearArrays(); // return; //} const CModel* pModel = CCopasiDataModel::Global->getModel(); //mpResult = pProblem->getResultAnnotated(); //mpScaledResult = pProblem->getScaledResultAnnotated(); const CArrayAnnotation * tmp; tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Stoichiometry(ann)"))); mArrayWidget1->setArrayAnnotation(tmp); tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Reduced stoichiometry(ann)"))); mArrayWidget2->setArrayAnnotation(tmp); tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Link matrix(ann)"))); mArrayWidget3->setArrayAnnotation(tmp); } void CQMathMatrixWidget::clearArrays() { mArrayWidget1->setArrayAnnotation(NULL); mArrayWidget2->setArrayAnnotation(NULL); mArrayWidget3->setArrayAnnotation(NULL); } //************************************* bool CQMathMatrixWidget::update(ListViews::ObjectType C_UNUSED(objectType), ListViews::Action C_UNUSED(action), const std::string & C_UNUSED(key)) { /* if (this->isShown()) return loadFromBackend(); else return true;*/ return true; } bool CQMathMatrixWidget::leave() { return true; } bool CQMathMatrixWidget::enter(const std::string & C_UNUSED(key)) { //clear the widget if the pointer to the result has changed /* CSensTask * pTask = dynamic_cast<CSensTask*>((*CCopasiDataModel::Global->getTaskList())["Sensitivities"]); if (!pTask) { clearArrays(); return false; } CSensProblem * pProblem = dynamic_cast< CSensProblem * >(pTask->getProblem()); if (!pProblem) { clearArrays(); return false; } if (mpResult != pProblem->getResultAnnotated()) { clearArrays(); return false; } */ loadMatrices(); return true; } <|endoftext|>
<commit_before>// Copyright (c)2008-2011, Preferred Infrastructure 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 Preferred Infrastructure nor the names of other // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <gtest/gtest.h> #include "./intern.h" #include <climits> #include <fstream> #include <string> #include <algorithm> #include "./serialization.h" using namespace std; using namespace jubatus::util::data; using namespace jubatus::util::data::serialization; static const char* tmp_file="./tmp"; TEST(intern_test, string) { srandom(time(NULL)); intern<string> im; // make a random string set vector<string> ss; for (int i=0;i<1000;++i) { string s; for (int j=0;j<32;++j) s+=random()%26+'a'; ss.push_back(s); } sort(ss.begin(),ss.end()); ss.erase(unique(ss.begin(),ss.end()),ss.end()); for (size_t i=0;i<ss.size();++i) EXPECT_EQ(-1,im.key2id(ss[i],false)); for (size_t i=0;i<ss.size();++i) EXPECT_EQ(int(i),im.key2id(ss[i],true)); for (size_t i=0;i<ss.size();++i) EXPECT_EQ(ss[i],im.id2key(i)); } TEST(intern_test, count) { intern<string> im; string hoge="hoge"; EXPECT_FALSE(im.exist_key(hoge)); EXPECT_FALSE(im.exist_id(0)); im.key2id(hoge); EXPECT_TRUE(im.exist_key(hoge)); EXPECT_TRUE(im.exist_id(0)); } TEST(intern_test, serialize) { srandom(time(NULL)); // make a random string set vector<string> ss; for (int i=0;i<1000;++i) { string s; for (int j=0;j<32;++j) s+=random()%26+'a'; ss.push_back(s); } sort(ss.begin(),ss.end()); ss.erase(unique(ss.begin(),ss.end()),ss.end()); { // serialize intern<string> im; for (size_t i=0;i<ss.size();++i) im.key2id(ss[i]); ofstream ofs(tmp_file); binary_oarchive oa(ofs); oa<<im; } { // deserialize intern<string> im; ifstream ifs(tmp_file); binary_iarchive ia(ifs); ia>>im; EXPECT_EQ(ss.size(),im.size()); for (size_t i=0;i<ss.size();++i) EXPECT_EQ(int(i),im.key2id(ss[i],false)); for (size_t i=0;i<ss.size();++i) EXPECT_EQ(ss[i],im.id2key(i)); } } <commit_msg>Remove fstream from intern_test; stringstream is used instead<commit_after>// Copyright (c)2008-2011, Preferred Infrastructure 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 Preferred Infrastructure nor the names of other // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <gtest/gtest.h> #include "./intern.h" #include <climits> #include <sstream> #include <string> #include <algorithm> #include "./serialization.h" using namespace std; using namespace jubatus::util::data; using namespace jubatus::util::data::serialization; TEST(intern_test, string) { srandom(time(NULL)); intern<string> im; // make a random string set vector<string> ss; for (int i=0;i<1000;++i) { string s; for (int j=0;j<32;++j) s+=random()%26+'a'; ss.push_back(s); } sort(ss.begin(),ss.end()); ss.erase(unique(ss.begin(),ss.end()),ss.end()); for (size_t i=0;i<ss.size();++i) EXPECT_EQ(-1,im.key2id(ss[i],false)); for (size_t i=0;i<ss.size();++i) EXPECT_EQ(int(i),im.key2id(ss[i],true)); for (size_t i=0;i<ss.size();++i) EXPECT_EQ(ss[i],im.id2key(i)); } TEST(intern_test, count) { intern<string> im; string hoge="hoge"; EXPECT_FALSE(im.exist_key(hoge)); EXPECT_FALSE(im.exist_id(0)); im.key2id(hoge); EXPECT_TRUE(im.exist_key(hoge)); EXPECT_TRUE(im.exist_id(0)); } TEST(intern_test, serialize) { srandom(time(NULL)); // make a random string set vector<string> ss; for (int i=0;i<1000;++i) { string s; for (int j=0;j<32;++j) s+=random()%26+'a'; ss.push_back(s); } sort(ss.begin(),ss.end()); ss.erase(unique(ss.begin(),ss.end()),ss.end()); stringstream stream; { // serialize intern<string> im; for (size_t i=0;i<ss.size();++i) im.key2id(ss[i]); binary_oarchive oa(stream); oa<<im; } { // deserialize intern<string> im; binary_iarchive ia(stream); ia>>im; EXPECT_EQ(ss.size(),im.size()); for (size_t i=0;i<ss.size();++i) EXPECT_EQ(int(i),im.key2id(ss[i],false)); for (size_t i=0;i<ss.size();++i) EXPECT_EQ(ss[i],im.id2key(i)); } } <|endoftext|>
<commit_before>/* ============================================================================== Copyright (c) 2016, Daniel Walz All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ============================================================================== juce_ak_layout.cpp Created: 21 Feb 2016 9:14:52pm ============================================================================== */ #include "juce_ak_layout.h" Layout::Layout(Orientation o, juce::Component* owner) : orientation (o), isUpdating (false), isCummulatingStretch (false), owningComponent (owner) { } Layout::~Layout() { } void Layout::setOrientation (const Orientation o) { orientation = o; } LayoutItem* Layout::addComponent (juce::Component* c, int idx) { LayoutItem* item = itemsList.insert (idx, new LayoutItem (c)); updateGeometry(); return item; } void Layout::removeComponent (juce::Component* c) { for (int i=0; i<itemsList.size(); ++i) { LayoutItem* item = itemsList.getUnchecked (i); if (item->isComponentItem() && item->getComponent() == c) { itemsList.remove (i); } } updateGeometry(); } LayoutItem* Layout::addLabeledComponent (juce::Component* c, Orientation o, juce::Label** labelPtr, int idx) { // if the layout is not owned by a component, the label will not show up, // because addAndMakeVisible can not be called. jassert (owningComponent); juce::Label* label = new juce::Label(); if (owningComponent) { owningComponent->addAndMakeVisible (label); } float h = label->getFont().getHeight(); Layout* sub = addSubLayout (o, idx, owningComponent); sub->addComponent (label)->setFixedHeight (h); LabeledLayoutItem* labeledItem = new LabeledLayoutItem (c, label); sub->addRawItem (labeledItem); if (labelPtr) { *labelPtr = label; } updateGeometry(); return labeledItem; } LayoutItem* Layout::addLabeledComponent (juce::Component* component, juce::StringRef text, Orientation o, int idx) { LayoutItem* item = addLabeledComponent(component, o, nullptr, idx); if (juce::Label* label = item->getLabel()) { label->setText (text, juce::dontSendNotification); label->setJustificationType (juce::Justification::centred); } return item; } Layout* Layout::addSubLayout (Orientation o, int idx, juce::Component* owner) { SubLayout* sub = new SubLayout (o, owningComponent); itemsList.insert (idx, sub); updateGeometry(); return sub; } LayoutItem* Layout::addSSpacer (float sx, float sy, int idx) { LayoutItem* item = itemsList.insert (idx, new LayoutItem (LayoutItem::SpacerItem)); updateGeometry(); return item; } LayoutItem* Layout::getLayoutItem (juce::Component* c) { for (int i=0; i<itemsList.size(); ++i) { LayoutItem* item = itemsList.getUnchecked (i); if (item->isComponentItem() && item->getComponent() == c) { return item; } else if (item->isSubLayout()) { // search also sub layouts recoursively if (LayoutItem* subItem = getLayoutItem (c)) { return subItem; } } } return nullptr; } void Layout::addRawItem (LayoutItem* item, int idx) { itemsList.insert (idx, item); } void Layout::updateGeometry () { if (owningComponent) { updateGeometry (owningComponent->getLocalBounds()); } } void Layout::updateGeometry (juce::Rectangle<int> bounds) { // recursion check if (isUpdating) { return; } isUpdating = true; // remove items of deleted or invalid components for (int i=0; i<itemsList.size(); ++i) { LayoutItem* item = itemsList.getUnchecked (i); if (!item->isValid()) { itemsList.remove (i); } } itemsBounds.resize (itemsList.size ()); float cummulatedX, cummulatedY; getCummulatedStretch (cummulatedX, cummulatedY); float availableWidth = bounds.getWidth(); float availableHeight = bounds.getHeight(); if (orientation == TopDown || orientation == BottomUp) { for (int i=0; i<itemsList.size(); ++i) { LayoutItem* item = itemsList.getUnchecked (i); float sx, sy; item->getStretch (sx, sy); float h = bounds.getHeight() * sy / cummulatedY; juce::Rectangle<int> childBounds (bounds.getX(), bounds.getY(), bounds.getWidth(), h); bool changedWidth, changedHeight; item->constrainBounds (childBounds, changedWidth, changedHeight); itemsBounds.set (i, childBounds); if (changedHeight) { itemBoundsFinal.set (i, true); availableHeight -= childBounds.getHeight(); cummulatedY -= sy; } else { itemBoundsFinal.set (i, false); } if (changedWidth) { availableWidth = std::max (bounds.getWidth(), childBounds.getWidth()); } } float y = bounds.getY(); if (orientation == BottomUp) { y = bounds.getY() + bounds.getHeight(); } for (int i=0; i<itemsList.size(); ++i) { LayoutItem* item = itemsList.getUnchecked (i); if (itemBoundsFinal.getUnchecked (i)) { float h = itemsBounds.getReference (i).getHeight(); if (orientation == BottomUp) { y -= h; } juce::Rectangle<int> childBounds (bounds.getX(), y, availableWidth, h); if (item->isSubLayout()) { if (Layout* sub = dynamic_cast<Layout*>(item)) { sub->updateGeometry (item->getPaddedBounds (childBounds)); } } if (juce::Component* c = item->getComponent()) { c->setBounds (item->getPaddedBounds (childBounds)); } if (orientation == TopDown) { y += h; } } else { float sx, sy; item->getStretch (sx, sy); float h = availableHeight * sy /cummulatedY; if (orientation == BottomUp) { y -= h; } juce::Rectangle<int> childBounds (bounds.getX(), y, availableWidth, h ); if (item->isSubLayout()) { if (Layout* sub = dynamic_cast<Layout*>(item)) { sub->updateGeometry (item->getPaddedBounds (childBounds)); } } if (juce::Component* c = item->getComponent()) { c->setBounds (item->getPaddedBounds (childBounds)); } if (orientation == TopDown) { y += h; } } } } else if (orientation == LeftToRight || orientation == RightToLeft) { for (int i=0; i<itemsList.size(); ++i) { LayoutItem* item = itemsList.getUnchecked (i); float sx, sy; item->getStretch (sx, sy); float w = bounds.getWidth() * sx / cummulatedX; juce::Rectangle<int> childBounds (bounds.getX(), bounds.getY(), w, bounds.getHeight()); bool changedWidth, changedHeight; item->constrainBounds (childBounds, changedWidth, changedHeight); itemsBounds.set (i, childBounds); if (changedWidth) { itemBoundsFinal.set (i, true); availableWidth -= childBounds.getWidth(); cummulatedX -= sx; } else { itemBoundsFinal.set (i, false); } if (changedHeight) { availableHeight = std::max (bounds.getHeight(), childBounds.getHeight()); } } float x = bounds.getX(); if (orientation == RightToLeft) { x = bounds.getX() + bounds.getWidth(); } for (int i=0; i<itemsList.size(); ++i) { LayoutItem* item = itemsList.getUnchecked (i); if (itemBoundsFinal.getUnchecked (i)) { float w = itemsBounds.getReference (i).getWidth(); if (orientation == RightToLeft) { x -= w; } juce::Rectangle<int> childBounds (x, bounds.getY(), w, availableHeight); if (item->isSubLayout()) { if (Layout* sub = dynamic_cast<Layout*>(item)) { sub->updateGeometry (item->getPaddedBounds (childBounds)); } } if (juce::Component* c = item->getComponent()) { c->setBounds (item->getPaddedBounds (childBounds)); } if (orientation == LeftToRight) { x += w; } } else { float sx, sy; item->getStretch (sx, sy); float w = availableWidth * sx /cummulatedX; if (orientation == RightToLeft) { x -= w; } juce::Rectangle<int> childBounds (x, bounds.getY(), w, availableHeight); if (item->isSubLayout()) { if (Layout* sub = dynamic_cast<Layout*>(item)) { sub->updateGeometry (item->getPaddedBounds (childBounds)); } } if (juce::Component* c = item->getComponent()) { c->setBounds (item->getPaddedBounds (childBounds)); } if (orientation == LeftToRight) { x += w; } } } } isUpdating = false; } void Layout::getCummulatedStretch (float& w, float& h) const { w = 0.0; h = 0.0; if (isCummulatingStretch) { return; } isCummulatingStretch = true; for (int i=0; i<itemsList.size(); ++i) { LayoutItem* item = itemsList.getUnchecked (i); float x, y; item->getStretch (x, y); if (orientation == LeftToRight || orientation == RightToLeft) { w += x; h = std::max (h, y); } else if (orientation == TopDown || orientation == BottomUp) { w = std::max (w, x); h += y; } else { w += x; h += y; } ++item; } isCummulatingStretch = false; } // ============================================================================= SubLayout::SubLayout (Orientation o, juce::Component* owner) : Layout (o, owner), LayoutItem (LayoutItem::SubLayout) { } void SubLayout::getStretch (float& w, float& h) const { w = 0.0; h = 0.0; getCummulatedStretch (w, h); } <commit_msg>Fixed missing stretch for spacer<commit_after>/* ============================================================================== Copyright (c) 2016, Daniel Walz All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ============================================================================== juce_ak_layout.cpp Created: 21 Feb 2016 9:14:52pm ============================================================================== */ #include "juce_ak_layout.h" Layout::Layout(Orientation o, juce::Component* owner) : orientation (o), isUpdating (false), isCummulatingStretch (false), owningComponent (owner) { } Layout::~Layout() { } void Layout::setOrientation (const Orientation o) { orientation = o; } LayoutItem* Layout::addComponent (juce::Component* c, int idx) { LayoutItem* item = itemsList.insert (idx, new LayoutItem (c)); updateGeometry(); return item; } void Layout::removeComponent (juce::Component* c) { for (int i=0; i<itemsList.size(); ++i) { LayoutItem* item = itemsList.getUnchecked (i); if (item->isComponentItem() && item->getComponent() == c) { itemsList.remove (i); } } updateGeometry(); } LayoutItem* Layout::addLabeledComponent (juce::Component* c, Orientation o, juce::Label** labelPtr, int idx) { // if the layout is not owned by a component, the label will not show up, // because addAndMakeVisible can not be called. jassert (owningComponent); juce::Label* label = new juce::Label(); if (owningComponent) { owningComponent->addAndMakeVisible (label); } float h = label->getFont().getHeight(); Layout* sub = addSubLayout (o, idx, owningComponent); sub->addComponent (label)->setFixedHeight (h); LabeledLayoutItem* labeledItem = new LabeledLayoutItem (c, label); sub->addRawItem (labeledItem); if (labelPtr) { *labelPtr = label; } updateGeometry(); return labeledItem; } LayoutItem* Layout::addLabeledComponent (juce::Component* component, juce::StringRef text, Orientation o, int idx) { LayoutItem* item = addLabeledComponent(component, o, nullptr, idx); if (juce::Label* label = item->getLabel()) { label->setText (text, juce::dontSendNotification); label->setJustificationType (juce::Justification::centred); } return item; } Layout* Layout::addSubLayout (Orientation o, int idx, juce::Component* owner) { SubLayout* sub = new SubLayout (o, owningComponent); itemsList.insert (idx, sub); updateGeometry(); return sub; } LayoutItem* Layout::addSSpacer (float sx, float sy, int idx) { LayoutItem* item = itemsList.insert (idx, new LayoutItem (LayoutItem::SpacerItem)); item->setStretch (sx, sy); updateGeometry(); return item; } LayoutItem* Layout::getLayoutItem (juce::Component* c) { for (int i=0; i<itemsList.size(); ++i) { LayoutItem* item = itemsList.getUnchecked (i); if (item->isComponentItem() && item->getComponent() == c) { return item; } else if (item->isSubLayout()) { // search also sub layouts recoursively if (LayoutItem* subItem = getLayoutItem (c)) { return subItem; } } } return nullptr; } void Layout::addRawItem (LayoutItem* item, int idx) { itemsList.insert (idx, item); } void Layout::updateGeometry () { if (owningComponent) { updateGeometry (owningComponent->getLocalBounds()); } } void Layout::updateGeometry (juce::Rectangle<int> bounds) { // recursion check if (isUpdating) { return; } isUpdating = true; // remove items of deleted or invalid components for (int i=0; i<itemsList.size(); ++i) { LayoutItem* item = itemsList.getUnchecked (i); if (!item->isValid()) { itemsList.remove (i); } } itemsBounds.resize (itemsList.size ()); float cummulatedX, cummulatedY; getCummulatedStretch (cummulatedX, cummulatedY); float availableWidth = bounds.getWidth(); float availableHeight = bounds.getHeight(); if (orientation == TopDown || orientation == BottomUp) { for (int i=0; i<itemsList.size(); ++i) { LayoutItem* item = itemsList.getUnchecked (i); float sx, sy; item->getStretch (sx, sy); float h = bounds.getHeight() * sy / cummulatedY; juce::Rectangle<int> childBounds (bounds.getX(), bounds.getY(), bounds.getWidth(), h); bool changedWidth, changedHeight; item->constrainBounds (childBounds, changedWidth, changedHeight); itemsBounds.set (i, childBounds); if (changedHeight) { itemBoundsFinal.set (i, true); availableHeight -= childBounds.getHeight(); cummulatedY -= sy; } else { itemBoundsFinal.set (i, false); } if (changedWidth) { availableWidth = std::max (bounds.getWidth(), childBounds.getWidth()); } } float y = bounds.getY(); if (orientation == BottomUp) { y = bounds.getY() + bounds.getHeight(); } for (int i=0; i<itemsList.size(); ++i) { LayoutItem* item = itemsList.getUnchecked (i); if (itemBoundsFinal.getUnchecked (i)) { float h = itemsBounds.getReference (i).getHeight(); if (orientation == BottomUp) { y -= h; } juce::Rectangle<int> childBounds (bounds.getX(), y, availableWidth, h); if (item->isSubLayout()) { if (Layout* sub = dynamic_cast<Layout*>(item)) { sub->updateGeometry (item->getPaddedBounds (childBounds)); } } if (juce::Component* c = item->getComponent()) { c->setBounds (item->getPaddedBounds (childBounds)); } if (orientation == TopDown) { y += h; } } else { float sx, sy; item->getStretch (sx, sy); float h = availableHeight * sy /cummulatedY; if (orientation == BottomUp) { y -= h; } juce::Rectangle<int> childBounds (bounds.getX(), y, availableWidth, h ); if (item->isSubLayout()) { if (Layout* sub = dynamic_cast<Layout*>(item)) { sub->updateGeometry (item->getPaddedBounds (childBounds)); } } if (juce::Component* c = item->getComponent()) { c->setBounds (item->getPaddedBounds (childBounds)); } if (orientation == TopDown) { y += h; } } } } else if (orientation == LeftToRight || orientation == RightToLeft) { for (int i=0; i<itemsList.size(); ++i) { LayoutItem* item = itemsList.getUnchecked (i); float sx, sy; item->getStretch (sx, sy); float w = bounds.getWidth() * sx / cummulatedX; juce::Rectangle<int> childBounds (bounds.getX(), bounds.getY(), w, bounds.getHeight()); bool changedWidth, changedHeight; item->constrainBounds (childBounds, changedWidth, changedHeight); itemsBounds.set (i, childBounds); if (changedWidth) { itemBoundsFinal.set (i, true); availableWidth -= childBounds.getWidth(); cummulatedX -= sx; } else { itemBoundsFinal.set (i, false); } if (changedHeight) { availableHeight = std::max (bounds.getHeight(), childBounds.getHeight()); } } float x = bounds.getX(); if (orientation == RightToLeft) { x = bounds.getX() + bounds.getWidth(); } for (int i=0; i<itemsList.size(); ++i) { LayoutItem* item = itemsList.getUnchecked (i); if (itemBoundsFinal.getUnchecked (i)) { float w = itemsBounds.getReference (i).getWidth(); if (orientation == RightToLeft) { x -= w; } juce::Rectangle<int> childBounds (x, bounds.getY(), w, availableHeight); if (item->isSubLayout()) { if (Layout* sub = dynamic_cast<Layout*>(item)) { sub->updateGeometry (item->getPaddedBounds (childBounds)); } } if (juce::Component* c = item->getComponent()) { c->setBounds (item->getPaddedBounds (childBounds)); } if (orientation == LeftToRight) { x += w; } } else { float sx, sy; item->getStretch (sx, sy); float w = availableWidth * sx /cummulatedX; if (orientation == RightToLeft) { x -= w; } juce::Rectangle<int> childBounds (x, bounds.getY(), w, availableHeight); if (item->isSubLayout()) { if (Layout* sub = dynamic_cast<Layout*>(item)) { sub->updateGeometry (item->getPaddedBounds (childBounds)); } } if (juce::Component* c = item->getComponent()) { c->setBounds (item->getPaddedBounds (childBounds)); } if (orientation == LeftToRight) { x += w; } } } } isUpdating = false; } void Layout::getCummulatedStretch (float& w, float& h) const { w = 0.0; h = 0.0; if (isCummulatingStretch) { return; } isCummulatingStretch = true; for (int i=0; i<itemsList.size(); ++i) { LayoutItem* item = itemsList.getUnchecked (i); float x, y; item->getStretch (x, y); if (orientation == LeftToRight || orientation == RightToLeft) { w += x; h = std::max (h, y); } else if (orientation == TopDown || orientation == BottomUp) { w = std::max (w, x); h += y; } else { w += x; h += y; } ++item; } isCummulatingStretch = false; } // ============================================================================= SubLayout::SubLayout (Orientation o, juce::Component* owner) : Layout (o, owner), LayoutItem (LayoutItem::SubLayout) { } void SubLayout::getStretch (float& w, float& h) const { w = 0.0; h = 0.0; getCummulatedStretch (w, h); } <|endoftext|>
<commit_before>/******************************************************************************\ * File: menu.cpp * Purpose: Implementation of wxExMenu class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <map> #include <wx/extension/menu.h> #include <wx/extension/art.h> #include <wx/extension/lexers.h> #include <wx/extension/tool.h> #include <wx/extension/util.h> // for wxExEllipsed #include <wx/extension/vcs.h> #if wxUSE_GUI wxExMenu::wxExMenu(long style) : m_Style(style) , m_MenuVCSFilled(false) { } wxExMenu::wxExMenu(const wxExMenu& menu) : m_Style(menu.m_Style) , m_MenuVCSFilled(menu.m_MenuVCSFilled) { } wxMenuItem* wxExMenu::Append(int id) { // Using wxMenu::Append(id) // also appends the stock item, // but does not add the bitmap. wxMenuItem* item = new wxMenuItem(this, id); const wxExStockArt art(id); if (art.GetBitmap().IsOk()) { item->SetBitmap(art.GetBitmap( wxART_MENU, wxArtProvider::GetSizeHint(wxART_MENU, true))); } return wxMenu::Append(item); } wxMenuItem* wxExMenu::Append( int id, const wxString& name, const wxString& helptext, const wxArtID& artid) { wxMenuItem* item = new wxMenuItem(this, id, name, helptext); if (!artid.empty()) { const wxBitmap bitmap = wxArtProvider::GetBitmap( artid, wxART_MENU, wxArtProvider::GetSizeHint(wxART_MENU, true)); if (bitmap.IsOk()) { item->SetBitmap(bitmap); } } return wxMenu::Append(item); } void wxExMenu::AppendBars() { AppendCheckItem(ID_VIEW_MENUBAR, _("&Menubar")); AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar")); AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar")); AppendCheckItem(ID_VIEW_FINDBAR, _("&Findbar")); } void wxExMenu::AppendEdit(bool add_invert) { if (!(m_Style & MENU_IS_READ_ONLY) && (m_Style & MENU_IS_SELECTED)) { Append(wxID_CUT); } if (m_Style & MENU_IS_SELECTED) { Append(wxID_COPY); } if (!(m_Style & MENU_IS_READ_ONLY) && (m_Style & MENU_CAN_PASTE)) { Append(wxID_PASTE); } if (!(m_Style & MENU_IS_SELECTED) && !(m_Style & MENU_IS_EMPTY)) { Append(wxID_SELECTALL); } else { if (add_invert && !(m_Style & MENU_IS_EMPTY)) { Append(ID_EDIT_SELECT_NONE, _("&Deselect All")); } } if (m_Style & MENU_ALLOW_CLEAR) { Append(wxID_CLEAR); } if (add_invert && !(m_Style & MENU_IS_EMPTY)) { Append(ID_EDIT_SELECT_INVERT, _("&Invert")); } if (!(m_Style & MENU_IS_READ_ONLY) && (m_Style & MENU_IS_SELECTED) && !(m_Style & MENU_IS_EMPTY)) { Append(wxID_DELETE); } } void wxExMenu::AppendPrint() { Append(wxID_PRINT_SETUP, wxExEllipsed(_("Page &Setup"))); Append(wxID_PREVIEW); Append(wxID_PRINT); } void wxExMenu::AppendSeparator() { if ( GetMenuItemCount() == 0 || FindItemByPosition(GetMenuItemCount() - 1)->IsSeparator()) { return; } wxMenu::AppendSeparator(); } void wxExMenu::AppendSubMenu( wxMenu *submenu, const wxString& text, const wxString& help, int itemid) { if (itemid == wxID_ANY) { wxMenu::AppendSubMenu(submenu, text, help); } else { // This one is deprecated, but is necessary if // we have an explicit itemid. wxMenu::Append(itemid, text, submenu, help); } } bool wxExMenu::AppendTools(int itemid) { if (wxExLexers::Get()->Count() == 0) { return false; } wxExMenu* menuTool = new wxExMenu(*this); for ( auto it = wxExTool::Get()->GetToolInfo().begin(); it != wxExTool::Get()->GetToolInfo().end(); ++it) { if (!it->second.GetText().empty()) { const bool vcs_type = wxExTool(it->first).IsRCSType(); if ((vcs_type && !wxExVCS::Get()->Use()) || !vcs_type) { menuTool->Append( it->first, it->second.GetText(), it->second.GetHelpText()); } } } AppendSubMenu(menuTool, _("&Tools"), wxEmptyString, itemid); return true; } // This is the VCS submenu, as present on a popup. // Therefore it is build when clicking, and does not // need to be destroyed an old one. void wxExMenu::AppendVCS(const wxExFileName& filename) { if (!wxExVCS::Get()->Use()) { return; } const int vcs_offset_id = ID_EDIT_VCS_LOWEST + 1; wxExMenu* vcsmenu = new wxExMenu; wxExVCS::Get()->BuildMenu(vcs_offset_id, vcsmenu, filename); if (vcsmenu->GetMenuItemCount() > 0) { AppendSubMenu(vcsmenu, "&VCS"); } } // This is the general VCS menu, it is in the main menu, // and because contents depends on actual VCS used, // it is rebuild after change of VCS system. void wxExMenu::BuildVCS(bool fill) { if (m_MenuVCSFilled) { wxMenuItem* item; while ((item = FindItem(wxID_SEPARATOR)) != NULL) { Destroy(item); } for (int id = ID_VCS_LOWEST + 1; id < ID_VCS_HIGHEST; id++) { // When using only Destroy, and the item does not exist, // an assert happens. if (FindItem(id) != NULL) { Destroy(id); } } } if (fill) { const int vcs_offset_id = ID_VCS_LOWEST + 1; wxExVCS::Get()->BuildMenu(vcs_offset_id, this, wxExFileName(), false); // no popup } m_MenuVCSFilled = fill; } #endif // wxUSE_GUI <commit_msg>fixed return value<commit_after>/******************************************************************************\ * File: menu.cpp * Purpose: Implementation of wxExMenu class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <map> #include <wx/extension/menu.h> #include <wx/extension/art.h> #include <wx/extension/lexers.h> #include <wx/extension/tool.h> #include <wx/extension/util.h> // for wxExEllipsed #include <wx/extension/vcs.h> #if wxUSE_GUI wxExMenu::wxExMenu(long style) : m_Style(style) , m_MenuVCSFilled(false) { } wxExMenu::wxExMenu(const wxExMenu& menu) : m_Style(menu.m_Style) , m_MenuVCSFilled(menu.m_MenuVCSFilled) { } wxMenuItem* wxExMenu::Append(int id) { // Using wxMenu::Append(id) // also appends the stock item, // but does not add the bitmap. wxMenuItem* item = new wxMenuItem(this, id); const wxExStockArt art(id); if (art.GetBitmap().IsOk()) { item->SetBitmap(art.GetBitmap( wxART_MENU, wxArtProvider::GetSizeHint(wxART_MENU, true))); } return wxMenu::Append(item); } wxMenuItem* wxExMenu::Append( int id, const wxString& name, const wxString& helptext, const wxArtID& artid) { wxMenuItem* item = new wxMenuItem(this, id, name, helptext); if (!artid.empty()) { const wxBitmap bitmap = wxArtProvider::GetBitmap( artid, wxART_MENU, wxArtProvider::GetSizeHint(wxART_MENU, true)); if (bitmap.IsOk()) { item->SetBitmap(bitmap); } } return wxMenu::Append(item); } void wxExMenu::AppendBars() { AppendCheckItem(ID_VIEW_MENUBAR, _("&Menubar")); AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar")); AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar")); AppendCheckItem(ID_VIEW_FINDBAR, _("&Findbar")); } void wxExMenu::AppendEdit(bool add_invert) { if (!(m_Style & MENU_IS_READ_ONLY) && (m_Style & MENU_IS_SELECTED)) { Append(wxID_CUT); } if (m_Style & MENU_IS_SELECTED) { Append(wxID_COPY); } if (!(m_Style & MENU_IS_READ_ONLY) && (m_Style & MENU_CAN_PASTE)) { Append(wxID_PASTE); } if (!(m_Style & MENU_IS_SELECTED) && !(m_Style & MENU_IS_EMPTY)) { Append(wxID_SELECTALL); } else { if (add_invert && !(m_Style & MENU_IS_EMPTY)) { Append(ID_EDIT_SELECT_NONE, _("&Deselect All")); } } if (m_Style & MENU_ALLOW_CLEAR) { Append(wxID_CLEAR); } if (add_invert && !(m_Style & MENU_IS_EMPTY)) { Append(ID_EDIT_SELECT_INVERT, _("&Invert")); } if (!(m_Style & MENU_IS_READ_ONLY) && (m_Style & MENU_IS_SELECTED) && !(m_Style & MENU_IS_EMPTY)) { Append(wxID_DELETE); } } void wxExMenu::AppendPrint() { Append(wxID_PRINT_SETUP, wxExEllipsed(_("Page &Setup"))); Append(wxID_PREVIEW); Append(wxID_PRINT); } void wxExMenu::AppendSeparator() { if ( GetMenuItemCount() == 0 || FindItemByPosition(GetMenuItemCount() - 1)->IsSeparator()) { return; } wxMenu::AppendSeparator(); } void wxExMenu::AppendSubMenu( wxMenu *submenu, const wxString& text, const wxString& help, int itemid) { if (itemid == wxID_ANY) { wxMenu::AppendSubMenu(submenu, text, help); } else { // This one is deprecated, but is necessary if // we have an explicit itemid. wxMenu::Append(itemid, text, submenu, help); } } bool wxExMenu::AppendTools(int itemid) { if (wxExLexers::Get()->Count() == 0) { return false; } wxExMenu* menuTool = new wxExMenu(*this); for ( auto it = wxExTool::Get()->GetToolInfo().begin(); it != wxExTool::Get()->GetToolInfo().end(); ++it) { if (!it->second.GetText().empty()) { const bool vcs_type = wxExTool(it->first).IsRCSType(); if ((vcs_type && !wxExVCS::Get()->Use()) || !vcs_type) { menuTool->Append( it->first, it->second.GetText(), it->second.GetHelpText()); } } } AppendSubMenu(menuTool, _("&Tools"), wxEmptyString, itemid); return true; } // This is the VCS submenu, as present on a popup. // Therefore it is build when clicking, and does not // need to be destroyed an old one. void wxExMenu::AppendVCS(const wxExFileName& filename) { if (!wxExVCS::Get()->Use()) { return; } const int vcs_offset_id = ID_EDIT_VCS_LOWEST + 1; wxExMenu* vcsmenu = new wxExMenu; wxExVCS::Get()->BuildMenu(vcs_offset_id, vcsmenu, filename); if (vcsmenu->GetMenuItemCount() > 0) { AppendSubMenu(vcsmenu, "&VCS"); } } // This is the general VCS menu, it is in the main menu, // and because contents depends on actual VCS used, // it is rebuild after change of VCS system. void wxExMenu::BuildVCS(bool fill) { if (m_MenuVCSFilled) { wxMenuItem* item; while ((item = FindItem(wxID_SEPARATOR)) != NULL) { Destroy(item); } for (int id = ID_VCS_LOWEST + 1; id < ID_VCS_HIGHEST; id++) { // When using only Destroy, and the item does not exist, // an assert happens. if (FindItem(id) != NULL) { Destroy(id); } } } if (fill) { const int vcs_offset_id = ID_VCS_LOWEST + 1; wxExVCS::Get()->BuildMenu( vcs_offset_id, this, wxExFileName(), false); // no popup if (GetMenuItemCount() == 0) { fill = false; } } m_MenuVCSFilled = fill; } #endif // wxUSE_GUI <|endoftext|>
<commit_before>#ifndef MODEL_HPP #define MODEL_HPP #include <vector> #include <iostream> #include <utility> #include <cmath> #include "../inc/quat.hpp" #include "../inc/dual.hpp" namespace Model { template<typename R = float> std::ostream& operator<<(std::ostream& lhs, quat<R> const& rhs) { quat<R> singlet = rhs.w; if(rhs == singlet) {return lhs << rhs.w;} return lhs << "[" << rhs.w << ", " << rhs.x << ", " << rhs.y << ", " << rhs.z << "]"; } template<typename R = float> std::ostream& operator<<(std::ostream& lhs, dual<R> const& rhs) { return lhs << "{" << rhs.u << ", " << rhs.v << "}"; } int test(void); } #endif <commit_msg>Added simple model container<commit_after>#ifndef MODEL_HPP #define MODEL_HPP #include <map> #include <vector> #include <functional> #include <iostream> #include <utility> #include <cmath> #include "../inc/quat.hpp" #include "../inc/dual.hpp" namespace Model { template<typename R = float> struct model { static unsigned int nextID; const unsigned int uid; bool operator<(model<R> const& rhs) const { return uid < rhs.uid; } std::map<model<R>,dual<R>> subs; model(void): uid(nextID++), subs{} {} }; template<typename R = float> std::ostream& operator<<(std::ostream& lhs, model<R> const& rhs) { for(auto &entry : rhs.subs) { lhs << entry.second << ": " << entry.first << "\r\n"; } return lhs; } template<typename R = float> std::ostream& operator<<(std::ostream& lhs, quat<R> const& rhs) { quat<R> singlet = rhs.w; if(rhs == singlet) {return lhs << rhs.w;} return lhs << "[" << rhs.w << ", " << rhs.x << ", " << rhs.y << ", " << rhs.z << "]"; } template<typename R = float> std::ostream& operator<<(std::ostream& lhs, dual<R> const& rhs) { return lhs << "{" << rhs.u << ", " << rhs.v << "}"; } int test(void); } #endif <|endoftext|>
<commit_before>// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 ProfitFuel Inc. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifdef HAVE_SPEEX // [ // SYSTEM INCLUDES #include <speex/speex_echo.h> #include <speex/speex_types.h> // APPLICATION INCLUDES #include "os/OsDefs.h" #include "mp/MpMisc.h" #include "mp/MpBuf.h" #include "mp/MpBufPool.h" #include "mp/MpBufferMsg.h" #include "mp/MprSpeexEchoCancel.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor MprSpeexEchoCancel::MprSpeexEchoCancel(const UtlString& rName, int samplesPerFrame, int samplesPerSec, int filterLength, int echoResiduePoolSize) : MpAudioResource(rName, 1, 1, 1, 2, samplesPerFrame, samplesPerSec) , mEchoResiduePool( MpArrayBuf::getHeaderSize() + sizeof(spx_int32_t)*(samplesPerFrame + 1), echoResiduePoolSize) { //Initilize Speex Echo state with framesize and number of frames for length of buffer mpEchoState = speex_echo_state_init(samplesPerFrame, samplesPerSec*filterLength/1000); //mpEchoResidue = (spx_int32_t*)malloc(sizeof(spx_int32_t) * (samplesPerFrame + 1)); mStartedCanceling = false; // Debug Use only } // Destructor MprSpeexEchoCancel::~MprSpeexEchoCancel() { if (mpEchoState != NULL) { speex_echo_state_destroy(mpEchoState); mpEchoState = NULL; } } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ UtlBoolean MprSpeexEchoCancel::doProcessFrame(MpBufPtr inBufs[], MpBufPtr outBufs[], int inBufsSize, int outBufsSize, UtlBoolean isEnabled, int samplesPerFrame, int samplesPerSecond) { MpAudioBufPtr outBuffer; MpAudioBufPtr inputBuffer; MpAudioBufPtr echoRefBuffer; MpArrayBufPtr echoResidueBuffer; MpBufferMsg* bufferMsg; spx_int32_t* pEchoResidue; // We don't need to do anything if we don't have an output. if (!isOutputConnected(0) && !isOutputConnected(1)) return FALSE; // If disabled pass buffer through if (!isEnabled) { outBufs[0].swap(inBufs[0]); return TRUE; } // Get incoming data inputBuffer.swap(inBufs[0]); // If the object is not enabled or we don't have valid input, // pass input to output if ( inputBuffer.isValid() && (inputBuffer->getSamplesNumber() == samplesPerFrame)) { // This buffer will be modified in place. Make sure we're the only owner. assert(inputBuffer.requestWrite()); // Try to get a reference frame for echo cancelation. 21 = MAX_SPKR_BUFFERS(12) + if (MpMisc.pEchoQ->numMsgs() > MAX_ECHO_QUEUE) { // Flush queue while ( (MpMisc.pEchoQ->receive((OsMsg*&) bufferMsg, OsTime::NO_WAIT_TIME) == OS_SUCCESS) && MpMisc.pEchoQ->numMsgs() > MAX_ECHO_QUEUE) { bufferMsg->releaseMsg(); } // Get buffer from the message and free message echoRefBuffer = bufferMsg->getBuffer(); assert(echoRefBuffer.isValid()); bufferMsg->releaseMsg(); if (echoRefBuffer->getSamplesNumber() == samplesPerFrame) { mStartedCanceling = true; // Get new buffer outBuffer = MpMisc.RawAudioPool->getBuffer(); assert(outBuffer.isValid()); outBuffer->setSamplesNumber(samplesPerFrame); outBuffer->setSpeechType(inputBuffer->getSpeechType()); if (isOutputConnected(1)) { echoResidueBuffer = mEchoResiduePool.getBuffer(); assert(outBuffer.isValid()); } if (outBuffer.isValid()) { pEchoResidue = (spx_int32_t*)echoResidueBuffer->getDataWritePtr(); } // Do echo cancelation speex_echo_cancel(mpEchoState, (spx_int16_t*)inputBuffer->getSamplesPtr(), (spx_int16_t*)echoRefBuffer->getSamplesPtr(), (spx_int16_t*)outBuffer->getSamplesPtr(), pEchoResidue); } else { //The sample count didn't match so we can't echo cancel. Pass the frame. outBuffer = inputBuffer; assert(!mStartedCanceling); } } else { //There was no speaker data to match. Pass the frame. outBuffer = inputBuffer; // osPrintf("SpeexEchoCancel: No frame to match...\n"); // assert (!mStartedCanceling); } } outBufs[0].swap(outBuffer); outBufs[1].swap(echoResidueBuffer); return TRUE; } /* ============================ FUNCTIONS ================================= */ #endif // HAVE_SPEEX ] <commit_msg>Moved inputBuffer.requestWrite() out of assert in MprSpeexEchoCancel.<commit_after>// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 ProfitFuel Inc. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifdef HAVE_SPEEX // [ // SYSTEM INCLUDES #include <speex/speex_echo.h> #include <speex/speex_types.h> // APPLICATION INCLUDES #include "os/OsDefs.h" #include "mp/MpMisc.h" #include "mp/MpBuf.h" #include "mp/MpBufPool.h" #include "mp/MpBufferMsg.h" #include "mp/MprSpeexEchoCancel.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor MprSpeexEchoCancel::MprSpeexEchoCancel(const UtlString& rName, int samplesPerFrame, int samplesPerSec, int filterLength, int echoResiduePoolSize) : MpAudioResource(rName, 1, 1, 1, 2, samplesPerFrame, samplesPerSec) , mEchoResiduePool( MpArrayBuf::getHeaderSize() + sizeof(spx_int32_t)*(samplesPerFrame + 1), echoResiduePoolSize) { //Initilize Speex Echo state with framesize and number of frames for length of buffer mpEchoState = speex_echo_state_init(samplesPerFrame, samplesPerSec*filterLength/1000); //mpEchoResidue = (spx_int32_t*)malloc(sizeof(spx_int32_t) * (samplesPerFrame + 1)); mStartedCanceling = false; // Debug Use only } // Destructor MprSpeexEchoCancel::~MprSpeexEchoCancel() { if (mpEchoState != NULL) { speex_echo_state_destroy(mpEchoState); mpEchoState = NULL; } } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ UtlBoolean MprSpeexEchoCancel::doProcessFrame(MpBufPtr inBufs[], MpBufPtr outBufs[], int inBufsSize, int outBufsSize, UtlBoolean isEnabled, int samplesPerFrame, int samplesPerSecond) { MpAudioBufPtr outBuffer; MpAudioBufPtr inputBuffer; MpAudioBufPtr echoRefBuffer; MpArrayBufPtr echoResidueBuffer; MpBufferMsg* bufferMsg; spx_int32_t* pEchoResidue; bool res = false; // We don't need to do anything if we don't have an output. if (!isOutputConnected(0) && !isOutputConnected(1)) return FALSE; // If disabled pass buffer through if (!isEnabled) { outBufs[0].swap(inBufs[0]); return TRUE; } // Get incoming data inputBuffer.swap(inBufs[0]); // If the object is not enabled or we don't have valid input, // pass input to output if ( inputBuffer.isValid() && (inputBuffer->getSamplesNumber() == samplesPerFrame)) { // This buffer will be modified in place. Make sure we're the only owner. res = inputBuffer.requestWrite(); assert(res); // Try to get a reference frame for echo cancelation. 21 = MAX_SPKR_BUFFERS(12) + if (MpMisc.pEchoQ->numMsgs() > MAX_ECHO_QUEUE) { // Flush queue while ( (MpMisc.pEchoQ->receive((OsMsg*&) bufferMsg, OsTime::NO_WAIT_TIME) == OS_SUCCESS) && MpMisc.pEchoQ->numMsgs() > MAX_ECHO_QUEUE) { bufferMsg->releaseMsg(); } // Get buffer from the message and free message echoRefBuffer = bufferMsg->getBuffer(); assert(echoRefBuffer.isValid()); bufferMsg->releaseMsg(); if (echoRefBuffer->getSamplesNumber() == samplesPerFrame) { mStartedCanceling = true; // Get new buffer outBuffer = MpMisc.RawAudioPool->getBuffer(); assert(outBuffer.isValid()); outBuffer->setSamplesNumber(samplesPerFrame); outBuffer->setSpeechType(inputBuffer->getSpeechType()); if (isOutputConnected(1)) { echoResidueBuffer = mEchoResiduePool.getBuffer(); assert(outBuffer.isValid()); } if (outBuffer.isValid()) { pEchoResidue = (spx_int32_t*)echoResidueBuffer->getDataWritePtr(); } // Do echo cancelation speex_echo_cancel(mpEchoState, (spx_int16_t*)inputBuffer->getSamplesPtr(), (spx_int16_t*)echoRefBuffer->getSamplesPtr(), (spx_int16_t*)outBuffer->getSamplesPtr(), pEchoResidue); } else { //The sample count didn't match so we can't echo cancel. Pass the frame. outBuffer = inputBuffer; assert(!mStartedCanceling); } } else { //There was no speaker data to match. Pass the frame. outBuffer = inputBuffer; // osPrintf("SpeexEchoCancel: No frame to match...\n"); // assert (!mStartedCanceling); } } outBufs[0].swap(outBuffer); outBufs[1].swap(echoResidueBuffer); return TRUE; } /* ============================ FUNCTIONS ================================= */ #endif // HAVE_SPEEX ] <|endoftext|>
<commit_before>#include "hill_climbing.h" #include <iostream> #include <cmath> //for fabs() using namespace std; namespace mo { Hill_climbing::Hill_climbing(const double& h0, const double& eps, const double& delta) : h0_{h0}, eps_{eps}, delta_{delta} { } void Hill_climbing::compute(){ } double Hill_climbing::linear_search(double (*f)(const double&), double(*df)(const double&), const double& x0){ double h = h0_; double x = x0; while(fabs(df(x)) > eps_){ // h = } return x; } } //namespace mo <commit_msg>implement sgn() in analysis.<commit_after>#include "hill_climbing.h" #include <iostream> #include <cmath> //for fabs() #include "../../analysis/src/analysis.h" //for sgn() using namespace std; namespace mo { Hill_climbing::Hill_climbing(const double& h0, const double& eps, const double& delta) : h0_{h0}, eps_{eps}, delta_{delta} { } void Hill_climbing::compute(){ } double Hill_climbing::linear_search(double (*f)(const double&), double(*df)(const double&), const double& x0){ double h = h0_; double x = x0; while(fabs(df(x)) > eps_){ h *= sgn(df(x)); } return x; } } //namespace mo <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/download/download_shelf.h" #include "app/l10n_util.h" #include "base/file_util.h" #include "chrome/browser/dom_ui/downloads_ui.h" #include "chrome/browser/download/download_item_model.h" #include "chrome/browser/download/download_manager.h" #include "chrome/browser/metrics/user_metrics.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/url_constants.h" #include "grit/generated_resources.h" #if defined(OS_WIN) #include "chrome/browser/download/download_util.h" #elif defined(OS_POSIX) #include "chrome/common/temp_scaffolding_stubs.h" #endif // DownloadShelf --------------------------------------------------------------- void DownloadShelf::ShowAllDownloads() { Profile* profile = tab_contents_->profile(); if (profile) UserMetrics::RecordAction(L"ShowDownloads", profile); tab_contents_->OpenURL(GURL(chrome::kChromeUIDownloadsURL), GURL(), SINGLETON_TAB, PageTransition::AUTO_BOOKMARK); } void DownloadShelf::ChangeTabContents(TabContents* old_contents, TabContents* new_contents) { DCHECK(old_contents == tab_contents_); tab_contents_ = new_contents; } // DownloadShelfContextMenu ---------------------------------------------------- DownloadShelfContextMenu::DownloadShelfContextMenu( BaseDownloadItemModel* download_model) : download_(download_model->download()), model_(download_model) { } DownloadShelfContextMenu::~DownloadShelfContextMenu() { } bool DownloadShelfContextMenu::ItemIsChecked(int id) const { switch (id) { case OPEN_WHEN_COMPLETE: return download_->open_when_complete(); case ALWAYS_OPEN_TYPE: { const FilePath::StringType extension = file_util::GetFileExtensionFromPath(download_->full_path()); return download_->manager()->ShouldOpenFileExtension(extension); } } return false; } bool DownloadShelfContextMenu::ItemIsDefault(int id) const { return id == OPEN_WHEN_COMPLETE; } std::wstring DownloadShelfContextMenu::GetItemLabel(int id) const { switch (id) { case SHOW_IN_FOLDER: return l10n_util::GetString(IDS_DOWNLOAD_LINK_SHOW); case OPEN_WHEN_COMPLETE: if (download_->state() == DownloadItem::IN_PROGRESS) return l10n_util::GetString(IDS_DOWNLOAD_MENU_OPEN_WHEN_COMPLETE); return l10n_util::GetString(IDS_DOWNLOAD_MENU_OPEN); case ALWAYS_OPEN_TYPE: return l10n_util::GetString(IDS_DOWNLOAD_MENU_ALWAYS_OPEN_TYPE); case CANCEL: return l10n_util::GetString(IDS_DOWNLOAD_MENU_CANCEL); default: NOTREACHED(); } return std::wstring(); } bool DownloadShelfContextMenu::IsItemCommandEnabled(int id) const { switch (id) { case SHOW_IN_FOLDER: case OPEN_WHEN_COMPLETE: return download_->state() != DownloadItem::CANCELLED; case ALWAYS_OPEN_TYPE: #if defined(OS_WIN) return download_util::CanOpenDownload(download_); #else // TODO(port): port download_util NOTIMPLEMENTED(); return true; #endif case CANCEL: return download_->state() == DownloadItem::IN_PROGRESS; default: return id > 0 && id < MENU_LAST; } } void DownloadShelfContextMenu::ExecuteItemCommand(int id) { switch (id) { case SHOW_IN_FOLDER: download_->manager()->ShowDownloadInShell(download_); break; case OPEN_WHEN_COMPLETE: #if defined(OS_WIN) download_util::OpenDownload(download_); #else // TODO(port): port download_util NOTIMPLEMENTED(); #endif break; case ALWAYS_OPEN_TYPE: { const FilePath::StringType extension = file_util::GetFileExtensionFromPath(download_->full_path()); download_->manager()->OpenFilesOfExtension( extension, !ItemIsChecked(ALWAYS_OPEN_TYPE)); break; } case CANCEL: model_->CancelTask(); break; default: NOTREACHED(); } } <commit_msg>Remove one more notimpl.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/download/download_shelf.h" #include "app/l10n_util.h" #include "base/file_util.h" #include "chrome/browser/dom_ui/downloads_ui.h" #include "chrome/browser/download/download_item_model.h" #include "chrome/browser/download/download_manager.h" #include "chrome/browser/metrics/user_metrics.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/url_constants.h" #include "grit/generated_resources.h" #if defined(OS_WIN) #include "chrome/browser/download/download_util.h" #elif defined(OS_POSIX) #include "chrome/common/temp_scaffolding_stubs.h" #endif // DownloadShelf --------------------------------------------------------------- void DownloadShelf::ShowAllDownloads() { Profile* profile = tab_contents_->profile(); if (profile) UserMetrics::RecordAction(L"ShowDownloads", profile); tab_contents_->OpenURL(GURL(chrome::kChromeUIDownloadsURL), GURL(), SINGLETON_TAB, PageTransition::AUTO_BOOKMARK); } void DownloadShelf::ChangeTabContents(TabContents* old_contents, TabContents* new_contents) { DCHECK(old_contents == tab_contents_); tab_contents_ = new_contents; } // DownloadShelfContextMenu ---------------------------------------------------- DownloadShelfContextMenu::DownloadShelfContextMenu( BaseDownloadItemModel* download_model) : download_(download_model->download()), model_(download_model) { } DownloadShelfContextMenu::~DownloadShelfContextMenu() { } bool DownloadShelfContextMenu::ItemIsChecked(int id) const { switch (id) { case OPEN_WHEN_COMPLETE: return download_->open_when_complete(); case ALWAYS_OPEN_TYPE: { const FilePath::StringType extension = file_util::GetFileExtensionFromPath(download_->full_path()); return download_->manager()->ShouldOpenFileExtension(extension); } } return false; } bool DownloadShelfContextMenu::ItemIsDefault(int id) const { return id == OPEN_WHEN_COMPLETE; } std::wstring DownloadShelfContextMenu::GetItemLabel(int id) const { switch (id) { case SHOW_IN_FOLDER: return l10n_util::GetString(IDS_DOWNLOAD_LINK_SHOW); case OPEN_WHEN_COMPLETE: if (download_->state() == DownloadItem::IN_PROGRESS) return l10n_util::GetString(IDS_DOWNLOAD_MENU_OPEN_WHEN_COMPLETE); return l10n_util::GetString(IDS_DOWNLOAD_MENU_OPEN); case ALWAYS_OPEN_TYPE: return l10n_util::GetString(IDS_DOWNLOAD_MENU_ALWAYS_OPEN_TYPE); case CANCEL: return l10n_util::GetString(IDS_DOWNLOAD_MENU_CANCEL); default: NOTREACHED(); } return std::wstring(); } bool DownloadShelfContextMenu::IsItemCommandEnabled(int id) const { switch (id) { case SHOW_IN_FOLDER: case OPEN_WHEN_COMPLETE: return download_->state() != DownloadItem::CANCELLED; case ALWAYS_OPEN_TYPE: #if defined(OS_WIN) return download_util::CanOpenDownload(download_); #elif defined(OS_LINUX) // Need to implement dangerous download stuff: http://crbug.com/11780 return false; #endif case CANCEL: return download_->state() == DownloadItem::IN_PROGRESS; default: return id > 0 && id < MENU_LAST; } } void DownloadShelfContextMenu::ExecuteItemCommand(int id) { switch (id) { case SHOW_IN_FOLDER: download_->manager()->ShowDownloadInShell(download_); break; case OPEN_WHEN_COMPLETE: #if defined(OS_WIN) download_util::OpenDownload(download_); #else // TODO(port): port download_util NOTIMPLEMENTED(); #endif break; case ALWAYS_OPEN_TYPE: { const FilePath::StringType extension = file_util::GetFileExtensionFromPath(download_->full_path()); download_->manager()->OpenFilesOfExtension( extension, !ItemIsChecked(ALWAYS_OPEN_TYPE)); break; } case CANCEL: model_->CancelTask(); break; default: NOTREACHED(); } } <|endoftext|>
<commit_before>#include "sudokuJudger.h" #include "sudokuGenerator.h" #include "sudokuPrinter.h" #include <stdlib.h> #include <iostream> using namespace std; int main() { int input[9][9]; int i, j; bool signal = false; SudokuGenerator sudokuGenerator; while (!signal) { signal = sudokuGenerator.Generator(); } SudokuPrinter sudokuPrinter; sudokuPrinter.Printer(sudokuGenerator.solution); /*for (i = 0; i < 9; i++) { for (j = 0; j < 9; j++) { cin >> input[i][j]; } } SudokuJudger sudokuJudger1; bool sudokuResult = sudokuJudger1.SudokuisSolved(input); if (sudokuResult) { cout << "Congratulations!" << endl; }*/ return 0; }<commit_msg>update main.cpp: add arguments<commit_after>#include "sudokuJudger.h" #include "sudokuGenerator.h" #include "sudokuPrinter.h" #include <stdlib.h> #include <iostream> using namespace std; int main(int argc, char *argv[]) { if (argc < 3) { cout << "Error occurs when parsing arguments." << endl; cout << "Usage: sudoku.exe -c [N]" << endl; return 1; } int solutionNumber = atoi(argv[2]); SudokuGenerator sudokuGenerator; SudokuPrinter sudokuPrinter; bool signal = false; for (int i = 0; i < solutionNumber; i++) { signal = sudokuGenerator.Generator(); if (signal) { sudokuPrinter.Printer(sudokuGenerator.solution); } else { cout << "Error occurs when applying sudokuGenerator." << endl; return 1; } } return 0; }<|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/base_paths.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/sys_info.h" #include "base/test/test_file_util.h" #include "base/test/test_timeouts.h" #include "base/values.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/automation_proxy.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "ui/gfx/native_widget_types.h" namespace { class BrowserTest : public UITest { }; class VisibleBrowserTest : public UITest { protected: VisibleBrowserTest() : UITest() { show_window_ = true; } }; } // namespace // The browser should quit quickly if it receives a WM_ENDSESSION message // on Windows, or SIGTERM on posix. TEST_F(BrowserTest, SessionEnd) { FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("title1.html"); NavigateToURL(net::FilePathToFileURL(test_file)); TerminateBrowser(); } // WindowOpenClose is flaky on ChromeOS and fails consistently on linux views. // See http://crbug.com/85763. #if defined (OS_CHROMEOS) #define MAYBE_WindowOpenClose FLAKY_WindowOpenClose #elif defined(OS_LINUX) && defined(TOOLKIT_VIEWS) #define MAYBE_WindowOpenClose FAILS_WindowOpenClose #else #define MAYBE_WindowOpenClose WindowOpenClose #endif TEST_F(VisibleBrowserTest, MAYBE_WindowOpenClose) { FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("window.close.html"); NavigateToURLBlockUntilNavigationsComplete( net::FilePathToFileURL(test_file), 2); EXPECT_EQ(L"Title Of Awesomeness", GetActiveTabTitle()); } class ShowModalDialogTest : public UITest { public: ShowModalDialogTest() { launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking); } }; // Flakiness returned. Re-opened crbug.com/17806 // TODO(estade): remove flaky label if prospective fix works. TEST_F(ShowModalDialogTest, FLAKY_BasicTest) { FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("showmodaldialog.html"); // This navigation should show a modal dialog that will be immediately // closed, but the fact that it was shown should be recorded. NavigateToURL(net::FilePathToFileURL(test_file)); ASSERT_TRUE(automation()->WaitForWindowCountToBecome(1)); // Verify that we set a mark on successful dialog show. scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); std::wstring title; ASSERT_TRUE(tab->GetTabTitle(&title)); ASSERT_EQ(L"SUCCESS", title); } class SecurityTest : public UITest { }; TEST_F(SecurityTest, DisallowFileUrlUniversalAccessTest) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("fileurl_universalaccess.html"); GURL url = net::FilePathToFileURL(test_file); ASSERT_TRUE(tab->NavigateToURL(url)); std::string value = WaitUntilCookieNonEmpty(tab.get(), url, "status", TestTimeouts::action_max_timeout_ms()); ASSERT_STREQ("Disallowed", value.c_str()); } #if !defined(OS_MACOSX) class KioskModeTest : public UITest { public: KioskModeTest() { launch_arguments_.AppendSwitch(switches::kKioskMode); } }; TEST_F(KioskModeTest, EnableKioskModeTest) { // Load a local file. FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("title1.html"); // Verify that the window is present. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); // Check if browser is in fullscreen mode. bool is_visible; ASSERT_TRUE(browser->IsFullscreen(&is_visible)); EXPECT_TRUE(is_visible); ASSERT_TRUE(browser->IsFullscreenBubbleVisible(&is_visible)); EXPECT_FALSE(is_visible); } #endif // !defined(OS_MACOSX) #if defined(OS_WIN) // This test verifies that Chrome can be launched with a user-data-dir path // which contains non ASCII characters. class LaunchBrowserWithNonAsciiUserDatadir : public UITest { public: void SetUp() { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); FilePath tmp_profile = temp_dir_.path().AppendASCII("tmp_profile"); tmp_profile = tmp_profile.Append(L"Test Chrome G�raldine"); ASSERT_TRUE(file_util::CreateDirectory(tmp_profile)); launch_arguments_.AppendSwitchPath(switches::kUserDataDir, tmp_profile); } bool LaunchAppWithProfile() { UITest::SetUp(); return true; } public: ScopedTempDir temp_dir_; }; TEST_F(LaunchBrowserWithNonAsciiUserDatadir, TestNonAsciiUserDataDir) { ASSERT_TRUE(LaunchAppWithProfile()); // Verify that the window is present. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); } #endif // defined(OS_WIN) // Tests to ensure that the browser continues running in the background after // the last window closes. class RunInBackgroundTest : public UITest { public: RunInBackgroundTest() { launch_arguments_.AppendSwitch(switches::kKeepAliveForTest); } }; TEST_F(RunInBackgroundTest, RunInBackgroundBasicTest) { // Close the browser window, then open a new one - the browser should keep // running. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int window_count; ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count)); EXPECT_EQ(1, window_count); ASSERT_TRUE(browser->RunCommand(IDC_CLOSE_WINDOW)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count)); EXPECT_EQ(0, window_count); ASSERT_TRUE(automation()->OpenNewBrowserWindow(Browser::TYPE_TABBED, true)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count)); EXPECT_EQ(1, window_count); // Set the shutdown type to 'SESSION_ENDING' since we are running in // background mode and neither closing all the windows nor quitting will // shut down the browser. set_shutdown_type(ProxyLauncher::SESSION_ENDING); } // Tests to ensure that the browser continues running in the background after // the last window closes. class NoStartupWindowTest : public UITest { public: NoStartupWindowTest() { launch_arguments_.AppendSwitch(switches::kNoStartupWindow); launch_arguments_.AppendSwitch(switches::kKeepAliveForTest); } }; TEST_F(NoStartupWindowTest, NoStartupWindowBasicTest) { // No browser window should be started by default. int window_count; ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count)); EXPECT_EQ(0, window_count); // Starting a browser window should work just fine. ASSERT_TRUE(automation()->OpenNewBrowserWindow(Browser::TYPE_TABBED, true)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count)); EXPECT_EQ(1, window_count); } // This test needs to be placed outside the anonymouse namespace because we // need to access private type of Browser. class AppModeTest : public UITest { public: AppModeTest() { // Load a local file. FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("title1.html"); GURL test_file_url(net::FilePathToFileURL(test_file)); launch_arguments_.AppendSwitchASCII(switches::kApp, test_file_url.spec()); } }; TEST_F(AppModeTest, EnableAppModeTest) { // Test that an application browser window loads correctly. // Verify that the window is present. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); // Verify the browser is in application mode. bool is_application; ASSERT_TRUE(browser->IsApplication(&is_application)); EXPECT_TRUE(is_application); } <commit_msg>ShowModalDialogTest: Remove FLAKE label from BasicTest.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/base_paths.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/sys_info.h" #include "base/test/test_file_util.h" #include "base/test/test_timeouts.h" #include "base/values.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/automation_proxy.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "ui/gfx/native_widget_types.h" namespace { class BrowserTest : public UITest { }; class VisibleBrowserTest : public UITest { protected: VisibleBrowserTest() : UITest() { show_window_ = true; } }; } // namespace // The browser should quit quickly if it receives a WM_ENDSESSION message // on Windows, or SIGTERM on posix. TEST_F(BrowserTest, SessionEnd) { FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("title1.html"); NavigateToURL(net::FilePathToFileURL(test_file)); TerminateBrowser(); } // WindowOpenClose is flaky on ChromeOS and fails consistently on linux views. // See http://crbug.com/85763. #if defined (OS_CHROMEOS) #define MAYBE_WindowOpenClose FLAKY_WindowOpenClose #elif defined(OS_LINUX) && defined(TOOLKIT_VIEWS) #define MAYBE_WindowOpenClose FAILS_WindowOpenClose #else #define MAYBE_WindowOpenClose WindowOpenClose #endif TEST_F(VisibleBrowserTest, MAYBE_WindowOpenClose) { FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("window.close.html"); NavigateToURLBlockUntilNavigationsComplete( net::FilePathToFileURL(test_file), 2); EXPECT_EQ(L"Title Of Awesomeness", GetActiveTabTitle()); } class ShowModalDialogTest : public UITest { public: ShowModalDialogTest() { launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking); } }; TEST_F(ShowModalDialogTest, BasicTest) { FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("showmodaldialog.html"); // This navigation should show a modal dialog that will be immediately // closed, but the fact that it was shown should be recorded. NavigateToURL(net::FilePathToFileURL(test_file)); ASSERT_TRUE(automation()->WaitForWindowCountToBecome(1)); // Verify that we set a mark on successful dialog show. scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); std::wstring title; ASSERT_TRUE(tab->GetTabTitle(&title)); ASSERT_EQ(L"SUCCESS", title); } class SecurityTest : public UITest { }; TEST_F(SecurityTest, DisallowFileUrlUniversalAccessTest) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("fileurl_universalaccess.html"); GURL url = net::FilePathToFileURL(test_file); ASSERT_TRUE(tab->NavigateToURL(url)); std::string value = WaitUntilCookieNonEmpty(tab.get(), url, "status", TestTimeouts::action_max_timeout_ms()); ASSERT_STREQ("Disallowed", value.c_str()); } #if !defined(OS_MACOSX) class KioskModeTest : public UITest { public: KioskModeTest() { launch_arguments_.AppendSwitch(switches::kKioskMode); } }; TEST_F(KioskModeTest, EnableKioskModeTest) { // Load a local file. FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("title1.html"); // Verify that the window is present. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); // Check if browser is in fullscreen mode. bool is_visible; ASSERT_TRUE(browser->IsFullscreen(&is_visible)); EXPECT_TRUE(is_visible); ASSERT_TRUE(browser->IsFullscreenBubbleVisible(&is_visible)); EXPECT_FALSE(is_visible); } #endif // !defined(OS_MACOSX) #if defined(OS_WIN) // This test verifies that Chrome can be launched with a user-data-dir path // which contains non ASCII characters. class LaunchBrowserWithNonAsciiUserDatadir : public UITest { public: void SetUp() { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); FilePath tmp_profile = temp_dir_.path().AppendASCII("tmp_profile"); tmp_profile = tmp_profile.Append(L"Test Chrome G�raldine"); ASSERT_TRUE(file_util::CreateDirectory(tmp_profile)); launch_arguments_.AppendSwitchPath(switches::kUserDataDir, tmp_profile); } bool LaunchAppWithProfile() { UITest::SetUp(); return true; } public: ScopedTempDir temp_dir_; }; TEST_F(LaunchBrowserWithNonAsciiUserDatadir, TestNonAsciiUserDataDir) { ASSERT_TRUE(LaunchAppWithProfile()); // Verify that the window is present. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); } #endif // defined(OS_WIN) // Tests to ensure that the browser continues running in the background after // the last window closes. class RunInBackgroundTest : public UITest { public: RunInBackgroundTest() { launch_arguments_.AppendSwitch(switches::kKeepAliveForTest); } }; TEST_F(RunInBackgroundTest, RunInBackgroundBasicTest) { // Close the browser window, then open a new one - the browser should keep // running. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int window_count; ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count)); EXPECT_EQ(1, window_count); ASSERT_TRUE(browser->RunCommand(IDC_CLOSE_WINDOW)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count)); EXPECT_EQ(0, window_count); ASSERT_TRUE(automation()->OpenNewBrowserWindow(Browser::TYPE_TABBED, true)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count)); EXPECT_EQ(1, window_count); // Set the shutdown type to 'SESSION_ENDING' since we are running in // background mode and neither closing all the windows nor quitting will // shut down the browser. set_shutdown_type(ProxyLauncher::SESSION_ENDING); } // Tests to ensure that the browser continues running in the background after // the last window closes. class NoStartupWindowTest : public UITest { public: NoStartupWindowTest() { launch_arguments_.AppendSwitch(switches::kNoStartupWindow); launch_arguments_.AppendSwitch(switches::kKeepAliveForTest); } }; TEST_F(NoStartupWindowTest, NoStartupWindowBasicTest) { // No browser window should be started by default. int window_count; ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count)); EXPECT_EQ(0, window_count); // Starting a browser window should work just fine. ASSERT_TRUE(automation()->OpenNewBrowserWindow(Browser::TYPE_TABBED, true)); ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count)); EXPECT_EQ(1, window_count); } // This test needs to be placed outside the anonymouse namespace because we // need to access private type of Browser. class AppModeTest : public UITest { public: AppModeTest() { // Load a local file. FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("title1.html"); GURL test_file_url(net::FilePathToFileURL(test_file)); launch_arguments_.AppendSwitchASCII(switches::kApp, test_file_url.spec()); } }; TEST_F(AppModeTest, EnableAppModeTest) { // Test that an application browser window loads correctly. // Verify that the window is present. scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); // Verify the browser is in application mode. bool is_application; ASSERT_TRUE(browser->IsApplication(&is_application)); EXPECT_TRUE(is_application); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "base/process_util.h" #include "base/test/multiprocess_test.h" #include "base/test/test_timeouts.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/main_function_params.h" #include "ipc/ipc_channel.h" #include "ipc/ipc_switches.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/multiprocess_func_list.h" // TODO(port): Bring up this test this on other platforms. #if defined(OS_POSIX) using base::ProcessHandle; const char kRendererTestChannelName[] = "test"; extern int RendererMain(const MainFunctionParams& parameters); // TODO(port): The IPC Channel tests have a class with extremely similar // functionality, we should combine them. class RendererMainTest : public base::MultiProcessTest { protected: RendererMainTest() {} // Create a new MessageLoopForIO For each test. virtual void SetUp(); virtual void TearDown(); // Spawns a child process of the specified type base::ProcessHandle SpawnChild(const std::string& procname, IPC::Channel* channel); // Created around each test instantiation. MessageLoopForIO *message_loop_; }; void RendererMainTest::SetUp() { MultiProcessTest::SetUp(); // Construct a fresh IO Message loop for the duration of each test. message_loop_ = new MessageLoopForIO(); } void RendererMainTest::TearDown() { delete message_loop_; message_loop_ = NULL; MultiProcessTest::TearDown(); } ProcessHandle RendererMainTest::SpawnChild(const std::string& procname, IPC::Channel* channel) { base::file_handle_mapping_vector fds_to_map; const int ipcfd = channel->GetClientFileDescriptor(); if (ipcfd > -1) { fds_to_map.push_back(std::pair<int,int>(ipcfd, 3)); } return MultiProcessTest::SpawnChild(procname, fds_to_map, false); } // Listener class that kills the message loop when it connects. class SuicidalListener : public IPC::Channel::Listener { public: explicit SuicidalListener(bool* suicide_success) : suicide_success_(suicide_success) {} void OnChannelConnected(int32 peer_pid) { *suicide_success_ = true; MessageLoop::current()->Quit(); } void OnMessageReceived(const IPC::Message& message) { // We shouldn't receive any messages ASSERT_TRUE(false); } // A flag that we set when we have successfully suicided. bool* suicide_success_; }; MULTIPROCESS_TEST_MAIN(SimpleRenderer) { SandboxInitWrapper dummy_sandbox_init; CommandLine cl(*CommandLine::ForCurrentProcess()); cl.AppendSwitchASCII(switches::kProcessChannelID, kRendererTestChannelName); MainFunctionParams dummy_params(cl, dummy_sandbox_init, NULL); return RendererMain(dummy_params); } TEST_F(RendererMainTest, CreateDestroy) { bool suicide_success = false; SuicidalListener listener(&suicide_success); IPC::Channel control_channel(kRendererTestChannelName, IPC::Channel::MODE_SERVER, &listener); base::ProcessHandle renderer_pid = SpawnChild("SimpleRenderer", &control_channel); ASSERT_TRUE(control_channel.Connect()); // The SuicidalListener *should* cause the following MessageLoop run // to quit, but just in case it doesn't, insert a QuitTask at the back // of the queue. MessageLoop::current()->PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask, TestTimeouts::action_timeout_ms()); MessageLoop::current()->Run(); ASSERT_TRUE(suicide_success); // The renderer should exit when we close the channel. control_channel.Close(); EXPECT_TRUE(base::WaitForSingleProcess(renderer_pid, TestTimeouts::action_timeout_ms())); } #endif // defined(OS_POSIX) <commit_msg>Revert most of my recent changes to RendererMainTest.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "base/process_util.h" #include "base/test/multiprocess_test.h" #include "base/test/test_timeouts.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/main_function_params.h" #include "ipc/ipc_channel.h" #include "ipc/ipc_switches.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/multiprocess_func_list.h" // TODO(port): Bring up this test this on other platforms. #if defined(OS_POSIX) using base::ProcessHandle; const char kRendererTestChannelName[] = "test"; extern int RendererMain(const MainFunctionParams& parameters); // TODO(port): The IPC Channel tests have a class with extremely similar // functionality, we should combine them. class RendererMainTest : public base::MultiProcessTest { protected: RendererMainTest() {} // Create a new MessageLoopForIO For each test. virtual void SetUp(); virtual void TearDown(); // Spawns a child process of the specified type base::ProcessHandle SpawnChild(const std::string& procname, IPC::Channel* channel); // Created around each test instantiation. MessageLoopForIO *message_loop_; }; void RendererMainTest::SetUp() { MultiProcessTest::SetUp(); // Construct a fresh IO Message loop for the duration of each test. message_loop_ = new MessageLoopForIO(); } void RendererMainTest::TearDown() { delete message_loop_; message_loop_ = NULL; MultiProcessTest::TearDown(); } ProcessHandle RendererMainTest::SpawnChild(const std::string& procname, IPC::Channel* channel) { base::file_handle_mapping_vector fds_to_map; const int ipcfd = channel->GetClientFileDescriptor(); if (ipcfd > -1) { fds_to_map.push_back(std::pair<int,int>(ipcfd, 3)); } return MultiProcessTest::SpawnChild(procname, fds_to_map, false); } // Listener class that kills the message loop when it connects. class SuicidalListener : public IPC::Channel::Listener { public: void OnChannelConnected(int32 peer_pid) { MessageLoop::current()->Quit(); } void OnMessageReceived(const IPC::Message& message) { // We shouldn't receive any messages ASSERT_TRUE(false); } }; MULTIPROCESS_TEST_MAIN(SimpleRenderer) { SandboxInitWrapper dummy_sandbox_init; CommandLine cl(*CommandLine::ForCurrentProcess()); cl.AppendSwitchASCII(switches::kProcessChannelID, kRendererTestChannelName); MainFunctionParams dummy_params(cl, dummy_sandbox_init, NULL); return RendererMain(dummy_params); } TEST_F(RendererMainTest, CreateDestroy) { SuicidalListener listener; IPC::Channel control_channel(kRendererTestChannelName, IPC::Channel::MODE_SERVER, &listener); base::ProcessHandle renderer_pid = SpawnChild("SimpleRenderer", &control_channel); ASSERT_TRUE(control_channel.Connect()); MessageLoop::current()->PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask, TestTimeouts::action_timeout_ms()); MessageLoop::current()->Run(); // The renderer should exit when we close the channel. control_channel.Close(); EXPECT_TRUE(base::WaitForSingleProcess(renderer_pid, TestTimeouts::action_timeout_ms())); } #endif // defined(OS_POSIX) <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH, Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iceoryx_binding_c/internal/cpp2c_subscriber.hpp" #include "iceoryx_binding_c/types.h" #include "iceoryx_posh/internal/mepoo/memory_manager.hpp" #include "iceoryx_posh/internal/popo/building_blocks/chunk_queue_popper.hpp" #include "iceoryx_posh/internal/popo/building_blocks/chunk_queue_pusher.hpp" #include "iceoryx_posh/internal/popo/ports/subscriber_port_single_producer.hpp" #include "iceoryx_posh/internal/popo/ports/subscriber_port_user.hpp" #include "iceoryx_posh/mepoo/mepoo_config.hpp" #include "mocks/wait_set_mock.hpp" using namespace iox; using namespace iox::popo; using namespace iox::capro; using namespace iox::mepoo; using namespace iox::cxx; using namespace iox::posix; extern "C" { #include "iceoryx_binding_c/subscriber.h" } #include "test.hpp" using namespace ::testing; class iox_sub_test : public Test { public: const iox::capro::ServiceDescription TEST_SERVICE_DESCRIPTION{"a", "b", "c"}; protected: iox_sub_test() { m_mempoolconf.addMemPool({CHUNK_SIZE, NUM_CHUNKS_IN_POOL}); m_memoryManager.configureMemoryManager(m_mempoolconf, &m_memoryAllocator, &m_memoryAllocator); m_subscriber->m_portData = &m_portPtr; } void SetUp() { m_triggerCallbackLatestArgument = nullptr; } void TearDown() { } void Subscribe(SubscriberPortData* ptr) { uint64_t queueCapacity = MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY; iox_sub_subscribe(m_sut, queueCapacity); SubscriberPortSingleProducer(ptr).tryGetCaProMessage(); iox::capro::CaproMessage caproMessage(iox::capro::CaproMessageType::ACK, TEST_SERVICE_DESCRIPTION); SubscriberPortSingleProducer(ptr).dispatchCaProMessageAndGetPossibleResponse(caproMessage); } static void triggerCallback(iox_sub_t sub) { m_triggerCallbackLatestArgument = sub; } static iox_sub_t m_triggerCallbackLatestArgument; static constexpr size_t MEMORY_SIZE = 1024 * 1024 * 100; uint8_t m_memory[MEMORY_SIZE]; static constexpr uint32_t NUM_CHUNKS_IN_POOL = MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY + 2; static constexpr uint32_t CHUNK_SIZE = 128; Allocator m_memoryAllocator{m_memory, MEMORY_SIZE}; MePooConfig m_mempoolconf; MemoryManager m_memoryManager; iox::cxx::GenericRAII m_uniqueRouDiId{[] { iox::popo::internal::setUniqueRouDiId(0); }, [] { iox::popo::internal::unsetUniqueRouDiId(); }}; iox::popo::SubscriberPortData m_portPtr{ TEST_SERVICE_DESCRIPTION, "myApp", iox::cxx::VariantQueueTypes::SoFi_SingleProducerSingleConsumer}; ChunkQueuePusher<SubscriberPortData::ChunkQueueData_t> m_chunkPusher{&m_portPtr.m_chunkReceiverData}; std::unique_ptr<cpp2c_Subscriber> m_subscriber{new cpp2c_Subscriber}; iox_sub_t m_sut = m_subscriber.get(); ConditionVariableData m_condVar; std::unique_ptr<WaitSetMock> m_waitSet{new WaitSetMock(&m_condVar)}; }; iox_sub_t iox_sub_test::m_triggerCallbackLatestArgument = nullptr; TEST_F(iox_sub_test, initialStateNotSubscribed) { EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_NOT_SUBSCRIBED); } TEST_F(iox_sub_test, offerLeadsToSubscibeRequestedState) { uint64_t queueCapacity = 1u; iox_sub_subscribe(m_sut, queueCapacity); SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage(); EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_SUBSCRIBE_REQUESTED); } TEST_F(iox_sub_test, NACKResponseLeadsToSubscribeWaitForOfferState) { uint64_t queueCapacity = 1u; iox_sub_subscribe(m_sut, queueCapacity); SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage(); iox::capro::CaproMessage caproMessage(iox::capro::CaproMessageType::NACK, TEST_SERVICE_DESCRIPTION); SubscriberPortSingleProducer(&m_portPtr).dispatchCaProMessageAndGetPossibleResponse(caproMessage); EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_WAIT_FOR_OFFER); } TEST_F(iox_sub_test, ACKResponseLeadsToSubscribedState) { uint64_t queueCapacity = 1u; iox_sub_subscribe(m_sut, queueCapacity); SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage(); iox::capro::CaproMessage caproMessage(iox::capro::CaproMessageType::ACK, TEST_SERVICE_DESCRIPTION); SubscriberPortSingleProducer(&m_portPtr).dispatchCaProMessageAndGetPossibleResponse(caproMessage); EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_SUBSCRIBED); } TEST_F(iox_sub_test, UnsubscribeLeadsToUnscribeRequestedState) { uint64_t queueCapacity = 1u; iox_sub_subscribe(m_sut, queueCapacity); SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage(); iox::capro::CaproMessage caproMessage(iox::capro::CaproMessageType::ACK, TEST_SERVICE_DESCRIPTION); SubscriberPortSingleProducer(&m_portPtr).dispatchCaProMessageAndGetPossibleResponse(caproMessage); iox_sub_unsubscribe(m_sut); SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage(); EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_UNSUBSCRIBE_REQUESTED); } TEST_F(iox_sub_test, initialStateNoChunksAvailable) { const void* chunk = nullptr; EXPECT_EQ(iox_sub_get_chunk(m_sut, &chunk), ChunkReceiveResult_NO_CHUNK_RECEIVED); } TEST_F(iox_sub_test, receiveChunkWhenThereIsOne) { this->Subscribe(&m_portPtr); m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); const void* chunk = nullptr; EXPECT_EQ(iox_sub_get_chunk(m_sut, &chunk), ChunkReceiveResult_SUCCESS); } TEST_F(iox_sub_test, receiveChunkWithContent) { this->Subscribe(&m_portPtr); struct data_t { int value; }; auto sharedChunk = m_memoryManager.getChunk(100); static_cast<data_t*>(sharedChunk.getPayload())->value = 1234; m_chunkPusher.tryPush(sharedChunk); const void* chunk = nullptr; ASSERT_EQ(iox_sub_get_chunk(m_sut, &chunk), ChunkReceiveResult_SUCCESS); EXPECT_THAT(static_cast<const data_t*>(chunk)->value, Eq(1234)); } TEST_F(iox_sub_test, receiveChunkWhenToManyChunksAreHold) { this->Subscribe(&m_portPtr); const void* chunk = nullptr; for (uint64_t i = 0; i < MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY + 1; ++i) { m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); iox_sub_get_chunk(m_sut, &chunk); } m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); EXPECT_EQ(iox_sub_get_chunk(m_sut, &chunk), ChunkReceiveResult_TOO_MANY_CHUNKS_HELD_IN_PARALLEL); } TEST_F(iox_sub_test, releaseChunkWorks) { this->Subscribe(&m_portPtr); m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); const void* chunk = nullptr; iox_sub_get_chunk(m_sut, &chunk); EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(1u)); iox_sub_release_chunk(m_sut, chunk); EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(0u)); } TEST_F(iox_sub_test, releaseChunkQueuedChunksWorks) { this->Subscribe(&m_portPtr); for (uint64_t i = 0; i < MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY; ++i) { m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); } EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY)); iox_sub_release_queued_chunks(m_sut); EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(0u)); } TEST_F(iox_sub_test, initialStateHasNewChunksFalse) { EXPECT_FALSE(iox_sub_has_new_chunks(m_sut)); } TEST_F(iox_sub_test, receivingChunkLeadsToHasNewChunksTrue) { this->Subscribe(&m_portPtr); m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); EXPECT_TRUE(iox_sub_has_new_chunks(m_sut)); } TEST_F(iox_sub_test, initialStateHasNoLostChunks) { EXPECT_FALSE(iox_sub_has_lost_chunks(m_sut)); } TEST_F(iox_sub_test, sendingTooMuchLeadsToLostChunks) { this->Subscribe(&m_portPtr); for (uint64_t i = 0; i < DefaultChunkQueueConfig::MAX_QUEUE_CAPACITY + 1; ++i) { m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); } EXPECT_TRUE(iox_sub_has_lost_chunks(m_sut)); } TEST_F(iox_sub_test, attachingToWaitSetWorks) { EXPECT_EQ(iox_sub_attach_to_waitset(m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, NULL), WaitSetResult_SUCCESS); EXPECT_EQ(m_waitSet->size(), 1U); } TEST_F(iox_sub_test, attachingToAnotherWaitsetCleansupAtOriginalWaitset) { WaitSetMock m_waitSet2{&m_condVar}; iox_sub_attach_to_waitset(m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, NULL); EXPECT_EQ(iox_sub_attach_to_waitset(m_sut, &m_waitSet2, SubscriberEvent_HAS_NEW_SAMPLES, 0, NULL), WaitSetResult_SUCCESS); EXPECT_EQ(m_waitSet->size(), 0U); EXPECT_EQ(m_waitSet2.size(), 1U); } TEST_F(iox_sub_test, detachingFromWaitSetWorks) { iox_sub_attach_to_waitset(m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, NULL); iox_sub_detach_event(m_sut, SubscriberEvent_HAS_NEW_SAMPLES); EXPECT_EQ(m_waitSet->size(), 0U); } TEST_F(iox_sub_test, hasNewSamplesTriggersWaitSetWithCorrectTriggerId) { iox_sub_attach_to_waitset(m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 587, NULL); this->Subscribe(&m_portPtr); m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); auto triggerVector = m_waitSet->wait(); ASSERT_EQ(triggerVector.size(), 1U); EXPECT_EQ(triggerVector[0].getTriggerId(), 587U); } TEST_F(iox_sub_test, hasNewSamplesTriggersWaitSetWithCorrectCallback) { iox_sub_attach_to_waitset( m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, iox_sub_test::triggerCallback); this->Subscribe(&m_portPtr); m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); auto triggerVector = m_waitSet->wait(); ASSERT_EQ(triggerVector.size(), 1U); triggerVector[0](); EXPECT_EQ(m_triggerCallbackLatestArgument, m_sut); } TEST_F(iox_sub_test, deinitSubscriberDetachesTriggerFromWaitSet) { iox_sub_attach_to_waitset( m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, iox_sub_test::triggerCallback); iox_sub_deinit(m_sut); EXPECT_EQ(m_waitSet->size(), 0U); m_subscriber.reset(); m_sut = nullptr; } <commit_msg>iox-#14 fix subscriber test take 2<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH, Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iceoryx_binding_c/internal/cpp2c_subscriber.hpp" #include "iceoryx_binding_c/types.h" #include "iceoryx_posh/internal/mepoo/memory_manager.hpp" #include "iceoryx_posh/internal/popo/building_blocks/chunk_queue_popper.hpp" #include "iceoryx_posh/internal/popo/building_blocks/chunk_queue_pusher.hpp" #include "iceoryx_posh/internal/popo/ports/subscriber_port_single_producer.hpp" #include "iceoryx_posh/internal/popo/ports/subscriber_port_user.hpp" #include "iceoryx_posh/mepoo/mepoo_config.hpp" #include "mocks/wait_set_mock.hpp" using namespace iox; using namespace iox::popo; using namespace iox::capro; using namespace iox::mepoo; using namespace iox::cxx; using namespace iox::posix; extern "C" { #include "iceoryx_binding_c/subscriber.h" } #include "test.hpp" using namespace ::testing; class iox_sub_test : public Test { public: const iox::capro::ServiceDescription TEST_SERVICE_DESCRIPTION{"a", "b", "c"}; protected: iox_sub_test() { m_mempoolconf.addMemPool({CHUNK_SIZE, NUM_CHUNKS_IN_POOL}); m_memoryManager.configureMemoryManager(m_mempoolconf, &m_memoryAllocator, &m_memoryAllocator); m_subscriber->m_portData = &m_portPtr; } void SetUp() { m_triggerCallbackLatestArgument = nullptr; } void TearDown() { } void Subscribe(SubscriberPortData* ptr) { uint64_t queueCapacity = MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY; iox_sub_subscribe(m_sut, queueCapacity); SubscriberPortSingleProducer(ptr).tryGetCaProMessage(); iox::capro::CaproMessage caproMessage(iox::capro::CaproMessageType::ACK, TEST_SERVICE_DESCRIPTION); SubscriberPortSingleProducer(ptr).dispatchCaProMessageAndGetPossibleResponse(caproMessage); } static void triggerCallback(iox_sub_t sub) { m_triggerCallbackLatestArgument = sub; } static iox_sub_t m_triggerCallbackLatestArgument; static constexpr size_t MEMORY_SIZE = 1024 * 1024 * 100; uint8_t m_memory[MEMORY_SIZE]; static constexpr uint32_t NUM_CHUNKS_IN_POOL = MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY + 2; static constexpr uint32_t CHUNK_SIZE = 128; Allocator m_memoryAllocator{m_memory, MEMORY_SIZE}; MePooConfig m_mempoolconf; MemoryManager m_memoryManager; iox::cxx::GenericRAII m_uniqueRouDiId{[] { iox::popo::internal::setUniqueRouDiId(0); }, [] { iox::popo::internal::unsetUniqueRouDiId(); }}; iox::popo::SubscriberPortData m_portPtr{ TEST_SERVICE_DESCRIPTION, "myApp", iox::cxx::VariantQueueTypes::SoFi_SingleProducerSingleConsumer}; ChunkQueuePusher<SubscriberPortData::ChunkQueueData_t> m_chunkPusher{&m_portPtr.m_chunkReceiverData}; std::unique_ptr<cpp2c_Subscriber> m_subscriber{new cpp2c_Subscriber}; iox_sub_t m_sut = m_subscriber.get(); ConditionVariableData m_condVar; std::unique_ptr<WaitSetMock> m_waitSet{new WaitSetMock(&m_condVar)}; }; iox_sub_t iox_sub_test::m_triggerCallbackLatestArgument = nullptr; TEST_F(iox_sub_test, initialStateNotSubscribed) { EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_NOT_SUBSCRIBED); } TEST_F(iox_sub_test, offerLeadsToSubscibeRequestedState) { uint64_t queueCapacity = 1u; iox_sub_subscribe(m_sut, queueCapacity); SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage(); EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_SUBSCRIBE_REQUESTED); } TEST_F(iox_sub_test, NACKResponseLeadsToSubscribeWaitForOfferState) { uint64_t queueCapacity = 1u; iox_sub_subscribe(m_sut, queueCapacity); SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage(); iox::capro::CaproMessage caproMessage(iox::capro::CaproMessageType::NACK, TEST_SERVICE_DESCRIPTION); SubscriberPortSingleProducer(&m_portPtr).dispatchCaProMessageAndGetPossibleResponse(caproMessage); EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_WAIT_FOR_OFFER); } TEST_F(iox_sub_test, ACKResponseLeadsToSubscribedState) { uint64_t queueCapacity = 1u; iox_sub_subscribe(m_sut, queueCapacity); SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage(); iox::capro::CaproMessage caproMessage(iox::capro::CaproMessageType::ACK, TEST_SERVICE_DESCRIPTION); SubscriberPortSingleProducer(&m_portPtr).dispatchCaProMessageAndGetPossibleResponse(caproMessage); EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_SUBSCRIBED); } TEST_F(iox_sub_test, UnsubscribeLeadsToUnscribeRequestedState) { uint64_t queueCapacity = 1u; iox_sub_subscribe(m_sut, queueCapacity); SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage(); iox::capro::CaproMessage caproMessage(iox::capro::CaproMessageType::ACK, TEST_SERVICE_DESCRIPTION); SubscriberPortSingleProducer(&m_portPtr).dispatchCaProMessageAndGetPossibleResponse(caproMessage); iox_sub_unsubscribe(m_sut); SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage(); EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_UNSUBSCRIBE_REQUESTED); } TEST_F(iox_sub_test, initialStateNoChunksAvailable) { const void* chunk = nullptr; EXPECT_EQ(iox_sub_get_chunk(m_sut, &chunk), ChunkReceiveResult_NO_CHUNK_RECEIVED); } TEST_F(iox_sub_test, receiveChunkWhenThereIsOne) { this->Subscribe(&m_portPtr); m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); const void* chunk = nullptr; EXPECT_EQ(iox_sub_get_chunk(m_sut, &chunk), ChunkReceiveResult_SUCCESS); } TEST_F(iox_sub_test, receiveChunkWithContent) { this->Subscribe(&m_portPtr); struct data_t { int value; }; auto sharedChunk = m_memoryManager.getChunk(100); static_cast<data_t*>(sharedChunk.getPayload())->value = 1234; m_chunkPusher.tryPush(sharedChunk); const void* chunk = nullptr; ASSERT_EQ(iox_sub_get_chunk(m_sut, &chunk), ChunkReceiveResult_SUCCESS); EXPECT_THAT(static_cast<const data_t*>(chunk)->value, Eq(1234)); } TEST_F(iox_sub_test, receiveChunkWhenToManyChunksAreHold) { this->Subscribe(&m_portPtr); const void* chunk = nullptr; for (uint64_t i = 0; i < MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY + 1; ++i) { m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); iox_sub_get_chunk(m_sut, &chunk); } m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); EXPECT_EQ(iox_sub_get_chunk(m_sut, &chunk), ChunkReceiveResult_TOO_MANY_CHUNKS_HELD_IN_PARALLEL); } TEST_F(iox_sub_test, releaseChunkWorks) { this->Subscribe(&m_portPtr); m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); const void* chunk = nullptr; iox_sub_get_chunk(m_sut, &chunk); EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(1u)); iox_sub_release_chunk(m_sut, chunk); EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(0u)); } TEST_F(iox_sub_test, releaseChunkQueuedChunksWorks) { this->Subscribe(&m_portPtr); for (uint64_t i = 0; i < MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY; ++i) { m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); } EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY)); iox_sub_release_queued_chunks(m_sut); EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(0u)); } TEST_F(iox_sub_test, initialStateHasNewChunksFalse) { EXPECT_FALSE(iox_sub_has_new_chunks(m_sut)); } TEST_F(iox_sub_test, receivingChunkLeadsToHasNewChunksTrue) { this->Subscribe(&m_portPtr); m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); EXPECT_TRUE(iox_sub_has_new_chunks(m_sut)); } TEST_F(iox_sub_test, initialStateHasNoLostChunks) { EXPECT_FALSE(iox_sub_has_lost_chunks(m_sut)); } TEST_F(iox_sub_test, sendingTooMuchLeadsToLostChunks) { this->Subscribe(&m_portPtr); for (uint64_t i = 0; i < DefaultChunkQueueConfig::MAX_QUEUE_CAPACITY + 1; ++i) { m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); } EXPECT_TRUE(iox_sub_has_lost_chunks(m_sut)); } TEST_F(iox_sub_test, attachingToWaitSetWorks) { EXPECT_EQ(iox_sub_attach_to_waitset(m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, NULL), WaitSetResult_SUCCESS); EXPECT_EQ(m_waitSet->size(), 1U); } TEST_F(iox_sub_test, attachingToAnotherWaitsetCleansupAtOriginalWaitset) { WaitSetMock m_waitSet2{&m_condVar}; iox_sub_attach_to_waitset(m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, NULL); EXPECT_EQ(iox_sub_attach_to_waitset(m_sut, &m_waitSet2, SubscriberEvent_HAS_NEW_SAMPLES, 0, NULL), WaitSetResult_SUCCESS); EXPECT_EQ(m_waitSet->size(), 0U); EXPECT_EQ(m_waitSet2.size(), 1U); } TEST_F(iox_sub_test, detachingFromWaitSetWorks) { iox_sub_attach_to_waitset(m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, NULL); iox_sub_detach_event(m_sut, SubscriberEvent_HAS_NEW_SAMPLES); EXPECT_EQ(m_waitSet->size(), 0U); } TEST_F(iox_sub_test, hasNewSamplesTriggersWaitSetWithCorrectTriggerId) { iox_sub_attach_to_waitset(m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 587, NULL); this->Subscribe(&m_portPtr); m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); auto triggerVector = m_waitSet->wait(); ASSERT_EQ(triggerVector.size(), 1U); EXPECT_EQ(triggerVector[0].getTriggerId(), 587U); } TEST_F(iox_sub_test, hasNewSamplesTriggersWaitSetWithCorrectCallback) { iox_sub_attach_to_waitset( m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, iox_sub_test::triggerCallback); this->Subscribe(&m_portPtr); m_chunkPusher.tryPush(m_memoryManager.getChunk(100)); auto triggerVector = m_waitSet->wait(); ASSERT_EQ(triggerVector.size(), 1U); triggerVector[0](); EXPECT_EQ(m_triggerCallbackLatestArgument, m_sut); } TEST_F(iox_sub_test, deinitSubscriberDetachesTriggerFromWaitSet) { // malloc is used since iox_sub_deinit calls the d'tor of cpp2c_Subscriber auto subscriber = new (malloc(sizeof(cpp2c_Subscriber))) cpp2c_Subscriber(); subscriber->m_portData = &m_portPtr; iox_sub_attach_to_waitset( subscriber, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, iox_sub_test::triggerCallback); iox_sub_deinit(subscriber); EXPECT_EQ(m_waitSet->size(), 0U); free(subscriber); } <|endoftext|>
<commit_before>//===--- Errors.cpp - Demangling library error handling ---------*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Provides the demangling library with its own error handling functions. // This is necessary because it isn't always linked with the runtime, so // it can't use the runtime's error handling. // //===----------------------------------------------------------------------===// #include "swift/Demangling/Errors.h" #include <inttypes.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if defined(_WIN32) #include <io.h> #endif #if SWIFT_STDLIB_HAS_ASL #include <asl.h> #elif defined(__ANDROID__) #include <android/log.h> #endif #if SWIFT_HAVE_CRASHREPORTERCLIENT #include <atomic> #include <malloc/malloc.h> #include "swift/Runtime/Atomic.h" #include "CrashReporter.h" #endif // SWIFT_HAVE_CRASHREPORTERCLIENT // -- Declarations ----------------------------------------------------------- static SWIFT_NORETURN void demangleFatal(uint32_t flags, const char *format, va_list val); static void demangleWarn(uint32_t flags, const char *format, va_list val); static int demangle_vasprintf(char **strp, const char *format, va_list val); #if SWIFT_HAVE_CRASHREPORTERCLIENT static int demangle_asprintf(char **strp, const char *format, ...); #endif // -- Crash reporter integration --------------------------------------------- // Report a message to any forthcoming crash log. static void reportOnCrash(uint32_t flags, const char *message) { #if SWIFT_HAVE_CRASHREPORTERCLIENT char *oldMessage = nullptr; char *newMessage = nullptr; oldMessage = std::atomic_load_explicit( (volatile std::atomic<char *> *)&gCRAnnotations.message, SWIFT_MEMORY_ORDER_CONSUME); do { if (newMessage) { free(newMessage); newMessage = nullptr; } if (oldMessage) { demangle_asprintf(&newMessage, "%s%s", oldMessage, message); } else { newMessage = strdup(message); } } while (!std::atomic_compare_exchange_strong_explicit( (volatile std::atomic<char *> *)&gCRAnnotations.message, &oldMessage, newMessage, std::memory_order_release, SWIFT_MEMORY_ORDER_CONSUME)); if (oldMessage && malloc_size(oldMessage)) free(oldMessage); #else // empty #endif // SWIFT_HAVE_CRASHREPORTERCLIENT } // -- Utility functions ------------------------------------------------------ // Report a message to system console and stderr. static void reportNow(uint32_t flags, const char *message) { #if defined(_WIN32) #define STDERR_FILENO 2 _write(STDERR_FILENO, message, strlen(message)); #else fputs(message, stderr); fflush(stderr); #endif #if SWIFT_STDLIB_HAS_ASL asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "%s", message); #elif defined(__ANDROID__) __android_log_print(ANDROID_LOG_FATAL, "SwiftDemangle", "%s", message); #endif } /// Report a fatal error to system console, stderr, and crash logs. /// Does not crash by itself. static void reportError(uint32_t flags, const char *message) { reportNow(flags, message); reportOnCrash(flags, message); } /// Not everything has vasprintf() SWIFT_VFORMAT(2) static int demangle_vasprintf(char **strp, const char *format, va_list args) { va_list args_for_len; va_copy(args_for_len, args); int len = vsnprintf(nullptr, 0, format, args_for_len); va_end(args_for_len); *strp = nullptr; if (len < 0) return -1; size_t bufsiz = len + 1; char *buffer = reinterpret_cast<char *>(malloc(bufsiz)); if (!buffer) return -1; int result = vsnprintf(buffer, bufsiz, format, args); if (result < 0) { free(buffer); return -1; } *strp = buffer; return result; } #if SWIFT_HAVE_CRASHREPORTERCLIENT SWIFT_FORMAT(2,3) static int demangle_asprintf(char **strp, const char *format, ...) { va_list val; va_start(val, format); int ret = demangle_vasprintf(strp, format, val); va_end(val); return ret; } #endif // SWIFT_HAVE_CRASHREPORTERCLIENT // -- Implementation --------------------------------------------------------- static SWIFT_NORETURN void demangleFatal(uint32_t flags, const char *format, va_list val) { char *message; if (demangle_vasprintf(&message, format, val) < 0) { reportError(flags, "unable to format fatal error message"); abort(); } reportError(flags, message); abort(); } static void demangleWarn(uint32_t flags, const char *format, va_list val) { char *message; if (demangle_vasprintf(&message, format, val) < 0) { reportNow(flags, "unable to format warning message"); return; } reportNow(flags, message); free(message); } // -- Public API ------------------------------------------------------------- namespace swift { namespace Demangle { SWIFT_BEGIN_INLINE_NAMESPACE SWIFT_NORETURN void fatal(uint32_t flags, const char *format, ...) { va_list val; va_start(val, format); fatalv(flags, format, val); } void warn(uint32_t flags, const char *format, ...) { va_list val; va_start(val, format); warnv(flags, format, val); va_end(val); } SWIFT_NORETURN void fatalv(uint32_t flags, const char *format, va_list val) { demangleFatal(flags, format, val); } void warnv(uint32_t flags, const char *format, va_list val) { demangleWarn(flags, format, val); } SWIFT_END_INLINE_NAMESPACE } // end namespace Demangle } // end namespace swift <commit_msg>[Demangler] Fix a couple of warnings.<commit_after>//===--- Errors.cpp - Demangling library error handling ---------*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Provides the demangling library with its own error handling functions. // This is necessary because it isn't always linked with the runtime, so // it can't use the runtime's error handling. // //===----------------------------------------------------------------------===// #include "swift/Demangling/Errors.h" #include <inttypes.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if defined(_WIN32) #include <io.h> #endif #if SWIFT_STDLIB_HAS_ASL #include <asl.h> #elif defined(__ANDROID__) #include <android/log.h> #endif #if SWIFT_HAVE_CRASHREPORTERCLIENT #include <atomic> #include <malloc/malloc.h> #include "swift/Runtime/Atomic.h" #include "CrashReporter.h" #endif // SWIFT_HAVE_CRASHREPORTERCLIENT // -- Declarations ----------------------------------------------------------- static SWIFT_NORETURN void demangleFatal(uint32_t flags, const char *format, va_list val); static void demangleWarn(uint32_t flags, const char *format, va_list val); static int demangle_vasprintf(char **strp, const char *format, va_list val); #if SWIFT_HAVE_CRASHREPORTERCLIENT static int demangle_asprintf(char **strp, const char *format, ...); #endif // -- Crash reporter integration --------------------------------------------- // Report a message to any forthcoming crash log. static void reportOnCrash(uint32_t flags, const char *message) { #if SWIFT_HAVE_CRASHREPORTERCLIENT char *oldMessage = nullptr; char *newMessage = nullptr; oldMessage = std::atomic_load_explicit( (volatile std::atomic<char *> *)&gCRAnnotations.message, SWIFT_MEMORY_ORDER_CONSUME); do { if (newMessage) { free(newMessage); newMessage = nullptr; } if (oldMessage) { demangle_asprintf(&newMessage, "%s%s", oldMessage, message); } else { newMessage = strdup(message); } } while (!std::atomic_compare_exchange_strong_explicit( (volatile std::atomic<char *> *)&gCRAnnotations.message, &oldMessage, newMessage, std::memory_order_release, SWIFT_MEMORY_ORDER_CONSUME)); if (oldMessage && malloc_size(oldMessage)) free(oldMessage); #else // empty #endif // SWIFT_HAVE_CRASHREPORTERCLIENT } // -- Utility functions ------------------------------------------------------ // Report a message to system console and stderr. static void reportNow(uint32_t flags, const char *message) { #if defined(_WIN32) #define STDERR_FILENO 2 _write(STDERR_FILENO, message, strlen(message)); #else fputs(message, stderr); fflush(stderr); #endif #if SWIFT_STDLIB_HAS_ASL asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "%s", message); #elif defined(__ANDROID__) __android_log_print(ANDROID_LOG_FATAL, "SwiftDemangle", "%s", message); #endif } /// Report a fatal error to system console, stderr, and crash logs. /// Does not crash by itself. static void reportError(uint32_t flags, const char *message) { reportNow(flags, message); reportOnCrash(flags, message); } /// Not everything has vasprintf() SWIFT_VFORMAT(2) static int demangle_vasprintf(char **strp, const char *format, va_list args) { va_list args_for_len; va_copy(args_for_len, args); int len = vsnprintf(nullptr, 0, format, args_for_len); va_end(args_for_len); *strp = nullptr; if (len < 0) return -1; size_t bufsiz = len + 1; char *buffer = reinterpret_cast<char *>(malloc(bufsiz)); if (!buffer) return -1; int result = vsnprintf(buffer, bufsiz, format, args); if (result < 0) { free(buffer); return -1; } *strp = buffer; return result; } #if SWIFT_HAVE_CRASHREPORTERCLIENT SWIFT_FORMAT(2,3) static int demangle_asprintf(char **strp, const char *format, ...) { va_list val; va_start(val, format); int ret = demangle_vasprintf(strp, format, val); va_end(val); return ret; } #endif // SWIFT_HAVE_CRASHREPORTERCLIENT // -- Implementation --------------------------------------------------------- SWIFT_VFORMAT(2) static SWIFT_NORETURN void demangleFatal(uint32_t flags, const char *format, va_list val) { char *message; if (demangle_vasprintf(&message, format, val) < 0) { reportError(flags, "unable to format fatal error message"); abort(); } reportError(flags, message); abort(); } SWIFT_VFORMAT(2) static void demangleWarn(uint32_t flags, const char *format, va_list val) { char *message; if (demangle_vasprintf(&message, format, val) < 0) { reportNow(flags, "unable to format warning message"); return; } reportNow(flags, message); free(message); } // -- Public API ------------------------------------------------------------- namespace swift { namespace Demangle { SWIFT_BEGIN_INLINE_NAMESPACE SWIFT_FORMAT(2, 3) SWIFT_NORETURN void fatal(uint32_t flags, const char *format, ...) { va_list val; va_start(val, format); fatalv(flags, format, val); } SWIFT_FORMAT(2, 3) void warn(uint32_t flags, const char *format, ...) { va_list val; va_start(val, format); warnv(flags, format, val); va_end(val); } SWIFT_VFORMAT(2) SWIFT_NORETURN void fatalv(uint32_t flags, const char *format, va_list val) { demangleFatal(flags, format, val); } SWIFT_VFORMAT(2) void warnv(uint32_t flags, const char *format, va_list val) { demangleWarn(flags, format, val); } SWIFT_END_INLINE_NAMESPACE } // end namespace Demangle } // end namespace swift <|endoftext|>
<commit_before>//===-- ASTMerge.cpp - AST Merging Frontent Action --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendActions.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTDiagnostic.h" #include "clang/AST/ASTImporter.h" using namespace clang; ASTConsumer *ASTMergeAction::CreateASTConsumer(CompilerInstance &CI, llvm::StringRef InFile) { return AdaptedAction->CreateASTConsumer(CI, InFile); } bool ASTMergeAction::BeginSourceFileAction(CompilerInstance &CI, llvm::StringRef Filename) { // FIXME: This is a hack. We need a better way to communicate the // AST file, compiler instance, and file name than member variables // of FrontendAction. AdaptedAction->setCurrentFile(getCurrentFile(), takeCurrentASTUnit()); AdaptedAction->setCompilerInstance(&CI); return AdaptedAction->BeginSourceFileAction(CI, Filename); } void ASTMergeAction::ExecuteAction() { CompilerInstance &CI = getCompilerInstance(); CI.getDiagnostics().getClient()->BeginSourceFile( CI.getASTContext().getLangOptions()); CI.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &CI.getASTContext()); for (unsigned I = 0, N = ASTFiles.size(); I != N; ++I) { ASTUnit *Unit = ASTUnit::LoadFromPCHFile(ASTFiles[I], CI.getDiagnostics(), false, true); if (!Unit) continue; ASTImporter Importer(CI.getDiagnostics(), CI.getASTContext(), CI.getFileManager(), Unit->getASTContext(), Unit->getFileManager()); TranslationUnitDecl *TU = Unit->getASTContext().getTranslationUnitDecl(); for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end(); D != DEnd; ++D) { // FIXME: We only merge variables whose names start with x and functions // whose names start with 'f'. Why would anyone want anything else? if (VarDecl *VD = dyn_cast<VarDecl>(*D)) { if (VD->getIdentifier() && *VD->getIdentifier()->getNameStart() == 'x') { Decl *Merged = Importer.Import(VD); (void)Merged; } } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) { if (FD->getIdentifier() && *FD->getIdentifier()->getNameStart() == 'f') { Decl *Merged = Importer.Import(FD); (void)Merged; } } } delete Unit; } AdaptedAction->ExecuteAction(); CI.getDiagnostics().getClient()->EndSourceFile(); } void ASTMergeAction::EndSourceFileAction() { return AdaptedAction->EndSourceFileAction(); } ASTMergeAction::ASTMergeAction(FrontendAction *AdaptedAction, std::string *ASTFiles, unsigned NumASTFiles) : AdaptedAction(AdaptedAction), ASTFiles(ASTFiles, ASTFiles + NumASTFiles) { assert(AdaptedAction && "ASTMergeAction needs an action to adapt"); } ASTMergeAction::~ASTMergeAction() { delete AdaptedAction; } bool ASTMergeAction::usesPreprocessorOnly() const { return AdaptedAction->usesPreprocessorOnly(); } bool ASTMergeAction::usesCompleteTranslationUnit() { return AdaptedAction->usesCompleteTranslationUnit(); } bool ASTMergeAction::hasPCHSupport() const { return AdaptedAction->hasPCHSupport(); } bool ASTMergeAction::hasASTSupport() const { return AdaptedAction->hasASTSupport(); } bool ASTMergeAction::hasCodeCompletionSupport() const { return AdaptedAction->hasCodeCompletionSupport(); } <commit_msg>Tell ASTMerge to merge every declaration it sees, rather than cherry-picking those declarations that we know will work.<commit_after>//===-- ASTMerge.cpp - AST Merging Frontent Action --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendActions.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTDiagnostic.h" #include "clang/AST/ASTImporter.h" using namespace clang; ASTConsumer *ASTMergeAction::CreateASTConsumer(CompilerInstance &CI, llvm::StringRef InFile) { return AdaptedAction->CreateASTConsumer(CI, InFile); } bool ASTMergeAction::BeginSourceFileAction(CompilerInstance &CI, llvm::StringRef Filename) { // FIXME: This is a hack. We need a better way to communicate the // AST file, compiler instance, and file name than member variables // of FrontendAction. AdaptedAction->setCurrentFile(getCurrentFile(), takeCurrentASTUnit()); AdaptedAction->setCompilerInstance(&CI); return AdaptedAction->BeginSourceFileAction(CI, Filename); } void ASTMergeAction::ExecuteAction() { CompilerInstance &CI = getCompilerInstance(); CI.getDiagnostics().getClient()->BeginSourceFile( CI.getASTContext().getLangOptions()); CI.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &CI.getASTContext()); for (unsigned I = 0, N = ASTFiles.size(); I != N; ++I) { ASTUnit *Unit = ASTUnit::LoadFromPCHFile(ASTFiles[I], CI.getDiagnostics(), false, true); if (!Unit) continue; ASTImporter Importer(CI.getDiagnostics(), CI.getASTContext(), CI.getFileManager(), Unit->getASTContext(), Unit->getFileManager()); TranslationUnitDecl *TU = Unit->getASTContext().getTranslationUnitDecl(); for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end(); D != DEnd; ++D) { Importer.Import(*D); } delete Unit; } AdaptedAction->ExecuteAction(); CI.getDiagnostics().getClient()->EndSourceFile(); } void ASTMergeAction::EndSourceFileAction() { return AdaptedAction->EndSourceFileAction(); } ASTMergeAction::ASTMergeAction(FrontendAction *AdaptedAction, std::string *ASTFiles, unsigned NumASTFiles) : AdaptedAction(AdaptedAction), ASTFiles(ASTFiles, ASTFiles + NumASTFiles) { assert(AdaptedAction && "ASTMergeAction needs an action to adapt"); } ASTMergeAction::~ASTMergeAction() { delete AdaptedAction; } bool ASTMergeAction::usesPreprocessorOnly() const { return AdaptedAction->usesPreprocessorOnly(); } bool ASTMergeAction::usesCompleteTranslationUnit() { return AdaptedAction->usesCompleteTranslationUnit(); } bool ASTMergeAction::hasPCHSupport() const { return AdaptedAction->hasPCHSupport(); } bool ASTMergeAction::hasASTSupport() const { return AdaptedAction->hasASTSupport(); } bool ASTMergeAction::hasCodeCompletionSupport() const { return AdaptedAction->hasCodeCompletionSupport(); } <|endoftext|>
<commit_before>a544d9a8-2e4f-11e5-97c6-28cfe91dbc4b<commit_msg>a54cd580-2e4f-11e5-853d-28cfe91dbc4b<commit_after>a54cd580-2e4f-11e5-853d-28cfe91dbc4b<|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Interpreter/Value.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Transaction.h" #include "cling/Interpreter/ValuePrinter.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/CanonicalType.h" #include "clang/AST/Type.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Sema.h" #include "llvm/Support/raw_os_ostream.h" #include "llvm/Support/raw_ostream.h" #include <iostream> #include <sstream> namespace { ///\brief The allocation starts with this layout; it is followed by the /// value's object at m_Payload. This class does not inherit from /// llvm::RefCountedBase because deallocation cannot use this type but must /// free the character array. class AllocatedValue { public: typedef void (*DtorFunc_t)(void*); private: ///\brief The reference count - once 0, this object will be deallocated. mutable unsigned m_RefCnt; ///\brief The destructor function. DtorFunc_t m_DtorFunc; ///\brief The size of the allocation (for arrays) unsigned long m_AllocSize; ///\brief The number of elements in the array unsigned long m_NElements; ///\brief The start of the allocation. char m_Payload[1]; static DtorFunc_t PtrToFunc(void* ptr) { union { void* m_Ptr; DtorFunc_t m_Func; }; m_Ptr = ptr; return m_Func; } public: ///\brief Initialize the storage management part of the allocated object. /// The allocator is referencing it, thus initialize m_RefCnt with 1. ///\param [in] dtorFunc - the function to be called before deallocation. AllocatedValue(void* dtorFunc, size_t allocSize, size_t nElements): m_RefCnt(1), m_DtorFunc(PtrToFunc(dtorFunc)), m_AllocSize(allocSize), m_NElements(nElements) {} char* getPayload() { return m_Payload; } static unsigned getPayloadOffset() { static const AllocatedValue Dummy(0,0,0); return Dummy.m_Payload - (const char*)&Dummy; } static AllocatedValue* getFromPayload(void* payload) { return reinterpret_cast<AllocatedValue*>((char*)payload - getPayloadOffset()); } void Retain() { ++m_RefCnt; } ///\brief This object must be allocated as a char array. Deallocate it as /// such. void Release() { assert (m_RefCnt > 0 && "Reference count is already zero."); if (--m_RefCnt == 0) { if (m_DtorFunc) { char* payload = getPayload(); for (size_t el = 0; el < m_NElements; ++el) (*m_DtorFunc)(payload + el * m_AllocSize / m_NElements); } delete [] (char*)this; } } }; } namespace cling { Value::Value(const Value& other): m_Storage(other.m_Storage), m_Type(other.m_Type), m_Interpreter(other.m_Interpreter) { if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Retain(); } Value::Value(Value&& other): m_Storage(other.m_Storage), m_Type(other.m_Type), m_Interpreter(other.m_Interpreter) { // Invalidate other so it will not release. other.m_Type = 0; } Value::Value(clang::QualType clangTy, Interpreter& Interp): m_Type(clangTy.getAsOpaquePtr()), m_Interpreter(&Interp) { if (needsManagedAllocation()) ManagedAllocate(); } Value& Value::operator =(const Value& other) { // Release old value. if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release(); // Retain new one. m_Type = other.m_Type; m_Storage = other.m_Storage; m_Interpreter = other.m_Interpreter; if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Retain(); return *this; } Value& Value::operator =(Value&& other) { // Release old value. if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release(); // Move new one. m_Type = other.m_Type; m_Storage = other.m_Storage; m_Interpreter = other.m_Interpreter; // Invalidate other so it will not release. other.m_Type = 0; return *this; } Value::~Value() { if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release(); } clang::QualType Value::getType() const { return clang::QualType::getFromOpaquePtr(m_Type); } clang::ASTContext& Value::getASTContext() const { return m_Interpreter->getCI()->getASTContext(); } bool Value::isValid() const { return !getType().isNull(); } bool Value::isVoid() const { const clang::ASTContext& Ctx = getASTContext(); return isValid() && Ctx.hasSameType(getType(), Ctx.VoidTy); } unsigned long Value::GetNumberOfElements() const { if (const clang::ConstantArrayType* ArrTy = llvm::dyn_cast<clang::ConstantArrayType>(getType())) { llvm::APInt arrSize(sizeof(unsigned long)*8, 1); do { arrSize *= ArrTy->getSize(); ArrTy = llvm::dyn_cast<clang::ConstantArrayType>(ArrTy->getElementType() .getTypePtr()); } while (ArrTy); return (unsigned long)arrSize.getZExtValue(); } return 1; } Value::EStorageType Value::getStorageType() const { const clang::Type* desugCanon = getType()->getUnqualifiedDesugaredType(); desugCanon = desugCanon->getCanonicalTypeUnqualified()->getTypePtr() ->getUnqualifiedDesugaredType(); if (desugCanon->isSignedIntegerOrEnumerationType()) return kSignedIntegerOrEnumerationType; else if (desugCanon->isUnsignedIntegerOrEnumerationType()) return kUnsignedIntegerOrEnumerationType; else if (desugCanon->isRealFloatingType()) { const clang::BuiltinType* BT = desugCanon->getAs<clang::BuiltinType>(); if (BT->getKind() == clang::BuiltinType::Double) return kDoubleType; else if (BT->getKind() == clang::BuiltinType::Float) return kFloatType; else if (BT->getKind() == clang::BuiltinType::LongDouble) return kLongDoubleType; } else if (desugCanon->isPointerType() || desugCanon->isObjectType() || desugCanon->isReferenceType()) return kPointerType; return kUnsupportedType; } bool Value::needsManagedAllocation() const { if (!isValid()) return false; const clang::Type* UnqDes = getType()->getUnqualifiedDesugaredType(); return UnqDes->isRecordType() || UnqDes->isConstantArrayType() || UnqDes->isMemberPointerType(); } void Value::ManagedAllocate() { void* dtorFunc = 0; clang::QualType DtorType = getType(); // For arrays we destruct the elements. if (const clang::ConstantArrayType* ArrTy = llvm::dyn_cast<clang::ConstantArrayType>(DtorType.getTypePtr())) { DtorType = ArrTy->getElementType(); } if (const clang::RecordType* RTy = DtorType->getAs<clang::RecordType>()) dtorFunc = GetDtorWrapperPtr(RTy->getDecl()); const clang::ASTContext& ctx = getASTContext(); unsigned payloadSize = ctx.getTypeSizeInChars(getType()).getQuantity(); char* alloc = new char[AllocatedValue::getPayloadOffset() + payloadSize]; AllocatedValue* allocVal = new (alloc) AllocatedValue(dtorFunc, payloadSize, GetNumberOfElements()); m_Storage.m_Ptr = allocVal->getPayload(); } void Value::AssertOnUnsupportedTypeCast() const { assert("unsupported type in Value, cannot cast simplistically!" && 0); } /// \brief Get the function address of the wrapper of the destructor. void* Value::GetDtorWrapperPtr(const clang::RecordDecl* RD) const { std::string funcname; { llvm::raw_string_ostream namestr(funcname); namestr << "__cling_StoredValue_Destruct_" << RD; } std::string code("extern \"C\" void "); { clang::QualType RDQT(RD->getTypeForDecl(), 0); std::string typeName = utils::TypeName::GetFullyQualifiedName(RDQT, RD->getASTContext()); std::string dtorName = RD->getNameAsString(); code += funcname + "(void* obj){((" + typeName + "*)obj)->~" + dtorName + "();}"; } return m_Interpreter->compileFunction(funcname, code, true /*ifUniq*/, false /*withAccessControl*/); } void Value::print(llvm::raw_ostream& Out) const { // Try to find user defined printing functions: // cling::printType(const void* const p, TY* const u, const Value& V) and // cling::printValue(const void* const p, TY* const u, const Value& V) using namespace clang; Sema& SemaR = m_Interpreter->getSema(); ASTContext& C = SemaR.getASTContext(); NamespaceDecl* ClingNSD = utils::Lookup::Namespace(&SemaR, "cling"); SourceLocation noLoc; LookupResult R(SemaR, &C.Idents.get("printType"), noLoc, Sema::LookupOrdinaryName, Sema::ForRedeclaration); assert(ClingNSD && "There must be a valid namespace."); { // Could trigger deserialization of decls. cling::Interpreter::PushTransactionRAII RAII(m_Interpreter); SemaR.LookupQualifiedName(R, ClingNSD); // We commit here because the possibly deserialized decls from the lookup // will be needed by evaluate. } QualType ValueTy = this->getType(); std::string ValueTyStr = ValueTy.getAsString(); std::string typeStr; std::string valueStr; if (!R.empty() && ValueTy->isPointerType()) { // There is such a routine call it: std::stringstream printTypeSS; printTypeSS << "cling::printType("; printTypeSS << '(' << ValueTyStr << ')' << this->getPtr() << ','; printTypeSS << '(' << ValueTyStr << ')' << this->getPtr() << ','; printTypeSS <<"(*(cling::Value*)" << this << "));"; Value printTypeV; m_Interpreter->evaluate(printTypeSS.str(), printTypeV); assert(printTypeV.isValid() && "Must return valid value."); typeStr = *(std::string*)printTypeV.getPtr(); // CXXScopeSpec CSS; // Expr* UnresolvedLookup // = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take(); // // Build Arg1: const void* const p // QualType ConstVoidPtrTy = C.VoidPtrTy.withConst(); // Expr* Arg1 // = utils::Synthesize::CStyleCastPtrExpr(SemaR, ConstVoidPtrTy, // (uint64_t)this->getPtr()); // // Build Arg2: TY* const u // Expr* Arg2 // = utils::Synthesize::CStyleCastPtrExpr(SemaR, ValueTy, // (uint64_t)this->getPtr()); // // Build Arg3: const Value& // RecordDecl* ClingValueDecl // = dyn_cast<RecordDecl>(utils::Lookup::Named(SemaR, "Value",ClingNSD)); // assert(ClingValueDecl && "Declaration must be found!"); // QualType ClingValueTy = m_Context->getTypeDeclType(ClingValueDecl); // Expr* Arg3 // = utils::Synthesize::CStyleCastPtrExpr(m_Sema, ClingValueTy, // (uint64_t)this); // llvm::SmallVector<Expr*, 4> CallArgs; // CallArgs.push_back(Arg1); // CallArgs.push_back(Arg2); // CallArgs.push_back(Arg3); // Expr* Call = m_Sema->ActOnCallExpr(/*Scope*/0, UnresolvedLookup, noLoc, // CallArgs, noLoc).take(); } else { llvm::raw_string_ostream o(typeStr); cling::valuePrinterInternal::printType_Default(o, *this); } R.clear(); R.setLookupName(&C.Idents.get("printValue")); { // Could trigger deserialization of decls. cling::Interpreter::PushTransactionRAII RAII(m_Interpreter); SemaR.LookupQualifiedName(R, ClingNSD); // We commit here because the possibly deserialized decls from the lookup // will be needed by evaluate. } if (!R.empty() && ValueTy->isPointerType()) { // There is such a routine call it: std::stringstream printValueSS; printValueSS << "cling::printValue("; printValueSS << '(' << ValueTyStr << ')' << this->getPtr() << ','; printValueSS << '(' << ValueTyStr << ')' << this->getPtr() << ','; printValueSS <<"(*(cling::Value*)" << this << "));"; Value printValueV; m_Interpreter->evaluate(printValueSS.str(), printValueV); assert(printValueV.isValid() && "Must return valid value."); valueStr = *(std::string*)printValueV.getPtr(); } else { llvm::raw_string_ostream o(valueStr); cling::valuePrinterInternal::printValue_Default(o, *this); } // print the type and the value: Out << typeStr + valueStr << "\n"; } void Value::dump() const { // We need stream that doesn't close its file descriptor, thus we are not // using llvm::outs. Keeping file descriptor open we will be able to use // the results in pipes (Savannah #99234). // Alternatively we could use llvm::errs() llvm::OwningPtr<llvm::raw_ostream> Out; Out.reset(new llvm::raw_os_ostream(std::cout)); print(*Out.get()); } } // namespace cling <commit_msg>Add a simple overload candidate selector.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Interpreter/Value.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Transaction.h" #include "cling/Interpreter/ValuePrinter.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/CanonicalType.h" #include "clang/AST/Type.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Sema.h" #include "llvm/Support/raw_os_ostream.h" #include "llvm/Support/raw_ostream.h" #include <iostream> #include <sstream> namespace { ///\brief The allocation starts with this layout; it is followed by the /// value's object at m_Payload. This class does not inherit from /// llvm::RefCountedBase because deallocation cannot use this type but must /// free the character array. class AllocatedValue { public: typedef void (*DtorFunc_t)(void*); private: ///\brief The reference count - once 0, this object will be deallocated. mutable unsigned m_RefCnt; ///\brief The destructor function. DtorFunc_t m_DtorFunc; ///\brief The size of the allocation (for arrays) unsigned long m_AllocSize; ///\brief The number of elements in the array unsigned long m_NElements; ///\brief The start of the allocation. char m_Payload[1]; static DtorFunc_t PtrToFunc(void* ptr) { union { void* m_Ptr; DtorFunc_t m_Func; }; m_Ptr = ptr; return m_Func; } public: ///\brief Initialize the storage management part of the allocated object. /// The allocator is referencing it, thus initialize m_RefCnt with 1. ///\param [in] dtorFunc - the function to be called before deallocation. AllocatedValue(void* dtorFunc, size_t allocSize, size_t nElements): m_RefCnt(1), m_DtorFunc(PtrToFunc(dtorFunc)), m_AllocSize(allocSize), m_NElements(nElements) {} char* getPayload() { return m_Payload; } static unsigned getPayloadOffset() { static const AllocatedValue Dummy(0,0,0); return Dummy.m_Payload - (const char*)&Dummy; } static AllocatedValue* getFromPayload(void* payload) { return reinterpret_cast<AllocatedValue*>((char*)payload - getPayloadOffset()); } void Retain() { ++m_RefCnt; } ///\brief This object must be allocated as a char array. Deallocate it as /// such. void Release() { assert (m_RefCnt > 0 && "Reference count is already zero."); if (--m_RefCnt == 0) { if (m_DtorFunc) { char* payload = getPayload(); for (size_t el = 0; el < m_NElements; ++el) (*m_DtorFunc)(payload + el * m_AllocSize / m_NElements); } delete [] (char*)this; } } }; } namespace cling { Value::Value(const Value& other): m_Storage(other.m_Storage), m_Type(other.m_Type), m_Interpreter(other.m_Interpreter) { if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Retain(); } Value::Value(Value&& other): m_Storage(other.m_Storage), m_Type(other.m_Type), m_Interpreter(other.m_Interpreter) { // Invalidate other so it will not release. other.m_Type = 0; } Value::Value(clang::QualType clangTy, Interpreter& Interp): m_Type(clangTy.getAsOpaquePtr()), m_Interpreter(&Interp) { if (needsManagedAllocation()) ManagedAllocate(); } Value& Value::operator =(const Value& other) { // Release old value. if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release(); // Retain new one. m_Type = other.m_Type; m_Storage = other.m_Storage; m_Interpreter = other.m_Interpreter; if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Retain(); return *this; } Value& Value::operator =(Value&& other) { // Release old value. if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release(); // Move new one. m_Type = other.m_Type; m_Storage = other.m_Storage; m_Interpreter = other.m_Interpreter; // Invalidate other so it will not release. other.m_Type = 0; return *this; } Value::~Value() { if (needsManagedAllocation()) AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release(); } clang::QualType Value::getType() const { return clang::QualType::getFromOpaquePtr(m_Type); } clang::ASTContext& Value::getASTContext() const { return m_Interpreter->getCI()->getASTContext(); } bool Value::isValid() const { return !getType().isNull(); } bool Value::isVoid() const { const clang::ASTContext& Ctx = getASTContext(); return isValid() && Ctx.hasSameType(getType(), Ctx.VoidTy); } unsigned long Value::GetNumberOfElements() const { if (const clang::ConstantArrayType* ArrTy = llvm::dyn_cast<clang::ConstantArrayType>(getType())) { llvm::APInt arrSize(sizeof(unsigned long)*8, 1); do { arrSize *= ArrTy->getSize(); ArrTy = llvm::dyn_cast<clang::ConstantArrayType>(ArrTy->getElementType() .getTypePtr()); } while (ArrTy); return (unsigned long)arrSize.getZExtValue(); } return 1; } Value::EStorageType Value::getStorageType() const { const clang::Type* desugCanon = getType()->getUnqualifiedDesugaredType(); desugCanon = desugCanon->getCanonicalTypeUnqualified()->getTypePtr() ->getUnqualifiedDesugaredType(); if (desugCanon->isSignedIntegerOrEnumerationType()) return kSignedIntegerOrEnumerationType; else if (desugCanon->isUnsignedIntegerOrEnumerationType()) return kUnsignedIntegerOrEnumerationType; else if (desugCanon->isRealFloatingType()) { const clang::BuiltinType* BT = desugCanon->getAs<clang::BuiltinType>(); if (BT->getKind() == clang::BuiltinType::Double) return kDoubleType; else if (BT->getKind() == clang::BuiltinType::Float) return kFloatType; else if (BT->getKind() == clang::BuiltinType::LongDouble) return kLongDoubleType; } else if (desugCanon->isPointerType() || desugCanon->isObjectType() || desugCanon->isReferenceType()) return kPointerType; return kUnsupportedType; } bool Value::needsManagedAllocation() const { if (!isValid()) return false; const clang::Type* UnqDes = getType()->getUnqualifiedDesugaredType(); return UnqDes->isRecordType() || UnqDes->isConstantArrayType() || UnqDes->isMemberPointerType(); } void Value::ManagedAllocate() { void* dtorFunc = 0; clang::QualType DtorType = getType(); // For arrays we destruct the elements. if (const clang::ConstantArrayType* ArrTy = llvm::dyn_cast<clang::ConstantArrayType>(DtorType.getTypePtr())) { DtorType = ArrTy->getElementType(); } if (const clang::RecordType* RTy = DtorType->getAs<clang::RecordType>()) dtorFunc = GetDtorWrapperPtr(RTy->getDecl()); const clang::ASTContext& ctx = getASTContext(); unsigned payloadSize = ctx.getTypeSizeInChars(getType()).getQuantity(); char* alloc = new char[AllocatedValue::getPayloadOffset() + payloadSize]; AllocatedValue* allocVal = new (alloc) AllocatedValue(dtorFunc, payloadSize, GetNumberOfElements()); m_Storage.m_Ptr = allocVal->getPayload(); } void Value::AssertOnUnsupportedTypeCast() const { assert("unsupported type in Value, cannot cast simplistically!" && 0); } /// \brief Get the function address of the wrapper of the destructor. void* Value::GetDtorWrapperPtr(const clang::RecordDecl* RD) const { std::string funcname; { llvm::raw_string_ostream namestr(funcname); namestr << "__cling_StoredValue_Destruct_" << RD; } std::string code("extern \"C\" void "); { clang::QualType RDQT(RD->getTypeForDecl(), 0); std::string typeName = utils::TypeName::GetFullyQualifiedName(RDQT, RD->getASTContext()); std::string dtorName = RD->getNameAsString(); code += funcname + "(void* obj){((" + typeName + "*)obj)->~" + dtorName + "();}"; } return m_Interpreter->compileFunction(funcname, code, true /*ifUniq*/, false /*withAccessControl*/); } void Value::print(llvm::raw_ostream& Out) const { // Try to find user defined printing functions: // cling::printType(const void* const p, TY* const u, const Value& V) and // cling::printValue(const void* const p, TY* const u, const Value& V) using namespace clang; Sema& SemaR = m_Interpreter->getSema(); ASTContext& C = SemaR.getASTContext(); NamespaceDecl* ClingNSD = utils::Lookup::Namespace(&SemaR, "cling"); SourceLocation noLoc; LookupResult R(SemaR, &C.Idents.get("printType"), noLoc, Sema::LookupOrdinaryName, Sema::ForRedeclaration); assert(ClingNSD && "There must be a valid namespace."); { // Could trigger deserialization of decls. cling::Interpreter::PushTransactionRAII RAII(m_Interpreter); SemaR.LookupQualifiedName(R, ClingNSD); // We commit here because the possibly deserialized decls from the lookup // will be needed by evaluate. } QualType ValueTy = this->getType(); std::string ValueTyStr = ValueTy.getAsString(); std::string typeStr; std::string valueStr; bool hasViablePrintTypeCandidate = false; if (!R.empty() && ValueTy->isPointerType()) { // Check if among the candidates there are functions with the same type: const UnresolvedSetImpl& unresolved = R.asUnresolvedSet(); // FIXME: Find a way to use the 'proper' overload checks. for (UnresolvedSetImpl::const_iterator I = unresolved.begin(), E = unresolved.end(); I < E; ++I) { if (FunctionDecl* FD = dyn_cast<FunctionDecl>(*I)) if (C.hasSameType(FD->getParamDecl(0)->getType(), ValueTy)) { hasViablePrintTypeCandidate = true; break; } } } if (hasViablePrintTypeCandidate) { // There is such a routine call it: std::stringstream printTypeSS; printTypeSS << "cling::printType("; printTypeSS << '(' << ValueTyStr << ')' << this->getPtr() << ','; printTypeSS << '(' << ValueTyStr << ')' << this->getPtr() << ','; printTypeSS <<"(*(cling::Value*)" << this << "));"; Value printTypeV; m_Interpreter->evaluate(printTypeSS.str(), printTypeV); assert(printTypeV.isValid() && "Must return valid value."); typeStr = *(std::string*)printTypeV.getPtr(); // CXXScopeSpec CSS; // Expr* UnresolvedLookup // = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take(); // // Build Arg1: const void* const p // QualType ConstVoidPtrTy = C.VoidPtrTy.withConst(); // Expr* Arg1 // = utils::Synthesize::CStyleCastPtrExpr(SemaR, ConstVoidPtrTy, // (uint64_t)this->getPtr()); // // Build Arg2: TY* const u // Expr* Arg2 // = utils::Synthesize::CStyleCastPtrExpr(SemaR, ValueTy, // (uint64_t)this->getPtr()); // // Build Arg3: const Value& // RecordDecl* ClingValueDecl // = dyn_cast<RecordDecl>(utils::Lookup::Named(SemaR, "Value",ClingNSD)); // assert(ClingValueDecl && "Declaration must be found!"); // QualType ClingValueTy = m_Context->getTypeDeclType(ClingValueDecl); // Expr* Arg3 // = utils::Synthesize::CStyleCastPtrExpr(m_Sema, ClingValueTy, // (uint64_t)this); // llvm::SmallVector<Expr*, 4> CallArgs; // CallArgs.push_back(Arg1); // CallArgs.push_back(Arg2); // CallArgs.push_back(Arg3); // Expr* Call = m_Sema->ActOnCallExpr(/*Scope*/0, UnresolvedLookup, noLoc, // CallArgs, noLoc).take(); } else { llvm::raw_string_ostream o(typeStr); cling::valuePrinterInternal::printType_Default(o, *this); } R.clear(); R.setLookupName(&C.Idents.get("printValue")); { // Could trigger deserialization of decls. cling::Interpreter::PushTransactionRAII RAII(m_Interpreter); SemaR.LookupQualifiedName(R, ClingNSD); // We commit here because the possibly deserialized decls from the lookup // will be needed by evaluate. } bool hasViablePrintValueCandidate = false; if (!R.empty() && ValueTy->isPointerType()) { // Check if among the candidates there are functions with the same type: const UnresolvedSetImpl& unresolved = R.asUnresolvedSet(); // FIXME: Find a way to use the 'proper' overload checks. for (UnresolvedSetImpl::const_iterator I = unresolved.begin(), E = unresolved.end(); I < E; ++I) { if (FunctionDecl* FD = dyn_cast<FunctionDecl>(*I)) if (C.hasSameType(FD->getParamDecl(0)->getType(), ValueTy)) { hasViablePrintValueCandidate = true; break; } } } if (hasViablePrintValueCandidate) { // There is such a routine call it: std::stringstream printValueSS; printValueSS << "cling::printValue("; printValueSS << '(' << ValueTyStr << ')' << this->getPtr() << ','; printValueSS << '(' << ValueTyStr << ')' << this->getPtr() << ','; printValueSS <<"(*(cling::Value*)" << this << "));"; Value printValueV; m_Interpreter->evaluate(printValueSS.str(), printValueV); assert(printValueV.isValid() && "Must return valid value."); valueStr = *(std::string*)printValueV.getPtr(); } else { llvm::raw_string_ostream o(valueStr); cling::valuePrinterInternal::printValue_Default(o, *this); } // print the type and the value: Out << typeStr + valueStr << "\n"; } void Value::dump() const { // We need stream that doesn't close its file descriptor, thus we are not // using llvm::outs. Keeping file descriptor open we will be able to use // the results in pipes (Savannah #99234). // Alternatively we could use llvm::errs() llvm::OwningPtr<llvm::raw_ostream> Out; Out.reset(new llvm::raw_os_ostream(std::cout)); print(*Out.get()); } } // namespace cling <|endoftext|>
<commit_before>#ifndef DENSE_ONE_TO_ONE_HOUGH_HH #define DENSE_ONE_TO_ONE_HOUGH_HH #include "openacc.h" #include "vpp/algorithms/Line_tracker_4_sfm/miscellanous/operations.hh" #include <opencv2/highgui.hpp> #include <opencv2/videoio.hpp> #include <vpp/vpp.hh> #include <Eigen/Core> #include <vpp/utils/opencv_bridge.hh> #include <iod/timer.hh> using namespace vpp; using namespace std; using namespace Eigen; using namespace iod; using namespace cv; namespace vpp{ #define Two_PI 2*M_PI std::list<vint2> Hough_Lines_Parallel(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu , image2d<uchar> &out , std::vector<std::list<vint2> > &points50); std::list<vint2> Hough_Lines_Parallel_Kmeans(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max,int rhomax, float& max_of_the_accu , image2d<uchar> &grad_img ); std::list<vint2> Hough_Lines_Parallel(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu , image2d<uchar> &grad_img, std::vector<vint4>& extremites); std::list<vint2> Hough_Lines_Parallel(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu , image2d<uchar> &grad_img); std::list<vint2> Hough_Lines_Parallel_Update_Threshold(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max,int rhomax, float& max_of_the_accu , image2d<uchar> &grad_img , float& grad_threshold , int N); std::list<vint2> Hough_Lines_Parallel_Sparse(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max, int rhomax, float& max_of_the_accu , image2d<uchar> &grad_img , float grad_threshold , int N); std::list<vint2> Hough_Lines_Parallel_Sparse1(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu , image2d<uchar> &grad_img); std::list<vint2> Hough_Lines_Parallel(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max, int rhomax, float& max_of_the_accu , image2d<uchar> &grad_img , float acc_threshold); std::list<vint2> Hough_Lines_Parallel_one(Mat bv, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu , Mat &grad_img); std::list<vint2> Hough_Lines_Parallel_one(image2d<uchar> img, Mat bv, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu , Mat &grad_img , std::vector<LineIterator> list_interest); void Hough_Lines_Sequentiel(image2d<vuchar1> img,int sigma,int nbsigma,std::vector<float>& t_accumulator, int nrows, int ncols); std::list<vint2> Hough_Lines_Parallel_Gradient(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu, image2d<uchar> &grad_img, std::vector<vint4> &points50); std::list<vint2> Hough_Lines_Parallel_Basic(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu); std::priority_queue<vint2> Hough_Lines_Parallel_V3(image2d<vuchar1> img, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu, int threshold, image2d<vuchar3> &cluster_colors , int nb_old); void adap_thresold(std::list<vfloat3> &list_temp , float &threshold_hough , int &calls , int &nb_calls_limits_reached , int rhomax, int T_theta, std::vector<float> t_accumulator); void reduce_number_of_max_local(std::list<vfloat3> &list_temp , float threshold_hough , int rhomax, int T_theta , std::vector<float> t_accumulator); void Hough_Lines_Parallel_Map(image2d<vuchar1> img); } #include "dense_one_to_one_hough.hpp" #endif // DENSE_ONE_TO_ONE_HOUGH_HH <commit_msg>Update dense_one_to_one_hough.hh<commit_after>#pragma once #include "openacc.h" #include "vpp/algorithms/Line_tracker_4_sfm/miscellanous/operations.hh" #include <opencv2/highgui.hpp> #include <opencv2/videoio.hpp> #include <vpp/vpp.hh> #include <Eigen/Core> #include <vpp/utils/opencv_bridge.hh> #include <iod/timer.hh> using namespace vpp; using namespace std; using namespace Eigen; using namespace iod; using namespace cv; namespace vpp{ #define Two_PI 2*M_PI std::list<vint2> Hough_Lines_Parallel(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu , image2d<uchar> &out , std::vector<std::list<vint2> > &points50); std::list<vint2> Hough_Lines_Parallel_Kmeans(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max,int rhomax, float& max_of_the_accu , image2d<uchar> &grad_img ); std::list<vint2> Hough_Lines_Parallel(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu , image2d<uchar> &grad_img, std::vector<vint4>& extremites); std::list<vint2> Hough_Lines_Parallel(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu , image2d<uchar> &grad_img); std::list<vint2> Hough_Lines_Parallel_Update_Threshold(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max,int rhomax, float& max_of_the_accu , image2d<uchar> &grad_img , float& grad_threshold , int N); std::list<vint2> Hough_Lines_Parallel_Sparse(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max, int rhomax, float& max_of_the_accu , image2d<uchar> &grad_img , float grad_threshold , int N); std::list<vint2> Hough_Lines_Parallel_Sparse1(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu , image2d<uchar> &grad_img); std::list<vint2> Hough_Lines_Parallel(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max, int rhomax, float& max_of_the_accu , image2d<uchar> &grad_img , float acc_threshold); std::list<vint2> Hough_Lines_Parallel_one(Mat bv, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu , Mat &grad_img); std::list<vint2> Hough_Lines_Parallel_one(image2d<uchar> img, Mat bv, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu , Mat &grad_img , std::vector<LineIterator> list_interest); void Hough_Lines_Sequentiel(image2d<vuchar1> img,int sigma,int nbsigma,std::vector<float>& t_accumulator, int nrows, int ncols); std::list<vint2> Hough_Lines_Parallel_Gradient(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu, image2d<uchar> &grad_img, std::vector<vint4> &points50); std::list<vint2> Hough_Lines_Parallel_Basic(image2d<uchar> img, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu); std::priority_queue<vint2> Hough_Lines_Parallel_V3(image2d<vuchar1> img, std::vector<float>& t_accumulator, int Theta_max, float& max_of_the_accu, int threshold, image2d<vuchar3> &cluster_colors , int nb_old); void adap_thresold(std::list<vfloat3> &list_temp , float &threshold_hough , int &calls , int &nb_calls_limits_reached , int rhomax, int T_theta, std::vector<float> t_accumulator); void reduce_number_of_max_local(std::list<vfloat3> &list_temp , float threshold_hough , int rhomax, int T_theta , std::vector<float> t_accumulator); void Hough_Lines_Parallel_Map(image2d<vuchar1> img); } #include "dense_one_to_one_hough.hpp" <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl> * Copyright (c) 2011 Giulio Camuffo <giuliocamuffo@gmail.com> * * 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 "uimanagercomponent.h" #include <core/debughelper.h> #include <graphics/item.h> #include <graphics/engine.h> #include <graphics/item.h> #include <graphics/material.h> #include <graphics/mesh.h> #include <graphics/rendertarget.h> #include <graphics/materialinstance.h> #include <engine/gameobject.h> #include <engine/asset.h> #include <QtCore/QMimeData> #include <QtCore/QVariant> #include <QtGui/QMatrix4x4> #include <QtGui/QColor> #include <QtGui/QGraphicsView> #include <QtGui/QGraphicsScene> #include <QtGui/QGraphicsWidget> #include <QtGui/QPixmap> #include <QtOpenGL/QGLFramebufferObject> #include <QtDeclarative/QDeclarativeEngine> #include <QtDeclarative/QDeclarativeExpression> #include <QtDeclarative/QDeclarativeContext> #include <QtDeclarative/qdeclarative.h> #include <QtScript/QScriptValue> #include <QtScript/QScriptEngine> #include <QtScript/QScriptValueIterator> #include <texture.h> #include <game.h> #include "uiasset.h" #include "engineaccess.h" #include "renderablescene.h" REGISTER_OBJECTTYPE( GluonEngine, UiManagerComponent ) using namespace GluonEngine; using namespace GluonGraphics; template <typename Tp> QScriptValue scriptValueFromQObject( QScriptEngine *engine, Tp const& qobject) { return engine->newQObject( qobject ); } template <typename Tp> void scriptValueToQObject(const QScriptValue &value, Tp &qobject) { qobject = qobject_cast<Tp>( value.toQObject() ); } template <typename Tp> int qScriptRegisterQObjectMetaType( QScriptEngine *engine ) { return qScriptRegisterMetaType<Tp>( engine, scriptValueFromQObject, scriptValueToQObject ); } class UiManagerComponent::UiManagerComponentPrivate { public: UiManagerComponentPrivate( UiManagerComponent *component ) : q(component) , scene(0) , ui(0) , updateFunction(0) { } void setupBindings( QScriptEngine* engine ) { //FIXME: this code is duplicated with the scripting conponent. //It should be moved to a common place. engine->importExtension( "jsmoke.qtcore" ); engine->importExtension( "jsmoke.qtgui" ); engine->importExtension( "jsmoke.qtopengl" ); qScriptRegisterQObjectMetaType<GameObject*>( engine ); qScriptRegisterQObjectMetaType<GluonObject*>( engine ); qScriptRegisterQObjectMetaType<Component*>( engine ); qScriptRegisterQObjectMetaType<Asset*>( engine ); qScriptRegisterQObjectMetaType<Scene*>( engine ); qScriptRegisterQObjectMetaType<GameProject*>( engine ); QScriptEngine::QObjectWrapOptions wrapOptions = QScriptEngine::AutoCreateDynamicProperties | QScriptEngine::ExcludeDeleteLater | QScriptEngine::PreferExistingWrapperObject; QScriptEngine::ValueOwnership ownership = QScriptEngine::QtOwnership; QScriptValue object = engine->globalObject(); QScriptValue component = engine->newQObject( q, ownership, wrapOptions ); object.setProperty( "Component", component ); QScriptValue gameObj = engine->newQObject( q->gameObject(), ownership, wrapOptions ); object.setProperty( "GameObject", gameObj ); QScriptValue sceneObj = engine->newQObject( q->gameObject()->scene(), ownership, wrapOptions ); object.setProperty( "Scene", sceneObj ); QScriptValue gameProjectObj = engine->newQObject( GluonEngine::Game::instance()->gameProject(), ownership, wrapOptions ); object.setProperty( "GameProject", gameProjectObj ); QScriptValue game = engine->newQObject( GluonEngine::Game::instance(), ownership, wrapOptions ); object.setProperty( "Game", game ); } UiManagerComponent* q; QPixmap pixmap; QGraphicsView* view; RenderableScene* scene; UiAsset *ui; QSizeF size; Item *item; EngineAccess* engineAccess; QDeclarativeExpression *updateFunction; }; UiManagerComponent::UiManagerComponent( QObject* parent ) : Component( parent ) , d( new UiManagerComponentPrivate( this ) ) { } UiManagerComponent::UiManagerComponent( const UiManagerComponent& other ) : Component( other ) , d( other.d ) { } UiManagerComponent::~UiManagerComponent() { delete d; } QString UiManagerComponent::category() const { return QString( "Graphics Rendering" ); } void UiManagerComponent::initialize() { // d->fbo = GluonGraphics::Engine::instance()->fbo(); // d->pixmap = QPixmap( widget->size() ); // d->pixmap.fill( Qt::transparent ); // d->view->setParent(widget->parentWidget()); // d->view->setAttribute(Qt::WA_TranslucentBackground); // d->view->setAttribute(Qt::WA_NoSystemBackground); // d->view->viewport()->setAttribute(Qt::WA_TranslucentBackground); // d->view->viewport()->setAttribute(Qt::WA_NoSystemBackground); // d->view->setStyleSheet("border: none"); // QPalette p = d->view->viewport()->palette(); // p.setColor(QPalette::Base, Qt::transparent); // d->view->viewport()->setPalette(p); // d->view->setScene(d->scene); // d->view->setSceneRect(QRectF(0,0,1000,1000)); // d->view->resize(widget->size()); // d->view->show(); // d->scene->setBackgroundBrush(Qt::blue); // d->texture = widget->bindTexture(d->pixmap); // widget->update(); // widget->updateGL(); // widget->makeCurrent(); if( !d->scene ) { d->scene = new RenderableScene( this ); d->scene->setSceneRect(QRectF(QPointF(0,0), QSize(1024,768))); } if( d->ui && !d->ui->isLoaded() ) { qmlRegisterType<GluonEngine::GameObject>("org.kde.gluon", 1, 0, "GameObject" ); qmlRegisterInterface<GluonEngine::GameObject>("gameObject"); d->ui->load(); QDeclarativeEngine* engine = d->ui->engine(); d->engineAccess = new EngineAccess(this); engine->rootContext()->setContextProperty( "__engineAccess", d->engineAccess ); //Glorious hack:steal the engine QDeclarativeExpression *expr = new QDeclarativeExpression( engine->rootContext(), d->ui->widget(), "__engineAccess.setEngine( this )" ); expr->evaluate(); delete expr; } if( d->ui && d->ui->isLoaded() ) { d->ui->execute(); QGraphicsWidget* gWidget = d->ui->widget(); if( gWidget ) { d->scene->addItem( gWidget ); d->updateFunction = new QDeclarativeExpression( d->ui->engine()->rootContext(), d->ui->widget(), "update()" ); } } } void UiManagerComponent::setScriptEngine( QScriptValue &value ) { QScriptEngine* engine = value.engine(); QScriptValue originalGlobalObject = engine->globalObject(); QScriptValue newGlobalObject = engine->newObject(); QString eval = QLatin1String( "eval" ); QString version = QLatin1String( "version" ); QScriptValueIterator iter( originalGlobalObject ); QVector<QString> names; QVector<QScriptValue> values; QVector<QScriptValue::PropertyFlags> flags; while ( iter.hasNext() ) { iter.next(); QString name = iter.name(); if ( name == version ) { continue; } if ( name != eval ) { names.append( name ); values.append( iter.value() ); flags.append( iter.flags() | QScriptValue::Undeletable ); } newGlobalObject.setProperty( iter.scriptName(), iter.value() ); } engine->setGlobalObject( newGlobalObject ); d->setupBindings( engine ); delete d->engineAccess; d->ui->engine()->rootContext()->setContextProperty( "__engineAccess", 0 ); } void UiManagerComponent::start() { } void UiManagerComponent::draw( int timeLapse ) { Q_UNUSED( timeLapse ) if( !d->scene || !d->ui || !d->ui->widget() ) { return; } d->scene->renderScene(); } void UiManagerComponent::update( int elapsedMilliseconds ) { if( d->updateFunction ) { d->updateFunction->evaluate(); if( d->updateFunction->hasError() ) { debug( d->updateFunction->error().toString() ); } } } void UiManagerComponent::cleanup() { if( !d->ui ) { return; } QGraphicsWidget* widget = d->ui->widget(); if( d->scene && widget && widget->scene() == d->scene ) { d->scene->removeItem( widget ); } delete d->scene; d->scene = 0; delete d->updateFunction; d->updateFunction = 0; } void UiManagerComponent::setUi(UiAsset* ui) { d->ui = ui; } UiAsset* UiManagerComponent::ui() const { return d->ui; } void UiManagerComponent::setSize( const QSizeF& size ) { d->size = size; } QSizeF UiManagerComponent::size() const { return d->size; } Q_EXPORT_PLUGIN2( gluon_component_uimanager, GluonEngine::UiManagerComponent ); #include "uimanagercomponent.moc" <commit_msg>Cleanings.<commit_after>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl> * Copyright (c) 2011 Giulio Camuffo <giuliocamuffo@gmail.com> * * 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 "uimanagercomponent.h" #include <core/debughelper.h> #include <graphics/item.h> #include <graphics/engine.h> #include <graphics/item.h> #include <graphics/material.h> #include <graphics/mesh.h> #include <graphics/rendertarget.h> #include <graphics/materialinstance.h> #include <engine/gameobject.h> #include <engine/asset.h> #include <QtCore/QMimeData> #include <QtCore/QVariant> #include <QtGui/QMatrix4x4> #include <QtGui/QColor> #include <QtGui/QGraphicsView> #include <QtGui/QGraphicsScene> #include <QtGui/QGraphicsWidget> #include <QtGui/QPixmap> #include <QtOpenGL/QGLFramebufferObject> #include <QtDeclarative/QDeclarativeEngine> #include <QtDeclarative/QDeclarativeExpression> #include <QtDeclarative/QDeclarativeContext> #include <QtDeclarative/qdeclarative.h> #include <QtScript/QScriptValue> #include <QtScript/QScriptEngine> #include <QtScript/QScriptValueIterator> #include <texture.h> #include <game.h> #include "uiasset.h" #include "engineaccess.h" #include "renderablescene.h" REGISTER_OBJECTTYPE( GluonEngine, UiManagerComponent ) using namespace GluonEngine; using namespace GluonGraphics; template <typename Tp> QScriptValue scriptValueFromQObject( QScriptEngine *engine, Tp const& qobject) { return engine->newQObject( qobject ); } template <typename Tp> void scriptValueToQObject(const QScriptValue &value, Tp &qobject) { qobject = qobject_cast<Tp>( value.toQObject() ); } template <typename Tp> int qScriptRegisterQObjectMetaType( QScriptEngine *engine ) { return qScriptRegisterMetaType<Tp>( engine, scriptValueFromQObject, scriptValueToQObject ); } class UiManagerComponent::UiManagerComponentPrivate { public: UiManagerComponentPrivate( UiManagerComponent *component ) : q(component) , scene(0) , ui(0) , updateFunction(0) { } void setupBindings( QScriptEngine* engine ) { //FIXME: this code is duplicated with the scripting conponent. //It should be moved to a common place. engine->importExtension( "jsmoke.qtcore" ); engine->importExtension( "jsmoke.qtgui" ); engine->importExtension( "jsmoke.qtopengl" ); qScriptRegisterQObjectMetaType<GameObject*>( engine ); qScriptRegisterQObjectMetaType<GluonObject*>( engine ); qScriptRegisterQObjectMetaType<Component*>( engine ); qScriptRegisterQObjectMetaType<Asset*>( engine ); qScriptRegisterQObjectMetaType<Scene*>( engine ); qScriptRegisterQObjectMetaType<GameProject*>( engine ); QScriptEngine::QObjectWrapOptions wrapOptions = QScriptEngine::AutoCreateDynamicProperties | QScriptEngine::ExcludeDeleteLater | QScriptEngine::PreferExistingWrapperObject; QScriptEngine::ValueOwnership ownership = QScriptEngine::QtOwnership; QScriptValue object = engine->globalObject(); QScriptValue component = engine->newQObject( q, ownership, wrapOptions ); object.setProperty( "Component", component ); QScriptValue gameObj = engine->newQObject( q->gameObject(), ownership, wrapOptions ); object.setProperty( "GameObject", gameObj ); QScriptValue sceneObj = engine->newQObject( q->gameObject()->scene(), ownership, wrapOptions ); object.setProperty( "Scene", sceneObj ); QScriptValue gameProjectObj = engine->newQObject( GluonEngine::Game::instance()->gameProject(), ownership, wrapOptions ); object.setProperty( "GameProject", gameProjectObj ); QScriptValue game = engine->newQObject( GluonEngine::Game::instance(), ownership, wrapOptions ); object.setProperty( "Game", game ); } UiManagerComponent* q; RenderableScene* scene; UiAsset *ui; QSizeF size; Item *item; EngineAccess* engineAccess; QDeclarativeExpression *updateFunction; }; UiManagerComponent::UiManagerComponent( QObject* parent ) : Component( parent ) , d( new UiManagerComponentPrivate( this ) ) { } UiManagerComponent::UiManagerComponent( const UiManagerComponent& other ) : Component( other ) , d( other.d ) { } UiManagerComponent::~UiManagerComponent() { delete d; } QString UiManagerComponent::category() const { return QString( "Graphics Rendering" ); } void UiManagerComponent::initialize() { if( !d->scene ) { d->scene = new RenderableScene( this ); d->scene->setSceneRect(QRectF(QPointF(0,0), QSize(1024,768))); } if( d->ui && !d->ui->isLoaded() ) { qmlRegisterType<GluonEngine::GameObject>("org.kde.gluon", 1, 0, "GameObject" ); qmlRegisterInterface<GluonEngine::GameObject>("gameObject"); d->ui->load(); QDeclarativeEngine* engine = d->ui->engine(); d->engineAccess = new EngineAccess(this); engine->rootContext()->setContextProperty( "__engineAccess", d->engineAccess ); //Glorious hack:steal the engine QDeclarativeExpression *expr = new QDeclarativeExpression( engine->rootContext(), d->ui->widget(), "__engineAccess.setEngine( this )" ); expr->evaluate(); delete expr; } if( d->ui && d->ui->isLoaded() ) { d->ui->execute(); QGraphicsWidget* gWidget = d->ui->widget(); if( gWidget ) { d->scene->addItem( gWidget ); d->updateFunction = new QDeclarativeExpression( d->ui->engine()->rootContext(), d->ui->widget(), "update()" ); } } } void UiManagerComponent::setScriptEngine( QScriptValue &value ) { QScriptEngine* engine = value.engine(); QScriptValue originalGlobalObject = engine->globalObject(); QScriptValue newGlobalObject = engine->newObject(); QString eval = QLatin1String( "eval" ); QString version = QLatin1String( "version" ); QScriptValueIterator iter( originalGlobalObject ); QVector<QString> names; QVector<QScriptValue> values; QVector<QScriptValue::PropertyFlags> flags; while ( iter.hasNext() ) { iter.next(); QString name = iter.name(); if ( name == version ) { continue; } if ( name != eval ) { names.append( name ); values.append( iter.value() ); flags.append( iter.flags() | QScriptValue::Undeletable ); } newGlobalObject.setProperty( iter.scriptName(), iter.value() ); } engine->setGlobalObject( newGlobalObject ); d->setupBindings( engine ); delete d->engineAccess; d->ui->engine()->rootContext()->setContextProperty( "__engineAccess", 0 ); } void UiManagerComponent::start() { } void UiManagerComponent::draw( int timeLapse ) { Q_UNUSED( timeLapse ) if( !d->scene || !d->ui || !d->ui->widget() ) { return; } d->scene->renderScene(); } void UiManagerComponent::update( int elapsedMilliseconds ) { if( d->updateFunction ) { d->updateFunction->evaluate(); if( d->updateFunction->hasError() ) { debug( d->updateFunction->error().toString() ); } } } void UiManagerComponent::cleanup() { if( !d->ui ) { return; } QGraphicsWidget* widget = d->ui->widget(); if( d->scene && widget && widget->scene() == d->scene ) { d->scene->removeItem( widget ); } delete d->scene; d->scene = 0; delete d->updateFunction; d->updateFunction = 0; } void UiManagerComponent::setUi(UiAsset* ui) { d->ui = ui; } UiAsset* UiManagerComponent::ui() const { return d->ui; } void UiManagerComponent::setSize( const QSizeF& size ) { d->size = size; } QSizeF UiManagerComponent::size() const { return d->size; } Q_EXPORT_PLUGIN2( gluon_component_uimanager, GluonEngine::UiManagerComponent ); #include "uimanagercomponent.moc" <|endoftext|>
<commit_before>/** * \file */ #pragma once #include <rleahylib/rleahylib.hpp> #include <traits.hpp> #include <cstddef> #include <new> #include <type_traits> #include <utility> namespace MCPP { /** * \cond */ namespace VariantImpl { template <typename...> class MaxAlignOfImpl { }; template <> class MaxAlignOfImpl<> { public: constexpr static Word Value=0; }; template <typename T, typename... Args> class MaxAlignOfImpl<T,Args...> { private: constexpr static Word next=MaxAlignOfImpl<Args...>::Value; public: constexpr static Word Value=(alignof(T)>next) ? alignof(T) : next; }; template <typename...> class MaxSizeOfImpl { }; template <> class MaxSizeOfImpl<> { public: constexpr static Word Value=0; }; template <typename T, typename... Args> class MaxSizeOfImpl<T,Args...> { private: constexpr static Word next=MaxSizeOfImpl<Args...>::Value; public: constexpr static Word Value=(sizeof(T)>next) ? sizeof(T) : next; }; template <Word, typename, typename...> class FindTypeImpl { }; template <Word i, typename T> class FindTypeImpl<i,T> { public: constexpr static Word Value=i; }; template <Word i, typename T, typename Curr, typename... Args> class FindTypeImpl<i,T,Curr,Args...> { public: constexpr static Word Value=std::is_same< typename std::decay<T>::type, typename std::decay<Curr>::type >::value ? i : FindTypeImpl<i+1,T,Args...>::Value; }; template <typename...> class NoThrowCopyableImpl { }; template <typename T, typename... Args> class NoThrowCopyableImpl<T,Args...> { public: constexpr static bool Value=std::is_nothrow_copy_constructible<T>::value ? NoThrowCopyableImpl<Args...>::Value : false; }; template <> class NoThrowCopyableImpl<> { public: constexpr static bool Value=true; }; template <typename...> class NoThrowMovableImpl { }; template <typename T, typename... Args> class NoThrowMovableImpl<T,Args...> { public: constexpr static bool Value=std::is_nothrow_move_constructible<T>::value ? NoThrowMovableImpl<Args...>::Value : false; }; template <> class NoThrowMovableImpl<> { public: constexpr static bool Value=true; }; template <typename... Args> class VariantInfo { public: template <Word i> class Types { public: typedef typename std::decay<typename GetType<i,Args...>::Type>::type Type; }; template <typename T> class FindType { public: constexpr static Word Value=FindTypeImpl<0,T,Args...>::Value; }; constexpr static Word MaxAlignOf=MaxAlignOfImpl<Args...>::Value; constexpr static Word MaxSizeOf=MaxSizeOfImpl<Args...>::Value; constexpr static bool NoThrowCopyable=NoThrowCopyableImpl<Args...>::Value; constexpr static bool NoThrowMovable=NoThrowMovableImpl<Args...>::Value; }; } /** * \endcond */ class BadVariantOperation : public std::exception { public: __attribute__((noreturn)) static void Raise () { throw BadVariantOperation(); } }; template <typename... Args> class Variant { private: typedef VariantImpl::VariantInfo<Args...> info; bool engaged; Word active; alignas( max_align_t //info::MaxAlignOf ) Byte buffer [info::MaxSizeOf]; template <typename T> T * get_ptr () noexcept { return reinterpret_cast<T *>( reinterpret_cast<void *>( buffer ) ); } template <typename T> const T * get_ptr () const noexcept { return reinterpret_cast<const T *>( reinterpret_cast<const void *>( buffer ) ); } template <Word i> typename std::enable_if< i>=sizeof...(Args) >::type destroy_impl () const noexcept { } template <Word i> typename std::enable_if< i<sizeof...(Args) >::type destroy_impl () noexcept { typedef typename info::template Types<i>::Type type; if (active==i) get_ptr<type>()->~type(); else destroy_impl<i+1>(); } void destroy () noexcept { if (engaged) { destroy_impl<0>(); engaged=false; } } template <typename T> typename std::enable_if< !std::is_same< typename std::decay<T>::type, Variant >::value >::type construct (T && item) noexcept( std::is_nothrow_constructible< typename std::decay<T>::type, T >::value ) { constexpr Word index=info::template FindType<T>::Value; static_assert( index!=sizeof...(Args), "Variant does not contain that type" ); new (buffer) typename std::decay<T>::type (std::forward<T>(item)); engaged=true; active=index; } template <Word i> typename std::enable_if< i>=sizeof...(Args) >::type copy_impl (const Variant &) const noexcept { } template <Word i> typename std::enable_if< std::is_copy_constructible<typename info::template Types<i>::Type>::value >::type copy_impl_impl (const Variant & other) noexcept( std::is_nothrow_copy_constructible<typename info::template Types<i>::Type>::value ) { typedef typename info::template Types<i>::Type type; new (buffer) type (*other.get_ptr<type>()); engaged=true; active=i; } template <Word i> typename std::enable_if< !std::is_copy_constructible<typename info::template Types<i>::Type>::value >::type copy_impl_impl (const Variant &) { BadVariantOperation::Raise(); } template <Word i> typename std::enable_if< i<sizeof...(Args) >::type copy_impl (const Variant & other) noexcept ( info::NoThrowCopyable ) { if (i==other.active) copy_impl_impl<i>(other); else copy_impl<i+1>(other); } template <Word i> typename std::enable_if< i>=sizeof...(Args) >::type move_impl (const Variant &) const noexcept { } template <Word i> typename std::enable_if< std::is_move_constructible<typename info::template Types<i>::Type>::value >::type move_impl_impl (Variant && other) noexcept( std::is_nothrow_move_constructible<typename info::template Types<i>::Type>::value ) { typedef typename info::template Types<i>::Type type; new (buffer) type (std::move(*other.get_ptr<type>())); engaged=true; active=i; } template <Word i> typename std::enable_if< !std::is_move_constructible<typename info::template Types<i>::Type>::value >::type move_impl_impl (const Variant &) { BadVariantOperation::Raise(); } template <Word i> typename std::enable_if< i<sizeof...(Args) >::type move_impl (Variant && other) noexcept( info::NoThrowMovable ) { if (i==other.active) move_impl_impl<i>(std::move(other)); else move_impl<i+1>(std::move(other)); } void construct (const Variant & other) noexcept( info::NoThrowCopyable ) { if (other.engaged) copy_impl<0>(other); } void construct (Variant && other) noexcept( info::NoThrowMovable ) { if (other.engaged) { move_impl<0>(std::move(other)); other.destroy(); } } template <typename T> void assign_impl (T && item) noexcept( info::NoThrowMovable && info::NoThrowCopyable ) { destroy(); construct(std::forward<T>(item)); } template <typename T> typename std::enable_if< std::is_same< typename std::decay<T>::type, Variant >::value >::type assign (T && item) noexcept( info::NoThrowMovable && info::NoThrowCopyable ) { if (reinterpret_cast<const void *>(&item)!=this) assign_impl(std::forward<T>(item)); } template <typename T> typename std::enable_if< !std::is_same< typename std::decay<T>::type, Variant >::value >::type assign (T && item) noexcept( info::NoThrowMovable && info::NoThrowCopyable ) { assign_impl(std::forward<T>(item)); } public: Variant () noexcept : engaged(false) { } Variant (Variant && other) noexcept( info::NoThrowMovable ) : engaged(false) { construct(std::move(other)); } Variant (const Variant & other) noexcept( info::NoThrowCopyable ) : engaged(false) { construct(other); } template <typename T> Variant (T && item) noexcept( info::NoThrowMovable && info::NoThrowCopyable ) : engaged(false) { construct(std::forward<T>(item)); } template <typename T> Variant & operator = (T && item) noexcept( info::NoThrowMovable && info::NoThrowCopyable ) { assign(std::forward<T>(item)); return *this; } template <typename T, typename... EmplaceArgs> typename std::enable_if< info::template FindType<T>::Value!=sizeof...(Args) >::type Construct (EmplaceArgs &&... args) noexcept( std::is_nothrow_constructible< T, EmplaceArgs... >::value ) { destroy(); new (buffer) T (std::forward<EmplaceArgs>(args)...); engaged=true; active=info::template FindType<T>::Value; } ~Variant () noexcept { destroy(); } void Destroy () noexcept { destroy(); } bool IsNull () const noexcept { return !engaged; } template <typename T> bool Is () const noexcept { return engaged && (active==info::template FindType<T>::Value); } template <typename T> T & Get () noexcept { return *get_ptr<T>(); } template <typename T> const T & Get () const noexcept { return *get_ptr<T>(); } }; } <commit_msg>Variant Documentation<commit_after>/** * \file */ #pragma once #include <rleahylib/rleahylib.hpp> #include <traits.hpp> #include <cstddef> #include <new> #include <type_traits> #include <utility> namespace MCPP { /** * \cond */ namespace VariantImpl { template <typename...> class MaxAlignOfImpl { }; template <> class MaxAlignOfImpl<> { public: constexpr static Word Value=0; }; template <typename T, typename... Args> class MaxAlignOfImpl<T,Args...> { private: constexpr static Word next=MaxAlignOfImpl<Args...>::Value; public: constexpr static Word Value=(alignof(T)>next) ? alignof(T) : next; }; template <typename...> class MaxSizeOfImpl { }; template <> class MaxSizeOfImpl<> { public: constexpr static Word Value=0; }; template <typename T, typename... Args> class MaxSizeOfImpl<T,Args...> { private: constexpr static Word next=MaxSizeOfImpl<Args...>::Value; public: constexpr static Word Value=(sizeof(T)>next) ? sizeof(T) : next; }; template <Word, typename, typename...> class FindTypeImpl { }; template <Word i, typename T> class FindTypeImpl<i,T> { public: constexpr static Word Value=i; }; template <Word i, typename T, typename Curr, typename... Args> class FindTypeImpl<i,T,Curr,Args...> { public: constexpr static Word Value=std::is_same< typename std::decay<T>::type, typename std::decay<Curr>::type >::value ? i : FindTypeImpl<i+1,T,Args...>::Value; }; template <typename...> class NoThrowCopyableImpl { }; template <typename T, typename... Args> class NoThrowCopyableImpl<T,Args...> { public: constexpr static bool Value=std::is_nothrow_copy_constructible<T>::value ? NoThrowCopyableImpl<Args...>::Value : false; }; template <> class NoThrowCopyableImpl<> { public: constexpr static bool Value=true; }; template <typename...> class NoThrowMovableImpl { }; template <typename T, typename... Args> class NoThrowMovableImpl<T,Args...> { public: constexpr static bool Value=std::is_nothrow_move_constructible<T>::value ? NoThrowMovableImpl<Args...>::Value : false; }; template <> class NoThrowMovableImpl<> { public: constexpr static bool Value=true; }; template <typename... Args> class VariantInfo { public: template <Word i> class Types { public: typedef typename std::decay<typename GetType<i,Args...>::Type>::type Type; }; template <typename T> class FindType { public: constexpr static Word Value=FindTypeImpl<0,T,Args...>::Value; }; constexpr static Word MaxAlignOf=MaxAlignOfImpl<Args...>::Value; constexpr static Word MaxSizeOf=MaxSizeOfImpl<Args...>::Value; constexpr static bool NoThrowCopyable=NoThrowCopyableImpl<Args...>::Value; constexpr static bool NoThrowMovable=NoThrowMovableImpl<Args...>::Value; }; } /** * \endcond */ /** * Thrown when an illegal operation * is undertaken on a Variant. */ class BadVariantOperation : public std::exception { public: /** * \cond */ __attribute__((noreturn)) static void Raise () { throw BadVariantOperation(); } /** * \endcond */ }; /** * An object which may be imbued with * any one of a number of types. * * This object does not use or allocate * heap memory for internal storage * of stored objects, rather it contains * an internal buffer with the necessary * size and alignment to contain any * of its possible types. */ template <typename... Args> class Variant { private: typedef VariantImpl::VariantInfo<Args...> info; bool engaged; Word active; alignas( max_align_t //info::MaxAlignOf ) Byte buffer [info::MaxSizeOf]; template <typename T> T * get_ptr () noexcept { return reinterpret_cast<T *>( reinterpret_cast<void *>( buffer ) ); } template <typename T> const T * get_ptr () const noexcept { return reinterpret_cast<const T *>( reinterpret_cast<const void *>( buffer ) ); } template <Word i> typename std::enable_if< i>=sizeof...(Args) >::type destroy_impl () const noexcept { } template <Word i> typename std::enable_if< i<sizeof...(Args) >::type destroy_impl () noexcept { typedef typename info::template Types<i>::Type type; if (active==i) get_ptr<type>()->~type(); else destroy_impl<i+1>(); } void destroy () noexcept { if (engaged) { destroy_impl<0>(); engaged=false; } } template <typename T> typename std::enable_if< !std::is_same< typename std::decay<T>::type, Variant >::value >::type construct (T && item) noexcept( std::is_nothrow_constructible< typename std::decay<T>::type, T >::value ) { constexpr Word index=info::template FindType<T>::Value; static_assert( index!=sizeof...(Args), "Variant does not contain that type" ); new (buffer) typename std::decay<T>::type (std::forward<T>(item)); engaged=true; active=index; } template <Word i> typename std::enable_if< i>=sizeof...(Args) >::type copy_impl (const Variant &) const noexcept { } template <Word i> typename std::enable_if< std::is_copy_constructible<typename info::template Types<i>::Type>::value >::type copy_impl_impl (const Variant & other) noexcept( std::is_nothrow_copy_constructible<typename info::template Types<i>::Type>::value ) { typedef typename info::template Types<i>::Type type; new (buffer) type (*other.get_ptr<type>()); engaged=true; active=i; } template <Word i> typename std::enable_if< !std::is_copy_constructible<typename info::template Types<i>::Type>::value >::type copy_impl_impl (const Variant &) { BadVariantOperation::Raise(); } template <Word i> typename std::enable_if< i<sizeof...(Args) >::type copy_impl (const Variant & other) noexcept ( info::NoThrowCopyable ) { if (i==other.active) copy_impl_impl<i>(other); else copy_impl<i+1>(other); } template <Word i> typename std::enable_if< i>=sizeof...(Args) >::type move_impl (const Variant &) const noexcept { } template <Word i> typename std::enable_if< std::is_move_constructible<typename info::template Types<i>::Type>::value >::type move_impl_impl (Variant && other) noexcept( std::is_nothrow_move_constructible<typename info::template Types<i>::Type>::value ) { typedef typename info::template Types<i>::Type type; new (buffer) type (std::move(*other.get_ptr<type>())); engaged=true; active=i; } template <Word i> typename std::enable_if< !std::is_move_constructible<typename info::template Types<i>::Type>::value >::type move_impl_impl (const Variant &) { BadVariantOperation::Raise(); } template <Word i> typename std::enable_if< i<sizeof...(Args) >::type move_impl (Variant && other) noexcept( info::NoThrowMovable ) { if (i==other.active) move_impl_impl<i>(std::move(other)); else move_impl<i+1>(std::move(other)); } void construct (const Variant & other) noexcept( info::NoThrowCopyable ) { if (other.engaged) copy_impl<0>(other); } void construct (Variant && other) noexcept( info::NoThrowMovable ) { if (other.engaged) { move_impl<0>(std::move(other)); other.destroy(); } } template <typename T> void assign_impl (T && item) noexcept( info::NoThrowMovable && info::NoThrowCopyable ) { destroy(); construct(std::forward<T>(item)); } template <typename T> typename std::enable_if< std::is_same< typename std::decay<T>::type, Variant >::value >::type assign (T && item) noexcept( info::NoThrowMovable && info::NoThrowCopyable ) { if (reinterpret_cast<const void *>(&item)!=this) assign_impl(std::forward<T>(item)); } template <typename T> typename std::enable_if< !std::is_same< typename std::decay<T>::type, Variant >::value >::type assign (T && item) noexcept( info::NoThrowMovable && info::NoThrowCopyable ) { assign_impl(std::forward<T>(item)); } public: /** * Creates an empty Variant. */ Variant () noexcept : engaged(false) { } /** * Creates a variant by moving another * Variant. * * \except BadVariantOperation * Thrown if \em other is currently * of a type which cannot be moved. * * \param [in] other * The Variant to move. */ Variant (Variant && other) noexcept( info::NoThrowMovable ) : engaged(false) { construct(std::move(other)); } /** * Creates a variant by copying another * Variant. * * \except BadVariantOperation * Thrown if \em other is currently * of a type which cannot be copied. * * \param [in] other * The Variant to copy. */ Variant (const Variant & other) noexcept( info::NoThrowCopyable ) : engaged(false) { construct(other); } /** * Creates a variant by imbuing it with a * certain object of a type which it may * contain. * * \param [in] item * The object to create this Variant from. */ template <typename T> Variant (T && item) noexcept( info::NoThrowMovable && info::NoThrowCopyable ) : engaged(false) { construct(std::forward<T>(item)); } /** * Assigns an item or another Variant to * this object. * * \except BadVariantOperation * Thrown if \em item is a Variant, and * the object within that Variant cannot * be copied or moved (as applicable). * * \param [in] item * The item to assign to this Variant. * * \return * A reference to this Variant. */ template <typename T> Variant & operator = (T && item) noexcept( info::NoThrowMovable && info::NoThrowCopyable ) { assign(std::forward<T>(item)); return *this; } template <typename T, typename... EmplaceArgs> typename std::enable_if< info::template FindType<T>::Value!=sizeof...(Args) >::type Construct (EmplaceArgs &&... args) noexcept( std::is_nothrow_constructible< T, EmplaceArgs... >::value ) { destroy(); new (buffer) T (std::forward<EmplaceArgs>(args)...); engaged=true; active=info::template FindType<T>::Value; } /** * Destroys this Variant and any object * contained within. */ ~Variant () noexcept { destroy(); } /** * Destroys the object within this Variant. */ void Destroy () noexcept { destroy(); } /** * Determines whether or not this Variant * currently contains an object. * * \return * \em true if this Variant does not * contain an object, \em false otherwise. */ bool IsNull () const noexcept { return !engaged; } /** * Determines whether this Variant currently * contains an object of type \em T. * * \tparam T * The type-in-question. * * \return * \em true if this Variant contains an * object of type \em T, \em false * otherwise. */ template <typename T> bool Is () const noexcept { return engaged && (active==info::template FindType<T>::Value); } /** * Returns the zero-relative index of the * type this Variant currently contains. * * If this Variant is empty, the behaviour * of this function is undefined. * * \return * The zero-relative index of the type * this Variant currently contains. */ Word Type () const noexcept { return active; } /** * Gets a reference to the object contained * within the variant. * * If the Variant is empty, or does not contain * an object of type \em T, the behaviour of * this function is undefined. * * \return * A reference to the object stored within * this Variant. */ template <typename T> T & Get () noexcept { return *get_ptr<T>(); } /** * Gets a reference to the object contained * within the variant. * * If the Variant is empty, or does not contain * an object of type \em T, the behaviour of * this function is undefined. * * \return * A reference to the object stored within * this Variant. */ template <typename T> const T & Get () const noexcept { return *get_ptr<T>(); } }; } <|endoftext|>
<commit_before>#pragma once #include "depthai-shared/common/ProcessorType.hpp" #include "depthai-shared/common/optional.hpp" #include "depthai-shared/properties/Properties.hpp" namespace dai { /** * Specify ScriptProperties options such as script uri, script name, ... */ struct ScriptProperties : PropertiesSerializable<Properties, ScriptProperties> { /** * Uri which points to actual script */ std::string scriptUri = ""; /** * Name of script */ std::string scriptName = "<script>"; /** * Which processor should execute the script */ ProcessorType processor = ProcessorType::LEON_MSS; }; DEPTHAI_SERIALIZE_EXT(ScriptProperties, scriptUri, scriptName, processor); } // namespace dai <commit_msg>Change default CPU to CSS<commit_after>#pragma once #include "depthai-shared/common/ProcessorType.hpp" #include "depthai-shared/common/optional.hpp" #include "depthai-shared/properties/Properties.hpp" namespace dai { /** * Specify ScriptProperties options such as script uri, script name, ... */ struct ScriptProperties : PropertiesSerializable<Properties, ScriptProperties> { /** * Uri which points to actual script */ std::string scriptUri = ""; /** * Name of script */ std::string scriptName = "<script>"; /** * Which processor should execute the script */ ProcessorType processor = ProcessorType::LEON_CSS; }; DEPTHAI_SERIALIZE_EXT(ScriptProperties, scriptUri, scriptName, processor); } // namespace dai <|endoftext|>
<commit_before>/** * \file * \brief SdMmcCardSpiBased class header * * \author Copyright (C) 2018-2019 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_DEVICES_MEMORY_SDMMCCARDSPIBASED_HPP_ #define INCLUDE_DISTORTOS_DEVICES_MEMORY_SDMMCCARDSPIBASED_HPP_ #include "distortos/devices/communication/SpiDevice.hpp" #include "distortos/devices/memory/BlockDevice.hpp" namespace distortos { namespace devices { /** * SdMmcCardSpiBased class is a SD or MMC card connected via SPI. * * \ingroup devices */ class SdMmcCardSpiBased : public BlockDevice { public: /// type of card connected via SPI enum class Type : uint8_t { /// unknown type unknown, /// MMC card mmc, /// SD version 1.0 card sdVersion1, /// SD version 2.0 card sdVersion2, }; /// size of block, bytes constexpr static size_t blockSize {512}; /** * \brief SdMmcCardSpiBased's constructor * * \param [in] spiMaster is a reference to SPI master to which this SD or MMC card is connected * \param [in] slaveSelectPin is a reference to slave select pin of this SD or MMC card * \param [in] clockFrequency is the desired clock frequency of SD or MMC card, Hz, default - 5 MHz */ constexpr SdMmcCardSpiBased(SpiMaster& spiMaster, OutputPin& slaveSelectPin, const uint32_t clockFrequency = 5000000) : spiDevice_{spiMaster, slaveSelectPin}, blocksCount_{}, auSize_{}, clockFrequency_{clockFrequency}, eraseTimeoutMs_{}, readTimeoutMs_{}, writeTimeoutMs_{}, blockAddressing_{}, type_{} { } /** * \brief SdMmcCardSpiBased's destructor */ ~SdMmcCardSpiBased() override; /** * \brief Closes SD or MMC card connected via SPI. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - error codes returned by SpiDevice::close(); */ int close() override; /** * \brief Erases blocks on a SD or MMC card connected via SPI. * * \warning This function must not be called from interrupt context! * * \param [in] address is the address of range that will be erased, must be a multiple of block size * \param [in] size is the size of erased range, bytes, must be a multiple of block size * * \return 0 on success, error code otherwise: * - EBADF - the device is not opened; * - EINVAL - \a address and/or \a size are not valid; * - ENOSPC - selected range is greater than size of device; * - error codes returned by executeCmd32(); * - error codes returned by executeCmd33(); * - error codes returned by executeCmd38(); * - error codes returned by SpiMasterProxy::configure(); */ int erase(uint64_t address, uint64_t size) override; /** * \return block size, bytes */ size_t getBlockSize() const override; /** * \return size of SD or MMC card connected via SPI, bytes */ uint64_t getSize() const override; /** * \brief Locks the device for exclusive use by current thread. * * When the object is locked, any call to any member function from other thread will be blocked until the object is * unlocked. Locking is optional, but may be useful when more than one transaction must be done atomically. * * \note Locks are recursive. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - error codes returned by SpiDevice::lock(); */ int lock() override; /** * \brief Opens SD or MMC card connected via SPI. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - error codes returned by initialize(); * - error codes returned by SpiDevice::open(); */ int open() override; /** * \brief Reads data from SD or MMC card connected via SPI. * * \warning This function must not be called from interrupt context! * * \param [in] address is the address of data that will be read, must be a multiple of block size * \param [out] buffer is the buffer into which the data will be read * \param [in] size is the size of \a buffer, bytes, must be a multiple of block size * * \return 0 on success, error code otherwise: * - EBADF - the device is not opened; * - EINVAL - \a address and/or \a buffer and/or \a size are not valid; * - EIO - error during communication with SD or MMC card; * - ENOSPC - selected range is greater than size of device; * - error codes returned by executeCmd12(); * - error codes returned by executeCmd17(); * - error codes returned by executeCmd18(); * - error codes returned by readDataBlock(); * - error codes returned by SpiMasterProxy::configure(); */ int read(uint64_t address, void* buffer, size_t size) override; /** * \brief Synchronizes state of SD or MMC card connected via SPI, ensuring all cached writes are finished. * * \return always 0 */ int synchronize() override; /** * \brief Unlocks the device which was previously locked by current thread. * * \note Locks are recursive. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - error codes returned by SpiDevice::unlock(); */ int unlock() override; /** * \brief Writes data to SD or MMC card connected via SPI. * * \warning This function must not be called from interrupt context! * * \param [in] address is the address of data that will be written, must be a multiple of block size * \param [in] buffer is the buffer with data that will be written * \param [in] size is the size of \a buffer, bytes, must be a multiple of block size * * \return 0 on success, error code otherwise: * - EBADF - the device is not opened; * - EINVAL - \a address and/or \a buffer and/or \a size are not valid; * - EIO - error during communication with SD or MMC card; * - ENOSPC - selected range is greater than size of device; * - error codes returned by executeAcmd23(); * - error codes returned by executeCmd24(); * - error codes returned by executeCmd25(); * - error codes returned by waitWhileBusy(); * - error codes returned by writeDataBlock(); * - error codes returned by SpiMasterProxy::configure(); * - error codes returned by SpiMasterProxy::executeTransaction(); */ int write(uint64_t address, const void* buffer, size_t size) override; private: /** * \brief Deinitializes SD or MMC card connected via SPI. */ void deinitialize(); /** * \brief Initializes SD or MMC card connected via SPI. * * Algorithm is based on ChaN's * [How to Use MMC/SDC: Initialization Procedure for SPI Mode](http://elm-chan.org/docs/mmc/mmc_e.html#spiinit). * * \param [in] spiDeviceProxy is a reference to SpiDeviceProxy associated with this object * * \return 0 on success, error code otherwise: * - EIO - error during communication with SD or MMC card; * - ETIMEDOUT - timed-out while waiting for SD or MMC card to respond; * - error codes returned by executeAcmd41(); * - error codes returned by executeCmd0(); * - error codes returned by executeCmd1(); * - error codes returned by executeCmd8(); * - error codes returned by executeCmd9(); * - error codes returned by executeCmd16(); * - error codes returned by executeCmd58(); * - error codes returned by SpiMasterProxy::configure(); * - error codes returned by SpiMasterProxy::executeTransaction(); */ int initialize(const SpiDeviceProxy& spiDeviceProxy); /// internal SPI slave device SpiDevice spiDevice_; /// number of blocks available on SD or MMC card size_t blocksCount_; /// size of AU, bytes uint32_t auSize_; /// desired clock frequency of SD or MMC card, Hz uint32_t clockFrequency_; /// timeout of erase operation of single AU, milliseconds uint16_t eraseTimeoutMs_; /// timeout of read operation, milliseconds uint16_t readTimeoutMs_; /// timeout of write operation, milliseconds uint16_t writeTimeoutMs_; /// selects whether card uses byte (false) or block (true) addressing bool blockAddressing_; /// type of card connected via SPI Type type_; }; } // namespace devices } // namespace distortos #endif // INCLUDE_DISTORTOS_DEVICES_MEMORY_SDMMCCARDSPIBASED_HPP_ <commit_msg>Increase default clock for SdMmcCardSpiBased to 25 MHz<commit_after>/** * \file * \brief SdMmcCardSpiBased class header * * \author Copyright (C) 2018-2019 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_DEVICES_MEMORY_SDMMCCARDSPIBASED_HPP_ #define INCLUDE_DISTORTOS_DEVICES_MEMORY_SDMMCCARDSPIBASED_HPP_ #include "distortos/devices/communication/SpiDevice.hpp" #include "distortos/devices/memory/BlockDevice.hpp" namespace distortos { namespace devices { /** * SdMmcCardSpiBased class is a SD or MMC card connected via SPI. * * \ingroup devices */ class SdMmcCardSpiBased : public BlockDevice { public: /// type of card connected via SPI enum class Type : uint8_t { /// unknown type unknown, /// MMC card mmc, /// SD version 1.0 card sdVersion1, /// SD version 2.0 card sdVersion2, }; /// size of block, bytes constexpr static size_t blockSize {512}; /** * \brief SdMmcCardSpiBased's constructor * * \param [in] spiMaster is a reference to SPI master to which this SD or MMC card is connected * \param [in] slaveSelectPin is a reference to slave select pin of this SD or MMC card * \param [in] clockFrequency is the desired clock frequency of SD or MMC card, Hz, default - 25 MHz */ constexpr SdMmcCardSpiBased(SpiMaster& spiMaster, OutputPin& slaveSelectPin, const uint32_t clockFrequency = 25000000) : spiDevice_{spiMaster, slaveSelectPin}, blocksCount_{}, auSize_{}, clockFrequency_{clockFrequency}, eraseTimeoutMs_{}, readTimeoutMs_{}, writeTimeoutMs_{}, blockAddressing_{}, type_{} { } /** * \brief SdMmcCardSpiBased's destructor */ ~SdMmcCardSpiBased() override; /** * \brief Closes SD or MMC card connected via SPI. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - error codes returned by SpiDevice::close(); */ int close() override; /** * \brief Erases blocks on a SD or MMC card connected via SPI. * * \warning This function must not be called from interrupt context! * * \param [in] address is the address of range that will be erased, must be a multiple of block size * \param [in] size is the size of erased range, bytes, must be a multiple of block size * * \return 0 on success, error code otherwise: * - EBADF - the device is not opened; * - EINVAL - \a address and/or \a size are not valid; * - ENOSPC - selected range is greater than size of device; * - error codes returned by executeCmd32(); * - error codes returned by executeCmd33(); * - error codes returned by executeCmd38(); * - error codes returned by SpiMasterProxy::configure(); */ int erase(uint64_t address, uint64_t size) override; /** * \return block size, bytes */ size_t getBlockSize() const override; /** * \return size of SD or MMC card connected via SPI, bytes */ uint64_t getSize() const override; /** * \brief Locks the device for exclusive use by current thread. * * When the object is locked, any call to any member function from other thread will be blocked until the object is * unlocked. Locking is optional, but may be useful when more than one transaction must be done atomically. * * \note Locks are recursive. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - error codes returned by SpiDevice::lock(); */ int lock() override; /** * \brief Opens SD or MMC card connected via SPI. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - error codes returned by initialize(); * - error codes returned by SpiDevice::open(); */ int open() override; /** * \brief Reads data from SD or MMC card connected via SPI. * * \warning This function must not be called from interrupt context! * * \param [in] address is the address of data that will be read, must be a multiple of block size * \param [out] buffer is the buffer into which the data will be read * \param [in] size is the size of \a buffer, bytes, must be a multiple of block size * * \return 0 on success, error code otherwise: * - EBADF - the device is not opened; * - EINVAL - \a address and/or \a buffer and/or \a size are not valid; * - EIO - error during communication with SD or MMC card; * - ENOSPC - selected range is greater than size of device; * - error codes returned by executeCmd12(); * - error codes returned by executeCmd17(); * - error codes returned by executeCmd18(); * - error codes returned by readDataBlock(); * - error codes returned by SpiMasterProxy::configure(); */ int read(uint64_t address, void* buffer, size_t size) override; /** * \brief Synchronizes state of SD or MMC card connected via SPI, ensuring all cached writes are finished. * * \return always 0 */ int synchronize() override; /** * \brief Unlocks the device which was previously locked by current thread. * * \note Locks are recursive. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - error codes returned by SpiDevice::unlock(); */ int unlock() override; /** * \brief Writes data to SD or MMC card connected via SPI. * * \warning This function must not be called from interrupt context! * * \param [in] address is the address of data that will be written, must be a multiple of block size * \param [in] buffer is the buffer with data that will be written * \param [in] size is the size of \a buffer, bytes, must be a multiple of block size * * \return 0 on success, error code otherwise: * - EBADF - the device is not opened; * - EINVAL - \a address and/or \a buffer and/or \a size are not valid; * - EIO - error during communication with SD or MMC card; * - ENOSPC - selected range is greater than size of device; * - error codes returned by executeAcmd23(); * - error codes returned by executeCmd24(); * - error codes returned by executeCmd25(); * - error codes returned by waitWhileBusy(); * - error codes returned by writeDataBlock(); * - error codes returned by SpiMasterProxy::configure(); * - error codes returned by SpiMasterProxy::executeTransaction(); */ int write(uint64_t address, const void* buffer, size_t size) override; private: /** * \brief Deinitializes SD or MMC card connected via SPI. */ void deinitialize(); /** * \brief Initializes SD or MMC card connected via SPI. * * Algorithm is based on ChaN's * [How to Use MMC/SDC: Initialization Procedure for SPI Mode](http://elm-chan.org/docs/mmc/mmc_e.html#spiinit). * * \param [in] spiDeviceProxy is a reference to SpiDeviceProxy associated with this object * * \return 0 on success, error code otherwise: * - EIO - error during communication with SD or MMC card; * - ETIMEDOUT - timed-out while waiting for SD or MMC card to respond; * - error codes returned by executeAcmd41(); * - error codes returned by executeCmd0(); * - error codes returned by executeCmd1(); * - error codes returned by executeCmd8(); * - error codes returned by executeCmd9(); * - error codes returned by executeCmd16(); * - error codes returned by executeCmd58(); * - error codes returned by SpiMasterProxy::configure(); * - error codes returned by SpiMasterProxy::executeTransaction(); */ int initialize(const SpiDeviceProxy& spiDeviceProxy); /// internal SPI slave device SpiDevice spiDevice_; /// number of blocks available on SD or MMC card size_t blocksCount_; /// size of AU, bytes uint32_t auSize_; /// desired clock frequency of SD or MMC card, Hz uint32_t clockFrequency_; /// timeout of erase operation of single AU, milliseconds uint16_t eraseTimeoutMs_; /// timeout of read operation, milliseconds uint16_t readTimeoutMs_; /// timeout of write operation, milliseconds uint16_t writeTimeoutMs_; /// selects whether card uses byte (false) or block (true) addressing bool blockAddressing_; /// type of card connected via SPI Type type_; }; } // namespace devices } // namespace distortos #endif // INCLUDE_DISTORTOS_DEVICES_MEMORY_SDMMCCARDSPIBASED_HPP_ <|endoftext|>
<commit_before>// // a21 — Arduino Toolkit. // Copyright (C) 2016-2017, Aleh Dzenisiuk. http://github.com/aleh/a21 // #pragma once #include <Arduino.h> #include <a21/pcd8544fonts.hpp> #include <a21/spi.hpp> namespace a21 { /** * Basic wrapper for a PCD8544 LCD display (such as the one that was used on Nokia 5110). */ template<typename pinRST, typename pinCE, typename pinDC, typename pinDIN, typename pinCLK, uint32_t maxFrequency = 4000000L> class PCD8544 { private: typedef SPI<pinDIN, pinCLK, pinCE, maxFrequency> spi; enum ValueType : uint8_t { Command, Data }; static void write(ValueType valueType, uint8_t value) { pinDC::write(valueType == Data); spi::write(value); } static void beginWriting() { spi::beginWriting(); } static void endWriting() { spi::endWriting(); } enum FunctionSetCommand : uint8_t { FunctionSet = 0x20, /** 0 - basic command set, 1 - extended command set. */ H = 1, /** 0 - horizontal addressing mode, 1 - vertical addressing mode. */ V = 2, /** 0 - chip active, 1 - chip in power down mode. */ PD = 4 }; enum DisplayControlCommand : uint8_t { DisplayControl = 0x08, D = 0x04, E = 0x01, DisplayBlank = (uint8_t)(~(D | E)), NormalMode = (uint8_t)(D & ~E), AllSegmentsOn = (uint8_t)(~D & E), InverseVideoMode = (uint8_t)(D | E) }; enum SetXAddressCommand : uint8_t { SetXAddress = 0x80, SetXAddressMask = 0x7F }; enum SetYAddressCommand : uint8_t { SetYAddress = 0x40, SetYAddressMask = 0x07 }; enum TemperatureControlExtendedCommand : uint8_t { TemperatureControl = 0x04, TemperatureControlMask = 0x3 }; enum BiasSystemExtendedCommand : uint8_t { BiasSystem = 0x10, BiasSystemMask = 0x07 }; enum SetVopExtendedCommand : uint8_t { SetVop = 0x80, SetVopMask = 0x7F }; static inline void extendedCommandSet(bool extended) { write( Command, extended ? (FunctionSet | H) & ~(PD | V) : (FunctionSet | 0) & ~(PD | V | H) ); } static inline void setAddressInternal(uint8_t col, uint8_t row) { extendedCommandSet(false); write(Command, SetXAddress | col); write(Command, SetYAddress | row); } static inline void config(uint8_t operatingVoltage, uint8_t biasSystem, uint8_t temperatureControl) { beginWriting(); // Not making the display mode a parameter here as those don't seem to be useful. extendedCommandSet(false); write(Command, DisplayControl | NormalMode); extendedCommandSet(true); write(Command, SetVop | (operatingVoltage & SetVopMask)); write(Command, BiasSystem | (biasSystem & BiasSystemMask)); write(Command, TemperatureControl | (temperatureControl & TemperatureControlMask)); endWriting(); } public: /** Number of addressable rows, with every row corresponding to 8 horizontal lines of actual pixels. */ static const int Rows = 6; /** Number of addressable columns, though unlike rows every column corresponds to 1 vertical line of pixels. */ static const int Cols = 84; /** Maximum value for the parameter of operatingVoltage function, though the actual usable values are usually much smaller. */ static const uint8_t MaxVoltage = 0x7F; /** Sets operational voltage affecting the contrast of the display. */ static void operatingVoltage(uint8_t value) { beginWriting(); extendedCommandSet(true); write(Command, SetVop | value); endWriting(); } /** Clears the display. */ static void clear() { beginWriting(); setAddressInternal(0, 0); for (int i = 0; i < Rows * Cols; i++) { write(Data, 0); } endWriting(); } /** Initializes the display. */ static void begin(uint8_t operatingVoltage = 52, uint8_t biasSystem = 4, uint8_t temperatureControl = 2) { spi::begin(); pinDC::setOutput(); pinDC::setLow(); pinRST::setOutput(); pinRST::setLow(); // TODO: add delay template instead delayMicroseconds(1000000.0 / maxFrequency); pinRST::setHigh(); config(operatingVoltage, biasSystem, temperatureControl); clear(); } /** * Transports a bunch of bytes for the given row. The layout directly corresponds with the memory layout of the LCD, * where each byte is responsible for a 8 pixel column within the row (MSB is in the bottom of the row, * LSB is in the top). * * The row is filled from left to right (i.e. column address is automatically incremented). * col col + 1 * line row * 8: # bit 0 # bit 0 ... * line row * 8 + 1: # bit 1 # bit 1 ... * ... * line row * 8 + 7: # bit 7 # bit 7 ... * ^ ^ * byte 0 byte 1 * * Note that if more bytes are provided than is left in the row, then they'll be written to the next one * (or the first one in case of the last row). */ static void writeRow(uint8_t col, uint8_t row, const uint8_t *data, uint8_t data_length) { beginWriting(); setAddressInternal(col, row); const uint8_t *src = data; for (uint8_t c = data_length; c > 0; c--) { write(Data, *src++); } endWriting(); } /** * Similar to writeRow, but the same byte is sent `length` times. */ static void fillRow(uint8_t col, uint8_t row, uint8_t filler, uint8_t length) { beginWriting(); setAddressInternal(col, row); for (uint8_t c = length; c > 0; c--) { write(Data, filler); } endWriting(); } // // Support for simple 8px high fonts fitting rows of the display exactly // /** * Returns the width of the glyph corresponding to a character in the given font and, if a buffer is provided, * copies glyph's bitmap bytes into it. */ static uint8_t dataForCharacter(PCD8544Font font, char ch, uint8_t *buffer) { const uint8_t *p = font; uint8_t options = pgm_read_byte(p++); if ((options & 1) && 'a' <= ch && ch <= 'z') { ch = ch - 'a' + 'A'; } while (true) { // First character in the range (0 would mean no more ranges are defined). uint8_t first = pgm_read_byte(p++); if (first == 0) break; // Last character in the range. uint8_t last = pgm_read_byte(p++); // Number of bytes every character in the range occupies. uint8_t bytes_per_character = pgm_read_byte(p++); if (first <= ch && ch <= last) { // Our character is in the range, let's copy the data for it. p += (ch - first) * bytes_per_character; // The first byte of the glyph data is the actual width of the glyph. uint8_t width = pgm_read_byte(p++); // Copy the bitmap if the caller expects it. if (buffer) { memcpy_PF(buffer, (uint_farptr_t)p, width); } return width; } // Well, let's skip to the next range of characters. p += (last + 1 - first) * bytes_per_character; } // Let's return data for sort of a default character. return dataForCharacter(font, '?', buffer); } /** The width of the string drawn with the given font. */ static uint8_t textWidth(PCD8544Font font, const char *text) { char ch; const char *src = text; uint8_t result = 0; while ((ch = *src++)) { uint8_t width = dataForCharacter(font, ch, NULL); result += width + 1; } return result; } /** * Renders a text string by sending the corresponding bytes directly to the LCD. * The row and col parameters use LCD addressing system, where each rows occupies 8 pixels. * The max_width parameter is not clipped to the actual width available. * The xor_mask set to 0xFF or 0x7E can be used to render inverted text, for example. */ static uint8_t drawText( PCD8544Font font, const uint8_t col, const uint8_t row, const uint8_t max_width, const char *text, const uint8_t xor_mask = 0 ) { beginWriting(); setAddressInternal(col, row); char ch; const char *src = text; // Well, let's clip it just in case. uint8_t m = Cols - col; uint8_t width_left = max_width < m ? max_width : m; while ((ch = *src++)) { uint8_t bitmap[8]; uint8_t width = dataForCharacter(font, ch, bitmap); for (uint8_t i = 0; i < width; i++) { write(Data, bitmap[i] ^ xor_mask); if (--width_left == 0) { endWriting(); return 0; } } write(Data, xor_mask); if (--width_left == 0) break; } endWriting(); return max_width - width_left; } /** Returns how many characters will fit max_width pixels without being truncacted. */ static uint8_t numberOfCharsFittingWidth(PCD8544Font font, const char *text, uint8_t max_width) { uint8_t result = 0; char ch; const char *src = text; uint8_t total_width = 0; while ((ch = *src++)) { uint8_t new_total_width = total_width + dataForCharacter(font, ch, NULL) + 1; if (new_total_width > max_width) break; total_width = new_total_width; result++; } return result; } }; /** * Turns a PCD8544 LCD into a simple text-only display with autoscrolling. * Note that we don't inherit Arduino's Print class to keep the compiled code size small. */ template<typename lcd, typename font> class PCD8544Console { private: static const uint8_t MaxCols = lcd::Cols / 4; char _buffer[lcd::Rows][MaxCols + 1]; uint8_t _row; uint8_t _col; uint8_t _rowWidth; uint8_t _filledRows; bool _dirty; void lf() { _col = 0; _rowWidth = 0; _row++; if (_row >= lcd::Rows) { _row = 0; } _filledRows++; if (_filledRows >= lcd::Rows) { _filledRows--; } _buffer[_row][_col] = 0; } void cr() { _col = 0; _rowWidth = 0; } public: PCD8544Console() : _row(0), _col(0), _rowWidth(0), _filledRows(0) {} /** Clears the console without redrawing it on the LCD. */ void clear() { _row = _filledRows = 0; _col = 0; _rowWidth = 0; for (uint8_t row = 0; row < lcd::Rows; row++) { _buffer[row][0] = 0; } _dirty = true; } /** Transfers the contents of the console buffer to the LCD. * Note that this is not called automatically for every print() function. */ void draw() { if (!_dirty) return; _dirty = false; for (uint8_t i = 0; i < lcd::Rows; i++) { int8_t row_index = _row - _filledRows + i; if (row_index < 0) row_index += lcd::Rows; // Print the row and erase the space after the last character. uint8_t width = lcd::drawText(font::font(), 0, i, lcd::Cols, _buffer[row_index]); lcd::fillRow(width, i, 0, lcd::Cols - width); } } void print(uint8_t c) { uint8_t ch = ch & 0x7F; if (ch >= ' ') { uint8_t width = lcd::dataForCharacter(font::font(), ch, NULL); if (_col >= MaxCols || _rowWidth + width >= lcd::Cols) { lf(); } _buffer[_row][_col] = ch; _col++; _buffer[_row][_col] = 0; _rowWidth += width + 1; } else if (ch == '\n') { lf(); } else if (ch == '\r') { cr(); } _dirty = true; } void print(const char *str) { const char *src = str; uint8_t ch; while (ch = *src++) { print(ch); } } void print(fstr_t *str) { const char *src = (const char *)str; uint8_t ch; while (ch = pgm_read_byte(src++)) { print(ch); } } void print(int n) { char buf[5 + 2]; itoa(n, buf, 10); print(buf); } void print(unsigned int n) { char buf[5 + 1]; utoa(n, buf, 10); print(buf); } void print(long n) { char buf[10 + 2]; ltoa(n, buf, 10); print(buf); } void print(unsigned long n) { char buf[10 + 1]; ltoa(n, buf, 10); print(buf); } void println(const char *str) { print(str); lf(); } void println(fstr_t *str) { print(str); lf(); } void println(int n) { print(n); lf(); } void println(unsigned int n) { print(n); lf(); } void println(long n) { print(n); lf(); } void println(unsigned long n) { print(n); lf(); } void println() { lf(); } }; } // namespace <commit_msg>PCD8544: Add video mode as a config parameter<commit_after>// // a21 — Arduino Toolkit. // Copyright (C) 2016-2017, Aleh Dzenisiuk. http://github.com/aleh/a21 // #pragma once #include <Arduino.h> #include <a21/pcd8544fonts.hpp> #include <a21/spi.hpp> namespace a21 { /** * Basic wrapper for a PCD8544 LCD display (such as the one that was used on Nokia 5110). */ template<typename pinRST, typename pinCE, typename pinDC, typename pinDIN, typename pinCLK, uint32_t maxFrequency = 4000000L> class PCD8544 { public: enum Flags { InverseVideo, NormalVideo }; private: typedef SPI<pinDIN, pinCLK, pinCE, maxFrequency> spi; enum ValueType : uint8_t { Command, Data }; static void write(ValueType valueType, uint8_t value) { pinDC::write(valueType == Data); spi::write(value); } static void beginWriting() { spi::beginWriting(); } static void endWriting() { spi::endWriting(); } enum FunctionSetCommand : uint8_t { FunctionSet = 0x20, /** 0 - basic command set, 1 - extended command set. */ H = 1, /** 0 - horizontal addressing mode, 1 - vertical addressing mode. */ V = 2, /** 0 - chip active, 1 - chip in power down mode. */ PD = 4 }; enum DisplayControlCommand : uint8_t { DisplayControl = 0x08, D = 0x04, E = 0x01, DisplayBlank = (uint8_t)(~(D | E)), NormalMode = (uint8_t)(D & ~E), AllSegmentsOn = (uint8_t)(~D & E), InverseVideoMode = (uint8_t)(D | E) }; enum SetXAddressCommand : uint8_t { SetXAddress = 0x80, SetXAddressMask = 0x7F }; enum SetYAddressCommand : uint8_t { SetYAddress = 0x40, SetYAddressMask = 0x07 }; enum TemperatureControlExtendedCommand : uint8_t { TemperatureControl = 0x04, TemperatureControlMask = 0x3 }; enum BiasSystemExtendedCommand : uint8_t { BiasSystem = 0x10, BiasSystemMask = 0x07 }; enum SetVopExtendedCommand : uint8_t { SetVop = 0x80, SetVopMask = 0x7F }; static inline void extendedCommandSet(bool extended) { write( Command, extended ? (FunctionSet | H) & ~(PD | V) : (FunctionSet | 0) & ~(PD | V | H) ); } static inline void setAddressInternal(uint8_t col, uint8_t row) { extendedCommandSet(false); write(Command, SetXAddress | col); write(Command, SetYAddress | row); } static inline void config(Flags flags, uint8_t operatingVoltage, uint8_t biasSystem, uint8_t temperatureControl) { beginWriting(); // Not making the display mode a parameter here as those don't seem to be useful. extendedCommandSet(false); write(Command, (flags == InverseVideo) ? (DisplayControl | InverseVideoMode) : (DisplayControl | NormalMode)); extendedCommandSet(true); write(Command, SetVop | (operatingVoltage & SetVopMask)); write(Command, BiasSystem | (biasSystem & BiasSystemMask)); write(Command, TemperatureControl | (temperatureControl & TemperatureControlMask)); endWriting(); } public: /** Number of addressable rows, with every row corresponding to 8 horizontal lines of actual pixels. */ static const int Rows = 6; /** Number of addressable columns, though unlike rows every column corresponds to 1 vertical line of pixels. */ static const int Cols = 84; /** Maximum value for the parameter of operatingVoltage function, though the actual usable values are usually much smaller. */ static const uint8_t MaxVoltage = 0x7F; /** Sets operational voltage affecting the contrast of the display. */ static void operatingVoltage(uint8_t value) { beginWriting(); extendedCommandSet(true); write(Command, SetVop | value); endWriting(); } /** Clears the display. */ static void clear() { beginWriting(); setAddressInternal(0, 0); for (int i = 0; i < Rows * Cols; i++) { write(Data, 0); } endWriting(); } /** Initializes the display. */ static void begin(Flags flags = NormalVideo, uint8_t operatingVoltage = 52, uint8_t biasSystem = 4, uint8_t temperatureControl = 2) { spi::begin(); pinDC::setOutput(); pinDC::setLow(); pinRST::setOutput(); pinRST::setLow(); // TODO: add delay template instead delayMicroseconds(1000000.0 / maxFrequency); pinRST::setHigh(); config(flags, operatingVoltage, biasSystem, temperatureControl); clear(); } /** * Transports a bunch of bytes for the given row. The layout directly corresponds with the memory layout of the LCD, * where each byte is responsible for a 8 pixel column within the row (MSB is in the bottom of the row, * LSB is in the top). * * The row is filled from left to right (i.e. column address is automatically incremented). * col col + 1 * line row * 8: # bit 0 # bit 0 ... * line row * 8 + 1: # bit 1 # bit 1 ... * ... * line row * 8 + 7: # bit 7 # bit 7 ... * ^ ^ * byte 0 byte 1 * * Note that if more bytes are provided than is left in the row, then they'll be written to the next one * (or the first one in case of the last row). */ static void writeRow(uint8_t col, uint8_t row, const uint8_t *data, uint8_t data_length) { beginWriting(); setAddressInternal(col, row); const uint8_t *src = data; for (uint8_t c = data_length; c > 0; c--) { write(Data, *src++); } endWriting(); } /** * Similar to writeRow, but the same byte is sent `length` times. */ static void fillRow(uint8_t col, uint8_t row, uint8_t filler, uint8_t length) { beginWriting(); setAddressInternal(col, row); for (uint8_t c = length; c > 0; c--) { write(Data, filler); } endWriting(); } // // Support for simple 8px high fonts fitting rows of the display exactly // /** * Returns the width of the glyph corresponding to a character in the given font and, if a buffer is provided, * copies glyph's bitmap bytes into it. */ static uint8_t dataForCharacter(PCD8544Font font, char ch, uint8_t *buffer) { const uint8_t *p = font; uint8_t options = pgm_read_byte(p++); if ((options & 1) && 'a' <= ch && ch <= 'z') { ch = ch - 'a' + 'A'; } while (true) { // First character in the range (0 would mean no more ranges are defined). uint8_t first = pgm_read_byte(p++); if (first == 0) break; // Last character in the range. uint8_t last = pgm_read_byte(p++); // Number of bytes every character in the range occupies. uint8_t bytes_per_character = pgm_read_byte(p++); if (first <= ch && ch <= last) { // Our character is in the range, let's copy the data for it. p += (ch - first) * bytes_per_character; // The first byte of the glyph data is the actual width of the glyph. uint8_t width = pgm_read_byte(p++); // Copy the bitmap if the caller expects it. if (buffer) { memcpy_PF(buffer, (uint_farptr_t)p, width); } return width; } // Well, let's skip to the next range of characters. p += (last + 1 - first) * bytes_per_character; } // Let's return data for sort of a default character. return dataForCharacter(font, '?', buffer); } /** The width of the string drawn with the given font. */ static uint8_t textWidth(PCD8544Font font, const char *text) { char ch; const char *src = text; uint8_t result = 0; while ((ch = *src++)) { uint8_t width = dataForCharacter(font, ch, NULL); result += width + 1; } return result; } /** * Renders a text string by sending the corresponding bytes directly to the LCD. * The row and col parameters use LCD addressing system, where each rows occupies 8 pixels. * The max_width parameter is not clipped to the actual width available. * The xor_mask set to 0xFF or 0x7E can be used to render inverted text, for example. */ static uint8_t drawText( PCD8544Font font, const uint8_t col, const uint8_t row, const uint8_t max_width, const char *text, const uint8_t xor_mask = 0 ) { beginWriting(); setAddressInternal(col, row); char ch; const char *src = text; // Well, let's clip it just in case. uint8_t m = Cols - col; uint8_t width_left = max_width < m ? max_width : m; while ((ch = *src++)) { uint8_t bitmap[8]; uint8_t width = dataForCharacter(font, ch, bitmap); for (uint8_t i = 0; i < width; i++) { write(Data, bitmap[i] ^ xor_mask); if (--width_left == 0) { endWriting(); return 0; } } write(Data, xor_mask); if (--width_left == 0) break; } endWriting(); return max_width - width_left; } /** Returns how many characters will fit max_width pixels without being truncacted. */ static uint8_t numberOfCharsFittingWidth(PCD8544Font font, const char *text, uint8_t max_width) { uint8_t result = 0; char ch; const char *src = text; uint8_t total_width = 0; while ((ch = *src++)) { uint8_t new_total_width = total_width + dataForCharacter(font, ch, NULL) + 1; if (new_total_width > max_width) break; total_width = new_total_width; result++; } return result; } }; /** * Turns a PCD8544 LCD into a simple text-only display with autoscrolling. * Note that we don't inherit Arduino's Print class to keep the compiled code size small. */ template<typename lcd, typename font> class PCD8544Console { private: static const uint8_t MaxCols = lcd::Cols / 4; char _buffer[lcd::Rows][MaxCols + 1]; uint8_t _row; uint8_t _col; uint8_t _rowWidth; uint8_t _filledRows; bool _dirty; void lf() { _col = 0; _rowWidth = 0; _row++; if (_row >= lcd::Rows) { _row = 0; } _filledRows++; if (_filledRows >= lcd::Rows) { _filledRows--; } _buffer[_row][_col] = 0; } void cr() { _col = 0; _rowWidth = 0; } public: PCD8544Console() : _row(0), _col(0), _rowWidth(0), _filledRows(0) {} /** Clears the console without redrawing it on the LCD. */ void clear() { _row = _filledRows = 0; _col = 0; _rowWidth = 0; for (uint8_t row = 0; row < lcd::Rows; row++) { _buffer[row][0] = 0; } _dirty = true; } /** Transfers the contents of the console buffer to the LCD. * Note that this is not called automatically for every print() function. */ void draw() { if (!_dirty) return; _dirty = false; for (uint8_t i = 0; i < lcd::Rows; i++) { int8_t row_index = _row - _filledRows + i; if (row_index < 0) row_index += lcd::Rows; // Print the row and erase the space after the last character. uint8_t width = lcd::drawText(font::font(), 0, i, lcd::Cols, _buffer[row_index]); lcd::fillRow(width, i, 0, lcd::Cols - width); } } void print(char ch) { if (ch >= ' ') { uint8_t width = lcd::dataForCharacter(font::font(), ch, NULL); if (_col >= MaxCols || _rowWidth + width >= lcd::Cols) { lf(); } _buffer[_row][_col] = ch; _col++; _buffer[_row][_col] = 0; _rowWidth += width + 1; } else if (ch == '\n') { lf(); } else if (ch == '\r') { cr(); } _dirty = true; } void print(const char *str) { const char *src = str; char ch; while (ch = *src++) { print(ch); } } void print(fstr_t *str) { const char *src = (const char *)str; char ch; while (ch = pgm_read_byte(src++)) { print(ch); } } void print(int n) { char buf[5 + 2]; itoa(n, buf, 10); print(buf); } void print(unsigned int n) { char buf[5 + 1]; utoa(n, buf, 10); print(buf); } void print(long n) { char buf[10 + 2]; ltoa(n, buf, 10); print(buf); } void print(unsigned long n) { char buf[10 + 1]; ltoa(n, buf, 10); print(buf); } void println(const char *str) { print(str); lf(); } void println(fstr_t *str) { print(str); lf(); } void println(int n) { print(n); lf(); } void println(unsigned int n) { print(n); lf(); } void println(long n) { print(n); lf(); } void println(unsigned long n) { print(n); lf(); } void println() { lf(); } }; } // namespace <|endoftext|>
<commit_before>#ifndef Compile_Assert_hh_ #define Compile_Assert_hh_ #include <stdlib.h> #include <iostream> /** \file CompileAssert.hh \author Kevin Wierman \date April 12th, 2014 \brief Defines static and runtime assertions. These are to be used as follows: ~~~~~~~~ Compile_RUNTIME_ASSERT(true, ThisIsATrueStatement); Compile_RUNTIME_ASSERT(false, ThisIsAFalseStatement); ~~~~~~~~ \note The second argument must be a single word, or else it will be interpreted as several arguments. **/ //! Body-less template template<int> struct CompileTimeError; //! Fully-defined template template<> struct CompileTimeError<true> {}; //! Use for performing static assertion #define Compile_STATIC_ASSERT(expr, msg) \ { CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; } //! Use for runtime assertions #define Compile_RUNTIME_ASSERT(expr, msg)\ {if(!expr) std::cerr<<#msg<<std::endl; abort();} #endif //Compile_Assert_h_<commit_msg>Compile time fix for runtime assert<commit_after>#ifndef Compile_Assert_hh_ #define Compile_Assert_hh_ #include <stdlib.h> #include <iostream> /** \file CompileAssert.hh \author Kevin Wierman \date April 12th, 2014 \brief Defines static and runtime assertions. These are to be used as follows: ~~~~~~~~ Compile_RUNTIME_ASSERT(true, ThisIsATrueStatement); Compile_RUNTIME_ASSERT(false, ThisIsAFalseStatement); ~~~~~~~~ \note The second argument must be a single word, or else it will be interpreted as several arguments. **/ //! Body-less template template<int> struct CompileTimeError; //! Fully-defined template template<> struct CompileTimeError<true> {}; //! Use for performing static assertion #define Compile_STATIC_ASSERT(expr, msg) \ { CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; } //! Use for runtime assertions #define Compile_RUNTIME_ASSERT(expr, msg) \ { if(!expr) std::cerr<<#msg<<std::endl; abort(); } #endif //Compile_Assert_h_<|endoftext|>
<commit_before>// -*-c++-*- #include <osgProducer/Viewer> #include <osgDB/ReadFile> #include <osg/Geode> #include <osg/Geometry> #include <osg/StateSet> #include <osg/Material> #include <osg/Texture2D> #include <osg/TextureRectangle> #include <osg/TexMat> #include <osg/CullFace> #include <osg/ImageStream> #include <osgGA/TrackballManipulator> osg::ImageStream* s_imageStream = 0; class PostSwapFinishCallback : public Producer::Camera::Callback { public: PostSwapFinishCallback() {} virtual void operator()(const Producer::Camera& camera) { // osg::Timer_t start_tick = osg::Timer::instance()->tick(); osgProducer::OsgSceneHandler* sh = const_cast<osgProducer::OsgSceneHandler*>(dynamic_cast<const osgProducer::OsgSceneHandler*>(camera.getSceneHandler())); if (s_imageStream && s_imageStream->getPixelBufferObject()) s_imageStream->getPixelBufferObject()->compileBuffer(*(sh->getSceneView()->getState())); // glFinish(); //osg::notify(osg::NOTICE)<<"callback after PBO "<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl; } }; class MovieEventHandler : public osgGA::GUIEventHandler { public: MovieEventHandler() {} void set(osg::Node* node); virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); } virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&); virtual void getUsage(osg::ApplicationUsage& usage) const; typedef std::vector< osg::ref_ptr<osg::ImageStream> > ImageStreamList; protected: virtual ~MovieEventHandler() {} class FindImageStreamsVisitor : public osg::NodeVisitor { public: FindImageStreamsVisitor(ImageStreamList& imageStreamList): _imageStreamList(imageStreamList) {} virtual void apply(osg::Geode& geode) { apply(geode.getStateSet()); for(unsigned int i=0;i<geode.getNumDrawables();++i) { apply(geode.getDrawable(i)->getStateSet()); } traverse(geode); } virtual void apply(osg::Node& node) { apply(node.getStateSet()); traverse(node); } inline void apply(osg::StateSet* stateset) { if (!stateset) return; osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE); if (attr) { osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr); if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage())); osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr); if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage())); } } inline void apply(osg::ImageStream* imagestream) { if (imagestream) { _imageStreamList.push_back(imagestream); s_imageStream = imagestream; } } ImageStreamList& _imageStreamList; }; ImageStreamList _imageStreamList; }; void MovieEventHandler::set(osg::Node* node) { _imageStreamList.clear(); if (node) { FindImageStreamsVisitor fisv(_imageStreamList); node->accept(fisv); } } bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&) { switch(ea.getEventType()) { case(osgGA::GUIEventAdapter::KEYDOWN): { if (ea.getKey()=='s') { for(ImageStreamList::iterator itr=_imageStreamList.begin(); itr!=_imageStreamList.end(); ++itr) { std::cout<<"Play"<<std::endl; (*itr)->play(); } return true; } else if (ea.getKey()=='p') { for(ImageStreamList::iterator itr=_imageStreamList.begin(); itr!=_imageStreamList.end(); ++itr) { std::cout<<"Pause"<<std::endl; (*itr)->pause(); } return true; } else if (ea.getKey()=='r') { return true; } else if (ea.getKey()=='l') { return true; } return false; } default: return false; } } void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const { usage.addKeyboardMouseBinding("p","Pause movie"); usage.addKeyboardMouseBinding("s","Play movie"); usage.addKeyboardMouseBinding("r","Start movie"); usage.addKeyboardMouseBinding("l","Toggle looping of movie"); } osg::Geometry* createTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image, bool useTextureRectangle) { if (useTextureRectangle) { osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos, osg::Vec3(width,0.0f,0.0f), osg::Vec3(0.0f,0.0f,height), 0.0f,image->t(), image->s(),0.0f); pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0, new osg::TextureRectangle(image), osg::StateAttribute::ON); return pictureQuad; } else { osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos, osg::Vec3(width,0.0f,0.0f), osg::Vec3(0.0f,0.0f,height), 0.0f,1.0f, 1.0f,0.0f); osg::Texture2D* texture = new osg::Texture2D(image); texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR); pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON); return pictureQuad; } } int main(int argc, char** argv) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); bool useTextureRectangle = true; bool useShader = false; // construct the viewer. osgProducer::Viewer viewer(arguments); while (arguments.read("--texture2D")) useTextureRectangle=false; while (arguments.read("--shader")) useShader=true; // set up the value with sensible default event handlers. viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS); // register the handler to add keyboard and mosue handling. MovieEventHandler* meh = new MovieEventHandler(); viewer.getEventHandlerList().push_front(meh); // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } osg::ref_ptr<osg::Geode> geode = new osg::Geode; osg::Vec3 pos(0.0f,0.0f,0.0f); osg::StateSet* stateset = geode->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); if (useShader) { //useTextureRectangle = false; static const char *shaderSourceTextureRec = { "uniform vec4 cutoff_color;\n" "uniform samplerRect movie_texture;" "void main(void)\n" "{\n" " vec4 texture_color = textureRect(movie_texture, gl_TexCoord[0]); \n" " if (all(lessThanEqual(texture_color,cutoff_color))) discard; \n" " gl_FragColor = texture_color;\n" "}\n" }; static const char *shaderSourceTexture2D = { "uniform vec4 cutoff_color;\n" "uniform sampler2D movie_texture;" "void main(void)\n" "{\n" " vec4 texture_color = texture2D(movie_texture, gl_TexCoord[0]); \n" " if (all(lessThanEqual(texture_color,cutoff_color))) discard; \n" " gl_FragColor = texture_color;\n" "}\n" }; osg::Program* program = new osg::Program; program->addShader(new osg::Shader(osg::Shader::FRAGMENT, useTextureRectangle ? shaderSourceTextureRec : shaderSourceTexture2D)); stateset->addUniform(new osg::Uniform("cutoff_color",osg::Vec4(0.1f,0.1f,0.1f,1.0f))); stateset->addUniform(new osg::Uniform("movie_texture",0)); stateset->setAttribute(program); } for(int i=1;i<arguments.argc();++i) { if (arguments.isString(i)) { osg::Image* image = osgDB::readImageFile(arguments[i]); osg::ImageStream* imagestream = dynamic_cast<osg::ImageStream*>(image); if (imagestream) imagestream->play(); if (image) { geode->addDrawable(createTexturedQuadGeometry(pos,image->s(),image->t(),image, useTextureRectangle)); pos.z() += image->t()*1.5f; } else { std::cout<<"Unable to read file "<<arguments[i]<<std::endl; } } } if (geode->getNumDrawables()==0) { // nothing loaded. return 1; } // pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate. meh->set(geode.get()); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } if (arguments.argc()<=1) { arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); } /* // set up a post swap callback to flush deleted GL objects and compile new GL objects for(unsigned int cameraNum=0;cameraNum<viewer.getNumberOfCameras();++cameraNum) { Producer::Camera* camera=viewer.getCamera(cameraNum); camera->addPostSwapCallback(new PostSwapFinishCallback()); } */ // set the scene to render viewer.setSceneData(geode.get()); // create the windows and run the threads. viewer.realize(); while( !viewer.done() ) { // wait for all cull and draw threads to complete. viewer.sync(); // update the scene by traversing it with the the update visitor which will // call all node update callbacks and animations. viewer.update(); // fire off the cull and draw traversals of the scene. viewer.frame(); } // wait for all cull and draw threads to complete before exit. viewer.sync(); return 0; } <commit_msg>Added \n to end of a couple shader source lines.<commit_after>// -*-c++-*- #include <osgProducer/Viewer> #include <osgDB/ReadFile> #include <osg/Geode> #include <osg/Geometry> #include <osg/StateSet> #include <osg/Material> #include <osg/Texture2D> #include <osg/TextureRectangle> #include <osg/TexMat> #include <osg/CullFace> #include <osg/ImageStream> #include <osgGA/TrackballManipulator> osg::ImageStream* s_imageStream = 0; class PostSwapFinishCallback : public Producer::Camera::Callback { public: PostSwapFinishCallback() {} virtual void operator()(const Producer::Camera& camera) { // osg::Timer_t start_tick = osg::Timer::instance()->tick(); osgProducer::OsgSceneHandler* sh = const_cast<osgProducer::OsgSceneHandler*>(dynamic_cast<const osgProducer::OsgSceneHandler*>(camera.getSceneHandler())); if (s_imageStream && s_imageStream->getPixelBufferObject()) s_imageStream->getPixelBufferObject()->compileBuffer(*(sh->getSceneView()->getState())); // glFinish(); //osg::notify(osg::NOTICE)<<"callback after PBO "<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl; } }; class MovieEventHandler : public osgGA::GUIEventHandler { public: MovieEventHandler() {} void set(osg::Node* node); virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); } virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&); virtual void getUsage(osg::ApplicationUsage& usage) const; typedef std::vector< osg::ref_ptr<osg::ImageStream> > ImageStreamList; protected: virtual ~MovieEventHandler() {} class FindImageStreamsVisitor : public osg::NodeVisitor { public: FindImageStreamsVisitor(ImageStreamList& imageStreamList): _imageStreamList(imageStreamList) {} virtual void apply(osg::Geode& geode) { apply(geode.getStateSet()); for(unsigned int i=0;i<geode.getNumDrawables();++i) { apply(geode.getDrawable(i)->getStateSet()); } traverse(geode); } virtual void apply(osg::Node& node) { apply(node.getStateSet()); traverse(node); } inline void apply(osg::StateSet* stateset) { if (!stateset) return; osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE); if (attr) { osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr); if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage())); osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr); if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage())); } } inline void apply(osg::ImageStream* imagestream) { if (imagestream) { _imageStreamList.push_back(imagestream); s_imageStream = imagestream; } } ImageStreamList& _imageStreamList; }; ImageStreamList _imageStreamList; }; void MovieEventHandler::set(osg::Node* node) { _imageStreamList.clear(); if (node) { FindImageStreamsVisitor fisv(_imageStreamList); node->accept(fisv); } } bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&) { switch(ea.getEventType()) { case(osgGA::GUIEventAdapter::KEYDOWN): { if (ea.getKey()=='s') { for(ImageStreamList::iterator itr=_imageStreamList.begin(); itr!=_imageStreamList.end(); ++itr) { std::cout<<"Play"<<std::endl; (*itr)->play(); } return true; } else if (ea.getKey()=='p') { for(ImageStreamList::iterator itr=_imageStreamList.begin(); itr!=_imageStreamList.end(); ++itr) { std::cout<<"Pause"<<std::endl; (*itr)->pause(); } return true; } else if (ea.getKey()=='r') { return true; } else if (ea.getKey()=='l') { return true; } return false; } default: return false; } } void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const { usage.addKeyboardMouseBinding("p","Pause movie"); usage.addKeyboardMouseBinding("s","Play movie"); usage.addKeyboardMouseBinding("r","Start movie"); usage.addKeyboardMouseBinding("l","Toggle looping of movie"); } osg::Geometry* createTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image, bool useTextureRectangle) { if (useTextureRectangle) { osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos, osg::Vec3(width,0.0f,0.0f), osg::Vec3(0.0f,0.0f,height), 0.0f,image->t(), image->s(),0.0f); pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0, new osg::TextureRectangle(image), osg::StateAttribute::ON); return pictureQuad; } else { osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos, osg::Vec3(width,0.0f,0.0f), osg::Vec3(0.0f,0.0f,height), 0.0f,1.0f, 1.0f,0.0f); osg::Texture2D* texture = new osg::Texture2D(image); texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR); pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON); return pictureQuad; } } int main(int argc, char** argv) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); bool useTextureRectangle = true; bool useShader = false; // construct the viewer. osgProducer::Viewer viewer(arguments); while (arguments.read("--texture2D")) useTextureRectangle=false; while (arguments.read("--shader")) useShader=true; // set up the value with sensible default event handlers. viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS); // register the handler to add keyboard and mosue handling. MovieEventHandler* meh = new MovieEventHandler(); viewer.getEventHandlerList().push_front(meh); // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } osg::ref_ptr<osg::Geode> geode = new osg::Geode; osg::Vec3 pos(0.0f,0.0f,0.0f); osg::StateSet* stateset = geode->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); if (useShader) { //useTextureRectangle = false; static const char *shaderSourceTextureRec = { "uniform vec4 cutoff_color;\n" "uniform samplerRect movie_texture;\n" "void main(void)\n" "{\n" " vec4 texture_color = textureRect(movie_texture, gl_TexCoord[0]); \n" " if (all(lessThanEqual(texture_color,cutoff_color))) discard; \n" " gl_FragColor = texture_color;\n" "}\n" }; static const char *shaderSourceTexture2D = { "uniform vec4 cutoff_color;\n" "uniform sampler2D movie_texture;\n" "void main(void)\n" "{\n" " vec4 texture_color = texture2D(movie_texture, gl_TexCoord[0]); \n" " if (all(lessThanEqual(texture_color,cutoff_color))) discard; \n" " gl_FragColor = texture_color;\n" "}\n" }; osg::Program* program = new osg::Program; program->addShader(new osg::Shader(osg::Shader::FRAGMENT, useTextureRectangle ? shaderSourceTextureRec : shaderSourceTexture2D)); stateset->addUniform(new osg::Uniform("cutoff_color",osg::Vec4(0.1f,0.1f,0.1f,1.0f))); stateset->addUniform(new osg::Uniform("movie_texture",0)); stateset->setAttribute(program); } for(int i=1;i<arguments.argc();++i) { if (arguments.isString(i)) { osg::Image* image = osgDB::readImageFile(arguments[i]); osg::ImageStream* imagestream = dynamic_cast<osg::ImageStream*>(image); if (imagestream) imagestream->play(); if (image) { geode->addDrawable(createTexturedQuadGeometry(pos,image->s(),image->t(),image, useTextureRectangle)); pos.z() += image->t()*1.5f; } else { std::cout<<"Unable to read file "<<arguments[i]<<std::endl; } } } if (geode->getNumDrawables()==0) { // nothing loaded. return 1; } // pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate. meh->set(geode.get()); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } if (arguments.argc()<=1) { arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); } /* // set up a post swap callback to flush deleted GL objects and compile new GL objects for(unsigned int cameraNum=0;cameraNum<viewer.getNumberOfCameras();++cameraNum) { Producer::Camera* camera=viewer.getCamera(cameraNum); camera->addPostSwapCallback(new PostSwapFinishCallback()); } */ // set the scene to render viewer.setSceneData(geode.get()); // create the windows and run the threads. viewer.realize(); while( !viewer.done() ) { // wait for all cull and draw threads to complete. viewer.sync(); // update the scene by traversing it with the the update visitor which will // call all node update callbacks and animations. viewer.update(); // fire off the cull and draw traversals of the scene. viewer.frame(); } // wait for all cull and draw threads to complete before exit. viewer.sync(); return 0; } <|endoftext|>
<commit_before>/* * SpawnAreaImplementation.cpp * * Created on: 11/12/2011 * Author: victor */ #include "server/zone/objects/area/SpawnArea.h" #include "server/zone/Zone.h" #include "server/zone/managers/creature/CreatureManager.h" #include "server/zone/managers/creature/CreatureTemplateManager.h" #include "server/zone/managers/creature/SpawnGroup.h" #include "server/zone/managers/collision/CollisionManager.h" #include "server/zone/managers/planet/PlanetManager.h" #include "server/zone/objects/area/SpawnAreaObserver.h" #include "server/zone/objects/area/areashapes/AreaShape.h" #include "server/ServerCore.h" #include "events/RemoveNoSpawnAreaTask.h" Vector3 SpawnAreaImplementation::getRandomPosition(SceneObject* player) { Vector3 position; bool positionFound = false; int retries = 10; while (!positionFound && retries-- > 0) { position = areaShape->getRandomPosition(player->getWorldPosition(), 64.0f, 256.0f); positionFound = true; for (int i = 0; i < noSpawnAreas.size(); ++i) { SpawnArea* noSpawnArea = noSpawnAreas.get(i); if (noSpawnArea->containsPoint(position.getX(), position.getY())) { positionFound = false; break; } } } if (!positionFound) { position.set(0, 0, 0); } return position; } int SpawnAreaImplementation::notifyObserverEvent(unsigned int eventType, Observable* observable, ManagedObject* arg1, int64 arg2) { if (eventType != ObserverEventType::OBJECTREMOVEDFROMZONE) return 1; TangibleObject* tano = dynamic_cast<TangibleObject*>(observable); if (tano == NULL) return 1; Locker locker(_this.get()); uint32 lairTemplate = spawnTypes.remove(tano->getObjectID()); if (lairTemplate != 0) { int currentSpawnCount = spawnCountByType.get(lairTemplate) - 1; if (currentSpawnCount < 1) spawnCountByType.remove(lairTemplate); else spawnCountByType.put(lairTemplate, currentSpawnCount); --totalSpawnCount; locker.release(); ManagedReference<ActiveArea*> area = (ServerCore::getZoneServer()->createObject(String("object/active_area.iff").hashCode(), 0)).castTo<ActiveArea*>(); area->setRadius(64); area->setNoSpawnArea(true); area->initializePosition(tano->getPositionX(), tano->getPositionZ(), tano->getPositionY()); zone->transferObject(area, -1, true); Reference<Task*> task = new RemoveNoSpawnAreaTask(area); task->schedule(300000); } return 1; } SpawnGroup* SpawnAreaImplementation::getSpawnGroup() { if (spawnGroup == NULL && spawnGroupTemplateCRC != 0) spawnGroup = CreatureTemplateManager::instance()->getSpawnGroup(spawnGroupTemplateCRC); return spawnGroup; } void SpawnAreaImplementation::notifyEnter(SceneObject* object) { if (tier & SpawnAreaMap::NOSPAWNAREA) { ActiveAreaImplementation::notifyEnter(object); return; } if (!object->isPlayerCreature()) return; ManagedReference<SceneObject*> parent = object->getParent(); if (parent != NULL && parent->isCellObject()) return; if (object->getCityRegion() != NULL) return; tryToSpawn(object); } void SpawnAreaImplementation::notifyPositionUpdate(QuadTreeEntry* obj) { if (tier & SpawnAreaMap::NOSPAWNAREA) return; CreatureObject* creature = dynamic_cast<CreatureObject*>(obj); if (creature == NULL) return; if (!creature->isPlayerCreature()) return; ManagedReference<SceneObject*> parent = creature->getParent(); if (parent != NULL && parent->isCellObject()) return; if (System::random(25) == 1) tryToSpawn(creature); } void SpawnAreaImplementation::notifyExit(SceneObject* object) { if (tier & SpawnAreaMap::NOSPAWNAREA) ActiveAreaImplementation::notifyExit(object); } int SpawnAreaImplementation::tryToSpawn(SceneObject* object) { if (spawnGroup == NULL && spawnGroupTemplateCRC != 0) spawnGroup = CreatureTemplateManager::instance()->getSpawnGroup(spawnGroupTemplateCRC); if (spawnGroup == NULL) { error("spawnGroup is NULL in spawn area: " + getDisplayedName()); return 1; } Vector<Reference<LairSpawn*> >* lairs = spawnGroup->getSpawnList(); int totalSize = lairs->size(); if (totalSize == 0) { error("totalSize is NULL"); return 2; } Zone* zone = getZone(); if (zone == NULL) { error("zone is NULL"); return 3; } if (totalSpawnCount >= maxSpawnLimit) return 4; if (lastSpawn.miliDifference() < MINSPAWNINTERVAL) return 5; //Lets choose 3 random spawns; LairSpawn* firstSpawn = lairs->get(System::random(totalSize - 1)); LairSpawn* secondSpawn = lairs->get(System::random(totalSize - 1)); LairSpawn* thirdSpawn = lairs->get(System::random(totalSize - 1)); LairSpawn* finalSpawn = NULL; int totalWeights = firstSpawn->getWeighting() + secondSpawn->getWeighting() + thirdSpawn->getWeighting(); int finalChoice = System::random(totalWeights); if (finalChoice <= firstSpawn->getWeighting()) { finalSpawn = firstSpawn; } else if (finalChoice <= firstSpawn->getWeighting() + secondSpawn->getWeighting()) { finalSpawn = secondSpawn; } else { finalSpawn = thirdSpawn; } ManagedReference<PlanetManager*> planetManager = zone->getPlanetManager(); Vector3 randomPosition = getRandomPosition(object); if (randomPosition.getX() == 0 && randomPosition.getY() == 0) { return 6; } float spawnZ = zone->getHeight(randomPosition.getX(), randomPosition.getY()); randomPosition.setZ(spawnZ); //lets check if we intersect with some object (buildings, etc..) if (CollisionManager::checkSphereCollision(randomPosition, 64.f + finalSpawn->getSize(), zone)) return 7; //don't spawn in cities SortedVector<ManagedReference<ActiveArea* > > activeAreas; zone->getInRangeActiveAreas(randomPosition.getX(), randomPosition.getY(), &activeAreas, true); for (int i = 0; i < activeAreas.size(); ++i) { ActiveArea* area = activeAreas.get(i); if (area->isRegion() || area->isMunicipalZone() || area->isNoSpawnArea()) return 8; } //check in range objects for no build radi if (!planetManager->isBuildingPermittedAt(randomPosition.getX(), randomPosition.getY(), object, finalSpawn->getSize() + 64.f)) { return 9; } // Only spawn on relatively flat land if (planetManager->getTerrainManager()->getHighestHeightDifference(randomPosition.getX() - 10, randomPosition.getY() - 10, randomPosition.getX() + 10, randomPosition.getY() + 10) > 10.0) { return 13; } int spawnLimit = finalSpawn->getSpawnLimit(); Locker _locker(_this.get()); lastSpawn.updateToCurrentTime(); String lairTemplate = finalSpawn->getLairTemplateName(); uint32 lairHashCode = lairTemplate.hashCode(); int currentSpawnCount = spawnCountByType.get(lairHashCode); if (spawnLimit != -1) { if (currentSpawnCount >= spawnLimit) return 10; } int maxDiff = finalSpawn->getMaxDifficulty(); int minDiff = finalSpawn->getMinDifficulty(); int difficultyLevel = System::random(maxDiff - minDiff) + minDiff; int difficulty = (difficultyLevel - minDiff) / ((maxDiff > (minDiff + 5) ? maxDiff - minDiff : 5) / 5); if (difficulty == 5) difficulty = 4; CreatureManager* creatureManager = zone->getCreatureManager(); ManagedReference<SceneObject*> obj = creatureManager->spawn(lairHashCode, difficultyLevel, difficulty, randomPosition.getX(), spawnZ, randomPosition.getY(), finalSpawn->getSize()); if (obj != NULL) { StringBuffer msg; msg << "lair spawned at " << obj->getPositionX() << " " << obj->getPositionY(); obj->info(msg.toString()); } else { error("could not spawn lair " + lairTemplate); return 11; } if (exitObserver == NULL) { exitObserver = new SpawnAreaObserver(_this.get()); exitObserver->deploy(); } spawnTypes.put(obj->getObjectID(), lairHashCode); Locker objLocker(obj); obj->registerObserver(ObserverEventType::OBJECTREMOVEDFROMZONE, exitObserver); ++totalSpawnCount; spawnCountByType.put(lairTemplate.hashCode(), currentSpawnCount); return 0; } <commit_msg>[Fixed] removal of dynamic spawn from a spawn area not being handled properly<commit_after>/* * SpawnAreaImplementation.cpp * * Created on: 11/12/2011 * Author: victor */ #include "server/zone/objects/area/SpawnArea.h" #include "server/zone/Zone.h" #include "server/zone/managers/creature/CreatureManager.h" #include "server/zone/managers/creature/CreatureTemplateManager.h" #include "server/zone/managers/creature/SpawnGroup.h" #include "server/zone/managers/collision/CollisionManager.h" #include "server/zone/managers/planet/PlanetManager.h" #include "server/zone/objects/area/SpawnAreaObserver.h" #include "server/zone/objects/area/areashapes/AreaShape.h" #include "server/ServerCore.h" #include "events/RemoveNoSpawnAreaTask.h" Vector3 SpawnAreaImplementation::getRandomPosition(SceneObject* player) { Vector3 position; bool positionFound = false; int retries = 10; while (!positionFound && retries-- > 0) { position = areaShape->getRandomPosition(player->getWorldPosition(), 64.0f, 256.0f); positionFound = true; for (int i = 0; i < noSpawnAreas.size(); ++i) { SpawnArea* noSpawnArea = noSpawnAreas.get(i); if (noSpawnArea->containsPoint(position.getX(), position.getY())) { positionFound = false; break; } } } if (!positionFound) { position.set(0, 0, 0); } return position; } int SpawnAreaImplementation::notifyObserverEvent(unsigned int eventType, Observable* observable, ManagedObject* arg1, int64 arg2) { if (eventType != ObserverEventType::OBJECTREMOVEDFROMZONE) return 1; SceneObject* sceno = dynamic_cast<SceneObject*>(observable); if (sceno == NULL) return 1; Locker locker(_this.get()); uint32 lairTemplate = spawnTypes.remove(sceno->getObjectID()); if (lairTemplate != 0) { int currentSpawnCount = spawnCountByType.get(lairTemplate) - 1; if (currentSpawnCount < 1) spawnCountByType.remove(lairTemplate); else spawnCountByType.put(lairTemplate, currentSpawnCount); --totalSpawnCount; locker.release(); ManagedReference<ActiveArea*> area = (ServerCore::getZoneServer()->createObject(String("object/active_area.iff").hashCode(), 0)).castTo<ActiveArea*>(); area->setRadius(64); area->setNoSpawnArea(true); area->initializePosition(sceno->getPositionX(), sceno->getPositionZ(), sceno->getPositionY()); zone->transferObject(area, -1, true); Reference<Task*> task = new RemoveNoSpawnAreaTask(area); task->schedule(300000); } return 1; } SpawnGroup* SpawnAreaImplementation::getSpawnGroup() { if (spawnGroup == NULL && spawnGroupTemplateCRC != 0) spawnGroup = CreatureTemplateManager::instance()->getSpawnGroup(spawnGroupTemplateCRC); return spawnGroup; } void SpawnAreaImplementation::notifyEnter(SceneObject* object) { if (tier & SpawnAreaMap::NOSPAWNAREA) { ActiveAreaImplementation::notifyEnter(object); return; } if (!object->isPlayerCreature()) return; ManagedReference<SceneObject*> parent = object->getParent(); if (parent != NULL && parent->isCellObject()) return; if (object->getCityRegion() != NULL) return; tryToSpawn(object); } void SpawnAreaImplementation::notifyPositionUpdate(QuadTreeEntry* obj) { if (tier & SpawnAreaMap::NOSPAWNAREA) return; CreatureObject* creature = dynamic_cast<CreatureObject*>(obj); if (creature == NULL) return; if (!creature->isPlayerCreature()) return; ManagedReference<SceneObject*> parent = creature->getParent(); if (parent != NULL && parent->isCellObject()) return; if (System::random(25) == 1) tryToSpawn(creature); } void SpawnAreaImplementation::notifyExit(SceneObject* object) { if (tier & SpawnAreaMap::NOSPAWNAREA) ActiveAreaImplementation::notifyExit(object); } int SpawnAreaImplementation::tryToSpawn(SceneObject* object) { if (spawnGroup == NULL && spawnGroupTemplateCRC != 0) spawnGroup = CreatureTemplateManager::instance()->getSpawnGroup(spawnGroupTemplateCRC); if (spawnGroup == NULL) { error("spawnGroup is NULL in spawn area: " + getDisplayedName()); return 1; } Vector<Reference<LairSpawn*> >* lairs = spawnGroup->getSpawnList(); int totalSize = lairs->size(); if (totalSize == 0) { error("totalSize is NULL"); return 2; } Zone* zone = getZone(); if (zone == NULL) { error("zone is NULL"); return 3; } if (totalSpawnCount >= maxSpawnLimit) return 4; if (lastSpawn.miliDifference() < MINSPAWNINTERVAL) return 5; //Lets choose 3 random spawns; LairSpawn* firstSpawn = lairs->get(System::random(totalSize - 1)); LairSpawn* secondSpawn = lairs->get(System::random(totalSize - 1)); LairSpawn* thirdSpawn = lairs->get(System::random(totalSize - 1)); LairSpawn* finalSpawn = NULL; int totalWeights = firstSpawn->getWeighting() + secondSpawn->getWeighting() + thirdSpawn->getWeighting(); int finalChoice = System::random(totalWeights); if (finalChoice <= firstSpawn->getWeighting()) { finalSpawn = firstSpawn; } else if (finalChoice <= firstSpawn->getWeighting() + secondSpawn->getWeighting()) { finalSpawn = secondSpawn; } else { finalSpawn = thirdSpawn; } ManagedReference<PlanetManager*> planetManager = zone->getPlanetManager(); Vector3 randomPosition = getRandomPosition(object); if (randomPosition.getX() == 0 && randomPosition.getY() == 0) { return 6; } float spawnZ = zone->getHeight(randomPosition.getX(), randomPosition.getY()); randomPosition.setZ(spawnZ); //lets check if we intersect with some object (buildings, etc..) if (CollisionManager::checkSphereCollision(randomPosition, 64.f + finalSpawn->getSize(), zone)) return 7; //don't spawn in cities SortedVector<ManagedReference<ActiveArea* > > activeAreas; zone->getInRangeActiveAreas(randomPosition.getX(), randomPosition.getY(), &activeAreas, true); for (int i = 0; i < activeAreas.size(); ++i) { ActiveArea* area = activeAreas.get(i); if (area->isRegion() || area->isMunicipalZone() || area->isNoSpawnArea()) return 8; } //check in range objects for no build radi if (!planetManager->isBuildingPermittedAt(randomPosition.getX(), randomPosition.getY(), object, finalSpawn->getSize() + 64.f)) { return 9; } // Only spawn on relatively flat land if (planetManager->getTerrainManager()->getHighestHeightDifference(randomPosition.getX() - 10, randomPosition.getY() - 10, randomPosition.getX() + 10, randomPosition.getY() + 10) > 10.0) { return 13; } int spawnLimit = finalSpawn->getSpawnLimit(); Locker _locker(_this.get()); lastSpawn.updateToCurrentTime(); String lairTemplate = finalSpawn->getLairTemplateName(); uint32 lairHashCode = lairTemplate.hashCode(); int currentSpawnCount = spawnCountByType.get(lairHashCode); if (spawnLimit != -1) { if (currentSpawnCount >= spawnLimit) return 10; } int maxDiff = finalSpawn->getMaxDifficulty(); int minDiff = finalSpawn->getMinDifficulty(); int difficultyLevel = System::random(maxDiff - minDiff) + minDiff; int difficulty = (difficultyLevel - minDiff) / ((maxDiff > (minDiff + 5) ? maxDiff - minDiff : 5) / 5); if (difficulty == 5) difficulty = 4; CreatureManager* creatureManager = zone->getCreatureManager(); ManagedReference<SceneObject*> obj = creatureManager->spawn(lairHashCode, difficultyLevel, difficulty, randomPosition.getX(), spawnZ, randomPosition.getY(), finalSpawn->getSize()); if (obj != NULL) { StringBuffer msg; msg << "lair spawned at " << obj->getPositionX() << " " << obj->getPositionY(); obj->info(msg.toString()); } else { error("could not spawn lair " + lairTemplate); return 11; } if (exitObserver == NULL) { exitObserver = new SpawnAreaObserver(_this.get()); exitObserver->deploy(); } spawnTypes.put(obj->getObjectID(), lairHashCode); Locker objLocker(obj); obj->registerObserver(ObserverEventType::OBJECTREMOVEDFROMZONE, exitObserver); ++totalSpawnCount; spawnCountByType.put(lairTemplate.hashCode(), currentSpawnCount); return 0; } <|endoftext|>
<commit_before>#include "Scene.h" Scene::Scene(void) { view_matrix = glm::lookAt(glm::vec3(0.f, 0.f, 0.f), glm::vec3(0.f, 0.f, -1.f), glm::vec3(0.f, 1.f, 0.f)); memset(&KeyStates, 0, sizeof(KeyStates)); // Init Player player = new Player(this, 0.0f, 0.0f); bool game = true; int score = 0; // Init Objects AddObstacle(new Obstacle(this, 15.0, 15.0, 7.00)); AddObstacle(new Obstacle(this, -12.0, -17.0, 9.00)); AddObstacle(new Obstacle(this, 12.0, -6.0, 5.00)); AddObstacle(new Obstacle(this, -16.0, 15.0, 6.00)); for (unsigned int i = 0; i < 10; ++i) AddZombie(new Zombie(this)); } Scene::~Scene(void) { if (player != 0) delete player; //if (test_zombie != 0) delete test_zombie; for (int i = 0; i < objects.size(); i++){ if (objects[i] != 0) delete objects[i]; } } bool Scene::CheckVictoryCondition(void) { int z = zombies.size(); game = true; for(unsigned int i=0; i<zombies.size(); ++i) { if(GetDistance(player->GetObjectPosition(), zombies[i]->GetObjectPosition()) < 2) { game = false; cout << "PRZEGRALES!" << endl; } if (GetDistance(player->GetObjectPosition(), zombies[i]->GetObjectPosition()) > 200) --z; } if(z == 0) { game = false; cout << "WYGRALES!" << endl; } return game; } void Scene::Update(double delta_time) { if (CheckVictoryCondition()){ GroupZombies(); for (unsigned int i = 0; i < objects.size(); i++) { objects[i]->Update(delta_time); } if (KeyStates['w'] || KeyStates['W']) player->Move(glm::vec2(0, 0.3), delta_time); if (KeyStates['s'] || KeyStates['S']) player->Move(glm::vec2(0, -0.3), delta_time); if (KeyStates['a'] || KeyStates['A']) player->Move(glm::vec2(-0.3, 0), delta_time); if (KeyStates['d'] || KeyStates['D']) player->Move(glm::vec2(0.3, 0), delta_time); player->Update(delta_time); } //if (KeyStates['r'] || KeyStates['R']) Restart(); } void Scene::Draw(void) { player->Draw(); for(unsigned int i = 0; i < objects.size(); i++) { objects[i]->Draw(); } } void Scene::PlayerRotate(glm::vec2 heading) { player->Rotate(heading); } void Scene::PlayerShoot(glm::vec2 aim) { player->Shoot(aim); } void Scene::ZombieTarget(glm::vec2 target) { test_zombie->MousePoint(target); } void Scene::Key(unsigned char key) { if (KeyStates['r']) test_zombie->RandomPoint(); } void Scene::KeyState(unsigned char key, bool tf) { KeyStates[key] = tf; } void Scene::AddObject(GameEntity *entity) { objects.push_back(entity); } void Scene::AddZombie(Zombie *entity) { zombies.push_back(entity); objects.push_back(entity); } void Scene::AddObstacle(Obstacle *entity) { obstacles.push_back(entity); objects.push_back(entity); } void Scene::GroupZombies(void) { } ostream& operator<<(ostream &o, const Scene &gw) { o << "---------------- SCENE ---------------" << "\n"; o << "--------------------------------------" << endl; return o; } <commit_msg>Update<commit_after>#include "Scene.h" Scene::Scene(void) { view_matrix = glm::lookAt(glm::vec3(0.f, 0.f, 0.f), glm::vec3(0.f, 0.f, -1.f), glm::vec3(0.f, 1.f, 0.f)); memset(&KeyStates, 0, sizeof(KeyStates)); // Init Player player = new Player(this, 0.0f, 0.0f); bool game = true; int score = 0; // Init Objects AddObstacle(new Obstacle(this, 15.0, 15.0, 7.00)); AddObstacle(new Obstacle(this, -12.0, -17.0, 9.00)); AddObstacle(new Obstacle(this, 12.0, -6.0, 5.00)); AddObstacle(new Obstacle(this, -16.0, 15.0, 6.00)); for (unsigned int i = 0; i < 10; ++i) AddZombie(new Zombie(this)); } Scene::~Scene(void) { if (player != 0) delete player; //if (test_zombie != 0) delete test_zombie; for (int i = 0; i < objects.size(); i++){ if (objects[i] != 0) delete objects[i]; } } bool Scene::CheckVictoryCondition(void) { int z = zombies.size(); game = true; for(unsigned int i=0; i<zombies.size(); ++i) { if(GetDistance(player->GetObjectPosition(), zombies[i]->GetObjectPosition()) < 2) { game = false; cout << "PRZEGRALES!" << endl; } if (GetDistance(player->GetObjectPosition(), zombies[i]->GetObjectPosition()) > 200) --z; } if(z == 0) { game = false; cout << "WYGRALES!" << endl; } return game; } void RenderBitmapString(float x, float y, char *string) { char *c; glColor3f(1, 0, 0); glRasterPos3f(x, y, -0.1); for(c=string; *c != '\0'; c++) { glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, *c); } } float GlutPrint(float x, float y, char *txt, float scale) { int i; int len=strlen(txt); for(i=0; i<len; i++) { glRasterPos2f(x, y); glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, txt[i]); x += glutBitmapWidth(GLUT_BITMAP_TIMES_ROMAN_24, txt[i])*scale; } return 0; } void PrintText(char* string, int x, int y) { if(string && strlen(string)) { glPushMatrix(); glLoadIdentity(); glScalef(0.003f, 0.003f,0.003f); glColor3f(1, 0, 0); glRasterPos3d(x, y, 0.1); while(*string) { glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, *string); string++; } glPopMatrix(); } } void Scene::Update(double delta_time) { if (CheckVictoryCondition()){ GroupZombies(); for (unsigned int i = 0; i < objects.size(); i++) { objects[i]->Update(delta_time); } if (KeyStates['w'] || KeyStates['W']) player->Move(glm::vec2(0, 0.3), delta_time); if (KeyStates['s'] || KeyStates['S']) player->Move(glm::vec2(0, -0.3), delta_time); if (KeyStates['a'] || KeyStates['A']) player->Move(glm::vec2(-0.3, 0), delta_time); if (KeyStates['d'] || KeyStates['D']) player->Move(glm::vec2(0.3, 0), delta_time); player->Update(delta_time); } //if (KeyStates['r'] || KeyStates['R']) Restart(); } void Scene::Draw(void) { player->Draw(); for(unsigned int i = 0; i < objects.size(); i++) { objects[i]->Draw(); } } void Scene::PlayerRotate(glm::vec2 heading) { player->Rotate(heading); } void Scene::PlayerShoot(glm::vec2 aim) { player->Shoot(aim); } void Scene::ZombieTarget(glm::vec2 target) { test_zombie->MousePoint(target); } void Scene::Key(unsigned char key) { if (KeyStates['r']) test_zombie->RandomPoint(); } void Scene::KeyState(unsigned char key, bool tf) { KeyStates[key] = tf; } void Scene::AddObject(GameEntity *entity) { objects.push_back(entity); } void Scene::AddZombie(Zombie *entity) { zombies.push_back(entity); objects.push_back(entity); } void Scene::AddObstacle(Obstacle *entity) { obstacles.push_back(entity); objects.push_back(entity); } void Scene::GroupZombies(void) { } ostream& operator<<(ostream &o, const Scene &gw) { o << "---------------- SCENE ---------------" << "\n"; o << "--------------------------------------" << endl; return o; } <|endoftext|>
<commit_before>//ArmCollisionDetector2018 //Created by Etienne C.-C. // coucaste@informatik.hu-berlin.de #include "ArmCollisionDetector2018.h" #include <PlatformInterface/Platform.h> #include "Tools/Math/Polygon.h" using namespace naoth; ArmCollisionDetector2018::ArmCollisionDetector2018() { //Debug Requests DEBUG_REQUEST_REGISTER("Motion:ArmCollisionDetector2018:showReferenceHull", "", false); DEBUG_REQUEST_REGISTER("Motion:ArmCollisionDetector2018:showLeftBuffer", "", false); DEBUG_REQUEST_REGISTER("Motion:ArmCollisionDetector2018:showRightBuffer", "", false); getDebugParameterList().add(&params); double alpha, beta; const std::string& dirlocation = Platform::getInstance().theConfigDirectory; std::ifstream fileLeft(dirlocation + params.point_configLeft); while (fileLeft>>alpha>>beta) { getCollisionPercept().referenceHullLeft.emplace_back(alpha, beta); } fileLeft.close(); std::ifstream fileRight(dirlocation + params.point_configRight); while (fileRight >> alpha >> beta) { getCollisionPercept().referenceHullRight.emplace_back(alpha, beta); } fileRight.close(); getCollisionPercept().referenceHullLeft = ConvexHull::convexHull(getCollisionPercept().referenceHullLeft); getCollisionPercept().referenceHullRight = ConvexHull::convexHull(getCollisionPercept().referenceHullRight); refpolyL.makeFromPointSet(getCollisionPercept().referenceHullLeft); refpolyR.makeFromPointSet(getCollisionPercept().referenceHullRight); } ArmCollisionDetector2018::~ArmCollisionDetector2018() { getDebugParameterList().remove(&params); } void ArmCollisionDetector2018::execute() { //Check if robot is in a suitable situation to recognize collisions# const bool bodymodeOK = getBodyState().fall_down_state != BodyState::upright; const bool armModeOK = getMotionRequest().armMotionRequest.id == ArmMotionRequest::arms_synchronised_with_walk || getMotionRequest().armMotionRequest.id == ArmMotionRequest::arms_down; const bool motionModeOK = getMotionStatus().currentMotion == motion::walk || getMotionStatus().currentMotion == motion::stand; // clear the joint command history in order to not check for collision while the robot is already executing a evasive movement for example if (!armModeOK || !motionModeOK || !bodymodeOK) { jointDataBufferLeft.clear(); jointDataBufferRight.clear(); collisionBufferLeft.clear(); collisionBufferRight.clear(); collisionBufferLeftRoll.clear(); collisionBufferRightRoll.clear(); return; } //collect Motorjoint Data and adjust timelag (Motor is 4 Frames ahead of Sensor) jointDataBufferLeft.add(getMotorJointData().position[JointData::LShoulderPitch]); jointDataBufferRight.add(getMotorJointData().position[JointData::RShoulderPitch]); jointDataBufferLeftRoll.add(getMotorJointData().position[JointData::LShoulderRoll]); jointDataBufferRightRoll.add(getMotorJointData().position[JointData::RShoulderRoll]); //When the robots arms are down, they are less sensible to collisions, so in that case we lower the sensitivity //by using the more sensitive threshold method if (getMotionRequest().armMotionRequest.id == ArmMotionRequest::arms_down) { if (jointDataBufferLeft.isFull()) { double e = jointDataBufferLeft.first() - getSensorJointData().position[JointData::LShoulderPitch]; collisionBufferLeft.add(std::fabs(e)); } if (jointDataBufferRight.isFull()) { double e = jointDataBufferRight.first() - getSensorJointData().position[JointData::RShoulderPitch]; collisionBufferRight.add(std::fabs(e)); } double max_error = params.maxErrorStand; // collision arm left if (collisionBufferLeft.isFull() && collisionBufferLeft.getAverage() > max_error) { getCollisionPercept().timeCollisionArmLeft = getFrameInfo().getTime(); jointDataBufferLeft.clear(); collisionBufferLeft.clear(); } // collision arm right if (collisionBufferRight.isFull() && collisionBufferRight.getAverage() > max_error) { getCollisionPercept().timeCollisionArmRight = getFrameInfo().getTime(); jointDataBufferRight.clear(); collisionBufferRight.clear(); } return; } else { collisionBufferLeft.clear(); collisionBufferRight.clear(); } { // Arm Roll Collision if (jointDataBufferLeftRoll.isFull()) { double e = jointDataBufferLeftRoll.first() - getSensorJointData().position[JointData::LShoulderRoll]; collisionBufferLeftRoll.add(e); } if (jointDataBufferRightRoll.isFull()) { double e = jointDataBufferRightRoll.first() - getSensorJointData().position[JointData::RShoulderRoll]; collisionBufferRightRoll.add(e); } double max_error = params.armRollError; // collision arm left if (collisionBufferLeftRoll.isFull() && std::fabs(collisionBufferLeftRoll.getAverage()) > max_error) { getCollisionPercept().timeCollisionArmLeft = getFrameInfo().getTime(); jointDataBufferLeftRoll.clear(); collisionBufferLeftRoll.clear(); } // collision arm right if (collisionBufferRightRoll.isFull() && std::fabs(collisionBufferRightRoll.getAverage()) > max_error) { getCollisionPercept().timeCollisionArmRight = getFrameInfo().getTime(); jointDataBufferRightRoll.clear(); collisionBufferRightRoll.clear(); } } //In this part we check for collision using the "Polygon method" if (jointDataBufferLeft.isFull()) { double a = jointDataBufferLeft.first(); double b = getSensorJointData().position[JointData::LShoulderPitch]; double er = (b - a); if (!refpolyL.isInside(Vector2d(a, er))) { //collision getCollisionPercept().timeCollisionArmLeft = getFrameInfo().getTime(); jointDataBufferLeft.clear(); } } if (jointDataBufferRight.isFull()) { double a = jointDataBufferRight.first(); double b = getSensorJointData().position[JointData::RShoulderPitch]; double er = (b - a); if (!refpolyR.isInside(Vector2d(a, er))) { //collision getCollisionPercept().timeCollisionArmRight = getFrameInfo().getTime(); jointDataBufferRight.clear(); } } }<commit_msg>reformatted<commit_after>//ArmCollisionDetector2018 //Created by Etienne C.-C. // coucaste@informatik.hu-berlin.de #include "ArmCollisionDetector2018.h" #include <PlatformInterface/Platform.h> #include "Tools/Math/Polygon.h" using namespace naoth; ArmCollisionDetector2018::ArmCollisionDetector2018() { //Debug Requests //Debug Requests end getDebugParameterList().add(&params); double alpha, beta; const std::string& dirlocation = Platform::getInstance().theConfigDirectory; std::ifstream fileLeft(dirlocation + params.point_configLeft); while (fileLeft >> alpha >> beta) { getCollisionPercept().referenceHullLeft.emplace_back(alpha, beta); } fileLeft.close(); std::ifstream fileRight(dirlocation + params.point_configRight); while (fileRight >> alpha >> beta) { getCollisionPercept().referenceHullRight.emplace_back(alpha, beta); } fileRight.close(); getCollisionPercept().referenceHullLeft = ConvexHull::convexHull(getCollisionPercept().referenceHullLeft); getCollisionPercept().referenceHullRight = ConvexHull::convexHull(getCollisionPercept().referenceHullRight); refpolyL.makeFromPointSet(getCollisionPercept().referenceHullLeft); refpolyR.makeFromPointSet(getCollisionPercept().referenceHullRight); } ArmCollisionDetector2018::~ArmCollisionDetector2018() { getDebugParameterList().remove(&params); } void ArmCollisionDetector2018::execute() { //Check if robot is in a suitable situation to recognize collisions# const bool bodymodeOK = getBodyState().fall_down_state != BodyState::upright; const bool armModeOK = getMotionRequest().armMotionRequest.id == ArmMotionRequest::arms_synchronised_with_walk || getMotionRequest().armMotionRequest.id == ArmMotionRequest::arms_down; const bool motionModeOK = getMotionStatus().currentMotion == motion::walk || getMotionStatus().currentMotion == motion::stand; // clear the joint command history in order to not check for collision while the robot is already executing a evasive movement for example if (!armModeOK || !motionModeOK || !bodymodeOK) { jointDataBufferLeft.clear(); jointDataBufferRight.clear(); collisionBufferLeft.clear(); collisionBufferRight.clear(); collisionBufferLeftRoll.clear(); collisionBufferRightRoll.clear(); return; } //collect Motorjoint Data and adjust timelag (Motor is 4 Frames ahead of Sensor) jointDataBufferLeft.add(getMotorJointData().position[JointData::LShoulderPitch]); jointDataBufferRight.add(getMotorJointData().position[JointData::RShoulderPitch]); jointDataBufferLeftRoll.add(getMotorJointData().position[JointData::LShoulderRoll]); jointDataBufferRightRoll.add(getMotorJointData().position[JointData::RShoulderRoll]); //When the robots arms are down, they are less sensible to collisions, so in that case we lower the sensitivity //by using the more sensitive threshold method if (getMotionRequest().armMotionRequest.id == ArmMotionRequest::arms_down) { if (jointDataBufferLeft.isFull()) { double e = jointDataBufferLeft.first() - getSensorJointData().position[JointData::LShoulderPitch]; collisionBufferLeft.add(std::fabs(e)); } if (jointDataBufferRight.isFull()) { double e = jointDataBufferRight.first() - getSensorJointData().position[JointData::RShoulderPitch]; collisionBufferRight.add(std::fabs(e)); } double max_error = params.maxErrorStand; // collision arm left if (collisionBufferLeft.isFull() && collisionBufferLeft.getAverage() > max_error) { getCollisionPercept().timeCollisionArmLeft = getFrameInfo().getTime(); jointDataBufferLeft.clear(); collisionBufferLeft.clear(); } // collision arm right if (collisionBufferRight.isFull() && collisionBufferRight.getAverage() > max_error) { getCollisionPercept().timeCollisionArmRight = getFrameInfo().getTime(); jointDataBufferRight.clear(); collisionBufferRight.clear(); } return; } //End of threshold method else { collisionBufferLeft.clear(); collisionBufferRight.clear(); } // Arm Roll Collision if (jointDataBufferLeftRoll.isFull()) { double e = jointDataBufferLeftRoll.first() - getSensorJointData().position[JointData::LShoulderRoll]; collisionBufferLeftRoll.add(e); } if (jointDataBufferRightRoll.isFull()) { double e = jointDataBufferRightRoll.first() - getSensorJointData().position[JointData::RShoulderRoll]; collisionBufferRightRoll.add(e); } double max_error = params.armRollError; // Arm Roll collision arm left if (collisionBufferLeftRoll.isFull() && std::fabs(collisionBufferLeftRoll.getAverage()) > max_error) { getCollisionPercept().timeCollisionArmLeft = getFrameInfo().getTime(); jointDataBufferLeftRoll.clear(); collisionBufferLeftRoll.clear(); } // Arm Roll collision arm right if (collisionBufferRightRoll.isFull() && std::fabs(collisionBufferRightRoll.getAverage()) > max_error) { getCollisionPercept().timeCollisionArmRight = getFrameInfo().getTime(); jointDataBufferRightRoll.clear(); collisionBufferRightRoll.clear(); } //In this part we check for collision using the "Polygon method" if (jointDataBufferLeft.isFull()) { double a = jointDataBufferLeft.first(); double b = getSensorJointData().position[JointData::LShoulderPitch]; double er = (b - a);// er < 0 means collision from behind, er > 0 from front if (!refpolyL.isInside(Vector2d(a, er))) { //collision getCollisionPercept().timeCollisionArmLeft = getFrameInfo().getTime(); jointDataBufferLeft.clear(); } } if (jointDataBufferRight.isFull()) { double a = jointDataBufferRight.first(); double b = getSensorJointData().position[JointData::RShoulderPitch]; double er = (b - a); // er < 0 means collision from behind, er > 0 from front if (!refpolyR.isInside(Vector2d(a, er))) { //collision getCollisionPercept().timeCollisionArmRight = getFrameInfo().getTime(); jointDataBufferRight.clear(); } } }<|endoftext|>