text
stringlengths
54
60.6k
<commit_before>#include <tree.h> #include <catch.hpp> SCENARIO ("init", "[init]") { Tree<int> test; REQUIRE(test.root_() == nullptr); REQUIRE(test.get_count() == 0); } SCENARIO("insert", "[init]") { Tree<int> test; test.insert_node(5); REQUIRE(test.get_count() == 1); REQUIRE(test.find_node(5, test.root_())->key == 5); } SCENARIO("find_node", "[init]") { Tree<int> test; test.insert_node(4); REQUIRE(test.find_node(4, test.root_()) != nullptr); REQUIRE(test.find_node(4, test.root_())->key == 4); } SCENARIO("get root", "[init]") { Tree<int> test; test.insert_node(4); REQUIRE(test.root_() != 0); } SCENARIO("insert equal elements", "[insert]") { Tree<int> test; test.insert_node(4); test.insert_node(4); REQUIRE(test.get_count() == 1); } SCENARIO ("reading/writing", "[init]") { Tree<int> test1; test1.insert_node(4); test1.insert_node(3); test1.writing("file2.txt"); Tree<int> test2; test2.reading("file2.txt"); REQUIRE(test2.find_node(4, test2.root_())!= nullptr); REQUIRE(test2.find_node(3, test2.root_())!= nullptr); REQUIRE(test1.get_count() == test2.get_count()); } SCENARIO("deleteX") { Tree<int> test; test.insert_node(6); test.insert_node(7); test.insert_node(9); test.deleteVal(6); test.deleteVal(9); REQUIRE(test.find_node(9, test.root_())== nullptr); REQUIRE(test.find_node(7, test.root_())== test.root_()); REQUIRE(test.root_() != nullptr); REQUIRE(test.get_count() == 1); } <commit_msg>Update init.cpp<commit_after>#include <tree.h> #include <catch.hpp> SCENARIO ("init", "[init]") { Tree<int> test; REQUIRE(test.root_() == nullptr); REQUIRE(test.get_count() == 0); } SCENARIO("insert", "[init]") { Tree<int> test; test.insnode(5); REQUIRE(test.get_count() == 1); REQUIRE(test.find_node(5, test.root_())->key == 5); } SCENARIO("find_node", "[init]") { Tree<int> test; test.insnode(4); REQUIRE(test.find_node(4, test.root_()) != nullptr); REQUIRE(test.find_node(4, test.root_())->key == 4); } SCENARIO("get root", "[init]") { Tree<int> test; test.insnode(4); REQUIRE(test.root_() != 0); } SCENARIO("insert equal elements", "[insert]") { Tree<int> test; test.insnode(4); test.insnode(4); REQUIRE(test.get_count() == 1); } SCENARIO ("reading/writing", "[init]") { Tree<int> test1; test1.insnode(4); test1.insnode(3); test1.write("file2.txt"); Tree<int> test2; test2.read("file2.txt"); REQUIRE(test2.find_node(4, test2.root_())!= nullptr); REQUIRE(test2.find_node(3, test2.root_())!= nullptr); REQUIRE(test1.get_count() == test2.get_count()); } SCENARIO("deleteX") { Tree<int> test; test.insnode(6); test.insnode(7); test.insnode(9); test.deleteVal(6); test.deleteVal(9); REQUIRE(test.find_node(9, test.root_())== nullptr); REQUIRE(test.find_node(7, test.root_())== test.root_()); REQUIRE(test.root_() != nullptr); REQUIRE(test.get_count() == 1); } <|endoftext|>
<commit_before>#include <stack.cpp> #include <catch.hpp> #include <iostream> //using namespace std; SCENARIO("count", "[count]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); } SCENARIO("push", "[push]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("top", "[top]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("pop", "[pop]"){ stack<int> s; s.push(1); s.push(2); s.pop(); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("prisv", "[prisv]"){ stack<int> s; s.push(1); stack<int> s2; s2=s; REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("copy", "[copy]"){ stack<int> s; s.push(1); stack <int> a = s; REQUIRE(a.count()==1); REQUIRE(a.top()==1); } SCENARIO("test", "[test]"){ stack<int> s; REQUIRE(s.count()==0); } SCENARIO("empty", "[empty]"){ stack<int> s; REQUIRE(s.empty()==true); } <commit_msg>Update init.cpp<commit_after>#include "stack.hpp" #include <catch.hpp> #include <iostream> //using namespace std; SCENARIO("count", "[count]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); } SCENARIO("push", "[push]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("top", "[top]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("pop", "[pop]"){ stack<int> s; s.push(1); s.push(2); s.pop(); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("prisv", "[prisv]"){ stack<int> s; s.push(1); stack<int> s2; s2=s; REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("copy", "[copy]"){ stack<int> s; s.push(1); stack <int> a = s; REQUIRE(a.count()==1); REQUIRE(a.top()==1); } SCENARIO("test", "[test]"){ stack<int> s; REQUIRE(s.count()==0); } SCENARIO("empty", "[empty]"){ stack<int> s; REQUIRE(s.empty()==true); } <|endoftext|>
<commit_before>#include <BST.hpp> #include <catch.hpp> #include <fstream> SCENARIO ("init", "[init]") { BST<int> test; REQUIRE(test.getroot() == nullptr); REQUIRE(test.getcount() == 0); } SCENARIO("insert", "[init]") { BST<int> test; test.add(10); REQUIRE(test.search(10, test.getroot()) != 0); } SCENARIO("find_node", "[init]") { BST<int> test; test.add(10); REQUIRE(test.search(10, test.getroot()) != 0); REQUIRE(test.search(10, test.getroot()) != 0); } SCENARIO("get root", "[init]") { BST<int> test; test.add(10); REQUIRE(test.getcount() == 1); REQUIRE(test.getroot() != 0); } SCENARIO("del", "[init]") { BST<int> test; test.add(1); test.add(2); test.add(3); test.del(test.getroot(), 1); test.del(test.getroot(), 2); REQUIRE(test.search(1, test.getroot()) != 0); REQUIRE(test.search(2, test.getroot()) == 0); REQUIRE(test.search(3, test.getroot())!= 0); } <commit_msg>Update init.cpp<commit_after>#include <BST.hpp> #include <catch.hpp> #include <fstream> SCENARIO ("init", "[init]") { BST<int> test; REQUIRE(test.getroot() == nullptr); REQUIRE(test.getcount() == 0); } SCENARIO("insert", "[init]") { BST<int> test; test.add(10); REQUIRE(test.search(10, test.getroot()) != 0); } SCENARIO("find_node", "[init]") { BST<int> test; test.add(10); REQUIRE(test.search(10, test.getroot()) != 0); REQUIRE(test.search(10, test.getroot()) != 0); } SCENARIO("get root", "[init]") { BST<int> test; test.add(10); REQUIRE(test.getcount() == 1); REQUIRE(test.getroot() != 0); } /*SCENARIO("del", "[init]") { BST<int> test; test.add(1); test.add(2); test.add(3); test.del(test.getroot(), 1); test.del(test.getroot(), 2); REQUIRE(test.search(1, test.getroot()) != 0); REQUIRE(test.search(2, test.getroot()) == 0); REQUIRE(test.search(3, test.getroot())!= 0); }*/ <|endoftext|>
<commit_before>#include "catch.hpp" #include <iostream> //#include "Database_Creator.hpp" #include "Database_Sorter.hpp" person readPerson(std::string file_name, size_t index) { person result; std::ifstream file(file_name); for (size_t i = 0; i < index + 1; i++) { file >> result; } file.close(); return result; } bool isANotMoreThanB(person A, person B) { char * A_name = A.getName(); char * B_name = B.getName(); for (size_t i = 0; i < A.name_length; i++) { char A_char = name[i]; char B_char = (i < B.name_length) ? B_name[i] : ' '; if (letterI(A_name[i], i == 0) < letterI(B_name[i], i == 0)) { return true; } else { if (A_name[i] != B_name[i]) { return false; } } } delete []A_char; delete []B_char; return true; } SCENARIO("Sort", "[s]") { size_t n_persons = 200; //system("start www.cyberforum.ru/cpp-beginners/thread82643.html#post458604"); size_t RAM_amount = 1; std::string names_file_name = "F:\\1\\names.txt"; std::string surnames_file_name = "F:\\1\\surnames.txt"; std::string database_file_name = "F:\\1\\8.txt"; std::string output_file_name = "F:\\1\\sorted_database.txt"; //Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons); Database_Sorter database_sorter(database_file_name, output_file_name, RAM_amount); size_t start = clock(); database_sorter.sortDatabase(); size_t result = clock() - start; database_sorter.closeDatabase(); std::cout << result << std::endl; for (size_t i = 0; i < 0; i++) { size_t person1_i = rand() % n_persons; size_t person2_i = person1_i + rand() % (n_persons - person1_i); person person1 = readPerson(output_file_name, person1_i); person person2 = readPerson(output_file_name, person2_i); REQUIRE(isANotMoreThanB(person1, person2)); } } <commit_msg>Update init.cpp<commit_after>#include "catch.hpp" #include <iostream> //#include "Database_Creator.hpp" #include "Database_Sorter.hpp" person readPerson(std::string file_name, size_t index) { person result; std::ifstream file(file_name); for (size_t i = 0; i < index + 1; i++) { file >> result; } file.close(); return result; } bool isANotMoreThanB(person A, person B) { char * A_name = A.getName(); char * B_name = B.getName(); for (size_t i = 0; i < A.name_length; i++) { char A_char = name[i]; char B_char = (i < B.name_length) ? B_name[i] : ' '; if (letterI(A_name[i], i == 0) < letterI(B_name[i], i == 0)) { return true; } else { if (A_name[i] != B_name[i]) { return false; } } } delete []A_char; delete []B_char; return true; } SCENARIO("Sort", "[s]") { size_t n_persons = 200; //system("start www.cyberforum.ru/cpp-beginners/thread82643.html#post458604"); size_t RAM_amount = 1; std::string names_file_name = "F:\\1\\names.txt"; std::string surnames_file_name = "F:\\1\\surnames.txt"; std::string database_file_name = "8.txt"; std::string output_file_name = "F:\\1\\sorted_database.txt"; //Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons); Database_Sorter database_sorter(database_file_name, output_file_name, RAM_amount); size_t start = clock(); database_sorter.sortDatabase(); size_t result = clock() - start; database_sorter.closeDatabase(); std::cout << result << std::endl; for (size_t i = 0; i < 0; i++) { size_t person1_i = rand() % n_persons; size_t person2_i = person1_i + rand() % (n_persons - person1_i); person person1 = readPerson(output_file_name, person1_i); person person2 = readPerson(output_file_name, person2_i); REQUIRE(isANotMoreThanB(person1, person2)); } } <|endoftext|>
<commit_before>#include <BinaryTree.hpp> #include <catch.hpp> SCENARIO ("init", "[init]") { BinaryTree<int> obj; REQUIRE(obj.root_() == nullptr); } SCENARIO("insert", "[insert]") { BinaryTree<int> obj; obj.insert_node(3); REQUIRE(obj.find_node(3, obj.root_())->data == 3); } SCENARIO("find_node", "[find_node]") { BinaryTree<int> obj; obj.insert_node(2); REQUIRE(obj.find_node(2, obj.root_()) != nullptr); REQUIRE(obj.find_node(2, obj.root_())->data == 2); } SCENARIO("get root", "[get root]") { BinaryTree<int> obj; obj.insert_node(4); REQUIRE(obj.root_() != 0); } SCENARIO ("reading", "[init]") { BinaryTree<int> obj; obj.reading("file2.txt"); REQUIRE(obj.search_result(1) == 1)); } <commit_msg>Update init.cpp<commit_after>#include <BinaryTree.hpp> #include <catch.hpp> SCENARIO ("init", "[init]") { BinaryTree<int> obj; REQUIRE(obj.root_() == nullptr); } SCENARIO("insert", "[insert]") { BinaryTree<int> obj; obj.insert_node(3); REQUIRE(obj.find_node(3, obj.root_())->data == 3); } SCENARIO("find_node", "[find_node]") { BinaryTree<int> obj; obj.insert_node(2); REQUIRE(obj.find_node(2, obj.root_()) != nullptr); REQUIRE(obj.find_node(2, obj.root_())->data == 2); } SCENARIO("get root", "[get root]") { BinaryTree<int> obj; obj.insert_node(4); REQUIRE(obj.root_() != 0); } SCENARIO ("reading", "[init]") { BinaryTree<int> obj; obj.reading("file2.txt"); REQUIRE(obj.search_result(1) == 1); } <|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" class ListTest : public ::testing::Test { protected: co_obj_t *List16; co_obj_t *List32; void InsertObj(); void DeleteObj(); ListTest() { List16 = co_list16_create(); List32 = co_list32_create(); } virtual void SetUp() { } ~ListTest() { co_obj_free(List16); co_obj_free(List32); } }; void ListTest::InsertObj() { co_obj_t *TestString1 = co_bin8_create("1TESTVALUE1", 11, 0); int ret = co_list_append(List16, TestString1); ASSERT_EQ(1, ret); ret = co_list_contains(List16, TestString1); ASSERT_EQ(1, ret); co_obj_t *TestString2 = co_bin8_create("2TESTVALUE2", 12, 0); ret = co_list_append(List16, TestString2); ASSERT_EQ(1, ret); ret = co_list_contains(List16, TestString2); ASSERT_EQ(1, ret); ret = co_list_append(List32, TestString1); ASSERT_EQ(1, ret); ret = co_list_contains(List32, TestString1); ASSERT_EQ(1, ret); ret = co_list_append(List32, TestString2); ASSERT_EQ(1, ret); ret = co_list_contains(List32, TestString2); ASSERT_EQ(1, ret); } void ListTest::DeleteObj() { co_obj_t *TestString1 = co_bin8_create("1TESTVALUE1", 11, 0); int ret = co_list_append(List16, TestString1); ASSERT_EQ(1, ret); co_obj_t *ptr = co_list_delete(List16, TestString1); ASSERT_EQ(TestString1, ptr); co_obj_t *TestString2 = co_bin8_create("2TESTVALUE2", 11, 0); ret = co_list_append(List16, TestString2); ASSERT_EQ(1, ret); ptr = co_list_delete(List16, TestString2); ASSERT_EQ(TestString2, ptr); } TEST_F(ListTest, ListInsertTest) { InsertObj(); } TEST_F(ListTest, ListDeleteTest) { DeleteObj(); } <commit_msg>refactored test setups<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" class ListTest : public ::testing::Test { protected: co_obj_t *List16; co_obj_t *List32; void InsertObj(); void DeleteObj(); co_obj_t *TestString1; co_obj_t *TestString2; co_obj_t *TestString3; ListTest() { List16 = co_list16_create(); List32 = co_list32_create(); TestString1 = co_bin8_create("1TESTVALUE1", 12, 0); TestString2 = co_bin8_create("2TESTVALUE2", 12, 0); TestString3 = co_bin8_create("3TESTVALUE3", 12, 0); } virtual void SetUp() { } ~ListTest() { co_obj_free(List16); co_obj_free(List32); } }; void ListTest::InsertObj() { int ret = co_list_append(List16, TestString1); ASSERT_EQ(1, ret); ret = co_list_contains(List16, TestString1); ASSERT_EQ(1, ret); ret = co_list_append(List16, TestString2); ASSERT_EQ(1, ret); ret = co_list_contains(List16, TestString2); ASSERT_EQ(1, ret); // repeat for List32 ret = co_list_append(List32, TestString1); ASSERT_EQ(1, ret); ret = co_list_contains(List32, TestString1); ASSERT_EQ(1, ret); ret = co_list_append(List32, TestString2); ASSERT_EQ(1, ret); ret = co_list_contains(List32, TestString2); ASSERT_EQ(1, ret); } void ListTest::DeleteObj() { int ret = co_list_append(List16, TestString1); ASSERT_EQ(1, ret); co_obj_t *ptr = co_list_delete(List16, TestString1); ASSERT_EQ(TestString1, ptr); ret = co_list_append(List16, TestString2); ASSERT_EQ(1, ret); ptr = co_list_delete(List16, TestString2); ASSERT_EQ(TestString2, ptr); } TEST_F(ListTest, ListInsertTest) { InsertObj(); } TEST_F(ListTest, ListDeleteTest) { DeleteObj(); } <|endoftext|>
<commit_before>/* C++ interface test */ #include <libmemcached/memcached.hpp> #include <cstdio> #include <cstdlib> #include <cstring> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <ctime> #include <libtest/server.h> #include <libtest/test.hpp> #include <string> #include <iostream> using namespace std; using namespace memcache; extern "C" { test_return_t basic_test(memcached_st *memc); test_return_t increment_test(memcached_st *memc); test_return_t basic_master_key_test(memcached_st *memc); test_return_t mget_result_function(memcached_st *memc); test_return_t basic_behavior(memcached_st *memc); test_return_t mget_test(memcached_st *memc); memcached_return_t callback_counter(const memcached_st *, memcached_result_st *, void *context); } static void populate_vector(vector<char> &vec, const string &str) { vec.reserve(str.length()); vec.assign(str.begin(), str.end()); } static void copy_vec_to_string(vector<char> &vec, string &str) { str.clear(); if (not vec.empty()) { str.assign(vec.begin(), vec.end()); } } test_return_t basic_test(memcached_st *memc) { Memcache foo(memc); const string value_set("This is some data"); std::vector<char> value; std::vector<char> test_value; populate_vector(value, value_set); test_true(foo.set("mine", value, 0, 0)); test_true(foo.get("mine", test_value)); test_memcmp(&test_value[0], &value[0], test_value.size()); test_false(foo.set("", value, 0, 0)); return TEST_SUCCESS; } test_return_t increment_test(memcached_st *original) { Memcache mcach(original); const string key("blah"); const string inc_value("1"); std::vector<char> inc_val; vector<char> ret_value; string ret_string; uint64_t int_inc_value; uint64_t int_ret_value; populate_vector(inc_val, inc_value); test_true(mcach.set(key, inc_val, 0, 0)); test_true(mcach.get(key, ret_value)); test_false(ret_value.empty()); copy_vec_to_string(ret_value, ret_string); int_inc_value= uint64_t(atol(inc_value.c_str())); int_ret_value= uint64_t(atol(ret_string.c_str())); test_compare(int_inc_value, int_ret_value); test_true(mcach.increment(key, 1, &int_ret_value)); test_compare(2, int_ret_value); test_true(mcach.increment(key, 1, &int_ret_value)); test_compare(3, int_ret_value); test_true(mcach.increment(key, 5, &int_ret_value)); test_compare(8, int_ret_value); return TEST_SUCCESS; } test_return_t basic_master_key_test(memcached_st *original) { Memcache foo(original); const string value_set("Data for server A"); vector<char> value; vector<char> test_value; const string master_key_a("server-a"); const string master_key_b("server-b"); const string key("xyz"); populate_vector(value, value_set); foo.setByKey(master_key_a, key, value, 0, 0); foo.getByKey(master_key_a, key, test_value); test_true((memcmp(&value[0], &test_value[0], value.size()) == 0)); test_value.clear(); foo.getByKey(master_key_b, key, test_value); test_true((memcmp(&value[0], &test_value[0], value.size()) == 0)); return TEST_SUCCESS; } /* Count the results */ memcached_return_t callback_counter(const memcached_st *, memcached_result_st *, void *context) { unsigned int *counter= static_cast<unsigned int *>(context); *counter= *counter + 1; return MEMCACHED_SUCCESS; } test_return_t mget_test(memcached_st *original) { Memcache memc(original); memcached_return_t mc_rc; vector<string> keys; vector< vector<char> *> values; keys.reserve(3); keys.push_back("fudge"); keys.push_back("son"); keys.push_back("food"); vector<char> val1; vector<char> val2; vector<char> val3; populate_vector(val1, "fudge"); populate_vector(val2, "son"); populate_vector(val3, "food"); values.reserve(3); values.push_back(&val1); values.push_back(&val2); values.push_back(&val3); string return_key; vector<char> return_value; /* We need to empty the server before we continue the test */ test_true(memc.flush()); test_true(memc.mget(keys)); test_compare(MEMCACHED_NOTFOUND, memc.fetch(return_key, return_value)); test_true(memc.setAll(keys, values, 50, 9)); test_true(memc.mget(keys)); size_t count= 0; while ((mc_rc= memc.fetch(return_key, return_value)) == MEMCACHED_SUCCESS) { test_compare(return_key.length(), return_value.size()); test_memcmp(&return_value[0], return_key.c_str(), return_value.size()); count++; } test_compare(values.size(), count); return TEST_SUCCESS; } test_return_t basic_behavior(memcached_st *original) { Memcache memc(original); uint64_t value= 1; test_true(memc.setBehavior(MEMCACHED_BEHAVIOR_VERIFY_KEY, value)); uint64_t behavior= memc.getBehavior(MEMCACHED_BEHAVIOR_VERIFY_KEY); test_compare(behavior, value); return TEST_SUCCESS; } test_st tests[] ={ { "basic", 0, reinterpret_cast<test_callback_fn*>(basic_test) }, { "basic_master_key", 0, reinterpret_cast<test_callback_fn*>(basic_master_key_test) }, { "increment_test", 0, reinterpret_cast<test_callback_fn*>(increment_test) }, { "mget", 1, reinterpret_cast<test_callback_fn*>(mget_test) }, { "basic_behavior", 0, reinterpret_cast<test_callback_fn*>(basic_behavior) }, {0, 0, 0} }; collection_st collection[] ={ {"block", 0, 0, tests}, {0, 0, 0, 0} }; #define SERVERS_TO_CREATE 5 #include "libmemcached_world.h" void get_world(Framework *world) { world->collections= collection; world->_create= reinterpret_cast<test_callback_create_fn*>(world_create); world->_destroy= reinterpret_cast<test_callback_fn*>(world_destroy); world->item._startup= reinterpret_cast<test_callback_fn*>(world_test_startup); world->item._flush= reinterpret_cast<test_callback_fn*>(world_flush); world->item.set_pre(reinterpret_cast<test_callback_fn*>(world_pre_run)); world->item.set_post(reinterpret_cast<test_callback_fn*>(world_post_run)); world->_on_error= reinterpret_cast<test_callback_error_fn*>(world_on_error); world->collection_startup= reinterpret_cast<test_callback_fn*>(world_container_startup); world->collection_shutdown= reinterpret_cast<test_callback_fn*>(world_container_shutdown); world->runner= &defualt_libmemcached_runner; } <commit_msg>Fix for lp:802952<commit_after>/* C++ interface test */ #include <libmemcached/memcached.hpp> #include <cstdio> #include <cstdlib> #include <cstring> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <ctime> #include <libtest/server.h> #include <libtest/test.hpp> #include <string> #include <iostream> using namespace std; using namespace memcache; extern "C" { test_return_t basic_test(memcached_st *memc); test_return_t increment_test(memcached_st *memc); test_return_t basic_master_key_test(memcached_st *memc); test_return_t mget_result_function(memcached_st *memc); test_return_t basic_behavior(memcached_st *memc); test_return_t mget_test(memcached_st *memc); memcached_return_t callback_counter(const memcached_st *, memcached_result_st *, void *context); } static void populate_vector(vector<char> &vec, const string &str) { vec.reserve(str.length()); vec.assign(str.begin(), str.end()); } static void copy_vec_to_string(vector<char> &vec, string &str) { str.clear(); if (not vec.empty()) { str.assign(vec.begin(), vec.end()); } } test_return_t basic_test(memcached_st *memc) { Memcache foo(memc); const string value_set("This is some data"); std::vector<char> value; std::vector<char> test_value; populate_vector(value, value_set); test_true(foo.set("mine", value, 0, 0)); test_true(foo.get("mine", test_value)); test_memcmp(&test_value[0], &value[0], test_value.size()); test_false(foo.set("", value, 0, 0)); return TEST_SUCCESS; } test_return_t increment_test(memcached_st *original) { Memcache mcach(original); const string key("blah"); const string inc_value("1"); std::vector<char> inc_val; vector<char> ret_value; string ret_string; uint64_t int_inc_value; uint64_t int_ret_value; populate_vector(inc_val, inc_value); test_true(mcach.set(key, inc_val, 0, 0)); test_true(mcach.get(key, ret_value)); test_false(ret_value.empty()); copy_vec_to_string(ret_value, ret_string); int_inc_value= uint64_t(atol(inc_value.c_str())); int_ret_value= uint64_t(atol(ret_string.c_str())); test_compare(int_inc_value, int_ret_value); test_true(mcach.increment(key, 1, &int_ret_value)); test_compare(2, int_ret_value); test_true(mcach.increment(key, 1, &int_ret_value)); test_compare(3, int_ret_value); test_true(mcach.increment(key, 5, &int_ret_value)); test_compare(8, int_ret_value); return TEST_SUCCESS; } test_return_t basic_master_key_test(memcached_st *original) { Memcache foo(original); const string value_set("Data for server A"); vector<char> value; vector<char> test_value; const string master_key_a("server-a"); const string master_key_b("server-b"); const string key("xyz"); populate_vector(value, value_set); test_true(foo.setByKey(master_key_a, key, value, 0, 0)); test_true(foo.getByKey(master_key_a, key, test_value)); test_compare(value.size(), test_value.size()); test_memcmp(&value[0], &test_value[0], value.size()); test_value.clear(); test_false(foo.getByKey(master_key_b, key, test_value)); test_compare(0, test_value.size()); return TEST_SUCCESS; } /* Count the results */ memcached_return_t callback_counter(const memcached_st *, memcached_result_st *, void *context) { unsigned int *counter= static_cast<unsigned int *>(context); *counter= *counter +1; return MEMCACHED_SUCCESS; } test_return_t mget_test(memcached_st *original) { Memcache memc(original); memcached_return_t mc_rc; vector<string> keys; vector< vector<char> *> values; keys.reserve(3); keys.push_back("fudge"); keys.push_back("son"); keys.push_back("food"); vector<char> val1; vector<char> val2; vector<char> val3; populate_vector(val1, "fudge"); populate_vector(val2, "son"); populate_vector(val3, "food"); values.reserve(3); values.push_back(&val1); values.push_back(&val2); values.push_back(&val3); string return_key; vector<char> return_value; /* We need to empty the server before we continue the test */ test_true(memc.flush()); test_true(memc.mget(keys)); test_compare(MEMCACHED_NOTFOUND, memc.fetch(return_key, return_value)); test_true(memc.setAll(keys, values, 50, 9)); test_true(memc.mget(keys)); size_t count= 0; while (memcached_success(mc_rc= memc.fetch(return_key, return_value))) { test_compare(return_key.length(), return_value.size()); test_memcmp(&return_value[0], return_key.c_str(), return_value.size()); count++; } test_compare(values.size(), count); return TEST_SUCCESS; } test_return_t basic_behavior(memcached_st *original) { Memcache memc(original); uint64_t value= 1; test_true(memc.setBehavior(MEMCACHED_BEHAVIOR_VERIFY_KEY, value)); uint64_t behavior= memc.getBehavior(MEMCACHED_BEHAVIOR_VERIFY_KEY); test_compare(behavior, value); return TEST_SUCCESS; } test_st tests[] ={ { "basic", 0, reinterpret_cast<test_callback_fn*>(basic_test) }, { "basic_master_key", 0, reinterpret_cast<test_callback_fn*>(basic_master_key_test) }, { "increment_test", 0, reinterpret_cast<test_callback_fn*>(increment_test) }, { "mget", 1, reinterpret_cast<test_callback_fn*>(mget_test) }, { "basic_behavior", 0, reinterpret_cast<test_callback_fn*>(basic_behavior) }, {0, 0, 0} }; collection_st collection[] ={ {"block", 0, 0, tests}, {0, 0, 0, 0} }; #define SERVERS_TO_CREATE 5 #include "libmemcached_world.h" void get_world(Framework *world) { world->collections= collection; world->_create= reinterpret_cast<test_callback_create_fn*>(world_create); world->_destroy= reinterpret_cast<test_callback_fn*>(world_destroy); world->item._startup= reinterpret_cast<test_callback_fn*>(world_test_startup); world->item._flush= reinterpret_cast<test_callback_fn*>(world_flush); world->item.set_pre(reinterpret_cast<test_callback_fn*>(world_pre_run)); world->item.set_post(reinterpret_cast<test_callback_fn*>(world_post_run)); world->_on_error= reinterpret_cast<test_callback_error_fn*>(world_on_error); world->collection_startup= reinterpret_cast<test_callback_fn*>(world_container_startup); world->collection_shutdown= reinterpret_cast<test_callback_fn*>(world_container_shutdown); world->runner= &defualt_libmemcached_runner; } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: shapeindex.cc 27 2005-03-30 21:45:40Z pavlenko $ #include <iostream> #include <vector> #include <string> #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> #include <boost/program_options.hpp> #include "quadtree.hpp" #include "shapefile.hpp" #include "shape_io.hpp" const int MAXDEPTH = 64; const int DEFAULT_DEPTH = 8; const double MINRATIO=0.5; const double MAXRATIO=0.8; const double DEFAULT_RATIO=0.55; int main (int argc,char** argv) { using namespace mapnik; namespace po = boost::program_options; using std::string; using std::vector; using std::clog; bool verbose=false; unsigned int depth=DEFAULT_DEPTH; double ratio=DEFAULT_RATIO; vector<string> shape_files; try { po::options_description desc("shapeindex utility"); desc.add_options() ("help,h", "produce usage message") ("version,V","print version string") ("verbose,v","verbose output") ("depth,d", po::value<unsigned int>(), "max tree depth\n(default 8)") ("ratio,r",po::value<double>(),"split ratio (default 0.55)") ("shape_files",po::value<vector<string> >(),"shape files to index: file1 file2 ...fileN") ; po::positional_options_description p; p.add("shape_files",-1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("version")) { clog<<"version 0.3.0" <<std::endl; return 1; } if (vm.count("help")) { clog << desc << "\n"; return 1; } if (vm.count("depth")) { depth = vm["depth"].as<unsigned int>(); } if (vm.count("ratio")) { ratio = vm["ratio"].as<double>(); } if (vm.count("shape_files")) { shape_files=vm["shape_files"].as< vector<string> >(); } } catch (...) { clog << "Exception of unknown type!"<<std::endl; return -1; } std::clog<<"max tree depth:"<<depth<<std::endl; std::clog<<"split ratio:"<<ratio<<std::endl; vector<string>::const_iterator itr=shape_files.begin(); if (itr==shape_files.end()) { std::clog << "no shape files to index"<<std::endl; return 0; } while (itr != shape_files.end()) { std::clog<<"processing "<<*itr << std::endl; //shape_file shp; std::string shapename(*itr++); shape_file shp(shapename+".shp"); if (!shp.is_open()) { std::clog<<"error : cannot open "<< (shapename+".shp") <<"\n"; continue; } int code = shp.read_xdr_integer(); //file_code == 9994 std::clog << code << "\n"; shp.skip(5*4); int file_length=shp.read_xdr_integer(); int version=shp.read_ndr_integer(); int shape_type=shp.read_ndr_integer(); Envelope<double> extent; shp.read_envelope(extent); std::clog<<"length="<<file_length<<std::endl; std::clog<<"version="<<version<<std::endl; std::clog<<"type="<<shape_type<<std::endl; std::clog<<"extent:"<<extent<<std::endl; int pos=50; shp.seek(pos*2); quadtree<int> tree(extent,depth,ratio); int count=0; while (true) { long offset=shp.pos(); int record_number=shp.read_xdr_integer(); int content_length=shp.read_xdr_integer(); //std::clog << "rec number = "<< record_number << "\n"; //std::clog << "content length = "<< content_length << "\n"; shp.skip(4); //std::clog << "offset= "<< offset << std::endl; Envelope<double> item_ext; if (shape_type==shape_io::shape_point) { double x=shp.read_double(); double y=shp.read_double(); item_ext=Envelope<double>(x,y,x,y); } else if (shape_type==shape_io::shape_pointm) { double x=shp.read_double(); double y=shp.read_double(); shp.read_double(); item_ext=Envelope<double>(x,y,x,y); } else if (shape_type==shape_io::shape_pointz) { double x=shp.read_double(); double y=shp.read_double(); shp.read_double(); shp.read_double(); item_ext=Envelope<double>(x,y,x,y); } else { shp.read_envelope(item_ext); shp.skip(2*content_length-4*8-4); } tree.insert(offset,item_ext); if (verbose) { std::clog<<"record number "<<record_number<<" box="<<item_ext<<std::endl; } pos+=4+content_length; ++count; if (pos>=file_length) { break; } } shp.close(); std::clog<<" number shapes="<<count<<std::endl; std::fstream file((shapename+".index").c_str(), std::ios::in | std::ios::out | std::ios::trunc | std::ios::binary); if (!file) { std::clog << "cannot open index file for writing file \"" <<(shapename+".index")<<"\""<<std::endl; } else { tree.trim(); std::clog<<" number nodes="<<tree.count()<<std::endl; file.exceptions(ios::failbit | ios::badbit); tree.write(file); file.flush(); file.close(); } } std::clog<<"done!"<<std::endl; return 0; } <commit_msg>added missing std namespace<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: shapeindex.cc 27 2005-03-30 21:45:40Z pavlenko $ #include <iostream> #include <vector> #include <string> #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> #include <boost/program_options.hpp> #include "quadtree.hpp" #include "shapefile.hpp" #include "shape_io.hpp" const int MAXDEPTH = 64; const int DEFAULT_DEPTH = 8; const double MINRATIO=0.5; const double MAXRATIO=0.8; const double DEFAULT_RATIO=0.55; int main (int argc,char** argv) { using namespace mapnik; namespace po = boost::program_options; using std::string; using std::vector; using std::clog; bool verbose=false; unsigned int depth=DEFAULT_DEPTH; double ratio=DEFAULT_RATIO; vector<string> shape_files; try { po::options_description desc("shapeindex utility"); desc.add_options() ("help,h", "produce usage message") ("version,V","print version string") ("verbose,v","verbose output") ("depth,d", po::value<unsigned int>(), "max tree depth\n(default 8)") ("ratio,r",po::value<double>(),"split ratio (default 0.55)") ("shape_files",po::value<vector<string> >(),"shape files to index: file1 file2 ...fileN") ; po::positional_options_description p; p.add("shape_files",-1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("version")) { clog<<"version 0.3.0" <<std::endl; return 1; } if (vm.count("help")) { clog << desc << "\n"; return 1; } if (vm.count("depth")) { depth = vm["depth"].as<unsigned int>(); } if (vm.count("ratio")) { ratio = vm["ratio"].as<double>(); } if (vm.count("shape_files")) { shape_files=vm["shape_files"].as< vector<string> >(); } } catch (...) { clog << "Exception of unknown type!"<<std::endl; return -1; } std::clog<<"max tree depth:"<<depth<<std::endl; std::clog<<"split ratio:"<<ratio<<std::endl; vector<string>::const_iterator itr=shape_files.begin(); if (itr==shape_files.end()) { std::clog << "no shape files to index"<<std::endl; return 0; } while (itr != shape_files.end()) { std::clog<<"processing "<<*itr << std::endl; //shape_file shp; std::string shapename(*itr++); shape_file shp(shapename+".shp"); if (!shp.is_open()) { std::clog<<"error : cannot open "<< (shapename+".shp") <<"\n"; continue; } int code = shp.read_xdr_integer(); //file_code == 9994 std::clog << code << "\n"; shp.skip(5*4); int file_length=shp.read_xdr_integer(); int version=shp.read_ndr_integer(); int shape_type=shp.read_ndr_integer(); Envelope<double> extent; shp.read_envelope(extent); std::clog<<"length="<<file_length<<std::endl; std::clog<<"version="<<version<<std::endl; std::clog<<"type="<<shape_type<<std::endl; std::clog<<"extent:"<<extent<<std::endl; int pos=50; shp.seek(pos*2); quadtree<int> tree(extent,depth,ratio); int count=0; while (true) { long offset=shp.pos(); int record_number=shp.read_xdr_integer(); int content_length=shp.read_xdr_integer(); //std::clog << "rec number = "<< record_number << "\n"; //std::clog << "content length = "<< content_length << "\n"; shp.skip(4); //std::clog << "offset= "<< offset << std::endl; Envelope<double> item_ext; if (shape_type==shape_io::shape_point) { double x=shp.read_double(); double y=shp.read_double(); item_ext=Envelope<double>(x,y,x,y); } else if (shape_type==shape_io::shape_pointm) { double x=shp.read_double(); double y=shp.read_double(); shp.read_double(); item_ext=Envelope<double>(x,y,x,y); } else if (shape_type==shape_io::shape_pointz) { double x=shp.read_double(); double y=shp.read_double(); shp.read_double(); shp.read_double(); item_ext=Envelope<double>(x,y,x,y); } else { shp.read_envelope(item_ext); shp.skip(2*content_length-4*8-4); } tree.insert(offset,item_ext); if (verbose) { std::clog<<"record number "<<record_number<<" box="<<item_ext<<std::endl; } pos+=4+content_length; ++count; if (pos>=file_length) { break; } } shp.close(); std::clog<<" number shapes="<<count<<std::endl; std::fstream file((shapename+".index").c_str(), std::ios::in | std::ios::out | std::ios::trunc | std::ios::binary); if (!file) { std::clog << "cannot open index file for writing file \"" <<(shapename+".index")<<"\""<<std::endl; } else { tree.trim(); std::clog<<" number nodes="<<tree.count()<<std::endl; file.exceptions(std::ios::failbit | std::ios::badbit); tree.write(file); file.flush(); file.close(); } } std::clog<<"done!"<<std::endl; return 0; } <|endoftext|>
<commit_before>/*****************************************************************************\ * ANALYSIS PERFORMANCE TOOLS * * libparaver-api * * API Library for libparaver-kernel * ***************************************************************************** * ___ This library is free software; you can redistribute it and/or * * / __ modify it under the terms of the GNU LGPL as published * * / / _____ by the Free Software Foundation; either version 2.1 * * / / / \ of the License, or (at your option) any later version. * * ( ( ( B S C ) * * \ \ \_____/ This library is distributed in 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 LGPL 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 * * The GNU LEsser General Public License is contained in the file COPYING. * * --------- * * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion * \*****************************************************************************/ #include <fstream> #include <sstream> #include <algorithm> #include "paraverlabels.h" template<typename dummy> RowLabels<dummy>::RowLabels( const std::string& filename ) { std::string strLine; std::string strLevel; std::string strSize; std::istringstream auxStream; std::istringstream sizeStream; globalMaxLength = 0; std::ifstream rowFile( filename.c_str() ); if ( !rowFile ) return; while ( !rowFile.eof() ) { std::vector<std::string> *tmpvector = nullptr; getline( rowFile, strLine ); if ( strLine.length() == 0 ) continue; else if ( strLine[ 0 ] == '#' ) continue; auxStream.clear(); auxStream.str( strLine ); getline( auxStream, strLevel, ' ' ); // 'LEVEL' getline( auxStream, strLevel, ' ' ); TWindowLevel level; if ( strLevel == LEVEL_WORKLOAD ) level = WORKLOAD; else if ( strLevel == LEVEL_APPLICATION ) level = APPLICATION; else if ( strLevel == LEVEL_TASK ) level = TASK; else if ( strLevel == LEVEL_THREAD ) level = THREAD; else if ( strLevel == LEVEL_SYSTEM ) level = SYSTEM; else if ( strLevel == LEVEL_NODE ) level = NODE; else if ( strLevel == LEVEL_CPU ) level = CPU; else continue; std::map<TWindowLevel, std::tuple< std::string, size_t, std::vector<std::string> > >::iterator currentLevelLabels; std::tuple< std::string, size_t, std::vector<std::string> > tmpEmptyLevel( strLevel, 0, std::vector<std::string>() ); std::tie( currentLevelLabels, std::ignore ) = levelLabels.insert( std::make_pair( level, tmpEmptyLevel ) ); getline( auxStream, strSize, 'S' ); // 'SIZE' getline( auxStream, strSize, ' ' ); // 'SIZE' getline( auxStream, strSize ); sizeStream.clear(); sizeStream.str( strSize ); int size; if ( !( sizeStream >> size ) ) continue; size_t currentLength; int i = 0; while ( !rowFile.eof() && i < size ) { getline( rowFile, strLine ); if( strLine[ strLine.length() - 1 ] == '\r' ) strLine.resize( strLine.length() - 1 ); std::get<2>( currentLevelLabels->second ).push_back( strLine ); currentLength = strLine.length(); // By level if ( std::get<1>( currentLevelLabels->second ) < currentLength ) std::get<1>( currentLevelLabels->second ) = currentLength; // Global if ( globalMaxLength < currentLength ) globalMaxLength = currentLength; ++i; } } rowFile.close(); } template<typename dummy> void RowLabels<dummy>::dumpToFile( const std::string& filename ) const { std::ofstream rowFile( filename.c_str() ); if ( !rowFile ) return; for( int i = CPU; i >= WORKLOAD; --i ) { std::map<TWindowLevel, std::tuple< std::string, size_t, std::vector<std::string> > >::const_iterator currentLevelLabels; if( ( currentLevelLabels = levelLabels.find( static_cast<TWindowLevel>( i ) ) ) != levelLabels.end() ) dumpLevel( currentLevelLabels->second, rowFile ); } rowFile.close(); } template<typename dummy> void RowLabels<dummy>::dumpLevel( const std::tuple< std::string, size_t, std::vector<std::string> >& whichLevel, std::ofstream& whichFile ) const { if( !std::get<2>( whichLevel ).empty() ) { whichFile << "LEVEL " << std::get<0>( whichLevel ) << " SIZE " << std::get<2>( whichLevel ).size() << std::endl; std::copy( std::get<2>( whichLevel ).begin(), std::get<2>( whichLevel ).end(), std::ostream_iterator<std::string>( whichFile, "\n" ) ); whichFile << std::endl; } } template<typename dummy> std::string RowLabels<dummy>::getRowLabel( TWindowLevel whichLevel, TObjectOrder whichRow ) const { std::map<TWindowLevel, std::tuple< std::string, size_t, std::vector<std::string> > >::const_iterator currentLevelLabels; if( ( currentLevelLabels = levelLabels.find( whichLevel ) ) == levelLabels.end() ) return ""; const std::vector<std::string>& vectorLabels = std::get<2>( currentLevelLabels->second ); if( vectorLabels.empty() || vectorLabels.size() <= whichRow ) return ""; return vectorLabels[ whichLevel ]; } template<typename dummy> void RowLabels<dummy>::pushBack( TWindowLevel whichLevel, const std::string& rowLabel ) { std::map<TWindowLevel, std::tuple< std::string, size_t, std::vector<std::string> > >::iterator currentLevelLabels; if( ( currentLevelLabels = levelLabels.find( whichLevel ) ) == levelLabels.end() ) { std::tuple< std::string, size_t, std::vector<std::string> > tmpCurrentLevel( LABEL_LEVELS[ whichLevel ], 0, std::vector<std::string>() ); std::tie( currentLevelLabels, std::ignore ) = levelLabels.insert( std::make_pair( whichLevel, tmpCurrentLevel ) ); } std::get<2>( currentLevelLabels->second ).push_back( rowLabel ); if( std::get<1>( currentLevelLabels->second ) < rowLabel.length() ) std::get<1>( currentLevelLabels->second ) = rowLabel.length(); if( globalMaxLength < rowLabel.length() ) globalMaxLength = rowLabel.length(); } // whichLevel == NONE (by default) ==> all levels MaxLength template<typename dummy> size_t RowLabels<dummy>::getMaxLength( TWindowLevel whichLevel ) const { if( whichLevel == NONE ) return globalMaxLength; std::map<TWindowLevel, std::tuple< std::string, size_t, std::vector<std::string> > >::const_iterator currentLevelLabels; if( ( currentLevelLabels = levelLabels.find( whichLevel ) ) == levelLabels.end() ) return 0; return std::get<1>( currentLevelLabels->second ); } <commit_msg>Fixed the correct variable to access the vector<commit_after>/*****************************************************************************\ * ANALYSIS PERFORMANCE TOOLS * * libparaver-api * * API Library for libparaver-kernel * ***************************************************************************** * ___ This library is free software; you can redistribute it and/or * * / __ modify it under the terms of the GNU LGPL as published * * / / _____ by the Free Software Foundation; either version 2.1 * * / / / \ of the License, or (at your option) any later version. * * ( ( ( B S C ) * * \ \ \_____/ This library is distributed in 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 LGPL 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 * * The GNU LEsser General Public License is contained in the file COPYING. * * --------- * * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion * \*****************************************************************************/ #include <fstream> #include <sstream> #include <algorithm> #include "paraverlabels.h" template<typename dummy> RowLabels<dummy>::RowLabels( const std::string& filename ) { std::string strLine; std::string strLevel; std::string strSize; std::istringstream auxStream; std::istringstream sizeStream; globalMaxLength = 0; std::ifstream rowFile( filename.c_str() ); if ( !rowFile ) return; while ( !rowFile.eof() ) { std::vector<std::string> *tmpvector = nullptr; getline( rowFile, strLine ); if ( strLine.length() == 0 ) continue; else if ( strLine[ 0 ] == '#' ) continue; auxStream.clear(); auxStream.str( strLine ); getline( auxStream, strLevel, ' ' ); // 'LEVEL' getline( auxStream, strLevel, ' ' ); TWindowLevel level; if ( strLevel == LEVEL_WORKLOAD ) level = WORKLOAD; else if ( strLevel == LEVEL_APPLICATION ) level = APPLICATION; else if ( strLevel == LEVEL_TASK ) level = TASK; else if ( strLevel == LEVEL_THREAD ) level = THREAD; else if ( strLevel == LEVEL_SYSTEM ) level = SYSTEM; else if ( strLevel == LEVEL_NODE ) level = NODE; else if ( strLevel == LEVEL_CPU ) level = CPU; else continue; std::map<TWindowLevel, std::tuple< std::string, size_t, std::vector<std::string> > >::iterator currentLevelLabels; std::tuple< std::string, size_t, std::vector<std::string> > tmpEmptyLevel( strLevel, 0, std::vector<std::string>() ); std::tie( currentLevelLabels, std::ignore ) = levelLabels.insert( std::make_pair( level, tmpEmptyLevel ) ); getline( auxStream, strSize, 'S' ); // 'SIZE' getline( auxStream, strSize, ' ' ); // 'SIZE' getline( auxStream, strSize ); sizeStream.clear(); sizeStream.str( strSize ); int size; if ( !( sizeStream >> size ) ) continue; size_t currentLength; int i = 0; while ( !rowFile.eof() && i < size ) { getline( rowFile, strLine ); if( strLine[ strLine.length() - 1 ] == '\r' ) strLine.resize( strLine.length() - 1 ); std::get<2>( currentLevelLabels->second ).push_back( strLine ); currentLength = strLine.length(); // By level if ( std::get<1>( currentLevelLabels->second ) < currentLength ) std::get<1>( currentLevelLabels->second ) = currentLength; // Global if ( globalMaxLength < currentLength ) globalMaxLength = currentLength; ++i; } } rowFile.close(); } template<typename dummy> void RowLabels<dummy>::dumpToFile( const std::string& filename ) const { std::ofstream rowFile( filename.c_str() ); if ( !rowFile ) return; for( int i = CPU; i >= WORKLOAD; --i ) { std::map<TWindowLevel, std::tuple< std::string, size_t, std::vector<std::string> > >::const_iterator currentLevelLabels; if( ( currentLevelLabels = levelLabels.find( static_cast<TWindowLevel>( i ) ) ) != levelLabels.end() ) dumpLevel( currentLevelLabels->second, rowFile ); } rowFile.close(); } template<typename dummy> void RowLabels<dummy>::dumpLevel( const std::tuple< std::string, size_t, std::vector<std::string> >& whichLevel, std::ofstream& whichFile ) const { if( !std::get<2>( whichLevel ).empty() ) { whichFile << "LEVEL " << std::get<0>( whichLevel ) << " SIZE " << std::get<2>( whichLevel ).size() << std::endl; std::copy( std::get<2>( whichLevel ).begin(), std::get<2>( whichLevel ).end(), std::ostream_iterator<std::string>( whichFile, "\n" ) ); whichFile << std::endl; } } template<typename dummy> std::string RowLabels<dummy>::getRowLabel( TWindowLevel whichLevel, TObjectOrder whichRow ) const { std::map<TWindowLevel, std::tuple< std::string, size_t, std::vector<std::string> > >::const_iterator currentLevelLabels; if( ( currentLevelLabels = levelLabels.find( whichLevel ) ) == levelLabels.end() ) return ""; const std::vector<std::string>& vectorLabels = std::get<2>( currentLevelLabels->second ); if( vectorLabels.empty() || vectorLabels.size() <= whichRow ) return ""; return vectorLabels[ whichRow ]; } template<typename dummy> void RowLabels<dummy>::pushBack( TWindowLevel whichLevel, const std::string& rowLabel ) { std::map<TWindowLevel, std::tuple< std::string, size_t, std::vector<std::string> > >::iterator currentLevelLabels; if( ( currentLevelLabels = levelLabels.find( whichLevel ) ) == levelLabels.end() ) { std::tuple< std::string, size_t, std::vector<std::string> > tmpCurrentLevel( LABEL_LEVELS[ whichLevel ], 0, std::vector<std::string>() ); std::tie( currentLevelLabels, std::ignore ) = levelLabels.insert( std::make_pair( whichLevel, tmpCurrentLevel ) ); } std::get<2>( currentLevelLabels->second ).push_back( rowLabel ); if( std::get<1>( currentLevelLabels->second ) < rowLabel.length() ) std::get<1>( currentLevelLabels->second ) = rowLabel.length(); if( globalMaxLength < rowLabel.length() ) globalMaxLength = rowLabel.length(); } // whichLevel == NONE (by default) ==> all levels MaxLength template<typename dummy> size_t RowLabels<dummy>::getMaxLength( TWindowLevel whichLevel ) const { if( whichLevel == NONE ) return globalMaxLength; std::map<TWindowLevel, std::tuple< std::string, size_t, std::vector<std::string> > >::const_iterator currentLevelLabels; if( ( currentLevelLabels = levelLabels.find( whichLevel ) ) == levelLabels.end() ) return 0; return std::get<1>( currentLevelLabels->second ); } <|endoftext|>
<commit_before>/******************************************************************************\ * File: process.cpp * Purpose: Implementation of class 'wxExProcess' * 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 <wx/regex.h> #include <wx/tokenzr.h> #include <wx/txtstrm.h> // for wxTextInputStream #include <wx/extension/configdlg.h> #include <wx/extension/util.h> // for wxExConfigFirstOf #include <wx/extension/report/process.h> #include <wx/extension/report/defs.h> #include <wx/extension/report/frame.h> #include <wx/extension/report/listitem.h> #include <wx/extension/report/listview.h> BEGIN_EVENT_TABLE(wxExProcess, wxProcess) EVT_TIMER(-1, wxExProcess::OnTimer) END_EVENT_TABLE() wxString wxExProcess::m_Command; wxString wxExProcess::m_WorkingDirKey = _("Process folder"); wxExProcess::wxExProcess( wxExFrameWithHistory* frame, const wxString& command) : wxProcess(wxPROCESS_REDIRECT) , m_Frame(frame) , m_ListView(NULL) , m_Timer(this) { if (!command.empty()) { m_Command = command; } } bool wxExProcess::CheckInput() { if (m_ListView == NULL) { return false; } bool hasInput = false; // This assumes that the output is always line buffered. wxString line; if (IsInputAvailable()) { wxTextInputStream tis(*GetInputStream()); line << tis.ReadLine(); hasInput = true; } else if (IsErrorAvailable()) { wxTextInputStream tis(*GetErrorStream()); line << tis.ReadLine(); hasInput = true; } if (hasInput && !line.empty()) { wxString lineno; wxString path; // Check on error in php script output. const wxRegEx regex(".*in \\(.*\\) on line \\(.*\\)", wxRE_ADVANCED); if (regex.Matches(line)) { size_t start, len; if (regex.GetMatch(&start, &len, 1)) { path = line.substr(start, len); } if (regex.GetMatch(&start, &len, 2)) { lineno = line.substr(start, len); } } else { // Check on error in gcc output (and some others). wxStringTokenizer tkz(line, ':'); path = tkz.GetNextToken(); if (tkz.HasMoreTokens()) { const wxString number = tkz.GetNextToken(); if (atoi(number.c_str()) != 0) lineno = number; } } wxFileName fn(path); fn.Normalize(); if (fn.FileExists()) { wxExListItem item(m_ListView, fn); item.Insert(); item.SetItem(_("Line"), line); item.SetItem(_("Line No"), lineno); } else { m_ListView->InsertItem(m_ListView->GetItemCount(), line, -1); } // If nothing selected, then ensure last line is visible. // Otherwise you are busy inspecting some line, and // it would be irritating to get it out of view. if (m_ListView->GetSelectedItemCount() == 0) { m_ListView->EnsureVisible(m_ListView->GetItemCount() - 1); } #if wxUSE_STATUSBAR m_ListView->UpdateStatusBar(); #endif } return hasInput; } int wxExProcess::ConfigDialog( wxWindow* parent, const wxString& title) { std::vector<wxExConfigItem> v; v.push_back(wxExConfigItem( _("Process"), CONFIG_COMBOBOX, wxEmptyString)); v.push_back(wxExConfigItem( m_WorkingDirKey, CONFIG_COMBOBOXDIR, wxEmptyString, true, 1000)); const auto result = wxExConfigDialog(parent, v, title).ShowModal(); if (result == wxID_OK) { m_Command = wxExConfigFirstOf(_("Process")); } return result; } long wxExProcess::Execute() { if (m_Command.empty()) { if (ConfigDialog(m_ListView) == wxID_CANCEL) { return -1; } } wxString cwd; const wxString dir = wxExConfigFirstOf(m_WorkingDirKey); if (!dir.empty()) { cwd = wxGetCwd(); if (!wxSetWorkingDirectory(dir)) { wxLogError(_("Cannot set working directory")); return -1; } } const long pid = wxExecute(m_Command, wxEXEC_ASYNC, this); if (pid != -1) { wxLogVerbose(_("Execute") + ": " + m_Command); if ((m_ListView = m_Frame->Activate(wxExListViewStandard::LIST_PROCESS)) == NULL) { wxLogStatus(_("No listview to collect output")); m_Timer.Stop(); } else { m_Timer.Start(1000); // each 1000 milliseconds } } if (!cwd.empty()) { wxSetWorkingDirectory(cwd); } return pid; } bool wxExProcess::IsRunning() const { if (GetPid() < 0) { return false; } return Exists(GetPid()); } wxKillError wxExProcess::Kill(wxSignal sig) { if (!IsRunning()) { return wxKILL_NO_PROCESS; } m_Timer.Stop(); wxLogStatus(_("Stopped")); DeletePendingEvents(); return wxProcess::Kill(GetPid(), sig); } void wxExProcess::OnTerminate( int WXUNUSED(pid), int WXUNUSED(status)) { m_Timer.Stop(); // Collect remaining input. while (CheckInput()) { // Do nothing. } wxLogStatus(_("Ready")); wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_TERMINATED_PROCESS); wxPostEvent(wxTheApp->GetTopWindow(), event); } void wxExProcess::OnTimer(wxTimerEvent& event) { while (CheckInput()) { // Do nothing. } } <commit_msg>trying to fix why there is no output running process in rep sample<commit_after>/******************************************************************************\ * File: process.cpp * Purpose: Implementation of class 'wxExProcess' * 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 <wx/regex.h> #include <wx/tokenzr.h> #include <wx/txtstrm.h> // for wxTextInputStream #include <wx/extension/configdlg.h> #include <wx/extension/util.h> // for wxExConfigFirstOf #include <wx/extension/report/process.h> #include <wx/extension/report/defs.h> #include <wx/extension/report/frame.h> #include <wx/extension/report/listitem.h> #include <wx/extension/report/listview.h> BEGIN_EVENT_TABLE(wxExProcess, wxProcess) EVT_TIMER(-1, wxExProcess::OnTimer) END_EVENT_TABLE() wxString wxExProcess::m_Command; wxString wxExProcess::m_WorkingDirKey = _("Process folder"); wxExProcess::wxExProcess( wxExFrameWithHistory* frame, const wxString& command) : wxProcess(wxPROCESS_REDIRECT) , m_Frame(frame) , m_ListView(NULL) , m_Timer(this) { if (!command.empty()) { m_Command = command; } } bool wxExProcess::CheckInput() { bool hasInput = false; // This assumes that the output is always line buffered. wxString line; if (IsInputAvailable()) { wxTextInputStream tis(*GetInputStream()); line << tis.ReadLine(); hasInput = true; } else if (IsErrorAvailable()) { wxTextInputStream tis(*GetErrorStream()); line << tis.ReadLine(); hasInput = true; } if (hasInput && !line.empty()) { wxString lineno; wxString path; // Check on error in php script output. const wxRegEx regex(".*in \\(.*\\) on line \\(.*\\)", wxRE_ADVANCED); if (regex.Matches(line)) { size_t start, len; if (regex.GetMatch(&start, &len, 1)) { path = line.substr(start, len); } if (regex.GetMatch(&start, &len, 2)) { lineno = line.substr(start, len); } } else { // Check on error in gcc output (and some others). wxStringTokenizer tkz(line, ':'); path = tkz.GetNextToken(); if (tkz.HasMoreTokens()) { const wxString number = tkz.GetNextToken(); if (atoi(number.c_str()) != 0) lineno = number; } } wxFileName fn(path); fn.Normalize(); if (m_ListView != NULL) { if (fn.FileExists()) { wxExListItem item(m_ListView, fn); item.Insert(); item.SetItem(_("Line"), line); item.SetItem(_("Line No"), lineno); } else { m_ListView->InsertItem(m_ListView->GetItemCount(), line, -1); } // If nothing selected, then ensure last line is visible. // Otherwise you are busy inspecting some line, and // it would be irritating to get it out of view. if (m_ListView->GetSelectedItemCount() == 0) { m_ListView->EnsureVisible(m_ListView->GetItemCount() - 1); } #if wxUSE_STATUSBAR m_ListView->UpdateStatusBar(); #endif } else { wxLogMessage(line); } } return hasInput; } int wxExProcess::ConfigDialog( wxWindow* parent, const wxString& title) { std::vector<wxExConfigItem> v; v.push_back(wxExConfigItem( _("Process"), CONFIG_COMBOBOX, wxEmptyString)); v.push_back(wxExConfigItem( m_WorkingDirKey, CONFIG_COMBOBOXDIR, wxEmptyString, true, 1000)); const auto result = wxExConfigDialog(parent, v, title).ShowModal(); if (result == wxID_OK) { m_Command = wxExConfigFirstOf(_("Process")); } return result; } long wxExProcess::Execute() { if (m_Command.empty()) { if (ConfigDialog(wxTheApp->GetTopWindow()) == wxID_CANCEL) { return -1; } } wxString cwd; const wxString dir = wxExConfigFirstOf(m_WorkingDirKey); if (!dir.empty()) { cwd = wxGetCwd(); if (!wxSetWorkingDirectory(dir)) { wxLogError(_("Cannot set working directory")); return -1; } } const long pid = wxExecute(m_Command, wxEXEC_ASYNC, this); if (pid != -1) { wxLogVerbose(_("Execute") + ": " + m_Command); if ((m_ListView = m_Frame->Activate(wxExListViewStandard::LIST_PROCESS)) == NULL) { wxLogStatus(_("No listview to collect output")); } m_Timer.Start(1000); // each 1000 milliseconds } if (!cwd.empty()) { wxSetWorkingDirectory(cwd); } return pid; } bool wxExProcess::IsRunning() const { if (GetPid() < 0) { return false; } return Exists(GetPid()); } wxKillError wxExProcess::Kill(wxSignal sig) { if (!IsRunning()) { return wxKILL_NO_PROCESS; } m_Timer.Stop(); wxLogStatus(_("Stopped")); DeletePendingEvents(); return wxProcess::Kill(GetPid(), sig); } void wxExProcess::OnTerminate( int WXUNUSED(pid), int WXUNUSED(status)) { m_Timer.Stop(); // Collect remaining input. while (CheckInput()) { // Do nothing. } wxLogStatus(_("Ready")); wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_TERMINATED_PROCESS); wxPostEvent(wxTheApp->GetTopWindow(), event); } void wxExProcess::OnTimer(wxTimerEvent& event) { while (CheckInput()) { // Do nothing. } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <sal/config.h> #include <com/sun/star/ucb/UniversalContentBroker.hpp> #include <comphelper/processfactory.hxx> #include <unotools/tempfile.hxx> #include <unotools/localfilehelper.hxx> #include <unotools/ucbstreamhelper.hxx> #include <ucbhelper/fileidentifierconverter.hxx> #include <rtl/ustring.hxx> #include <rtl/instance.hxx> #include <osl/file.hxx> #include <tools/time.hxx> #include <tools/debug.hxx> #include <stdio.h> #ifdef UNX #include <sys/stat.h> #endif using namespace osl; namespace { struct TempNameBase_Impl : public rtl::Static< OUString, TempNameBase_Impl > {}; } namespace utl { OUString getParentName( const OUString& aFileName ) { sal_Int32 lastIndex = aFileName.lastIndexOf( '/' ); OUString aParent = aFileName.copy( 0, lastIndex ); if( aParent.endsWith(":") && aParent.getLength() == 6 ) aParent += "/"; if( aParent.equalsAscii( "file://" ) ) aParent = "file:///"; return aParent; } bool ensuredir( const OUString& rUnqPath ) { OUString aPath; if ( rUnqPath.isEmpty() ) return false; // remove trailing slash if ( rUnqPath.endsWith("/") ) aPath = rUnqPath.copy( 0, rUnqPath.getLength() - 1 ); else aPath = rUnqPath; // HACK: create directory on a mount point with nobrowse option // returns ENOSYS in any case !! osl::Directory aDirectory( aPath ); osl::FileBase::RC nError = aDirectory.open(); aDirectory.close(); if( nError == osl::File::E_None ) return true; // try to create the directory nError = osl::Directory::create( aPath ); bool bSuccess = ( nError == osl::File::E_None || nError == osl::FileBase::E_EXIST ); if( !bSuccess ) { // perhaps parent(s) don't exist OUString aParentDir = getParentName( aPath ); if ( aParentDir != aPath ) { bSuccess = ensuredir( getParentName( aPath ) ); // After parent directory structure exists try it one's more if ( bSuccess ) { // Parent directory exists, retry creation of directory nError = osl::Directory::create( aPath ); bSuccess =( nError == osl::File::E_None || nError == osl::FileBase::E_EXIST ); } } } return bSuccess; } OUString ConstructTempDir_Impl( const OUString* pParent ) { OUString aName; if ( pParent && !pParent->isEmpty() ) { com::sun::star::uno::Reference< com::sun::star::ucb::XUniversalContentBroker > pBroker( com::sun::star::ucb::UniversalContentBroker::create( comphelper::getProcessComponentContext() ) ); // if parent given try to use it OUString aTmp( *pParent ); // test for valid filename OUString aRet; ::osl::FileBase::getFileURLFromSystemPath( ::ucbhelper::getSystemPathFromFileURL( pBroker, aTmp ), aRet ); if ( !aRet.isEmpty() ) { ::osl::DirectoryItem aItem; sal_Int32 i = aRet.getLength(); if ( aRet[i-1] == '/' ) i--; if ( DirectoryItem::get( aRet.copy(0, i), aItem ) == FileBase::E_None ) aName = aRet; } } if ( aName.isEmpty() ) { OUString &rTempNameBase_Impl = TempNameBase_Impl::get(); if (rTempNameBase_Impl.isEmpty()) { OUString ustrTempDirURL; ::osl::FileBase::RC rc = ::osl::File::getTempDirURL( ustrTempDirURL ); if (rc == ::osl::FileBase::E_None) rTempNameBase_Impl = ustrTempDirURL; } // if no parent or invalid parent : use default directory DBG_ASSERT( !rTempNameBase_Impl.isEmpty(), "No TempDir!" ); aName = rTempNameBase_Impl; ensuredir( aName ); } // Make sure that directory ends with a separator if( !aName.isEmpty() && !aName.endsWith("/") ) aName += "/"; return aName; } void CreateTempName_Impl( OUString& rName, bool bKeep, bool bDir = true ) { // add a suitable tempname // 36 ** 6 == 2176782336 unsigned const nRadix = 36; unsigned long const nMax = (nRadix*nRadix*nRadix*nRadix*nRadix*nRadix); OUString aName; OUString aEyeCatcher = "lu"; #ifdef DBG_UTIL #ifdef UNX const char* eye = getenv("LO_TESTNAME"); if(eye) { aEyeCatcher = OUString(eye, strlen(eye), RTL_TEXTENCODING_ASCII_US); } #endif #endif aName = rName + aEyeCatcher; rName = ""; static unsigned long u = Time::GetSystemTicks() % nMax; for ( unsigned long nSeed = u; ++u != nSeed; ) { u %= nMax; OUString aTmp( aName ); aTmp += OUString::number(u, nRadix); aTmp += ".tmp"; if ( bDir ) { FileBase::RC err = Directory::create( aTmp ); if ( err == FileBase::E_None ) { // !bKeep: only for creating a name, not a file or directory if ( bKeep || Directory::remove( aTmp ) == FileBase::E_None ) rName = aTmp; break; } else if ( err != FileBase::E_EXIST ) { // if f.e. name contains invalid chars stop trying to create dirs break; } } else { DBG_ASSERT( bKeep, "Too expensive, use directory for creating name!" ); File aFile( aTmp ); #ifdef UNX /* RW permission for the user only! */ mode_t old_mode = umask(077); #endif FileBase::RC err = aFile.open( osl_File_OpenFlag_Create | osl_File_OpenFlag_NoLock ); #ifdef UNX umask(old_mode); #endif if ( err == FileBase::E_None ) { rName = aTmp; aFile.close(); break; } else if ( err != FileBase::E_EXIST ) { // if f.e. name contains invalid chars stop trying to create files // but if there is a folder with such name proceed further DirectoryItem aTmpItem; FileStatus aTmpStatus( osl_FileStatus_Mask_Type ); if ( DirectoryItem::get( aTmp, aTmpItem ) != FileBase::E_None || aTmpItem.getFileStatus( aTmpStatus ) != FileBase::E_None || aTmpStatus.getFileType() != FileStatus::Directory ) break; } } } } OUString lcl_createName(const OUString& rLeadingChars, bool _bStartWithZero, const OUString* pExtension, const OUString* pParent, bool bDirectory) { // get correct directory OUString aName = ConstructTempDir_Impl( pParent ); bool bUseNumber = _bStartWithZero; // now use special naming scheme ( name takes leading chars and an index counting up from zero aName += rLeadingChars; for ( sal_Int32 i=0;; i++ ) { OUString aTmp( aName ); if ( bUseNumber ) aTmp += OUString::number( i ); bUseNumber = true; if ( pExtension ) aTmp += *pExtension; else aTmp += ".tmp"; if ( bDirectory ) { FileBase::RC err = Directory::create( aTmp ); if ( err == FileBase::E_None ) { return aTmp; } else if ( err != FileBase::E_EXIST ) // if f.e. name contains invalid chars stop trying to create dirs return OUString(); } else { File aFile( aTmp ); #ifdef UNX /* RW permission for the user only! */ mode_t old_mode = umask(077); #endif FileBase::RC err = aFile.open(osl_File_OpenFlag_Create); #ifdef UNX umask(old_mode); #endif if ( err == FileBase::E_None || err == FileBase::E_NOLCK ) { aFile.close(); return aTmp; } else if ( err != FileBase::E_EXIST ) { // if f.e. name contains invalid chars stop trying to create dirs // but if there is a folder with such name proceed further DirectoryItem aTmpItem; FileStatus aTmpStatus( osl_FileStatus_Mask_Type ); if ( DirectoryItem::get( aTmp, aTmpItem ) != FileBase::E_None || aTmpItem.getFileStatus( aTmpStatus ) != FileBase::E_None || aTmpStatus.getFileType() != FileStatus::Directory ) return OUString(); } } if ( !_bStartWithZero ) aTmp += OUString::number( i ); } } OUString TempFile::CreateTempName() { // get correct directory OUString aName = ConstructTempDir_Impl( 0 ); // get TempFile name with default naming scheme CreateTempName_Impl( aName, false ); // convert to file URL OUString aTmp; if ( !aName.isEmpty() ) FileBase::getSystemPathFromFileURL( aName, aTmp ); return aTmp; } TempFile::TempFile( const OUString* pParent, bool bDirectory ) : pStream( 0 ) , bIsDirectory( bDirectory ) , bKillingFileEnabled( false ) { // get correct directory aName = ConstructTempDir_Impl( pParent ); // get TempFile with default naming scheme CreateTempName_Impl( aName, true, bDirectory ); } TempFile::TempFile( const OUString& rLeadingChars, const OUString* pExtension, const OUString* pParent, bool bDirectory) : pStream( 0 ) , bIsDirectory( bDirectory ) , bKillingFileEnabled( false ) { aName = lcl_createName(rLeadingChars, true, pExtension, pParent, bDirectory); } TempFile::TempFile( const OUString& rLeadingChars, bool _bStartWithZero, const OUString* pExtension, const OUString* pParent, bool bDirectory) : pStream( 0 ) , bIsDirectory( bDirectory ) , bKillingFileEnabled( false ) { aName = lcl_createName(rLeadingChars, _bStartWithZero, pExtension, pParent, bDirectory); } TempFile::~TempFile() { delete pStream; if ( bKillingFileEnabled ) { if ( bIsDirectory ) { // at the moment no recursiv algorithm present Directory::remove( aName ); } else { File::remove( aName ); } } } bool TempFile::IsValid() const { return !aName.isEmpty(); } OUString TempFile::GetFileName() const { OUString aTmp; FileBase::getSystemPathFromFileURL( aName, aTmp ); return aTmp; } OUString TempFile::GetURL() { if ( aURL.isEmpty() ) { OUString aTmp; LocalFileHelper::ConvertPhysicalNameToURL( GetFileName(), aTmp ); aURL = aTmp; } return aURL; } SvStream* TempFile::GetStream( StreamMode eMode ) { if ( !pStream ) { if ( !GetURL().isEmpty() ) pStream = UcbStreamHelper::CreateStream( aURL, eMode, true /* bFileExists */ ); else pStream = new SvMemoryStream( eMode ); } return pStream; } void TempFile::CloseStream() { if ( pStream ) { delete pStream; pStream = NULL; } } OUString TempFile::SetTempNameBaseDirectory( const OUString &rBaseName ) { if( rBaseName.isEmpty() ) return OUString(); OUString aUnqPath( rBaseName ); // remove trailing slash if ( rBaseName.endsWith("/") ) aUnqPath = rBaseName.copy( 0, rBaseName.getLength() - 1 ); // try to create the directory bool bRet = false; osl::FileBase::RC err = osl::Directory::create( aUnqPath ); if ( err != FileBase::E_None && err != FileBase::E_EXIST ) // perhaps parent(s) don't exist bRet = ensuredir( aUnqPath ); else bRet = true; // failure to create base directory means returning an empty string OUString aTmp; if ( bRet ) { // append own internal directory bRet = true; OUString &rTempNameBase_Impl = TempNameBase_Impl::get(); rTempNameBase_Impl = rBaseName; rTempNameBase_Impl += OUString('/'); TempFile aBase( NULL, true ); if ( aBase.IsValid() ) // use it in case of success rTempNameBase_Impl = aBase.aName; // return system path of used directory FileBase::getSystemPathFromFileURL( rTempNameBase_Impl, aTmp ); } return aTmp; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Remove nonsensical code<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <sal/config.h> #include <com/sun/star/ucb/UniversalContentBroker.hpp> #include <comphelper/processfactory.hxx> #include <unotools/tempfile.hxx> #include <unotools/localfilehelper.hxx> #include <unotools/ucbstreamhelper.hxx> #include <ucbhelper/fileidentifierconverter.hxx> #include <rtl/ustring.hxx> #include <rtl/instance.hxx> #include <osl/file.hxx> #include <tools/time.hxx> #include <tools/debug.hxx> #include <stdio.h> #ifdef UNX #include <sys/stat.h> #endif using namespace osl; namespace { struct TempNameBase_Impl : public rtl::Static< OUString, TempNameBase_Impl > {}; } namespace utl { OUString getParentName( const OUString& aFileName ) { sal_Int32 lastIndex = aFileName.lastIndexOf( '/' ); OUString aParent = aFileName.copy( 0, lastIndex ); if( aParent.endsWith(":") && aParent.getLength() == 6 ) aParent += "/"; if( aParent.equalsAscii( "file://" ) ) aParent = "file:///"; return aParent; } bool ensuredir( const OUString& rUnqPath ) { OUString aPath; if ( rUnqPath.isEmpty() ) return false; // remove trailing slash if ( rUnqPath.endsWith("/") ) aPath = rUnqPath.copy( 0, rUnqPath.getLength() - 1 ); else aPath = rUnqPath; // HACK: create directory on a mount point with nobrowse option // returns ENOSYS in any case !! osl::Directory aDirectory( aPath ); osl::FileBase::RC nError = aDirectory.open(); aDirectory.close(); if( nError == osl::File::E_None ) return true; // try to create the directory nError = osl::Directory::create( aPath ); bool bSuccess = ( nError == osl::File::E_None || nError == osl::FileBase::E_EXIST ); if( !bSuccess ) { // perhaps parent(s) don't exist OUString aParentDir = getParentName( aPath ); if ( aParentDir != aPath ) { bSuccess = ensuredir( getParentName( aPath ) ); // After parent directory structure exists try it one's more if ( bSuccess ) { // Parent directory exists, retry creation of directory nError = osl::Directory::create( aPath ); bSuccess =( nError == osl::File::E_None || nError == osl::FileBase::E_EXIST ); } } } return bSuccess; } OUString ConstructTempDir_Impl( const OUString* pParent ) { OUString aName; if ( pParent && !pParent->isEmpty() ) { com::sun::star::uno::Reference< com::sun::star::ucb::XUniversalContentBroker > pBroker( com::sun::star::ucb::UniversalContentBroker::create( comphelper::getProcessComponentContext() ) ); // if parent given try to use it OUString aTmp( *pParent ); // test for valid filename OUString aRet; ::osl::FileBase::getFileURLFromSystemPath( ::ucbhelper::getSystemPathFromFileURL( pBroker, aTmp ), aRet ); if ( !aRet.isEmpty() ) { ::osl::DirectoryItem aItem; sal_Int32 i = aRet.getLength(); if ( aRet[i-1] == '/' ) i--; if ( DirectoryItem::get( aRet.copy(0, i), aItem ) == FileBase::E_None ) aName = aRet; } } if ( aName.isEmpty() ) { OUString &rTempNameBase_Impl = TempNameBase_Impl::get(); if (rTempNameBase_Impl.isEmpty()) { OUString ustrTempDirURL; ::osl::FileBase::RC rc = ::osl::File::getTempDirURL( ustrTempDirURL ); if (rc == ::osl::FileBase::E_None) rTempNameBase_Impl = ustrTempDirURL; } // if no parent or invalid parent : use default directory DBG_ASSERT( !rTempNameBase_Impl.isEmpty(), "No TempDir!" ); aName = rTempNameBase_Impl; ensuredir( aName ); } // Make sure that directory ends with a separator if( !aName.isEmpty() && !aName.endsWith("/") ) aName += "/"; return aName; } void CreateTempName_Impl( OUString& rName, bool bKeep, bool bDir = true ) { // add a suitable tempname // 36 ** 6 == 2176782336 unsigned const nRadix = 36; unsigned long const nMax = (nRadix*nRadix*nRadix*nRadix*nRadix*nRadix); OUString aName; OUString aEyeCatcher = "lu"; #ifdef DBG_UTIL #ifdef UNX const char* eye = getenv("LO_TESTNAME"); if(eye) { aEyeCatcher = OUString(eye, strlen(eye), RTL_TEXTENCODING_ASCII_US); } #endif #endif aName = rName + aEyeCatcher; rName = ""; static unsigned long u = Time::GetSystemTicks() % nMax; for ( unsigned long nSeed = u; ++u != nSeed; ) { u %= nMax; OUString aTmp( aName ); aTmp += OUString::number(u, nRadix); aTmp += ".tmp"; if ( bDir ) { FileBase::RC err = Directory::create( aTmp ); if ( err == FileBase::E_None ) { // !bKeep: only for creating a name, not a file or directory if ( bKeep || Directory::remove( aTmp ) == FileBase::E_None ) rName = aTmp; break; } else if ( err != FileBase::E_EXIST ) { // if f.e. name contains invalid chars stop trying to create dirs break; } } else { DBG_ASSERT( bKeep, "Too expensive, use directory for creating name!" ); File aFile( aTmp ); #ifdef UNX /* RW permission for the user only! */ mode_t old_mode = umask(077); #endif FileBase::RC err = aFile.open( osl_File_OpenFlag_Create | osl_File_OpenFlag_NoLock ); #ifdef UNX umask(old_mode); #endif if ( err == FileBase::E_None ) { rName = aTmp; aFile.close(); break; } else if ( err != FileBase::E_EXIST ) { // if f.e. name contains invalid chars stop trying to create files // but if there is a folder with such name proceed further DirectoryItem aTmpItem; FileStatus aTmpStatus( osl_FileStatus_Mask_Type ); if ( DirectoryItem::get( aTmp, aTmpItem ) != FileBase::E_None || aTmpItem.getFileStatus( aTmpStatus ) != FileBase::E_None || aTmpStatus.getFileType() != FileStatus::Directory ) break; } } } } OUString lcl_createName(const OUString& rLeadingChars, bool _bStartWithZero, const OUString* pExtension, const OUString* pParent, bool bDirectory) { // get correct directory OUString aName = ConstructTempDir_Impl( pParent ); bool bUseNumber = _bStartWithZero; // now use special naming scheme ( name takes leading chars and an index counting up from zero aName += rLeadingChars; for ( sal_Int32 i=0;; i++ ) { OUString aTmp( aName ); if ( bUseNumber ) aTmp += OUString::number( i ); bUseNumber = true; if ( pExtension ) aTmp += *pExtension; else aTmp += ".tmp"; if ( bDirectory ) { FileBase::RC err = Directory::create( aTmp ); if ( err == FileBase::E_None ) { return aTmp; } else if ( err != FileBase::E_EXIST ) // if f.e. name contains invalid chars stop trying to create dirs return OUString(); } else { File aFile( aTmp ); #ifdef UNX /* RW permission for the user only! */ mode_t old_mode = umask(077); #endif FileBase::RC err = aFile.open(osl_File_OpenFlag_Create); #ifdef UNX umask(old_mode); #endif if ( err == FileBase::E_None || err == FileBase::E_NOLCK ) { aFile.close(); return aTmp; } else if ( err != FileBase::E_EXIST ) { // if f.e. name contains invalid chars stop trying to create dirs // but if there is a folder with such name proceed further DirectoryItem aTmpItem; FileStatus aTmpStatus( osl_FileStatus_Mask_Type ); if ( DirectoryItem::get( aTmp, aTmpItem ) != FileBase::E_None || aTmpItem.getFileStatus( aTmpStatus ) != FileBase::E_None || aTmpStatus.getFileType() != FileStatus::Directory ) return OUString(); } } } } OUString TempFile::CreateTempName() { // get correct directory OUString aName = ConstructTempDir_Impl( 0 ); // get TempFile name with default naming scheme CreateTempName_Impl( aName, false ); // convert to file URL OUString aTmp; if ( !aName.isEmpty() ) FileBase::getSystemPathFromFileURL( aName, aTmp ); return aTmp; } TempFile::TempFile( const OUString* pParent, bool bDirectory ) : pStream( 0 ) , bIsDirectory( bDirectory ) , bKillingFileEnabled( false ) { // get correct directory aName = ConstructTempDir_Impl( pParent ); // get TempFile with default naming scheme CreateTempName_Impl( aName, true, bDirectory ); } TempFile::TempFile( const OUString& rLeadingChars, const OUString* pExtension, const OUString* pParent, bool bDirectory) : pStream( 0 ) , bIsDirectory( bDirectory ) , bKillingFileEnabled( false ) { aName = lcl_createName(rLeadingChars, true, pExtension, pParent, bDirectory); } TempFile::TempFile( const OUString& rLeadingChars, bool _bStartWithZero, const OUString* pExtension, const OUString* pParent, bool bDirectory) : pStream( 0 ) , bIsDirectory( bDirectory ) , bKillingFileEnabled( false ) { aName = lcl_createName(rLeadingChars, _bStartWithZero, pExtension, pParent, bDirectory); } TempFile::~TempFile() { delete pStream; if ( bKillingFileEnabled ) { if ( bIsDirectory ) { // at the moment no recursiv algorithm present Directory::remove( aName ); } else { File::remove( aName ); } } } bool TempFile::IsValid() const { return !aName.isEmpty(); } OUString TempFile::GetFileName() const { OUString aTmp; FileBase::getSystemPathFromFileURL( aName, aTmp ); return aTmp; } OUString TempFile::GetURL() { if ( aURL.isEmpty() ) { OUString aTmp; LocalFileHelper::ConvertPhysicalNameToURL( GetFileName(), aTmp ); aURL = aTmp; } return aURL; } SvStream* TempFile::GetStream( StreamMode eMode ) { if ( !pStream ) { if ( !GetURL().isEmpty() ) pStream = UcbStreamHelper::CreateStream( aURL, eMode, true /* bFileExists */ ); else pStream = new SvMemoryStream( eMode ); } return pStream; } void TempFile::CloseStream() { if ( pStream ) { delete pStream; pStream = NULL; } } OUString TempFile::SetTempNameBaseDirectory( const OUString &rBaseName ) { if( rBaseName.isEmpty() ) return OUString(); OUString aUnqPath( rBaseName ); // remove trailing slash if ( rBaseName.endsWith("/") ) aUnqPath = rBaseName.copy( 0, rBaseName.getLength() - 1 ); // try to create the directory bool bRet = false; osl::FileBase::RC err = osl::Directory::create( aUnqPath ); if ( err != FileBase::E_None && err != FileBase::E_EXIST ) // perhaps parent(s) don't exist bRet = ensuredir( aUnqPath ); else bRet = true; // failure to create base directory means returning an empty string OUString aTmp; if ( bRet ) { // append own internal directory bRet = true; OUString &rTempNameBase_Impl = TempNameBase_Impl::get(); rTempNameBase_Impl = rBaseName; rTempNameBase_Impl += OUString('/'); TempFile aBase( NULL, true ); if ( aBase.IsValid() ) // use it in case of success rTempNameBase_Impl = aBase.aName; // return system path of used directory FileBase::getSystemPathFromFileURL( rTempNameBase_Impl, aTmp ); } return aTmp; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#ifndef VIENNAGRID_ELEMENT_CREATION_HPP #define VIENNAGRID_ELEMENT_CREATION_HPP /* ======================================================================= Copyright (c) 2011-2013, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaGrid - The Vienna Grid Library ----------------- License: MIT (X11), see file LICENSE in the base directory ======================================================================= */ #include "viennagrid/domain/domain.hpp" #include "viennagrid/domain/segmentation.hpp" #include "viennagrid/topology/plc.hpp" #include "viennagrid/algorithm/norm.hpp" namespace viennagrid { template<typename ElementTypeOrTag, typename DomainType, typename HandleIteratorType> typename result_of::handle<DomainType, ElementTypeOrTag>::type make_element( DomainType & domain, HandleIteratorType array_start, HandleIteratorType const & array_end ) { typedef typename viennagrid::result_of::element<DomainType, ElementTypeOrTag>::type ElementType; ElementType element = ElementType( inserter(domain).get_physical_container_collection() ); size_t element_index = 0; for ( ; array_start != array_end; ++array_start, ++element_index ) viennagrid::set_vertex( element, *array_start, element_index ); return push_element<true, true>(domain, element).first; } template<typename ElementTypeOrTag, typename DomainType, typename HandleIteratorType> typename result_of::handle<DomainType, ElementTypeOrTag>::type make_element_with_id( DomainType & domain, HandleIteratorType array_start, HandleIteratorType const & array_end, typename viennagrid::result_of::element<DomainType, ElementTypeOrTag>::type::id_type id ) { typedef typename viennagrid::result_of::element<DomainType, ElementTypeOrTag>::type ElementType; ElementType element = ElementType( inserter(domain).get_physical_container_collection() ); element.id( id ); size_t element_index = 0; for ( ; array_start != array_end; ++array_start, ++element_index ) viennagrid::set_vertex( element, *array_start, element_index ); return push_element<false, true>(domain, element ).first; } template<typename DomainType, typename HandleIteratorType> typename result_of::cell_handle<DomainType>::type make_cell( DomainType & domain, HandleIteratorType array_start, HandleIteratorType const & array_end ) { typedef typename viennagrid::result_of::cell_tag<DomainType>::type CellTagType; return make_element<CellTagType>( domain, array_start, array_end ); } template<typename DomainType, typename HandleIteratorType> typename result_of::cell_handle<DomainType>::type make_cell_with_id( DomainType & domain, HandleIteratorType array_start, HandleIteratorType const & array_end, typename viennagrid::result_of::cell<DomainType>::type::id_type id ) { typedef typename viennagrid::result_of::cell_tag<DomainType>::type CellTagType; return make_element_with_id<CellTagType>( domain, array_start, array_end, id ); } template<typename DomainType> typename result_of::handle<DomainType, vertex_tag>::type make_vertex( DomainType & domain ) { typedef typename result_of::element<DomainType, vertex_tag>::type element_type; return push_element<true, true>(domain, element_type() ).first; } template<typename ConfigType> typename viennagrid::result_of::vertex_handle< domain_t<ConfigType> >::type make_vertex( domain_t<ConfigType> & domain, typename result_of::point< domain_t<ConfigType> >::type const & point ) { typename viennagrid::result_of::vertex_handle< domain_t<ConfigType> >::type vtx_handle = make_vertex(domain); viennagrid::point(domain, vtx_handle) = point; return vtx_handle; } template<typename ConfigType> typename viennagrid::result_of::vertex_handle< domain_t<ConfigType> >::type make_vertex( domain_t<ConfigType> & domain, typename viennagrid::result_of::element< domain_t<ConfigType>, vertex_tag>::type::id_type id, typename result_of::point< domain_t<ConfigType> >::type const & point ) { typedef typename result_of::element< domain_t<ConfigType>, vertex_tag>::type element_type; element_type element; element.id( id ); typename result_of::handle< domain_t<ConfigType>, element_type>::type ret = push_element<false, true>(domain, element ).first; viennagrid::point(domain, ret) = point; return ret; } template<typename ConfigType> typename result_of::handle<domain_t<ConfigType>, vertex_tag>::type make_unique_vertex( domain_t<ConfigType> & domain, typename result_of::point< domain_t<ConfigType> >::type const & p, typename result_of::coord< domain_t<ConfigType> >::type tolerance ) { typedef domain_t<ConfigType> DomainType; typedef typename result_of::element_range<DomainType, vertex_tag>::type vertex_range_type; typedef typename result_of::iterator<vertex_range_type>::type vertex_range_iterator; vertex_range_type vertices = viennagrid::elements<vertex_tag>(domain); for (vertex_range_iterator hit = vertices.begin(); hit != vertices.end(); ++hit) { if (viennagrid::norm_2( p - point(domain, *hit) ) < tolerance ) return hit.handle(); } return make_vertex(domain, p); } template<typename ConfigType> typename result_of::handle<domain_t<ConfigType>, vertex_tag>::type make_unique_vertex( domain_t<ConfigType> & domain, typename result_of::point< domain_t<ConfigType> >::type const & p) { return make_unique_vertex( domain, p, viennagrid::norm_2(p) / 1e6 ); } template<typename DomainType, typename vertex_handle_type> typename result_of::handle<DomainType, line_tag>::type make_line( DomainType & domain, vertex_handle_type v0, vertex_handle_type v1 ) { viennagrid::storage::static_array<vertex_handle_type, 2> handles; handles[0] = v0; handles[1] = v1; return make_element<viennagrid::line_tag>( domain, handles.begin(), handles.end() ); } template<typename DomainType, typename vertex_handle_type> typename result_of::handle<DomainType, triangle_tag>::type make_triangle( DomainType & domain, vertex_handle_type v0, vertex_handle_type v1, vertex_handle_type v2 ) { viennagrid::storage::static_array<vertex_handle_type, 3> handles; handles[0] = v0; handles[1] = v1; handles[2] = v2; return make_element<viennagrid::triangle_tag>( domain, handles.begin(), handles.end() ); } template<typename DomainType, typename LineHandleIteratorType, typename VertexHandleIteratorType, typename PointIteraorType> typename result_of::handle<DomainType, plc_tag>::type make_plc(DomainType & domain, LineHandleIteratorType line_begin, LineHandleIteratorType line_end, VertexHandleIteratorType vertex_begin, VertexHandleIteratorType vertex_end, PointIteraorType point_begin, PointIteraorType point_end) { typedef typename viennagrid::result_of::element<DomainType, plc_tag>::type PLCType;; typedef typename result_of::handle<DomainType, plc_tag>::type PLCHandleType; PLCType plc( inserter(domain).get_physical_container_collection() ); for ( ; line_begin != line_end; ++line_begin) plc.container( viennagrid::line_tag() ).insert_unique_handle( *line_begin ); for ( ; vertex_begin != vertex_end; ++vertex_begin) plc.container( viennagrid::vertex_tag() ).insert_unique_handle( *vertex_begin ); PLCHandleType handle = viennagrid::push_element<true, true>(domain, plc ).first; PLCType & inserted_plc = viennagrid::dereference_handle(domain, handle); std::copy(point_begin, point_end, std::back_inserter( inserted_plc.appendix() ) ); return handle; } template<typename DomainType, typename vertex_handle_type> typename result_of::handle<DomainType, tetrahedron_tag>::type make_tetrahedron( DomainType & domain, vertex_handle_type v0, vertex_handle_type v1, vertex_handle_type v2, vertex_handle_type v3 ) { viennagrid::storage::static_array<vertex_handle_type, 4> handles; handles[0] = v0; handles[1] = v1; handles[2] = v2; handles[3] = v3; return make_element<viennagrid::tetrahedron_tag>( domain, handles.begin(), handles.end() ); } template<typename DomainType, typename vertex_handle_type> typename result_of::handle<DomainType, quadrilateral_tag>::type make_quadrilateral( DomainType & domain, vertex_handle_type v0, vertex_handle_type v1, vertex_handle_type v2, vertex_handle_type v3 ) { viennagrid::storage::static_array<vertex_handle_type, 4> handles; handles[0] = v0; handles[1] = v1; handles[2] = v2; handles[3] = v3; return make_element<viennagrid::quadrilateral_tag>( domain, handles.begin(), handles.end() ); } template<typename DomainType, typename vertex_handle_type> typename result_of::handle<DomainType, hexahedron_tag>::type make_hexahedron( DomainType & domain, vertex_handle_type v0, vertex_handle_type v1, vertex_handle_type v2, vertex_handle_type v3, vertex_handle_type v4, vertex_handle_type v5, vertex_handle_type v6, vertex_handle_type v7 ) { viennagrid::storage::static_array<vertex_handle_type, 8> handles; handles[0] = v0; handles[1] = v1; handles[2] = v2; handles[3] = v3; handles[4] = v4; handles[5] = v5; handles[6] = v6; handles[7] = v7; return make_element<viennagrid::hexahedron_tag>( domain, handles.begin(), handles.end() ); } } #endif <commit_msg>changed type and variable names<commit_after>#ifndef VIENNAGRID_ELEMENT_CREATION_HPP #define VIENNAGRID_ELEMENT_CREATION_HPP /* ======================================================================= Copyright (c) 2011-2013, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaGrid - The Vienna Grid Library ----------------- License: MIT (X11), see file LICENSE in the base directory ======================================================================= */ #include "viennagrid/domain/domain.hpp" #include "viennagrid/domain/segmentation.hpp" #include "viennagrid/topology/plc.hpp" #include "viennagrid/algorithm/norm.hpp" namespace viennagrid { template<typename ElementTypeOrTag, typename DomainType, typename VertexHandleIteratorT> typename result_of::handle<DomainType, ElementTypeOrTag>::type make_element( DomainType & domain, VertexHandleIteratorT vertices_begin, VertexHandleIteratorT const & vertices_end ) { typedef typename viennagrid::result_of::element<DomainType, ElementTypeOrTag>::type ElementType; ElementType element = ElementType( inserter(domain).get_physical_container_collection() ); size_t element_index = 0; for ( ; vertices_begin != vertices_end; ++vertices_begin, ++element_index ) viennagrid::set_vertex( element, *vertices_begin, element_index ); return push_element<true, true>(domain, element).first; } template<typename ElementTypeOrTag, typename DomainType, typename VertexHandleIteratorT> typename result_of::handle<DomainType, ElementTypeOrTag>::type make_element_with_id( DomainType & domain, VertexHandleIteratorT vertices_begin, VertexHandleIteratorT const & vertices_end, typename result_of::id< typename result_of::element<DomainType, ElementTypeOrTag>::type >::type id ) { typedef typename viennagrid::result_of::element<DomainType, ElementTypeOrTag>::type ElementType; ElementType element = ElementType( inserter(domain).get_physical_container_collection() ); element.id( id ); size_t element_index = 0; for ( ; vertices_begin != vertices_end; ++vertices_begin, ++element_index ) viennagrid::set_vertex( element, *vertices_begin, element_index ); return push_element<false, true>(domain, element ).first; } template<typename DomainType, typename VertexHandleIteratorT> typename result_of::cell_handle<DomainType>::type make_cell( DomainType & domain, VertexHandleIteratorT vertices_begin, VertexHandleIteratorT const & vertices_end ) { typedef typename viennagrid::result_of::cell_tag<DomainType>::type CellTagType; return make_element<CellTagType>( domain, vertices_begin, vertices_end ); } template<typename DomainType, typename VertexHandleIteratorT> typename result_of::cell_handle<DomainType>::type make_cell_with_id( DomainType & domain, VertexHandleIteratorT vertices_begin, VertexHandleIteratorT const & vertices_end, typename viennagrid::result_of::cell<DomainType>::type::id_type id ) { typedef typename viennagrid::result_of::cell_tag<DomainType>::type CellTagType; return make_element_with_id<CellTagType>( domain, vertices_begin, vertices_end, id ); } template<typename DomainType> typename result_of::handle<DomainType, vertex_tag>::type make_vertex( DomainType & domain ) { typedef typename result_of::element<DomainType, vertex_tag>::type element_type; return push_element<true, true>(domain, element_type() ).first; } template<typename ConfigType> typename viennagrid::result_of::vertex_handle< domain_t<ConfigType> >::type make_vertex( domain_t<ConfigType> & domain, typename result_of::point< domain_t<ConfigType> >::type const & point ) { typename viennagrid::result_of::vertex_handle< domain_t<ConfigType> >::type vtx_handle = make_vertex(domain); viennagrid::point(domain, vtx_handle) = point; return vtx_handle; } template<typename ConfigType> typename viennagrid::result_of::vertex_handle< domain_t<ConfigType> >::type make_vertex( domain_t<ConfigType> & domain, typename viennagrid::result_of::element< domain_t<ConfigType>, vertex_tag>::type::id_type id, typename result_of::point< domain_t<ConfigType> >::type const & point ) { typedef typename result_of::element< domain_t<ConfigType>, vertex_tag>::type element_type; element_type element; element.id( id ); typename result_of::handle< domain_t<ConfigType>, element_type>::type ret = push_element<false, true>(domain, element ).first; viennagrid::point(domain, ret) = point; return ret; } template<typename ConfigType> typename result_of::handle<domain_t<ConfigType>, vertex_tag>::type make_unique_vertex( domain_t<ConfigType> & domain, typename result_of::point< domain_t<ConfigType> >::type const & p, typename result_of::coord< domain_t<ConfigType> >::type tolerance ) { typedef domain_t<ConfigType> DomainType; typedef typename result_of::element_range<DomainType, vertex_tag>::type vertex_range_type; typedef typename result_of::iterator<vertex_range_type>::type vertex_range_iterator; vertex_range_type vertices = viennagrid::elements<vertex_tag>(domain); for (vertex_range_iterator hit = vertices.begin(); hit != vertices.end(); ++hit) { if (viennagrid::norm_2( p - point(domain, *hit) ) < tolerance ) return hit.handle(); } return make_vertex(domain, p); } template<typename ConfigType> typename result_of::handle<domain_t<ConfigType>, vertex_tag>::type make_unique_vertex( domain_t<ConfigType> & domain, typename result_of::point< domain_t<ConfigType> >::type const & p) { return make_unique_vertex( domain, p, viennagrid::norm_2(p) / 1e6 ); } template<typename DomainType, typename vertex_handle_type> typename result_of::handle<DomainType, line_tag>::type make_line( DomainType & domain, vertex_handle_type v0, vertex_handle_type v1 ) { viennagrid::storage::static_array<vertex_handle_type, 2> handles; handles[0] = v0; handles[1] = v1; return make_element<viennagrid::line_tag>( domain, handles.begin(), handles.end() ); } template<typename DomainType, typename vertex_handle_type> typename result_of::handle<DomainType, triangle_tag>::type make_triangle( DomainType & domain, vertex_handle_type v0, vertex_handle_type v1, vertex_handle_type v2 ) { viennagrid::storage::static_array<vertex_handle_type, 3> handles; handles[0] = v0; handles[1] = v1; handles[2] = v2; return make_element<viennagrid::triangle_tag>( domain, handles.begin(), handles.end() ); } template<typename DomainType, typename LineHandleIteratorT, typename VertexHandleIteratorT, typename PointIteraorType> typename result_of::handle<DomainType, plc_tag>::type make_plc(DomainType & domain, LineHandleIteratorT lines_begin, LineHandleIteratorT lines_end, VertexHandleIteratorT vertices_begin, VertexHandleIteratorT vertices_end, PointIteraorType hole_points_begin, PointIteraorType hole_points_end) { typedef typename viennagrid::result_of::element<DomainType, plc_tag>::type PLCType;; typedef typename result_of::handle<DomainType, plc_tag>::type PLCHandleType; PLCType plc( inserter(domain).get_physical_container_collection() ); for ( ; lines_begin != lines_end; ++lines_begin) plc.container( viennagrid::line_tag() ).insert_unique_handle( *lines_begin ); for ( ; vertices_begin != vertices_end; ++vertices_begin) plc.container( viennagrid::vertex_tag() ).insert_unique_handle( *vertices_begin ); PLCHandleType handle = viennagrid::push_element<true, true>(domain, plc ).first; PLCType & inserted_plc = viennagrid::dereference_handle(domain, handle); std::copy(hole_points_begin, hole_points_end, std::back_inserter( inserted_plc.appendix() ) ); return handle; } template<typename DomainType, typename vertex_handle_type> typename result_of::handle<DomainType, tetrahedron_tag>::type make_tetrahedron( DomainType & domain, vertex_handle_type v0, vertex_handle_type v1, vertex_handle_type v2, vertex_handle_type v3 ) { viennagrid::storage::static_array<vertex_handle_type, 4> handles; handles[0] = v0; handles[1] = v1; handles[2] = v2; handles[3] = v3; return make_element<viennagrid::tetrahedron_tag>( domain, handles.begin(), handles.end() ); } template<typename DomainType, typename vertex_handle_type> typename result_of::handle<DomainType, quadrilateral_tag>::type make_quadrilateral( DomainType & domain, vertex_handle_type v0, vertex_handle_type v1, vertex_handle_type v2, vertex_handle_type v3 ) { viennagrid::storage::static_array<vertex_handle_type, 4> handles; handles[0] = v0; handles[1] = v1; handles[2] = v2; handles[3] = v3; return make_element<viennagrid::quadrilateral_tag>( domain, handles.begin(), handles.end() ); } template<typename DomainType, typename vertex_handle_type> typename result_of::handle<DomainType, hexahedron_tag>::type make_hexahedron( DomainType & domain, vertex_handle_type v0, vertex_handle_type v1, vertex_handle_type v2, vertex_handle_type v3, vertex_handle_type v4, vertex_handle_type v5, vertex_handle_type v6, vertex_handle_type v7 ) { viennagrid::storage::static_array<vertex_handle_type, 8> handles; handles[0] = v0; handles[1] = v1; handles[2] = v2; handles[3] = v3; handles[4] = v4; handles[5] = v5; handles[6] = v6; handles[7] = v7; return make_element<viennagrid::hexahedron_tag>( domain, handles.begin(), handles.end() ); } } #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: backendaccess.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2003-04-04 16:11:27 $ * * 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 CONFIGMGR_BACKEND_BACKENDACCESS_HXX_ #include "backendaccess.hxx" #endif // CONFIGMGR_BACKEND_BACKENDACCESS_HXX_ #ifndef CONFIGMGR_MATCHLOCALE_HXX #include "matchlocale.hxx" #endif // CONFIGMGR_MATCHLOCALE_HXX #ifndef CONFIGMGR_BACKEND_LAYERMERGE_HXX #include "layermerge.hxx" #endif // CONFIGMGR_BACKEND_LAYERMERGE_HXX #ifndef CONFIGMGR_BACKEND_SCHEMABUILDER_HXX #include "schemabuilder.hxx" #endif // CONFIGMGR_BACKEND_SCHEMABUILDER_HXX #ifndef CONFIGMGR_BACKEND_UPDATEDISPATCHER_HXX #include "updatedispatch.hxx" #endif // CONFIGMGR_BACKEND_UPDATEDISPATCHER_HXX #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XCOMPOSITELAYER_HPP_ #include <drafts/com/sun/star/configuration/backend/XCompositeLayer.hpp> #endif // _COM_SUN_STAR_CONFIGURATION_BACKEND_XCOMPOSITELAYER_HPP_ #ifndef _RTL_LOGFILE_HXX_ #include <rtl/logfile.hxx> #endif #define RTL_LOGFILE_OU2A(rtlOUString) (::rtl::OUStringToOString((rtlOUString), RTL_TEXTENCODING_ASCII_US).getStr()) #include <drafts/com/sun/star/configuration/backend/MalformedDataException.hpp> #ifndef _COM_SUN_STAR_CONTAINER_NOSUCHELEMENTEXCEPTION_HPP_ #include <com/sun/star/container/NoSuchElementException.hpp> #endif namespace configmgr { namespace backend { //============================================================================== //------------------------------------------------------------------------------ BackendAccess::BackendAccess( const uno::Reference<backenduno::XBackend>& xBackend, const uno::Reference<uno::XComponentContext>& xContext) : mFactory(xContext->getServiceManager(), uno::UNO_QUERY) , mBackend(xBackend) { OSL_ENSURE(mFactory.is(), "BackendAccess: Context has no ServiceManager (or it is missing an interface)"); if (!mFactory.is()) throw uno::RuntimeException(OUString::createFromAscii("BackendAccess: Context has no ServiceManager (or it is missing an interface)"), NULL); } //------------------------------------------------------------------------------ BackendAccess::~BackendAccess(void) {} //------------------------------------------------------------------------------ static rtl::OUString findBestLocale( const uno::Sequence<rtl::OUString>& aLocales, const rtl::OUString& aWanted) { rtl::OUString fallback ; for (sal_Int32 i = 0 ; i < aLocales.getLength() ; ++ i) { if (aLocales [i].equals(aWanted)) { return aWanted ; } if (fallback.getLength() == 0) { sal_Int32 compLength = aWanted.getLength() ; if (aLocales [i].getLength() < compLength) { compLength = aLocales [i].getLength() ; } if (aLocales [i].compareTo(aWanted, compLength) == 0) { fallback = aLocales [i] ; } } } return fallback ; } //------------------------------------------------------------------------------ static void merge( const uno::Reference<lang::XMultiServiceFactory>& aFactory, MergedComponentData& aData, const uno::Sequence<uno::Reference<backenduno::XLayer> >& aLayers, sal_Int32 aNbLayers, const rtl::OUString& aLocale, ITemplateDataProvider *aTemplateProvider=NULL) { LayerMergeHandler * pMerger = new LayerMergeHandler(aFactory, aData, aTemplateProvider); uno::Reference<backenduno::XLayerHandler> xLayerMerger(pMerger); RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::backend::BackendAccess", "jb99855", "configmgr: BackendAccess::merge()"); RTL_LOGFILE_CONTEXT_TRACE1(aLog, "merging %d layers", int(aNbLayers) ); for (sal_Int32 i = 0 ; i < aNbLayers ; ++ i) { pMerger->prepareLayer() ; aLayers [i]->readData(xLayerMerger) ; uno::Reference<backenduno::XCompositeLayer> compositeLayer( aLayers [i], uno::UNO_QUERY) ; if (compositeLayer.is()) { if(localehelper::isAnyLocale(aLocale)) { uno::Sequence<rtl::OUString> aLayerIds = compositeLayer->listSubLayerIds(); //Loop thru layers for (sal_Int32 i = 0; i < aLayerIds.getLength(); ++i) { if(pMerger->prepareSublayer(aLayerIds[i])); { compositeLayer->readSubLayerData(xLayerMerger,aLayerIds[i]) ; } } } else { rtl::OUString bestLocale = findBestLocale( compositeLayer->listSubLayerIds(), aLocale) ; if (pMerger->prepareSublayer(bestLocale) ) { compositeLayer->readSubLayerData(xLayerMerger, bestLocale) ; } } } } } //------------------------------------------------------------------------------ ComponentResult BackendAccess::getNodeData(const ComponentRequest& aRequest, ITemplateDataProvider *aTemplateProvider, INodeDataListener *aListener) CFG_UNO_THROW_ALL() { rtl::OUString component = aRequest.getComponentName().toString() ; SchemaBuilder *schemaBuilder = new backend::SchemaBuilder( component, aTemplateProvider == NULL ? this:aTemplateProvider ) ; uno::Reference<backenduno::XSchemaHandler> schemaHandler = schemaBuilder ; uno::Sequence<uno::Reference<backenduno::XLayer> > layers ; uno::Reference<backenduno::XSchema> schema ; RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::backend::BackendAccess", "jb99855", "configmgr: BackendAccess::getNodeData()"); RTL_LOGFILE_CONTEXT_TRACE1(aLog, "request path: %s", RTL_LOGFILE_OU2A(aRequest.getComponentName().toString()) ); AbsolutePath aRequestPath = AbsolutePath::makeModulePath(aRequest.getComponentName(), AbsolutePath::NoValidate()); NodeRequest aNodeRequest(aRequestPath, aRequest.getOptions()); getSchemaAndLayers(aNodeRequest, schema, layers) ; schema->readSchema(schemaHandler) ; merge(mFactory, schemaBuilder->result(), layers, layers.getLength(), aNodeRequest.getOptions().getLocale(),aTemplateProvider ); ComponentInstance retCode(schemaBuilder->result().extractSchemaTree(), schemaBuilder->result().extractTemplatesTree(), aRequest.getComponentName()) ; return ComponentResult(retCode) ; } //------------------------------------------------------------------------------ void BackendAccess::updateNodeData(const UpdateRequest& aUpdate) CFG_UNO_THROW_ALL() { rtl::OUString entity = aUpdate.getOptions().getEntity() ; rtl::OUString component = aUpdate.getUpdateRoot().getModuleName().toString() ; uno::Reference<backenduno::XUpdateHandler> handler ; RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::backend::BackendAccess", "jb99855", "configmgr: BackendAccess::updateNodeData()"); RTL_LOGFILE_CONTEXT_TRACE1(aLog, "updating component: %s", RTL_LOGFILE_OU2A(component) ); if (entity.getLength() == 0) { handler = mBackend->getOwnUpdateHandler(component) ; } else { handler = mBackend->getUpdateHandler(component, entity) ; } UpdateDispatcher dispatcher(handler, aUpdate.getOptions().getLocale()) ; dispatcher.dispatchUpdate(aUpdate.getUpdateRoot().location(), *aUpdate.getUpdateData()) ; } //------------------------------------------------------------------------------ NodeResult BackendAccess::getDefaultData(const NodeRequest& aRequest) CFG_UNO_THROW_ALL() { rtl::OUString component = aRequest.getPath().getModuleName().toString() ; SchemaBuilder *schemaBuilder = new backend::SchemaBuilder(component) ; uno::Reference<backenduno::XSchemaHandler> schemaHandler = schemaBuilder ; uno::Sequence<uno::Reference<backenduno::XLayer> > layers ; uno::Reference<backenduno::XSchema> schema ; RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::backend::BackendAccess", "jb99855", "configmgr: BackendAccess::getDefaultData()"); RTL_LOGFILE_CONTEXT_TRACE1(aLog, "request path: %s", RTL_LOGFILE_OU2A(aRequest.getPath().toString()) ); getSchemaAndLayers(aRequest, schema, layers) ; schema->readSchema(schemaHandler) ; merge(mFactory, schemaBuilder->result(), layers,layers.getLength() - 1, aRequest.getOptions().getLocale()); promoteToDefault(schemaBuilder->result()); //Extract required tree form the schemaTree std::auto_ptr<ISubtree> aSubTree = schemaBuilder->result().extractSchemaTree(); AbsolutePath aPath = aRequest.getPath(); if( aPath.begin()+1 != aPath.end()) { for(AbsolutePath::Iterator it=aPath.begin()+1,endIt=aPath.end();it!=endIt; ++it) { std::auto_ptr<INode> aChild=aSubTree->removeChild(it->getName().toString()); if(aChild.get()== NULL) { OUString sMsg = OUString::createFromAscii("BackendAccess:getDefaultData: No Such Element"); throw container::NoSuchElementException( sMsg, mBackend); } ISubtree *pChildAsSubtree = aChild->asISubtree(); if(pChildAsSubtree == NULL) { OUString sMsg = OUString::createFromAscii("BackendAccess:getDefaultData: Node Expected, Found Property "); throw MalformedDataException(sMsg, mBackend); } aSubTree.reset(pChildAsSubtree); aChild.release(); } } NodeInstance retCode(aSubTree, aRequest.getPath()) ; return NodeResult(retCode) ; } //------------------------------------------------------------------------------ TemplateResult BackendAccess::getTemplateData(const TemplateRequest& aRequest) CFG_UNO_THROW_ALL() { uno::Reference<backenduno::XSchema> schema = mBackend->getComponentSchema(aRequest.getComponentName().toString()) ; rtl::OUString component = aRequest.getComponentName().toString(); SchemaBuilder *schemaBuilder = new SchemaBuilder( component ) ; uno::Reference<backenduno::XSchemaHandler> handler = schemaBuilder ; RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::backend::BackendAccess", "jb99855", "configmgr: BackendAccess::getTemplateData()"); RTL_LOGFILE_CONTEXT_TRACE2(aLog, "requested template: %s/%s", RTL_LOGFILE_OU2A(aRequest.getComponentName().toString()) , aRequest.isComponentRequest() ? "*" : RTL_LOGFILE_OU2A(aRequest.getComponentName().toString()) ); schema->readTemplates(handler) ; TemplateInstance::Data aResultData; if (aRequest.isComponentRequest()) { aResultData.reset( schemaBuilder->result().extractTemplatesTree().release() ); } else { backenduno::TemplateIdentifier templateId ; templateId.Name = aRequest.getTemplateName().toString() ; templateId.Component = aRequest.getComponentName().toString() ; aResultData = schemaBuilder->result().extractTemplateNode(templateId.Name); } TemplateInstance retCode(aResultData,aRequest.getTemplateName(), aRequest.getComponentName()) ; return TemplateResult(retCode) ; } //------------------------------------------------------------------------------ void BackendAccess::getSchemaAndLayers(const NodeRequest& aRequest, uno::Reference<backenduno::XSchema>& aSchema, uno::Sequence<uno::Reference<backenduno::XLayer> >& aLayers) { rtl::OUString component = aRequest.getPath().getModuleName().toString() ; rtl::OUString entity = aRequest.getOptions().getEntity() ; aSchema = mBackend->getComponentSchema(component) ; if (entity.getLength() == 0) { // Use own entity instead aLayers = mBackend->listOwnLayers(component) ; } else { aLayers = mBackend->listLayers(component, entity) ; } } //------------------------------------------------------------------------------ } } // configmgr.backend <commit_msg>INTEGRATION: CWS configapi01 (1.12.2); FILE MERGED 2003/04/10 15:46:59 jb 1.12.2.1: #1077715# Move configuration backend API out of drafts; adjust to API changes<commit_after>/************************************************************************* * * $RCSfile: backendaccess.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: rt $ $Date: 2003-04-17 13:13:06 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CONFIGMGR_BACKEND_BACKENDACCESS_HXX_ #include "backendaccess.hxx" #endif // CONFIGMGR_BACKEND_BACKENDACCESS_HXX_ #ifndef CONFIGMGR_MATCHLOCALE_HXX #include "matchlocale.hxx" #endif // CONFIGMGR_MATCHLOCALE_HXX #ifndef CONFIGMGR_BACKEND_LAYERMERGE_HXX #include "layermerge.hxx" #endif // CONFIGMGR_BACKEND_LAYERMERGE_HXX #ifndef CONFIGMGR_BACKEND_SCHEMABUILDER_HXX #include "schemabuilder.hxx" #endif // CONFIGMGR_BACKEND_SCHEMABUILDER_HXX #ifndef CONFIGMGR_BACKEND_UPDATEDISPATCHER_HXX #include "updatedispatch.hxx" #endif // CONFIGMGR_BACKEND_UPDATEDISPATCHER_HXX #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XSCHEMASUPPLIER_HPP_ #include <com/sun/star/configuration/backend/XSchemaSupplier.hpp> #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XCOMPOSITELAYER_HPP_ #include <com/sun/star/configuration/backend/XCompositeLayer.hpp> #endif // _COM_SUN_STAR_CONFIGURATION_BACKEND_XCOMPOSITELAYER_HPP_ #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_MALFORMEDDATAEXCEPTION_HPP_ #include <com/sun/star/configuration/backend/MalformedDataException.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_NOSUCHELEMENTEXCEPTION_HPP_ #include <com/sun/star/container/NoSuchElementException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_NULLPOINTEREXCEPTION_HPP_ #include <com/sun/star/lang/NullPointerException.hpp> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _RTL_LOGFILE_HXX_ #include <rtl/logfile.hxx> #endif #define RTL_LOGFILE_OU2A(rtlOUString) (::rtl::OUStringToOString((rtlOUString), RTL_TEXTENCODING_ASCII_US).getStr()) #define OUSTR(txt) OUString( RTL_CONSTASCII_USTRINGPARAM(txt) ) namespace configmgr { namespace backend { //============================================================================== //------------------------------------------------------------------------------ BackendAccess::BackendAccess( const uno::Reference<backenduno::XBackend>& xBackend, const uno::Reference<uno::XComponentContext>& xContext) : mFactory(xContext->getServiceManager(), uno::UNO_QUERY) , mBackend(xBackend) { OSL_ENSURE(mFactory.is(), "BackendAccess: Context has no ServiceManager (or it is missing an interface)"); if (!mFactory.is()) throw lang::NullPointerException(OUString::createFromAscii("BackendAccess: Context has no ServiceManager (or it is missing an interface)"), NULL); if (!xBackend.is()) throw lang::NullPointerException(OUSTR("Configuration: Trying to create backend access without backend"),NULL); if (!uno::Reference<backenduno::XSchemaSupplier>::query(xBackend).is()) throw lang::NullPointerException(OUSTR("Configuration: No backend for schemas available"),NULL); } //------------------------------------------------------------------------------ BackendAccess::~BackendAccess(void) {} //------------------------------------------------------------------------------ static rtl::OUString findBestLocale( const uno::Sequence<rtl::OUString>& aLocales, const rtl::OUString& aWanted) { rtl::OUString fallback ; for (sal_Int32 i = 0 ; i < aLocales.getLength() ; ++ i) { if (aLocales [i].equals(aWanted)) { return aWanted ; } if (fallback.getLength() == 0) { sal_Int32 compLength = aWanted.getLength() ; if (aLocales [i].getLength() < compLength) { compLength = aLocales [i].getLength() ; } if (aLocales [i].compareTo(aWanted, compLength) == 0) { fallback = aLocales [i] ; } } } return fallback ; } //------------------------------------------------------------------------------ static void merge( const uno::Reference<lang::XMultiServiceFactory>& aFactory, MergedComponentData& aData, const uno::Sequence<uno::Reference<backenduno::XLayer> >& aLayers, sal_Int32 aNbLayers, const rtl::OUString& aLocale, ITemplateDataProvider *aTemplateProvider=NULL) { LayerMergeHandler * pMerger = new LayerMergeHandler(aFactory, aData, aTemplateProvider); uno::Reference<backenduno::XLayerHandler> xLayerMerger(pMerger); RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::backend::BackendAccess", "jb99855", "configmgr: BackendAccess::merge()"); RTL_LOGFILE_CONTEXT_TRACE1(aLog, "merging %d layers", int(aNbLayers) ); for (sal_Int32 i = 0 ; i < aNbLayers ; ++ i) { pMerger->prepareLayer() ; aLayers [i]->readData(xLayerMerger) ; uno::Reference<backenduno::XCompositeLayer> compositeLayer( aLayers [i], uno::UNO_QUERY) ; if (compositeLayer.is()) { if(localehelper::isAnyLocale(aLocale)) { uno::Sequence<rtl::OUString> aLayerIds = compositeLayer->listSubLayerIds(); //Loop thru layers for (sal_Int32 i = 0; i < aLayerIds.getLength(); ++i) { if(pMerger->prepareSublayer(aLayerIds[i])) { compositeLayer->readSubLayerData(xLayerMerger,aLayerIds[i]) ; } } } else { rtl::OUString bestLocale = findBestLocale( compositeLayer->listSubLayerIds(), aLocale) ; if (pMerger->prepareSublayer(bestLocale) ) { compositeLayer->readSubLayerData(xLayerMerger, bestLocale) ; } } } } } //------------------------------------------------------------------------------ ComponentResult BackendAccess::getNodeData(const ComponentRequest& aRequest, ITemplateDataProvider *aTemplateProvider, INodeDataListener *aListener) CFG_UNO_THROW_ALL() { rtl::OUString component = aRequest.getComponentName().toString() ; SchemaBuilder *schemaBuilder = new backend::SchemaBuilder( component, aTemplateProvider == NULL ? this:aTemplateProvider ) ; uno::Reference<backenduno::XSchemaHandler> schemaHandler = schemaBuilder ; RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::backend::BackendAccess", "jb99855", "configmgr: BackendAccess::getNodeData()"); RTL_LOGFILE_CONTEXT_TRACE1(aLog, "request path: %s", RTL_LOGFILE_OU2A(aRequest.getComponentName().toString()) ); uno::Reference<backenduno::XSchema> schema = this->getSchema(component); uno::Sequence<uno::Reference<backenduno::XLayer> > layers ; this->getLayers(component, aRequest.getOptions(), layers) ; schema->readSchema(schemaHandler) ; merge(mFactory, schemaBuilder->result(), layers, layers.getLength(), aRequest.getOptions().getLocale(),aTemplateProvider ); ComponentInstance retCode(schemaBuilder->result().extractSchemaTree(), schemaBuilder->result().extractTemplatesTree(), aRequest.getComponentName()) ; return ComponentResult(retCode) ; } //------------------------------------------------------------------------------ void BackendAccess::updateNodeData(const UpdateRequest& aUpdate) CFG_UNO_THROW_ALL() { rtl::OUString entity = aUpdate.getOptions().getEntity() ; rtl::OUString component = aUpdate.getUpdateRoot().getModuleName().toString() ; uno::Reference<backenduno::XUpdateHandler> handler ; RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::backend::BackendAccess", "jb99855", "configmgr: BackendAccess::updateNodeData()"); RTL_LOGFILE_CONTEXT_TRACE1(aLog, "updating component: %s", RTL_LOGFILE_OU2A(component) ); if (entity.getLength() == 0) { handler = mBackend->getOwnUpdateHandler(component) ; } else { handler = mBackend->getUpdateHandler(component, entity) ; } UpdateDispatcher dispatcher(handler, aUpdate.getOptions().getLocale()) ; dispatcher.dispatchUpdate(aUpdate.getUpdateRoot().location(), *aUpdate.getUpdateData()) ; } //------------------------------------------------------------------------------ NodeResult BackendAccess::getDefaultData(const NodeRequest& aRequest) CFG_UNO_THROW_ALL() { rtl::OUString component = aRequest.getPath().getModuleName().toString() ; SchemaBuilder *schemaBuilder = new backend::SchemaBuilder(component) ; uno::Reference<backenduno::XSchemaHandler> schemaHandler = schemaBuilder ; RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::backend::BackendAccess", "jb99855", "configmgr: BackendAccess::getDefaultData()"); RTL_LOGFILE_CONTEXT_TRACE1(aLog, "request path: %s", RTL_LOGFILE_OU2A(aRequest.getPath().toString()) ); uno::Reference<backenduno::XSchema> schema = this->getSchema(component); uno::Sequence<uno::Reference<backenduno::XLayer> > layers ; this->getLayers(component, aRequest.getOptions(), layers) ; schema->readSchema(schemaHandler) ; merge(mFactory, schemaBuilder->result(), layers,layers.getLength() - 1, aRequest.getOptions().getLocale()); promoteToDefault(schemaBuilder->result()); //Extract required tree form the schemaTree std::auto_ptr<ISubtree> aSubTree = schemaBuilder->result().extractSchemaTree(); AbsolutePath aPath = aRequest.getPath(); if( aPath.begin() != aPath.end()) { for(AbsolutePath::Iterator it=aPath.begin()+1,endIt=aPath.end();it!=endIt; ++it) { std::auto_ptr<INode> aChild=aSubTree->removeChild(it->getName().toString()); if(aChild.get()== NULL) { OUString sMsg = OUString::createFromAscii("BackendAccess::getDefaultData - No Such Element: ").concat(aPath.toString()); throw com::sun::star::container::NoSuchElementException( sMsg, mBackend); } ISubtree *pChildAsSubtree = aChild->asISubtree(); if(pChildAsSubtree == NULL) { OUString sMsg = OUString::createFromAscii("BackendAccess::getDefaultData - Node Expected, Found Property: ").concat(it->getName().toString()); throw MalformedDataException(sMsg, mBackend, uno::Any()); } aSubTree.reset(pChildAsSubtree); aChild.release(); } } NodeInstance retCode(aSubTree, aRequest.getPath()) ; return NodeResult(retCode) ; } //------------------------------------------------------------------------------ TemplateResult BackendAccess::getTemplateData(const TemplateRequest& aRequest) CFG_UNO_THROW_ALL() { rtl::OUString component = aRequest.getComponentName().toString(); SchemaBuilder *schemaBuilder = new SchemaBuilder( component ) ; uno::Reference<backenduno::XSchemaHandler> handler = schemaBuilder ; RTL_LOGFILE_CONTEXT_AUTHOR(aLog, "configmgr::backend::BackendAccess", "jb99855", "configmgr: BackendAccess::getTemplateData()"); RTL_LOGFILE_CONTEXT_TRACE2(aLog, "requested template: %s/%s", RTL_LOGFILE_OU2A(aRequest.getComponentName().toString()) , aRequest.isComponentRequest() ? "*" : RTL_LOGFILE_OU2A(aRequest.getComponentName().toString()) ); uno::Reference<backenduno::XSchema> schema = this->getSchema(component); schema->readTemplates(handler) ; TemplateInstance::Data aResultData; if (aRequest.isComponentRequest()) { aResultData.reset( schemaBuilder->result().extractTemplatesTree().release() ); } else { backenduno::TemplateIdentifier templateId ; templateId.Name = aRequest.getTemplateName().toString() ; templateId.Component = aRequest.getComponentName().toString() ; aResultData = schemaBuilder->result().extractTemplateNode(templateId.Name); } TemplateInstance retCode(aResultData,aRequest.getTemplateName(), aRequest.getComponentName()) ; return TemplateResult(retCode) ; } //------------------------------------------------------------------------------ uno::Reference< backenduno::XSchema > BackendAccess::getSchema(const OUString& aComponent) { uno::Reference< backenduno::XSchemaSupplier > xSchemaBackend(mBackend, uno::UNO_QUERY); OSL_ASSERT(xSchemaBackend.is()); uno::Reference< backenduno::XSchema > xSchema = xSchemaBackend->getComponentSchema(aComponent) ; if (!xSchema.is()) { rtl::OUStringBuffer sMessage; sMessage.appendAscii("Configuration: No data for request. Component \""); sMessage.append(aComponent); sMessage.appendAscii("\" is unknown. [No schema available]"); throw com::sun::star::container::NoSuchElementException(sMessage.makeStringAndClear(),xSchemaBackend); } return xSchema; } //------------------------------------------------------------------------------ void BackendAccess::getLayers(const OUString& aComponent,const RequestOptions& aOptions, uno::Sequence< uno::Reference<backenduno::XLayer> >& aLayers) { rtl::OUString aEntity = aOptions.getEntity() ; if (aEntity.getLength() == 0) { // Use own entity instead aLayers = mBackend->listOwnLayers(aComponent) ; } else { aLayers = mBackend->listLayers(aComponent, aEntity) ; } } //------------------------------------------------------------------------------ } } // configmgr.backend <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: bootstrapcontext.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2003-03-19 16:19:22 $ * * 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: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "bootstrapcontext.hxx" #ifndef _UNO_CURRENT_CONTEXT_HXX_ #include <uno/current_context.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #ifndef _CPPUHELPER_EXC_HLP_HXX_ #include <cppuhelper/exc_hlp.hxx> #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif namespace configmgr { // --------------------------------------------------------------------------- #define IMPL_ITEM_PREFIX_ "/implementations/com.sun.star.com.configuration.bootstrap.ComponentContext/" #define IMPL_ITEM_PASSTHRU IMPL_ITEM_PREFIX_"isPassthrough" #define IMPL_ITEM_BASECONTEXT IMPL_ITEM_PREFIX_"theBaseContext" #define A_SERVICEMANAGER "com.sun.star.lang.theServiceManager" // --------------------------------------------------------------------------- #define OUSTR( text ) OUString( RTL_CONSTASCII_USTRINGPARAM( text ) ) #define OU2ASCII( str ) ( rtl::OUStringToOString(str,RTL_TEXTENCODING_ASCII_US) .getStr() ) // --------------------------------------------------------------------------- #if 0 static void testComplete() { uno::Reference< uno::XInterface > test = * new ComponentContext(ComponentContext::Context(),ComponentContext::Overrides(),true); } #endif // --------------------------------------------------------------------------- ComponentContext::ComponentContext(Context const & _xContext) : ComponentContext_Base(m_aMutex) , m_aMutex() , m_xContext(_xContext) , m_hBootstrapData(NULL) { } // --------------------------------------------------------------------------- ComponentContext::~ComponentContext() { if (m_hBootstrapData) rtl_bootstrap_args_close(m_hBootstrapData); } // --------------------------------------------------------------------------- void ComponentContext::initialize( const OUString& _aURL ) { osl::ClearableMutexGuard lock(mutex()); OSL_ASSERT(!m_hBootstrapData); m_hBootstrapData = rtl_bootstrap_args_open(_aURL.pData); uno::Reference< lang::XComponent > xOwner(m_xContext, uno::UNO_QUERY); lock.clear(); if (xOwner.is()) DisposingForwarder::forward(xOwner,this); if (!m_xContext.is()) { OSL_ENSURE(rBHelper.bDisposed,"ComponentContext::initialize - Context unexpectedly missing"); throw lang::DisposedException(OUSTR("Parent context has been disposed early"),*this); } } // --------------------------------------------------------------------------- // ComponentHelper void SAL_CALL ComponentContext::disposing() { osl::MutexGuard lock(mutex()); m_xContext.clear(); if (m_hBootstrapData) { rtl_bootstrap_args_close(m_hBootstrapData); m_hBootstrapData = NULL; } } // --------------------------------------------------------------------------- OUString ComponentContext::getBootstrapURL() const { OUString aResult; osl::MutexGuard lock(mutex()); if (m_hBootstrapData) { rtl_bootstrap_get_iniName_from_handle(m_hBootstrapData,&aResult.pData); } else { OSL_TRACE( "configmgr: No bootstrap data URL set"); } return aResult; } // --------------------------------------------------------------------------- void ComponentContext::changeBootstrapURL( const OUString& _aURL ) { osl::MutexGuard lock(mutex()); if (rtlBootstrapHandle hNew = rtl_bootstrap_args_open(_aURL.pData)) { rtl_bootstrap_args_close(m_hBootstrapData); m_hBootstrapData = hNew; } else { OSL_TRACE( "configmgr: Cannot open bootstrap data URL: %s", OU2ASCII(_aURL) ); } } // --------------------------------------------------------------------------- uno::Reference< lang::XMultiComponentFactory > SAL_CALL ComponentContext::getServiceManager( ) throw (uno::RuntimeException) { Context xBase = basecontext(); if (!xBase.is()) throw lang::DisposedException(OUSTR("Parent context has been disposed"),*this); return xBase->getServiceManager(); } // --------------------------------------------------------------------------- uno::Any SAL_CALL ComponentContext::getValueByName( const OUString& aName ) throw (uno::RuntimeException) { uno::Any aResult; bool bFound = lookupInContext ( aResult, aName ) || lookupInBootstrap( aResult, aName ); return aResult; } // --------------------------------------------------------------------------- sal_Bool ComponentContext::isPassthrough(Context const & _xContext) { OSL_ENSURE(_xContext.is(),"Unexpected NULL context"); if (!_xContext.is()) return false; sal_Bool bValue = false; _xContext->getValueByName(OUSTR(IMPL_ITEM_PASSTHRU)) >>= bValue; return bValue; } // --------------------------------------------------------------------------- beans::NamedValue ComponentContext::makePassthroughMarker(sal_Bool bPassthrough) { return beans::NamedValue(OUSTR(IMPL_ITEM_PASSTHRU),uno::makeAny(bPassthrough)); } // --------------------------------------------------------------------------- ComponentContext::Context ComponentContext::getBaseContext(Context const & _xContext) { OSL_ENSURE(_xContext.is(),"Unexpected NULL context"); Context xResult = _xContext; if (_xContext.is()) { _xContext->getValueByName(OUSTR(IMPL_ITEM_BASECONTEXT)) >>= xResult; } return xResult; } // --------------------------------------------------------------------------- bool ComponentContext::lookupInContext( uno::Any & _rValue, const OUString& _aName ) const { Context xBase = basecontext(); if (!xBase.is()) throw lang::DisposedException(OUSTR("Parent context has been disposed"),const_cast<ComponentContext&>(*this)); if (_aName.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM( IMPL_ITEM_BASECONTEXT ))) { _rValue = uno::makeAny(xBase); return true; } uno::Any aCtxValue = xBase->getValueByName( _aName ); if (aCtxValue.hasValue()) { _rValue = aCtxValue; return true; } else return false; } // --------------------------------------------------------------------------- bool ComponentContext::lookupInBootstrap( uno::Any & _rValue, const OUString& _aName ) const { osl::MutexGuard lock(mutex()); OUString sResult; if ( rtl_bootstrap_get_from_handle( m_hBootstrapData, _aName.pData, &sResult.pData, 0) ) { _rValue <<= sResult; return true; } else return false; } // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- static const char k_TunneledContext[] = "/services/com.sun.star.configuration.bootstrap.Context"; class UnoContextTunnel::Tunnel : public ::cppu::WeakImplHelper2< uno::XCurrentContext, lang::XUnoTunnel > { Context m_xTunneledContext; CurrentContext m_xOldContext; uno::Any m_aFailure; public: Tunnel(Context const & xTunneledContext, CurrentContext const & xOldContext) : m_xTunneledContext(xTunneledContext) , m_xOldContext(xOldContext) , m_aFailure() {} virtual uno::Any SAL_CALL getValueByName( const OUString& Name ) throw (uno::RuntimeException) { if (Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM(k_TunneledContext) ) ) { return uno::makeAny(m_xTunneledContext); } else if (m_xOldContext.is()) { return m_xOldContext->getValueByName(Name); } else { return uno::Any(); } } virtual sal_Int64 SAL_CALL getSomething( const uno::Sequence< sal_Int8 >& aIdentifier ) throw (uno::RuntimeException) { if (getTunnelId() == aIdentifier) return reinterpret_cast<sal_Int64>(&m_aFailure); else return 0; } static uno::Any * getFailure(FailureTunnel const & xTunnel); static uno::Sequence< sal_Int8 > getTunnelId(); }; // --------------------------------------------------------------------------- uno::Sequence< sal_Int8 > UnoContextTunnel::Tunnel::getTunnelId() { static ::cppu::OImplementationId aTunnelId; return aTunnelId.getImplementationId(); } // --------------------------------------------------------------------------- uno::Any * UnoContextTunnel::Tunnel::getFailure(FailureTunnel const & xTunnel) { if (xTunnel.is()) { if (sal_Int64 nSomething = xTunnel->getSomething(getTunnelId())) { return reinterpret_cast<uno::Any *>(nSomething); } } return NULL; } // --------------------------------------------------------------------------- UnoContextTunnel::UnoContextTunnel() : m_xOldContext( uno::getCurrentContext() ) , m_xActiveTunnel() { } // --------------------------------------------------------------------------- UnoContextTunnel::~UnoContextTunnel() { uno::setCurrentContext( m_xOldContext ); } // --------------------------------------------------------------------------- void UnoContextTunnel::passthru(Context const & xContext) { OSL_ASSERT( xContext.is() ); if ( ComponentContext::isPassthrough(xContext) ) { this ->tunnel(xContext); } else { this->tunnel(NULL); } } // --------------------------------------------------------------------------- void UnoContextTunnel::tunnel(Context const & xContext) { Tunnel * pNewTunnel = new Tunnel(xContext,m_xOldContext); m_xActiveTunnel = pNewTunnel; uno::setCurrentContext( pNewTunnel ); } // --------------------------------------------------------------------------- UnoContextTunnel::Context UnoContextTunnel::recoverContext(Context const & xFallback ) { try { CurrentContext const xCurrContext = uno::getCurrentContext(); if (xCurrContext.is()) { OUString aName(RTL_CONSTASCII_USTRINGPARAM(k_TunneledContext)); Context xResult; if (xCurrContext->getValueByName(aName) >>= xResult) { if (xResult.is()) return xResult; } else { OSL_ASSERT( !xResult.is() ); OSL_ENSURE( !xCurrContext->getValueByName(aName).hasValue(), "Value in context has wrong type"); } } } catch (uno::Exception &) { OSL_ENSURE(false, "Unexpected: Exception from accessing current context"); } return xFallback; } // --------------------------------------------------------------------------- uno::Any UnoContextTunnel::recoverFailure(bool bRaise) { if (uno::Any * pFail = UnoContextTunnel::Tunnel::getFailure(m_xActiveTunnel)) { if (bRaise) { if (pFail->hasValue()) cppu::throwException(*pFail); else throw; } return *pFail; } return uno::Any(); } // --------------------------------------------------------------------------- bool UnoContextTunnel::tunnelFailure(uno::Any const & aException, bool bRaise) { OSL_ASSERT( !aException.hasValue() || aException.getValueTypeClass() == uno::TypeClass_EXCEPTION ); FailureTunnel xTunnel( uno::getCurrentContext(), uno::UNO_QUERY ); if (uno::Any * pFail = Tunnel::getFailure(xTunnel)) { *pFail = aException; if (bRaise && aException.hasValue()) cppu::throwException(aException); if (bRaise) throw; return true; } else { if (bRaise) throw; return false; } } // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- void DisposingForwarder::disposing( lang::EventObject const & rSource ) throw (uno::RuntimeException) { m_xTarget->dispose(); m_xTarget.clear(); } // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- } // namespace config <commit_msg>INTEGRATION: CWS cfglooseends (1.2.150); FILE MERGED 2004/11/02 16:57:22 jb 1.2.150.1: #109882# Use own servicemanager (-wrapper) for bootstrap context<commit_after>/************************************************************************* * * $RCSfile: bootstrapcontext.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2004-11-15 13:37:06 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "bootstrapcontext.hxx" #ifndef _UNO_CURRENT_CONTEXT_HXX_ #include <uno/current_context.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #ifndef _CPPUHELPER_EXC_HLP_HXX_ #include <cppuhelper/exc_hlp.hxx> #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif namespace configmgr { // --------------------------------------------------------------------------- #define IMPL_ITEM_PREFIX_ "/implementations/com.sun.star.com.configuration.bootstrap.ComponentContext/" #define IMPL_ITEM_PASSTHRU IMPL_ITEM_PREFIX_"isPassthrough" #define IMPL_ITEM_BASECONTEXT IMPL_ITEM_PREFIX_"theBaseContext" #define A_SERVICEMANAGER "com.sun.star.lang.theServiceManager" // --------------------------------------------------------------------------- #define OUSTR( text ) OUString( RTL_CONSTASCII_USTRINGPARAM( text ) ) #define OU2ASCII( str ) ( rtl::OUStringToOString(str,RTL_TEXTENCODING_ASCII_US) .getStr() ) // --------------------------------------------------------------------------- #if 0 static void testComplete() { uno::Reference< uno::XInterface > test = * new ComponentContext(ComponentContext::Context(),ComponentContext::Overrides(),true); } #endif // --------------------------------------------------------------------------- ComponentContext::ComponentContext(Context const & _xContext) : ComponentContext_Base(m_aMutex) , m_aMutex() , m_xContext(_xContext) , m_hBootstrapData(NULL) , m_xServiceManager() { } // --------------------------------------------------------------------------- ComponentContext::~ComponentContext() { if (m_hBootstrapData) rtl_bootstrap_args_close(m_hBootstrapData); } // --------------------------------------------------------------------------- void ComponentContext::initialize( const OUString& _aURL ) { osl::ClearableMutexGuard lock(mutex()); OSL_ASSERT(!m_hBootstrapData); m_hBootstrapData = rtl_bootstrap_args_open(_aURL.pData); uno::Reference< lang::XComponent > xOwner(m_xContext, uno::UNO_QUERY); lock.clear(); if (xOwner.is()) DisposingForwarder::forward(xOwner,this); if (!m_xContext.is()) { OSL_ENSURE(rBHelper.bDisposed,"ComponentContext::initialize - Context unexpectedly missing"); throw lang::DisposedException(OUSTR("Parent context has been disposed early"),*this); } } // --------------------------------------------------------------------------- // ComponentHelper void SAL_CALL ComponentContext::disposing() { osl::MutexGuard lock(mutex()); m_xContext.clear(); if (m_hBootstrapData) { rtl_bootstrap_args_close(m_hBootstrapData); m_hBootstrapData = NULL; } } // --------------------------------------------------------------------------- OUString ComponentContext::getBootstrapURL() const { OUString aResult; osl::MutexGuard lock(mutex()); if (m_hBootstrapData) { rtl_bootstrap_get_iniName_from_handle(m_hBootstrapData,&aResult.pData); } else { OSL_TRACE( "configmgr: No bootstrap data URL set"); } return aResult; } // --------------------------------------------------------------------------- void ComponentContext::changeBootstrapURL( const OUString& _aURL ) { osl::MutexGuard lock(mutex()); if (rtlBootstrapHandle hNew = rtl_bootstrap_args_open(_aURL.pData)) { rtl_bootstrap_args_close(m_hBootstrapData); m_hBootstrapData = hNew; } else { OSL_TRACE( "configmgr: Cannot open bootstrap data URL: %s", OU2ASCII(_aURL) ); } } // --------------------------------------------------------------------------- uno::Reference< lang::XMultiComponentFactory > SAL_CALL ComponentContext::getServiceManager( ) throw (uno::RuntimeException) { osl::MutexGuard lock(mutex()); if (!m_xServiceManager.is()) { Context xBase = basecontext(); if (!xBase.is()) throw lang::DisposedException(OUSTR("Parent context has been disposed"),*this); ServiceManager xBaseServiceManager = xBase->getServiceManager(); OSL_ENSURE( xBaseServiceManager.is(), "Base context has no service manager"); if (xBaseServiceManager.is()) { // create new smgr based on delegate's one m_xServiceManager.set( xBaseServiceManager->createInstanceWithContext( OUSTR("com.sun.star.comp.stoc.OServiceManagerWrapper"), xBase ), uno::UNO_QUERY ); // patch DefaultContext property of new one uno::Reference< beans::XPropertySet > xProps( m_xServiceManager, uno::UNO_QUERY ); OSL_ASSERT( xProps.is() ); if (xProps.is()) { uno::Reference< XComponentContext > xThis( this ); xProps->setPropertyValue( OUSTR("DefaultContext"), uno::makeAny( xThis ) ); } else OSL_ENSURE(!m_xServiceManager.is(), "Cannot set Default Context of Service Manager Wrapper: no property set"); } } return m_xServiceManager; } // --------------------------------------------------------------------------- uno::Any SAL_CALL ComponentContext::getValueByName( const OUString& aName ) throw (uno::RuntimeException) { uno::Any aResult; bool bFound = lookupInContext ( aResult, aName ) || lookupInBootstrap( aResult, aName ); return aResult; } // --------------------------------------------------------------------------- sal_Bool ComponentContext::isPassthrough(Context const & _xContext) { OSL_ENSURE(_xContext.is(),"Unexpected NULL context"); if (!_xContext.is()) return false; sal_Bool bValue = false; _xContext->getValueByName(OUSTR(IMPL_ITEM_PASSTHRU)) >>= bValue; return bValue; } // --------------------------------------------------------------------------- beans::NamedValue ComponentContext::makePassthroughMarker(sal_Bool bPassthrough) { return beans::NamedValue(OUSTR(IMPL_ITEM_PASSTHRU),uno::makeAny(bPassthrough)); } // --------------------------------------------------------------------------- ComponentContext::Context ComponentContext::getBaseContext(Context const & _xContext) { OSL_ENSURE(_xContext.is(),"Unexpected NULL context"); Context xResult = _xContext; if (_xContext.is()) { _xContext->getValueByName(OUSTR(IMPL_ITEM_BASECONTEXT)) >>= xResult; } return xResult; } // --------------------------------------------------------------------------- bool ComponentContext::lookupInContext( uno::Any & _rValue, const OUString& _aName ) const { Context xBase = basecontext(); if (!xBase.is()) throw lang::DisposedException(OUSTR("Parent context has been disposed"),const_cast<ComponentContext&>(*this)); if (_aName.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM( IMPL_ITEM_BASECONTEXT ))) { _rValue = uno::makeAny(xBase); return true; } uno::Any aCtxValue = xBase->getValueByName( _aName ); if (aCtxValue.hasValue()) { _rValue = aCtxValue; return true; } else return false; } // --------------------------------------------------------------------------- bool ComponentContext::lookupInBootstrap( uno::Any & _rValue, const OUString& _aName ) const { osl::MutexGuard lock(mutex()); OUString sResult; if ( rtl_bootstrap_get_from_handle( m_hBootstrapData, _aName.pData, &sResult.pData, 0) ) { _rValue <<= sResult; return true; } else return false; } // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- static const char k_TunneledContext[] = "/services/com.sun.star.configuration.bootstrap.Context"; class UnoContextTunnel::Tunnel : public ::cppu::WeakImplHelper2< uno::XCurrentContext, lang::XUnoTunnel > { Context m_xTunneledContext; CurrentContext m_xOldContext; uno::Any m_aFailure; public: Tunnel(Context const & xTunneledContext, CurrentContext const & xOldContext) : m_xTunneledContext(xTunneledContext) , m_xOldContext(xOldContext) , m_aFailure() {} virtual uno::Any SAL_CALL getValueByName( const OUString& Name ) throw (uno::RuntimeException) { if (Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM(k_TunneledContext) ) ) { return uno::makeAny(m_xTunneledContext); } else if (m_xOldContext.is()) { return m_xOldContext->getValueByName(Name); } else { return uno::Any(); } } virtual sal_Int64 SAL_CALL getSomething( const uno::Sequence< sal_Int8 >& aIdentifier ) throw (uno::RuntimeException) { if (getTunnelId() == aIdentifier) return reinterpret_cast<sal_Int64>(&m_aFailure); else return 0; } static uno::Any * getFailure(FailureTunnel const & xTunnel); static uno::Sequence< sal_Int8 > getTunnelId(); }; // --------------------------------------------------------------------------- uno::Sequence< sal_Int8 > UnoContextTunnel::Tunnel::getTunnelId() { static ::cppu::OImplementationId aTunnelId; return aTunnelId.getImplementationId(); } // --------------------------------------------------------------------------- uno::Any * UnoContextTunnel::Tunnel::getFailure(FailureTunnel const & xTunnel) { if (xTunnel.is()) { if (sal_Int64 nSomething = xTunnel->getSomething(getTunnelId())) { return reinterpret_cast<uno::Any *>(nSomething); } } return NULL; } // --------------------------------------------------------------------------- UnoContextTunnel::UnoContextTunnel() : m_xOldContext( uno::getCurrentContext() ) , m_xActiveTunnel() { } // --------------------------------------------------------------------------- UnoContextTunnel::~UnoContextTunnel() { uno::setCurrentContext( m_xOldContext ); } // --------------------------------------------------------------------------- void UnoContextTunnel::passthru(Context const & xContext) { OSL_ASSERT( xContext.is() ); if ( ComponentContext::isPassthrough(xContext) ) { this ->tunnel(xContext); } else { this->tunnel(NULL); } } // --------------------------------------------------------------------------- void UnoContextTunnel::tunnel(Context const & xContext) { Tunnel * pNewTunnel = new Tunnel(xContext,m_xOldContext); m_xActiveTunnel = pNewTunnel; uno::setCurrentContext( pNewTunnel ); } // --------------------------------------------------------------------------- UnoContextTunnel::Context UnoContextTunnel::recoverContext(Context const & xFallback ) { try { CurrentContext const xCurrContext = uno::getCurrentContext(); if (xCurrContext.is()) { OUString aName(RTL_CONSTASCII_USTRINGPARAM(k_TunneledContext)); Context xResult; if (xCurrContext->getValueByName(aName) >>= xResult) { if (xResult.is()) return xResult; } else { OSL_ASSERT( !xResult.is() ); OSL_ENSURE( !xCurrContext->getValueByName(aName).hasValue(), "Value in context has wrong type"); } } } catch (uno::Exception &) { OSL_ENSURE(false, "Unexpected: Exception from accessing current context"); } return xFallback; } // --------------------------------------------------------------------------- uno::Any UnoContextTunnel::recoverFailure(bool bRaise) { if (uno::Any * pFail = UnoContextTunnel::Tunnel::getFailure(m_xActiveTunnel)) { if (bRaise) { if (pFail->hasValue()) cppu::throwException(*pFail); else throw; } return *pFail; } return uno::Any(); } // --------------------------------------------------------------------------- bool UnoContextTunnel::tunnelFailure(uno::Any const & aException, bool bRaise) { OSL_ASSERT( !aException.hasValue() || aException.getValueTypeClass() == uno::TypeClass_EXCEPTION ); FailureTunnel xTunnel( uno::getCurrentContext(), uno::UNO_QUERY ); if (uno::Any * pFail = Tunnel::getFailure(xTunnel)) { *pFail = aException; if (bRaise && aException.hasValue()) cppu::throwException(aException); if (bRaise) throw; return true; } else { if (bRaise) throw; return false; } } // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- void DisposingForwarder::disposing( lang::EventObject const & rSource ) throw (uno::RuntimeException) { m_xTarget->dispose(); m_xTarget.clear(); } // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- } // namespace config <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tools.cxx,v $ * * $Revision: 1.28 $ * * last change: $Author: rt $ $Date: 2008-01-30 07:55:41 $ * * 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_connectivity.hxx" #include <cstdarg> #ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_ #include "java/tools.hxx" #endif #ifndef _CONNECTIVITY_JAVA_LANG_STRING_HXX_ #include "java/lang/String.hxx" #endif #ifndef _CONNECTIVITY_JAVA_LANG_CLASS_HXX_ #include "java/lang/Class.hxx" #endif #ifndef CONNECTIVITY_java_util_Properties #include "java/util/Property.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_DRIVERPROPERTYINFO_HPP_ #include <com/sun/star/sdbc/DriverPropertyInfo.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif using namespace connectivity; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; // using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; void java_util_Properties::setProperty(const ::rtl::OUString key, const ::rtl::OUString& value) { SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); jobject out(0); if( t.pEnv ) { jvalue args[2]; // Parameter konvertieren args[0].l = convertwchar_tToJavaString(t.pEnv,key); args[1].l = convertwchar_tToJavaString(t.pEnv,value); // temporaere Variable initialisieren static const char * cSignature = "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;"; static const char * cMethodName = "setProperty"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ) { out = t.pEnv->CallObjectMethod(object, mID, args[0].l,args[1].l); ThrowSQLException(t.pEnv,NULL); } t.pEnv->DeleteLocalRef((jstring)args[1].l); t.pEnv->DeleteLocalRef((jstring)args[0].l); ThrowSQLException(t.pEnv,0); if(out) t.pEnv->DeleteLocalRef(out); } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! } jclass java_util_Properties::theClass = 0; java_util_Properties::~java_util_Properties() {} jclass java_util_Properties::getMyClass() { // die Klasse muss nur einmal geholt werden, daher statisch if( !theClass ){ SDBThreadAttach t; if( !t.pEnv ) return (jclass)NULL; jclass tempClass = t.pEnv->FindClass( "java/util/Properties" ); jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass ); t.pEnv->DeleteLocalRef( tempClass ); saveClassRef( globClass ); } return theClass; } void java_util_Properties::saveClassRef( jclass pClass ) { if( pClass==NULL ) return; // der uebergebe Klassen-Handle ist schon global, daher einfach speichern theClass = pClass; } //-------------------------------------------------------------------------- java_util_Properties::java_util_Properties( ): java_lang_Object( NULL, (jobject)NULL ) { SDBThreadAttach t; if( !t.pEnv ) return; // Java-Call fuer den Konstruktor absetzen // temporaere Variable initialisieren static const char * cSignature = "()V"; jobject tempObj; static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), "<init>", cSignature );OSL_ENSURE(mID,"Unknown method id!"); tempObj = t.pEnv->NewObject( getMyClass(), mID); saveRef( t.pEnv, tempObj ); t.pEnv->DeleteLocalRef( tempObj ); } // -------------------------------------------------------------------------------- jstring connectivity::convertwchar_tToJavaString(JNIEnv *pEnv,const ::rtl::OUString& _rTemp) { OSL_ENSURE(pEnv,"Environment is NULL!"); jstring pStr = pEnv->NewString(_rTemp.getStr(), _rTemp.getLength()); pEnv->ExceptionClear(); OSL_ENSURE(pStr,"Could not create a jsstring object!"); return pStr; } // -------------------------------------------------------------------------------- java_util_Properties* connectivity::createStringPropertyArray(const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException) { java_util_Properties* pProps = new java_util_Properties(); const PropertyValue* pBegin = info.getConstArray(); const PropertyValue* pEnd = pBegin + info.getLength(); for(;pBegin != pEnd;++pBegin) { // this is a special property to find the jdbc driver if( pBegin->Name.compareToAscii("JavaDriverClass") && pBegin->Name.compareToAscii("JavaDriverClassPath") && pBegin->Name.compareToAscii("SystemProperties") && pBegin->Name.compareToAscii("CharSet") && pBegin->Name.compareToAscii("AppendTableAlias") && pBegin->Name.compareToAscii("GenerateASBeforeCorrelationName") && pBegin->Name.compareToAscii("EscapeDateTime") && pBegin->Name.compareToAscii("ParameterNameSubstitution") && pBegin->Name.compareToAscii("IsPasswordRequired") && pBegin->Name.compareToAscii("IsAutoRetrievingEnabled") && pBegin->Name.compareToAscii("AutoRetrievingStatement") && pBegin->Name.compareToAscii("UseCatalogInSelect") && pBegin->Name.compareToAscii("UseSchemaInSelect") && pBegin->Name.compareToAscii("AutoIncrementCreation") && pBegin->Name.compareToAscii("Extension") && pBegin->Name.compareToAscii("NoNameLengthLimit") && pBegin->Name.compareToAscii("EnableSQL92Check") && pBegin->Name.compareToAscii("EnableOuterJoinEscape") && pBegin->Name.compareToAscii("BooleanComparisonMode") && pBegin->Name.compareToAscii("IgnoreCurrency") && pBegin->Name.compareToAscii("TypeInfoSettings") && pBegin->Name.compareToAscii("IgnoreDriverPrivileges")) { ::rtl::OUString aStr; OSL_VERIFY( pBegin->Value >>= aStr ); pProps->setProperty(pBegin->Name,aStr); } } return pProps; } // -------------------------------------------------------------------------------- ::rtl::OUString connectivity::JavaString2String(JNIEnv *pEnv,jstring _Str) { ::rtl::OUString aStr; if(_Str) { jboolean bCopy(sal_True); const jchar* pChar = pEnv->GetStringChars(_Str,&bCopy); jsize len = pEnv->GetStringLength(_Str); aStr = ::rtl::OUString(pChar,len); if(bCopy) pEnv->ReleaseStringChars(_Str,pChar); pEnv->DeleteLocalRef(_Str); } return aStr; } // -------------------------------------------------------------------------------- jobject connectivity::convertTypeMapToJavaMap(JNIEnv* /*pEnv*/,const Reference< ::com::sun::star::container::XNameAccess > & _rMap) { ::com::sun::star::uno::Sequence< ::rtl::OUString > aNames = _rMap->getElementNames(); if ( aNames.getLength() > 0 ) ::dbtools::throwFeatureNotImplementedException( "Type maps", NULL ); return 0; } // ----------------------------------------------------------------------------- sal_Bool connectivity::isExceptionOccured(JNIEnv *pEnv,sal_Bool _bClear) { if ( !pEnv ) return sal_False; jthrowable pThrowable = pEnv->ExceptionOccurred(); sal_Bool bRet = pThrowable != NULL; if ( pThrowable ) { if ( _bClear ) pEnv->ExceptionClear(); #if OSL_DEBUG_LEVEL > 1 if(pEnv->IsInstanceOf(pThrowable,java_sql_SQLException_BASE::getMyClass())) { java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,pThrowable); ::rtl::OUString sError = pException->getMessage(); delete pException; } #else pEnv->DeleteLocalRef(pThrowable); #endif } return bRet; } <commit_msg>INTEGRATION: CWS changefileheader (1.28.22); FILE MERGED 2008/04/01 10:53:05 thb 1.28.22.2: #i85898# Stripping all external header guards 2008/03/28 15:23:43 rt 1.28.22.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tools.cxx,v $ * $Revision: 1.29 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include <cstdarg> #include "java/tools.hxx" #include "java/lang/String.hxx" #include "java/lang/Class.hxx" #include "java/util/Property.hxx" #include <com/sun/star/sdbc/DriverPropertyInfo.hpp> #include <com/sun/star/container/XNameAccess.hpp> #include <connectivity/dbexception.hxx> using namespace connectivity; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; // using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; void java_util_Properties::setProperty(const ::rtl::OUString key, const ::rtl::OUString& value) { SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); jobject out(0); if( t.pEnv ) { jvalue args[2]; // Parameter konvertieren args[0].l = convertwchar_tToJavaString(t.pEnv,key); args[1].l = convertwchar_tToJavaString(t.pEnv,value); // temporaere Variable initialisieren static const char * cSignature = "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;"; static const char * cMethodName = "setProperty"; // Java-Call absetzen static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ) { out = t.pEnv->CallObjectMethod(object, mID, args[0].l,args[1].l); ThrowSQLException(t.pEnv,NULL); } t.pEnv->DeleteLocalRef((jstring)args[1].l); t.pEnv->DeleteLocalRef((jstring)args[0].l); ThrowSQLException(t.pEnv,0); if(out) t.pEnv->DeleteLocalRef(out); } //t.pEnv // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! } jclass java_util_Properties::theClass = 0; java_util_Properties::~java_util_Properties() {} jclass java_util_Properties::getMyClass() { // die Klasse muss nur einmal geholt werden, daher statisch if( !theClass ){ SDBThreadAttach t; if( !t.pEnv ) return (jclass)NULL; jclass tempClass = t.pEnv->FindClass( "java/util/Properties" ); jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass ); t.pEnv->DeleteLocalRef( tempClass ); saveClassRef( globClass ); } return theClass; } void java_util_Properties::saveClassRef( jclass pClass ) { if( pClass==NULL ) return; // der uebergebe Klassen-Handle ist schon global, daher einfach speichern theClass = pClass; } //-------------------------------------------------------------------------- java_util_Properties::java_util_Properties( ): java_lang_Object( NULL, (jobject)NULL ) { SDBThreadAttach t; if( !t.pEnv ) return; // Java-Call fuer den Konstruktor absetzen // temporaere Variable initialisieren static const char * cSignature = "()V"; jobject tempObj; static jmethodID mID = NULL; if ( !mID ) mID = t.pEnv->GetMethodID( getMyClass(), "<init>", cSignature );OSL_ENSURE(mID,"Unknown method id!"); tempObj = t.pEnv->NewObject( getMyClass(), mID); saveRef( t.pEnv, tempObj ); t.pEnv->DeleteLocalRef( tempObj ); } // -------------------------------------------------------------------------------- jstring connectivity::convertwchar_tToJavaString(JNIEnv *pEnv,const ::rtl::OUString& _rTemp) { OSL_ENSURE(pEnv,"Environment is NULL!"); jstring pStr = pEnv->NewString(_rTemp.getStr(), _rTemp.getLength()); pEnv->ExceptionClear(); OSL_ENSURE(pStr,"Could not create a jsstring object!"); return pStr; } // -------------------------------------------------------------------------------- java_util_Properties* connectivity::createStringPropertyArray(const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException) { java_util_Properties* pProps = new java_util_Properties(); const PropertyValue* pBegin = info.getConstArray(); const PropertyValue* pEnd = pBegin + info.getLength(); for(;pBegin != pEnd;++pBegin) { // this is a special property to find the jdbc driver if( pBegin->Name.compareToAscii("JavaDriverClass") && pBegin->Name.compareToAscii("JavaDriverClassPath") && pBegin->Name.compareToAscii("SystemProperties") && pBegin->Name.compareToAscii("CharSet") && pBegin->Name.compareToAscii("AppendTableAlias") && pBegin->Name.compareToAscii("GenerateASBeforeCorrelationName") && pBegin->Name.compareToAscii("EscapeDateTime") && pBegin->Name.compareToAscii("ParameterNameSubstitution") && pBegin->Name.compareToAscii("IsPasswordRequired") && pBegin->Name.compareToAscii("IsAutoRetrievingEnabled") && pBegin->Name.compareToAscii("AutoRetrievingStatement") && pBegin->Name.compareToAscii("UseCatalogInSelect") && pBegin->Name.compareToAscii("UseSchemaInSelect") && pBegin->Name.compareToAscii("AutoIncrementCreation") && pBegin->Name.compareToAscii("Extension") && pBegin->Name.compareToAscii("NoNameLengthLimit") && pBegin->Name.compareToAscii("EnableSQL92Check") && pBegin->Name.compareToAscii("EnableOuterJoinEscape") && pBegin->Name.compareToAscii("BooleanComparisonMode") && pBegin->Name.compareToAscii("IgnoreCurrency") && pBegin->Name.compareToAscii("TypeInfoSettings") && pBegin->Name.compareToAscii("IgnoreDriverPrivileges")) { ::rtl::OUString aStr; OSL_VERIFY( pBegin->Value >>= aStr ); pProps->setProperty(pBegin->Name,aStr); } } return pProps; } // -------------------------------------------------------------------------------- ::rtl::OUString connectivity::JavaString2String(JNIEnv *pEnv,jstring _Str) { ::rtl::OUString aStr; if(_Str) { jboolean bCopy(sal_True); const jchar* pChar = pEnv->GetStringChars(_Str,&bCopy); jsize len = pEnv->GetStringLength(_Str); aStr = ::rtl::OUString(pChar,len); if(bCopy) pEnv->ReleaseStringChars(_Str,pChar); pEnv->DeleteLocalRef(_Str); } return aStr; } // -------------------------------------------------------------------------------- jobject connectivity::convertTypeMapToJavaMap(JNIEnv* /*pEnv*/,const Reference< ::com::sun::star::container::XNameAccess > & _rMap) { ::com::sun::star::uno::Sequence< ::rtl::OUString > aNames = _rMap->getElementNames(); if ( aNames.getLength() > 0 ) ::dbtools::throwFeatureNotImplementedException( "Type maps", NULL ); return 0; } // ----------------------------------------------------------------------------- sal_Bool connectivity::isExceptionOccured(JNIEnv *pEnv,sal_Bool _bClear) { if ( !pEnv ) return sal_False; jthrowable pThrowable = pEnv->ExceptionOccurred(); sal_Bool bRet = pThrowable != NULL; if ( pThrowable ) { if ( _bClear ) pEnv->ExceptionClear(); #if OSL_DEBUG_LEVEL > 1 if(pEnv->IsInstanceOf(pThrowable,java_sql_SQLException_BASE::getMyClass())) { java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,pThrowable); ::rtl::OUString sError = pException->getMessage(); delete pException; } #else pEnv->DeleteLocalRef(pThrowable); #endif } return bRet; } <|endoftext|>
<commit_before>#include <derecho/derecho.h> #include <derecho/view.h> #include <chrono> #include <fstream> #include <map> #include <string> #include <thread> #include <vector> #include <algorithm> using namespace derecho; using std::ifstream; using std::string; using std::vector; int main(int argc, char* argv[]) { if (argc < 5) { // Print out error message exit(1); } std::map<node_id_t, ifstream*> input_file_map; const string my_input_file = argv[1]; const uint32_t num_nodes = std::stoi(argv[2]); const uint32_t num_msgs = std::stoi(argv[3]); const uint32_t msg_size = std::stoi(argv[4]); Conf::initialize(argc, argv); uint32_t node_id = derecho::getConfUInt32(CONF_DERECHO_LOCAL_ID); SubgroupInfo subgroup_info( {{std::type_index(typeid(RawObject)), [num_nodes](const View& curr_view, int& next_unassigned_rank) { if(curr_view.members.size() < num_nodes) { std::cout << "Waiting for all nodes to join. Throwing subgroup provisioning exception!" << std::endl; throw subgroup_provisioning_exception(); } return one_subgroup_entire_view(curr_view, next_unassigned_rank); }}}); auto get_next_line = [&input_file_map](node_id_t sender_id) { string line; if(input_file_map.at(sender_id)->is_open()) { getline(*(input_file_map.at(sender_id)), line); return line; } std::cout << "Error: Input file not open!!!" << std::endl; exit(1); }; Group<>* group; uint32_t my_rank; uint32_t max_msg_size = getConfUInt64(CONF_DERECHO_MAX_PAYLOAD_SIZE); volatile bool done = false; auto delivery_callback = [&, num_received_msgs_map = std::map<node_id_t, uint32_t>(), received_msgs_index_map = std::map<node_id_t, uint32_t>(), received_msgs = std::vector<node_id_t>(), finished_nodes = std::set<node_id_t>()](subgroup_id_t subgroup_id, node_id_t sender_id, message_id_t index, std::optional<std::pair<char*, long long int>> data, persistent::version_t ver) mutable { char *buf; long long int size; std::tie(buf, size) = data.value(); if(num_received_msgs_map[sender_id] == 0) { std::cout << "Received input file name for node " << sender_id << std::endl; ifstream* input_file = new ifstream(buf); if(input_file->is_open()) { input_file_map[sender_id] = input_file; } else { std::cout << "Unable to open input file!" << std::endl; exit(1); } } else if(num_received_msgs_map[sender_id] <= num_msgs) { //std::cout << "Receiving random message from node " << sender_id << std::endl; //std::cout << "Num received messages is: " << num_received_msgs_map[sender_id] << std::endl; received_msgs.push_back(sender_id); string line = get_next_line(sender_id); string msg_received(buf, size); if(line != msg_received) { std::cout << "Error: Message contents mismatch or violation of local order!!!" << std::endl; exit(1); } if(received_msgs.size() == num_msgs * num_nodes) {//sender_id == node_id && num_received_msgs_map[sender_id] == num_msgs) { std::cout << "Local ordering test successful!" << std::endl; if(my_rank != 0) { std::cout << "Sending my received messages to leader" << std::endl; std::thread temp([&]() { uint32_t num_msgs_sent = 0; uint32_t num_entries; RawSubgroup& group_as_subgroup = group->get_subgroup<RawObject>(); while (num_msgs_sent < received_msgs.size()) { num_entries = std::min(received_msgs.size() - num_msgs_sent, max_msg_size / sizeof(node_id_t) - 50); group_as_subgroup.send(num_entries * sizeof(node_id_t), [&received_msgs, &num_msgs_sent, &num_entries](char* buf){ for(uint i = 0; i < num_entries; i++) { if (num_msgs_sent + i >= received_msgs.size()) { break; } (node_id_t&)buf[sizeof(node_id_t) * i] = received_msgs[num_msgs_sent + i]; } }); num_msgs_sent = num_msgs_sent + num_entries; } //group_as_subgroup.send(received_msgs.size() * sizeof(node_id_t), [received_msgs](char* buf) { //for(uint i = 0; i < received_msgs.size(); i++) { // (node_id_t&)buf[sizeof(node_id_t) * i] = received_msgs[i]; //} //}); }); temp.detach(); } } } else { if(my_rank == 0) { long long int curr_size = 0; std::cout << "Received node " << sender_id << "'s received_msgs" << std::endl; std::cout << "Size is: " << size << std::endl; while (curr_size < size) { //std::cout << "curr size is: " << curr_size << std::endl; node_id_t val = *((node_id_t*)buf); buf += sizeof(node_id_t); curr_size += sizeof(node_id_t); //std::cout << "Received messages index for sender id " << sender_id << " is " << received_msgs_index_map[sender_id] << std::endl; node_id_t node = received_msgs[received_msgs_index_map[sender_id]]; //std::cout << "Node is: " << node << std::endl; //std::cout << "Val is: " << val << std::endl; if(node != val) { std::cout << "Error: Violation of global order!!!" << std::endl; exit(1); } received_msgs_index_map[sender_id] += 1; } //std::cout << "Testing for global ordering" << std::endl; // verify the message against received_msgs //for(auto node : received_msgs) { // node_id_t val = *((node_id_t*)buf); // buf += sizeof(node_id_t); // if(node != val) { // std::cout << "Error: Violation of global order!!!" << std::endl; // exit(1); // } //} std::cout << "Received msgs size is: " << received_msgs.size() << std::endl; std::cout << "Received msgs index map entry for " << sender_id << std::endl; std::cout << received_msgs_index_map[sender_id] << std::endl; if (received_msgs_index_map[sender_id] == received_msgs.size()) { finished_nodes.insert(sender_id); } if(finished_nodes.size() == num_nodes - 1) { done = true; } } //std::cout << "Received msgs size is: " << received_msgs.size() << std::endl; //std::cout << "Received msgs index map entry for " << sender_id << std::endl; //std::cout << received_msgs_index_map[sender_id] << std::endl; //if (received_msgs_index_map[sender_id] == received_msgs.size()) { // finished_nodes.insert(sender_id); //} //if(finished_nodes.size() == num_nodes - 1) { // done = true; //} } num_received_msgs_map[sender_id] = num_received_msgs_map[sender_id] + 1; }; group = new Group<>(CallbackSet{delivery_callback}, subgroup_info); std::cout << "Finished constructing/joining Group" << std::endl; RawSubgroup& group_as_subgroup = group->get_subgroup<RawObject>(); // my_rank = group_as_subgroup.get_my_rank(); my_rank = -1; auto members_order = group->get_members(); std::cout << "The order of members is :" << std::endl; for(uint i = 0; i < num_nodes; ++i) { std::cout << members_order[i] << " "; if(members_order[i] == node_id) { my_rank = i; } } std::cout << std::endl; ifstream input_file(my_input_file); std::cout << "Constructed file handler" << std::endl; group_as_subgroup.send(my_input_file.size(), [my_input_file](char* buf){ my_input_file.copy(buf, my_input_file.size()); }); string line; uint32_t msg_counter = 0; std::cout << "Attempting to send messages" << std::endl; while(msg_counter < num_msgs) { getline(input_file, line); //std::cout << "Sending message: " << line << std::endl; //std::cout << "Message size is: " << line.size() << std::endl; group_as_subgroup.send(msg_size, [line](char* buf){ line.copy(buf, line.size()); }); msg_counter = msg_counter + 1; } input_file.close(); if (my_rank != 0) {done = true;} while(!done) { } if (my_rank == 0) { std::cout << "Global ordering test successful!" << std::endl; } group->barrier_sync(); group->leave(); return 0; } <commit_msg>group is now a unique_ptr so that memory is cleaned up nicely<commit_after>#include <derecho/derecho.h> #include <derecho/view.h> #include <chrono> #include <fstream> #include <map> #include <memory> #include <string> #include <thread> #include <vector> #include <algorithm> using namespace derecho; using std::ifstream; using std::string; using std::vector; int main(int argc, char* argv[]) { if (argc < 5) { // Print out error message exit(1); } std::map<node_id_t, ifstream*> input_file_map; const string my_input_file = argv[1]; const uint32_t num_nodes = std::stoi(argv[2]); const uint32_t num_msgs = std::stoi(argv[3]); const uint32_t msg_size = std::stoi(argv[4]); Conf::initialize(argc, argv); uint32_t node_id = derecho::getConfUInt32(CONF_DERECHO_LOCAL_ID); SubgroupInfo subgroup_info( {{std::type_index(typeid(RawObject)), [num_nodes](const View& curr_view, int& next_unassigned_rank) { if(curr_view.members.size() < num_nodes) { std::cout << "Waiting for all nodes to join. Throwing subgroup provisioning exception!" << std::endl; throw subgroup_provisioning_exception(); } return one_subgroup_entire_view(curr_view, next_unassigned_rank); }}}); auto get_next_line = [&input_file_map](node_id_t sender_id) { string line; if(input_file_map.at(sender_id)->is_open()) { getline(*(input_file_map.at(sender_id)), line); return line; } std::cout << "Error: Input file not open!!!" << std::endl; exit(1); }; std::unique_ptr<Group<>> group; uint32_t my_rank; uint32_t max_msg_size = getConfUInt64(CONF_DERECHO_MAX_PAYLOAD_SIZE); volatile bool done = false; auto delivery_callback = [&, num_received_msgs_map = std::map<node_id_t, uint32_t>(), received_msgs_index_map = std::map<node_id_t, uint32_t>(), received_msgs = std::vector<node_id_t>(), finished_nodes = std::set<node_id_t>()](subgroup_id_t subgroup_id, node_id_t sender_id, message_id_t index, std::optional<std::pair<char*, long long int>> data, persistent::version_t ver) mutable { char *buf; long long int size; std::tie(buf, size) = data.value(); if(num_received_msgs_map[sender_id] == 0) { std::cout << "Received input file name for node " << sender_id << std::endl; ifstream* input_file = new ifstream(buf); if(input_file->is_open()) { input_file_map[sender_id] = input_file; } else { std::cout << "Unable to open input file!" << std::endl; exit(1); } } else if(num_received_msgs_map[sender_id] <= num_msgs) { //std::cout << "Receiving random message from node " << sender_id << std::endl; //std::cout << "Num received messages is: " << num_received_msgs_map[sender_id] << std::endl; received_msgs.push_back(sender_id); string line = get_next_line(sender_id); string msg_received(buf, size); if(line != msg_received) { std::cout << "Error: Message contents mismatch or violation of local order!!!" << std::endl; exit(1); } if(received_msgs.size() == num_msgs * num_nodes) {//sender_id == node_id && num_received_msgs_map[sender_id] == num_msgs) { std::cout << "Local ordering test successful!" << std::endl; if(my_rank != 0) { std::cout << "Sending my received messages to leader" << std::endl; std::thread temp([&]() { uint32_t num_msgs_sent = 0; uint32_t num_entries; RawSubgroup& group_as_subgroup = group->get_subgroup<RawObject>(); while (num_msgs_sent < received_msgs.size()) { num_entries = std::min(received_msgs.size() - num_msgs_sent, max_msg_size / sizeof(node_id_t) - 50); group_as_subgroup.send(num_entries * sizeof(node_id_t), [&received_msgs, &num_msgs_sent, &num_entries](char* buf){ for(uint i = 0; i < num_entries; i++) { if (num_msgs_sent + i >= received_msgs.size()) { break; } (node_id_t&)buf[sizeof(node_id_t) * i] = received_msgs[num_msgs_sent + i]; } }); num_msgs_sent = num_msgs_sent + num_entries; } //group_as_subgroup.send(received_msgs.size() * sizeof(node_id_t), [received_msgs](char* buf) { //for(uint i = 0; i < received_msgs.size(); i++) { // (node_id_t&)buf[sizeof(node_id_t) * i] = received_msgs[i]; //} //}); }); temp.detach(); } } } else { if(my_rank == 0) { long long int curr_size = 0; std::cout << "Received node " << sender_id << "'s received_msgs" << std::endl; std::cout << "Size is: " << size << std::endl; while (curr_size < size) { //std::cout << "curr size is: " << curr_size << std::endl; node_id_t val = *((node_id_t*)buf); buf += sizeof(node_id_t); curr_size += sizeof(node_id_t); //std::cout << "Received messages index for sender id " << sender_id << " is " << received_msgs_index_map[sender_id] << std::endl; node_id_t node = received_msgs[received_msgs_index_map[sender_id]]; //std::cout << "Node is: " << node << std::endl; //std::cout << "Val is: " << val << std::endl; if(node != val) { std::cout << "Error: Violation of global order!!!" << std::endl; exit(1); } received_msgs_index_map[sender_id] += 1; } //std::cout << "Testing for global ordering" << std::endl; // verify the message against received_msgs //for(auto node : received_msgs) { // node_id_t val = *((node_id_t*)buf); // buf += sizeof(node_id_t); // if(node != val) { // std::cout << "Error: Violation of global order!!!" << std::endl; // exit(1); // } //} std::cout << "Received msgs size is: " << received_msgs.size() << std::endl; std::cout << "Received msgs index map entry for " << sender_id << std::endl; std::cout << received_msgs_index_map[sender_id] << std::endl; if (received_msgs_index_map[sender_id] == received_msgs.size()) { finished_nodes.insert(sender_id); } if(finished_nodes.size() == num_nodes - 1) { done = true; } } //std::cout << "Received msgs size is: " << received_msgs.size() << std::endl; //std::cout << "Received msgs index map entry for " << sender_id << std::endl; //std::cout << received_msgs_index_map[sender_id] << std::endl; //if (received_msgs_index_map[sender_id] == received_msgs.size()) { // finished_nodes.insert(sender_id); //} //if(finished_nodes.size() == num_nodes - 1) { // done = true; //} } num_received_msgs_map[sender_id] = num_received_msgs_map[sender_id] + 1; }; group = std::make_unique<Group<>>(CallbackSet{delivery_callback}, subgroup_info); std::cout << "Finished constructing/joining Group" << std::endl; RawSubgroup& group_as_subgroup = group->get_subgroup<RawObject>(); // my_rank = group_as_subgroup.get_my_rank(); my_rank = -1; auto members_order = group->get_members(); std::cout << "The order of members is :" << std::endl; for(uint i = 0; i < num_nodes; ++i) { std::cout << members_order[i] << " "; if(members_order[i] == node_id) { my_rank = i; } } std::cout << std::endl; ifstream input_file(my_input_file); std::cout << "Constructed file handler" << std::endl; group_as_subgroup.send(my_input_file.size(), [my_input_file](char* buf){ my_input_file.copy(buf, my_input_file.size()); }); string line; uint32_t msg_counter = 0; std::cout << "Attempting to send messages" << std::endl; while(msg_counter < num_msgs) { getline(input_file, line); //std::cout << "Sending message: " << line << std::endl; //std::cout << "Message size is: " << line.size() << std::endl; group_as_subgroup.send(msg_size, [line](char* buf){ line.copy(buf, line.size()); }); msg_counter = msg_counter + 1; } input_file.close(); if (my_rank != 0) {done = true;} while(!done) { } if (my_rank == 0) { std::cout << "Global ordering test successful!" << std::endl; } group->barrier_sync(); group->leave(); return 0; } <|endoftext|>
<commit_before>/** * @file Cosa/Driver/DHT22.hh * @version 1.0 * * @section License * Copyright (C) 2012-2013, Mikael Patel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * * This file is part of the Arduino Che Cosa project. */ #ifndef __COSA_DRIVER_DHT22_HH__ #define __COSA_DRIVER_DHT22_HH__ #include "Cosa/Driver/DHT.hh" /** * DHT22 Humidity & Temperature Sensor device driver. Subclass * and implement the event handler, on_event(), to allow periodic * read of device (attach to watchdog timeout queue). Note that the * values read from the device are scaled by a factor of 10, i.e. one * decimal accurracy. * * @section Circuit * Connect DHT22 to pin, VCC and ground. A pullup resistor from * the pin to VCC should be used. Most DHT22 modules have a built-in * pullup resistor. * * @section Limitations * The driver will turn off interrupt handling during data read * from the device. * * @section See Also * [1] http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/Weather/RHT03.pdf<br> */ class DHT22 : public DHT { private: /** * @override * Adjust data from the device. Byte order and representation of * negative temperature values. */ virtual void adjust_data() { m_data.humidity = swap(m_data.humidity); m_data.temperature = swap(m_data.temperature); if (m_data.temperature < 0) { m_data.temperature = -(m_data.temperature & 0x7ff); } } public: /** * Construct connection to a DHT22 device on given in/output-pin. * Set humidity and temperature calibration offsets to zero. * @param[in] pin data. */ DHT22(Board::DigitalPin pin) : DHT(pin) {} }; #endif <commit_msg>Fixed DHT22 handling of negative temperature reading.<commit_after>/** * @file Cosa/Driver/DHT22.hh * @version 1.0 * * @section License * Copyright (C) 2012-2013, Mikael Patel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * * This file is part of the Arduino Che Cosa project. */ #ifndef __COSA_DRIVER_DHT22_HH__ #define __COSA_DRIVER_DHT22_HH__ #include "Cosa/Driver/DHT.hh" /** * DHT22 Humidity & Temperature Sensor device driver. Subclass * and implement the event handler, on_event(), to allow periodic * read of device (attach to watchdog timeout queue). Note that the * values read from the device are scaled by a factor of 10, i.e. one * decimal accurracy. * * @section Circuit * Connect DHT22 to pin, VCC and ground. A pullup resistor from * the pin to VCC should be used. Most DHT22 modules have a built-in * pullup resistor. * * @section Limitations * The driver will turn off interrupt handling during data read * from the device. * * @section See Also * [1] http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/Weather/RHT03.pdf<br> */ class DHT22 : public DHT { private: /** * @override * Adjust data from the device. Byte order and representation of * negative temperature values. */ virtual void adjust_data() { m_data.humidity = swap(m_data.humidity); m_data.temperature = swap(m_data.temperature); if (m_data.temperature < 0) { m_data.temperature = -(m_data.temperature & 0x7fff); } } public: /** * Construct connection to a DHT22 device on given in/output-pin. * Set humidity and temperature calibration offsets to zero. * @param[in] pin data. */ DHT22(Board::DigitalPin pin) : DHT(pin) {} }; #endif <|endoftext|>
<commit_before>// // SamplerVoice.cpp // AudioKit Core // // Created by Shane Dunne, revision history on Github. // Copyright © 2018 AudioKit. All rights reserved. // #include "SamplerVoice.hpp" #include <stdio.h> #define MIDDLE_C_HZ 262.626f namespace AudioKitCore { void SamplerVoice::init(double sampleRate) { samplingRate = float(sampleRate); leftFilter.init(sampleRate); rightFilter.init(sampleRate); ampEnvelope.init(); filterEnvelope.init(); pitchEnvelope.init(); vibratoLFO.waveTable.sinusoid(); vibratoLFO.init(sampleRate/AKCORESAMPLER_CHUNKSIZE, 5.0f); volumeRamper.init(0.0f); tempGain = 0.0f; } void SamplerVoice::start(unsigned note, float sampleRate, float frequency, float volume, SampleBuffer *buffer) { sampleBuffer = buffer; oscillator.indexPoint = buffer->startPoint; oscillator.increment = (buffer->sampleRate / sampleRate) * (frequency / buffer->noteFrequency); oscillator.multiplier = 1.0; oscillator.isLooping = buffer->isLooping; noteVolume = volume; ampEnvelope.start(); volumeRamper.init(0.0f); samplingRate = sampleRate; leftFilter.updateSampleRate(double(samplingRate)); rightFilter.updateSampleRate(double(samplingRate)); filterEnvelope.start(); pitchEnvelope.start(); pitchEnvelopeSemitones = 0.0f; voiceLFOSemitones = 0.0f; glideSemitones = 0.0f; if (*glideSecPerOctave != 0.0f && noteFrequency != 0.0 && noteFrequency != frequency) { // prepare to glide glideSemitones = -12.0f * log2f(frequency / noteFrequency); if (fabsf(glideSemitones) < 0.01f) glideSemitones = 0.0f; } noteFrequency = frequency; noteNumber = note; } void SamplerVoice::restartNewNote(unsigned note, float sampleRate, float frequency, float volume, SampleBuffer *buffer) { samplingRate = sampleRate; leftFilter.updateSampleRate(double(samplingRate)); rightFilter.updateSampleRate(double(samplingRate)); oscillator.increment = (sampleBuffer->sampleRate / sampleRate) * (frequency / sampleBuffer->noteFrequency); glideSemitones = 0.0f; if (*glideSecPerOctave != 0.0f && noteFrequency != 0.0 && noteFrequency != frequency) { // prepare to glide glideSemitones = -12.0f * log2f(frequency / noteFrequency); if (fabsf(glideSemitones) < 0.01f) glideSemitones = 0.0f; } pitchEnvelopeSemitones = 0.0f; voiceLFOSemitones = 0.0f; noteFrequency = frequency; noteNumber = note; tempNoteVolume = noteVolume; newSampleBuffer = buffer; ampEnvelope.restart(); noteVolume = volume; filterEnvelope.restart(); pitchEnvelope.restart(); vibratoLFO.phase = 0; } void SamplerVoice::restartNewNoteLegato(unsigned note, float sampleRate, float frequency) { samplingRate = sampleRate; leftFilter.updateSampleRate(double(samplingRate)); rightFilter.updateSampleRate(double(samplingRate)); oscillator.increment = (sampleBuffer->sampleRate / sampleRate) * (frequency / sampleBuffer->noteFrequency); glideSemitones = 0.0f; if (*glideSecPerOctave != 0.0f && noteFrequency != 0.0 && noteFrequency != frequency) { // prepare to glide glideSemitones = -12.0f * log2f(frequency / noteFrequency); if (fabsf(glideSemitones) < 0.01f) glideSemitones = 0.0f; } noteFrequency = frequency; noteNumber = note; } void SamplerVoice::restartSameNote(float volume, SampleBuffer *buffer) { tempNoteVolume = noteVolume; newSampleBuffer = buffer; ampEnvelope.restart(); noteVolume = volume; filterEnvelope.restart(); pitchEnvelope.restart(); vibratoLFO.phase = 0; } void SamplerVoice::release(bool loopThruRelease) { if (!loopThruRelease) oscillator.isLooping = false; ampEnvelope.release(); filterEnvelope.release(); pitchEnvelope.release(); } void SamplerVoice::stop() { noteNumber = -1; ampEnvelope.reset(); volumeRamper.init(0.0f); filterEnvelope.reset(); pitchEnvelope.reset(); vibratoLFO.phase = 0; } bool SamplerVoice::prepToGetSamples(int sampleCount, float masterVolume, float pitchOffset, float cutoffMultiple, float keyTracking, float cutoffEnvelopeStrength, float cutoffEnvelopeVelocityScaling, float resLinear, float pitchADSRSemitones, float voiceLFODepthSemitones, float voiceLFOFrequencyHz) { if (ampEnvelope.isIdle()) return true; if (ampEnvelope.isPreStarting()) { tempGain = masterVolume * tempNoteVolume; volumeRamper.reinit(ampEnvelope.getSample(), sampleCount); // This can execute as part of the voice-stealing mechanism, and will be executed rarely. // To test, set MAX_POLYPHONY in AKCoreSampler.cpp to something small like 2 or 3. if (!ampEnvelope.isPreStarting()) { tempGain = masterVolume * noteVolume; volumeRamper.reinit(ampEnvelope.getSample(), sampleCount); sampleBuffer = newSampleBuffer; oscillator.increment = (sampleBuffer->sampleRate / samplingRate) * (noteFrequency / sampleBuffer->noteFrequency); oscillator.indexPoint = sampleBuffer->startPoint; oscillator.isLooping = sampleBuffer->isLooping; } } else { tempGain = masterVolume * noteVolume; volumeRamper.reinit(ampEnvelope.getSample(), sampleCount); } if (*glideSecPerOctave != 0.0f && glideSemitones != 0.0f) { float seconds = sampleCount / samplingRate; float semitones = 12.0f * seconds / *glideSecPerOctave; if (glideSemitones < 0.0f) { glideSemitones += semitones; if (glideSemitones > 0.0f) glideSemitones = 0.0f; } else { glideSemitones -= semitones; if (glideSemitones < 0.0f) glideSemitones = 0.0f; } } float pitchCurveAmount = 1.0f; // >1 = faster curve, 0 < curve < 1 = slower curve - make this a parameter if (pitchCurveAmount < 0) { pitchCurveAmount = 0; } pitchEnvelopeSemitones = pow(pitchEnvelope.getSample(), pitchCurveAmount) * pitchADSRSemitones; vibratoLFO.setFrequency(voiceLFOFrequencyHz); voiceLFOSemitones = vibratoLFO.getSample() * voiceLFODepthSemitones; float pitchOffsetModified = pitchOffset + glideSemitones + pitchEnvelopeSemitones + voiceLFOSemitones; oscillator.setPitchOffsetSemitones(pitchOffsetModified); // negative value of cutoffMultiple means filters are disabled if (cutoffMultiple < 0.0f) { isFilterEnabled = false; } else { isFilterEnabled = true; float noteHz = noteFrequency * powf(2.0f, (pitchOffsetModified) / 12.0f); float baseFrequency = MIDDLE_C_HZ + keyTracking * (noteHz - MIDDLE_C_HZ); float envStrength = ((1.0f - cutoffEnvelopeVelocityScaling) + cutoffEnvelopeVelocityScaling * noteVolume); double cutoffFrequency = baseFrequency * (1.0f + cutoffMultiple + cutoffEnvelopeStrength * envStrength * filterEnvelope.getSample()); leftFilter.setParameters(cutoffFrequency, resLinear); rightFilter.setParameters(cutoffFrequency, resLinear); } return false; } bool SamplerVoice::getSamples(int sampleCount, float *leftOutput, float *rightOutput) { for (int i=0; i < sampleCount; i++) { float gain = tempGain * volumeRamper.getNextValue(); float leftSample, rightSample; if (oscillator.getSamplePair(sampleBuffer, sampleCount, &leftSample, &rightSample, gain)) return true; if (isFilterEnabled) { *leftOutput++ += leftFilter.process(leftSample); *rightOutput++ += rightFilter.process(rightSample); } else { *leftOutput++ += leftSample; *rightOutput++ += rightSample; } } return false; } } <commit_msg>Revert "re-enable filter + pitchenvelope"<commit_after>// // SamplerVoice.cpp // AudioKit Core // // Created by Shane Dunne, revision history on Github. // Copyright © 2018 AudioKit. All rights reserved. // #include "SamplerVoice.hpp" #include <stdio.h> #define MIDDLE_C_HZ 262.626f namespace AudioKitCore { void SamplerVoice::init(double sampleRate) { samplingRate = float(sampleRate); leftFilter.init(sampleRate); rightFilter.init(sampleRate); ampEnvelope.init(); filterEnvelope.init(); pitchEnvelope.init(); vibratoLFO.waveTable.sinusoid(); vibratoLFO.init(sampleRate/AKCORESAMPLER_CHUNKSIZE, 5.0f); volumeRamper.init(0.0f); tempGain = 0.0f; } void SamplerVoice::start(unsigned note, float sampleRate, float frequency, float volume, SampleBuffer *buffer) { sampleBuffer = buffer; oscillator.indexPoint = buffer->startPoint; oscillator.increment = (buffer->sampleRate / sampleRate) * (frequency / buffer->noteFrequency); oscillator.multiplier = 1.0; oscillator.isLooping = buffer->isLooping; noteVolume = volume; ampEnvelope.start(); volumeRamper.init(0.0f); samplingRate = sampleRate; leftFilter.updateSampleRate(double(samplingRate)); rightFilter.updateSampleRate(double(samplingRate)); // filterEnvelope.start(); // // pitchEnvelope.start(); pitchEnvelopeSemitones = 0.0f; voiceLFOSemitones = 0.0f; glideSemitones = 0.0f; if (*glideSecPerOctave != 0.0f && noteFrequency != 0.0 && noteFrequency != frequency) { // prepare to glide glideSemitones = -12.0f * log2f(frequency / noteFrequency); if (fabsf(glideSemitones) < 0.01f) glideSemitones = 0.0f; } noteFrequency = frequency; noteNumber = note; } void SamplerVoice::restartNewNote(unsigned note, float sampleRate, float frequency, float volume, SampleBuffer *buffer) { samplingRate = sampleRate; leftFilter.updateSampleRate(double(samplingRate)); rightFilter.updateSampleRate(double(samplingRate)); oscillator.increment = (sampleBuffer->sampleRate / sampleRate) * (frequency / sampleBuffer->noteFrequency); glideSemitones = 0.0f; if (*glideSecPerOctave != 0.0f && noteFrequency != 0.0 && noteFrequency != frequency) { // prepare to glide glideSemitones = -12.0f * log2f(frequency / noteFrequency); if (fabsf(glideSemitones) < 0.01f) glideSemitones = 0.0f; } pitchEnvelopeSemitones = 0.0f; voiceLFOSemitones = 0.0f; noteFrequency = frequency; noteNumber = note; tempNoteVolume = noteVolume; newSampleBuffer = buffer; ampEnvelope.restart(); noteVolume = volume; // filterEnvelope.restart(); // pitchEnvelope.restart(); vibratoLFO.phase = 0; } void SamplerVoice::restartNewNoteLegato(unsigned note, float sampleRate, float frequency) { samplingRate = sampleRate; leftFilter.updateSampleRate(double(samplingRate)); rightFilter.updateSampleRate(double(samplingRate)); oscillator.increment = (sampleBuffer->sampleRate / sampleRate) * (frequency / sampleBuffer->noteFrequency); glideSemitones = 0.0f; if (*glideSecPerOctave != 0.0f && noteFrequency != 0.0 && noteFrequency != frequency) { // prepare to glide glideSemitones = -12.0f * log2f(frequency / noteFrequency); if (fabsf(glideSemitones) < 0.01f) glideSemitones = 0.0f; } noteFrequency = frequency; noteNumber = note; } void SamplerVoice::restartSameNote(float volume, SampleBuffer *buffer) { tempNoteVolume = noteVolume; newSampleBuffer = buffer; ampEnvelope.restart(); noteVolume = volume; // filterEnvelope.restart(); // pitchEnvelope.restart(); vibratoLFO.phase = 0; } void SamplerVoice::release(bool loopThruRelease) { if (!loopThruRelease) oscillator.isLooping = false; ampEnvelope.release(); // filterEnvelope.release(); // pitchEnvelope.release(); } void SamplerVoice::stop() { noteNumber = -1; ampEnvelope.reset(); volumeRamper.init(0.0f); // filterEnvelope.reset(); // pitchEnvelope.reset(); vibratoLFO.phase = 0; } bool SamplerVoice::prepToGetSamples(int sampleCount, float masterVolume, float pitchOffset, float cutoffMultiple, float keyTracking, float cutoffEnvelopeStrength, float cutoffEnvelopeVelocityScaling, float resLinear, float pitchADSRSemitones, float voiceLFODepthSemitones, float voiceLFOFrequencyHz) { if (ampEnvelope.isIdle()) return true; if (ampEnvelope.isPreStarting()) { tempGain = masterVolume * tempNoteVolume; volumeRamper.reinit(ampEnvelope.getSample(), sampleCount); // This can execute as part of the voice-stealing mechanism, and will be executed rarely. // To test, set MAX_POLYPHONY in AKCoreSampler.cpp to something small like 2 or 3. if (!ampEnvelope.isPreStarting()) { tempGain = masterVolume * noteVolume; volumeRamper.reinit(ampEnvelope.getSample(), sampleCount); sampleBuffer = newSampleBuffer; oscillator.increment = (sampleBuffer->sampleRate / samplingRate) * (noteFrequency / sampleBuffer->noteFrequency); oscillator.indexPoint = sampleBuffer->startPoint; oscillator.isLooping = sampleBuffer->isLooping; } } else { tempGain = masterVolume * noteVolume; volumeRamper.reinit(ampEnvelope.getSample(), sampleCount); } if (*glideSecPerOctave != 0.0f && glideSemitones != 0.0f) { float seconds = sampleCount / samplingRate; float semitones = 12.0f * seconds / *glideSecPerOctave; if (glideSemitones < 0.0f) { glideSemitones += semitones; if (glideSemitones > 0.0f) glideSemitones = 0.0f; } else { glideSemitones -= semitones; if (glideSemitones < 0.0f) glideSemitones = 0.0f; } } float pitchCurveAmount = 1.0f; // >1 = faster curve, 0 < curve < 1 = slower curve - make this a parameter if (pitchCurveAmount < 0) { pitchCurveAmount = 0; } pitchEnvelopeSemitones = pow(pitchEnvelope.getSample(), pitchCurveAmount) * pitchADSRSemitones; vibratoLFO.setFrequency(voiceLFOFrequencyHz); voiceLFOSemitones = vibratoLFO.getSample() * voiceLFODepthSemitones; float pitchOffsetModified = pitchOffset + glideSemitones + pitchEnvelopeSemitones + voiceLFOSemitones; oscillator.setPitchOffsetSemitones(pitchOffsetModified); // negative value of cutoffMultiple means filters are disabled if (cutoffMultiple < 0.0f) { isFilterEnabled = false; } else { isFilterEnabled = true; float noteHz = noteFrequency * powf(2.0f, (pitchOffsetModified) / 12.0f); float baseFrequency = MIDDLE_C_HZ + keyTracking * (noteHz - MIDDLE_C_HZ); float envStrength = ((1.0f - cutoffEnvelopeVelocityScaling) + cutoffEnvelopeVelocityScaling * noteVolume); double cutoffFrequency = baseFrequency * (1.0f + cutoffMultiple + cutoffEnvelopeStrength * envStrength * filterEnvelope.getSample()); leftFilter.setParameters(cutoffFrequency, resLinear); rightFilter.setParameters(cutoffFrequency, resLinear); } return false; } bool SamplerVoice::getSamples(int sampleCount, float *leftOutput, float *rightOutput) { for (int i=0; i < sampleCount; i++) { float gain = tempGain * volumeRamper.getNextValue(); float leftSample, rightSample; if (oscillator.getSamplePair(sampleBuffer, sampleCount, &leftSample, &rightSample, gain)) return true; if (isFilterEnabled) { *leftOutput++ += leftFilter.process(leftSample); *rightOutput++ += rightFilter.process(rightSample); } else { *leftOutput++ += leftSample; *rightOutput++ += rightSample; } } return false; } } <|endoftext|>
<commit_before>/** * @file * exercise_02_41_part_5.cpp * @author * Henrik Samuelsson, henrik.samuelsson(at)gmail.com * @brief * Part five of exercise 2.41 from the book C++ Primer (5th edition). * @details * The book store program from section 1.6 but using the Sales_data class * instead of the Sales_item.h */ #include <iostream> struct Sales_data { std::string isbn; unsigned units_sold = 0; double revenue = 0.0; }; int main() { Sales_data total; // variable to hold data for the next transaction // read the first transaction and ensure that there are data to process if (std::cin >> total.isbn >> total.units_sold >> total.revenue) { Sales_data trans; // variable to hold the running sum // read and process the remaining transactions while (std::cin >> trans.isbn >> trans.units_sold >> trans.revenue) { // if we're still processing the same book if (total.isbn == trans.isbn) total.units_sold += trans.units_sold; // update the running total else { // print results for the previous book std::cout << total.units_sold << std::endl; total = trans; // total now refers to the next book } } std::cout << total.units_sold << std::endl; // print the last transaction } else { // no input! warn the user std::cerr << "No data?!" << std::endl; return -1; // indicate failure } return 0; }<commit_msg>Update exercise_02_41_part_5.cpp<commit_after>/** * @file * exercise_02_41_part_5.cpp * @author * Henrik Samuelsson, henrik.samuelsson(at)gmail.com * @brief * Part five of exercise 2.41 from the book C++ Primer (5th edition). * @details * The book store program from section 1.6 but using the Sales_data class * instead of the Sales_item.h include file. */ #include <iostream> struct Sales_data { std::string isbn; unsigned units_sold = 0; double revenue = 0.0; }; int main() { Sales_data total; // variable to hold data for the next transaction // read the first transaction and ensure that there are data to process if (std::cin >> total.isbn >> total.units_sold >> total.revenue) { Sales_data trans; // variable to hold the running sum // read and process the remaining transactions while (std::cin >> trans.isbn >> trans.units_sold >> trans.revenue) { // if we're still processing the same book if (total.isbn == trans.isbn) total.units_sold += trans.units_sold; // update the running total else { // print results for the previous book std::cout << total.units_sold << std::endl; total = trans; // total now refers to the next book } } std::cout << total.units_sold << std::endl; // print the last transaction } else { // no input! warn the user std::cerr << "No data?!" << std::endl; return -1; // indicate failure } return 0; } <|endoftext|>
<commit_before>/* * Copyright 2014-2019 Real Logic Ltd. * * 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 "ControlResponsePoller.h" #include "ArchiveException.h" #include "aeron_archive_client/MessageHeader.h" #include "aeron_archive_client/ControlResponse.h" using namespace aeron; using namespace aeron::archive::client; static aeron::controlled_poll_fragment_handler_t controlHandler(ControlResponsePoller& poller) { return [&](AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header) { return poller.onFragment(buffer, offset, length, header); }; } ControlResponsePoller::ControlResponsePoller(std::shared_ptr<Subscription> subscription, int fragmentLimit) : m_fragmentAssembler(controlHandler(*this)), m_fragmentHandler(m_fragmentAssembler.handler()), m_subscription(std::move(subscription)), m_fragmentLimit(fragmentLimit) { } ControlledPollAction ControlResponsePoller::onFragment( AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header) { MessageHeader msgHeader( buffer.sbeData() + offset, static_cast<std::uint64_t>(length), MessageHeader::sbeSchemaVersion()); const std::int16_t schemaId = msgHeader.schemaId(); if (schemaId != MessageHeader::sbeSchemaId()) { throw ArchiveException( "expected schemaId=" + std::to_string(MessageHeader::sbeSchemaId()) + ", actual=" + std::to_string(schemaId), SOURCEINFO); } m_templateId = msgHeader.templateId(); if (ControlResponse::sbeTemplateId() == m_templateId) { ControlResponse response( buffer.sbeData() + offset + MessageHeader::encodedLength(), static_cast<std::uint64_t>(length) - MessageHeader::encodedLength(), msgHeader.blockLength(), msgHeader.version()); m_controlSessionId = response.controlSessionId(); m_correlationId = response.correlationId(); m_relevantId = response.relevantId(); ControlResponseCode::Value code = response.code(); m_codeValue = code; m_isCodeError = ControlResponseCode::Value::ERROR == code; m_isCodeOk = ControlResponseCode::Value::OK == code; m_errorMessage = response.getErrorMessageAsString(); m_isControlResponse = true; m_pollComplete = true; } return ControlledPollAction::BREAK; } <commit_msg>[C++] Stop consuming polled responses from the archive when a control response has been captured.<commit_after>/* * Copyright 2014-2019 Real Logic Ltd. * * 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 "ControlResponsePoller.h" #include "ArchiveException.h" #include "aeron_archive_client/MessageHeader.h" #include "aeron_archive_client/ControlResponse.h" using namespace aeron; using namespace aeron::archive::client; static aeron::controlled_poll_fragment_handler_t controlHandler(ControlResponsePoller& poller) { return [&](AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header) { return poller.onFragment(buffer, offset, length, header); }; } ControlResponsePoller::ControlResponsePoller(std::shared_ptr<Subscription> subscription, int fragmentLimit) : m_fragmentAssembler(controlHandler(*this)), m_fragmentHandler(m_fragmentAssembler.handler()), m_subscription(std::move(subscription)), m_fragmentLimit(fragmentLimit) { } ControlledPollAction ControlResponsePoller::onFragment( AtomicBuffer& buffer, util::index_t offset, util::index_t length, Header& header) { MessageHeader msgHeader( buffer.sbeData() + offset, static_cast<std::uint64_t>(length), MessageHeader::sbeSchemaVersion()); const std::int16_t schemaId = msgHeader.schemaId(); if (schemaId != MessageHeader::sbeSchemaId()) { throw ArchiveException( "expected schemaId=" + std::to_string(MessageHeader::sbeSchemaId()) + ", actual=" + std::to_string(schemaId), SOURCEINFO); } m_templateId = msgHeader.templateId(); if (ControlResponse::sbeTemplateId() == m_templateId) { if (m_pollComplete) { return ControlledPollAction::ABORT; } ControlResponse response( buffer.sbeData() + offset + MessageHeader::encodedLength(), static_cast<std::uint64_t>(length) - MessageHeader::encodedLength(), msgHeader.blockLength(), msgHeader.version()); m_controlSessionId = response.controlSessionId(); m_correlationId = response.correlationId(); m_relevantId = response.relevantId(); ControlResponseCode::Value code = response.code(); m_codeValue = code; m_isCodeError = ControlResponseCode::Value::ERROR == code; m_isCodeOk = ControlResponseCode::Value::OK == code; m_errorMessage = response.getErrorMessageAsString(); m_isControlResponse = true; m_pollComplete = true; return ControlledPollAction::BREAK; } return ControlledPollAction::CONTINUE; } <|endoftext|>
<commit_before># pragma once # include <Siv3D.hpp> # include "AscMessageManager.hpp" # include "AscSpriteManager.hpp" namespace asc { using namespace s3d; using Commnad = std::pair<int32, String>; class Novel { private: bool m_isUpdating; int32 m_currentLine; Array<Commnad> m_commands; MessageManager m_messageManager; SpriteManager m_spriteManager; void finish() { m_isUpdating = false; m_messageManager.clear(); m_spriteManager.clearSprite(); } void execute() { switch (m_commands[m_currentLine].first) { // Point case 0: finish(); return; // Text case 1: m_messageManager.setText(m_commands[m_currentLine].second); m_messageManager.start(); break; // Name case 2: m_messageManager.setName(m_commands[m_currentLine].second); break; // AddSprite case 3: m_spriteManager.addSprite(Sprite(m_commands[m_currentLine].second)); break; // AddFixedSprite case 4: m_spriteManager.addSprite(FixedSprite(m_commands[m_currentLine].second)); break; default: break; } m_currentLine++; } public: Novel() : m_isUpdating(false), m_currentLine(0) { m_commands.push_back({ 0, L"0"}); m_commands.push_back({ 1, L"0: Write Text"}); m_commands.push_back({ 0, L"1"}); m_commands.push_back({ 3, L"1,character1,0,0,640,720" }); m_commands.push_back({ 3, L"3,character3,480,180,320,360" }); m_commands.push_back({ 1, L"1: Write Text" }); m_commands.push_back({ 1, L"1: Write Text2" }); m_commands.push_back({ 0, L"-1" }); } virtual ~Novel() = default; bool start(int32 seekPoint) { const auto size = m_commands.size() - 1; for (auto i = 0u; i < size; i++) { const auto index = (m_currentLine + i) % m_commands.size(); const auto command = m_commands[index]; if ( command.first == 0 && Parse<int32>(command.second) == seekPoint ) { m_isUpdating = true; m_currentLine = index + 1; return true; } } return false; } void update() { while ( m_isUpdating && !m_messageManager.isUpdating() ) { execute(); } m_messageManager.update(); } bool isUpdating() { return m_isUpdating; } void draw() const { m_spriteManager.draw(); m_messageManager.draw(); } }; }<commit_msg>Clear on Start.<commit_after># pragma once # include <Siv3D.hpp> # include "AscMessageManager.hpp" # include "AscSpriteManager.hpp" namespace asc { using namespace s3d; using Commnad = std::pair<int32, String>; class Novel { private: bool m_isUpdating; int32 m_currentLine; Array<Commnad> m_commands; MessageManager m_messageManager; SpriteManager m_spriteManager; void execute() { switch (m_commands[m_currentLine].first) { // Point case 0: m_isUpdating = false; return; // Text case 1: m_messageManager.setText(m_commands[m_currentLine].second); m_messageManager.start(); break; // Name case 2: m_messageManager.setName(m_commands[m_currentLine].second); break; // AddSprite case 3: m_spriteManager.addSprite(Sprite(m_commands[m_currentLine].second)); break; // AddFixedSprite case 4: m_spriteManager.addSprite(FixedSprite(m_commands[m_currentLine].second)); break; default: break; } m_currentLine++; } public: Novel() : m_isUpdating(false), m_currentLine(0) { m_commands.push_back({ 0, L"0"}); m_commands.push_back({ 1, L"0: Write Text"}); m_commands.push_back({ 0, L"1"}); m_commands.push_back({ 3, L"1,character1,0,0,640,720" }); m_commands.push_back({ 3, L"3,character3,480,180,320,360" }); m_commands.push_back({ 1, L"1: Write Text" }); m_commands.push_back({ 1, L"1: Write Text2" }); m_commands.push_back({ 0, L"-1" }); } virtual ~Novel() = default; bool start(int32 seekPoint) { const auto size = m_commands.size() - 1; for (auto i = 0u; i < size; i++) { const auto index = (m_currentLine + i) % m_commands.size(); const auto command = m_commands[index]; if ( command.first == 0 && Parse<int32>(command.second) == seekPoint ) { m_isUpdating = true; m_messageManager.clear(); m_spriteManager.clearSprite(); m_currentLine = index + 1; return true; } } return false; } void update() { while ( m_isUpdating && !m_messageManager.isUpdating() ) { execute(); } m_messageManager.update(); } bool isUpdating() { return m_isUpdating; } void draw() const { m_spriteManager.draw(); m_messageManager.draw(); } }; }<|endoftext|>
<commit_before><commit_msg>cp: warnings: initalize mpNatPunchthroughClient after mpReplicaManager3<commit_after><|endoftext|>
<commit_before>/*========================================================================= * * Copyright LUMC and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ // First include the header file to be tested: #include "itkImageMaskSpatialObject2.h" #include <gtest/gtest.h> namespace { template <unsigned NDimension> void Expect_New_returns_valid_ImageMaskSpatialObject2_Pointer() { using Type = itk::ImageMaskSpatialObject2<NDimension>; static_assert( std::is_same<decltype(Type::New()), typename Type::Pointer>::value, "Type::New() should return a Type::Pointer"); EXPECT_NE(Type::New(), nullptr); } } GTEST_TEST(ImageMaskSpatialObject2, NewReturnsValidPointer) { Expect_New_returns_valid_ImageMaskSpatialObject2_Pointer<1>(); Expect_New_returns_valid_ImageMaskSpatialObject2_Pointer<2>(); Expect_New_returns_valid_ImageMaskSpatialObject2_Pointer<3>(); } <commit_msg>DOC: Fixed copyright text<commit_after>/*========================================================================= * * Copyright UMC Utrecht and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ // First include the header file to be tested: #include "itkImageMaskSpatialObject2.h" #include <gtest/gtest.h> namespace { template <unsigned NDimension> void Expect_New_returns_valid_ImageMaskSpatialObject2_Pointer() { using Type = itk::ImageMaskSpatialObject2<NDimension>; static_assert( std::is_same<decltype(Type::New()), typename Type::Pointer>::value, "Type::New() should return a Type::Pointer"); EXPECT_NE(Type::New(), nullptr); } } GTEST_TEST(ImageMaskSpatialObject2, NewReturnsValidPointer) { Expect_New_returns_valid_ImageMaskSpatialObject2_Pointer<1>(); Expect_New_returns_valid_ImageMaskSpatialObject2_Pointer<2>(); Expect_New_returns_valid_ImageMaskSpatialObject2_Pointer<3>(); } <|endoftext|>
<commit_before>/* * Copyright 2016 Nu-book Inc. * Copyright 2016 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "oned/ODUPCEANExtensionSupport.h" #include "oned/ODUPCEANReader.h" #include "oned/ODUPCEANCommon.h" #include "Result.h" #include "BitArray.h" #include "TextDecoder.h" #include "ZXContainerAlgorithms.h" #include "ZXStrConvWorkaround.h" #include <array> #include <sstream> #include <iomanip> namespace ZXing { namespace OneD { /** * @see UPCEANExtension2Support */ namespace UPCEANExtension5Support { static int ExtensionChecksum(const std::string& s) { int length = static_cast<int>(s.length()); int sum = 0; for (int i = length - 2; i >= 0; i -= 2) { sum += (int)s[i] - (int) '0'; } sum *= 3; for (int i = length - 1; i >= 0; i -= 2) { sum += (int)s[i] - (int) '0'; } sum *= 3; return sum % 10; } static BitArray::Range DecodeMiddle(const BitArray& row, BitArray::Iterator begin, std::string& resultString) { BitArray::Range next = {begin, row.end()}; const BitArray::Range notFound = {begin, begin}; int lgPatternFound = 0; for (int x = 0; x < 5; x++) { int bestMatch = UPCEANReader::DecodeDigit(&next, UPCEANCommon::L_AND_G_PATTERNS, &resultString); if (bestMatch == -1) return notFound; if (bestMatch >= 10) { lgPatternFound |= 1 << (4 - x); } if (x != 4) { // Read off separator if not last next.begin = row.getNextSet(next.begin); next.begin = row.getNextUnset(next.begin); } } constexpr int CHECK_DIGIT_ENCODINGS[] = {0x18, 0x14, 0x12, 0x11, 0x0C, 0x06, 0x03, 0x0A, 0x09, 0x05}; if (ExtensionChecksum(resultString) != IndexOf(CHECK_DIGIT_ENCODINGS, lgPatternFound)) return notFound; return {begin, next.begin}; } static std::string ParseExtension5String(const std::string& raw) { std::string currency; switch (raw.front()) { case '0': currency = "\xa3"; break; case '5': currency = "$"; break; case '9': // Reference: http://www.jollytech.com if (raw == "90000") { // No suggested retail price return std::string(); } if (raw == "99991") { // Complementary return "0.00"; } if (raw == "99990") { return "Used"; } // Otherwise... unknown currency? currency = ""; break; default: currency = ""; break; } int rawAmount = std::stoi(raw.substr(1)); std::stringstream buf; buf << currency << std::fixed << std::setprecision(2) << (float(rawAmount) / 100); return buf.str(); } /** * @param raw raw content of extension * @return formatted interpretation of raw content as a {@link Map} mapping * one {@link ResultMetadataType} to appropriate value, or {@code null} if not known */ static void ParseExtensionString(const std::string& raw, Result& result) { if (raw.length() == 5) { std::string value = ParseExtension5String(raw); if (!value.empty()) { result.metadata().put(ResultMetadata::SUGGESTED_PRICE, TextDecoder::FromLatin1(value)); } } } static Result DecodeRow(int rowNumber, const BitArray& row, int extStartRangeBegin, int extStartRangeEnd) { std::string resultString; auto range = DecodeMiddle(row, row.iterAt(extStartRangeEnd), resultString); if (!range) return Result(DecodeStatus::NotFound); float y = static_cast<float>(rowNumber); float x1 = 0.5f * static_cast<float>(extStartRangeBegin + extStartRangeEnd); float x2 = static_cast<float>(range.end - row.begin()); Result result(TextDecoder::FromLatin1(resultString), ByteArray(), { ResultPoint(x1, y), ResultPoint(x2, y) }, BarcodeFormat::UPC_EAN_EXTENSION); ParseExtensionString(resultString, result); return result; } } // UPCEANExtension5Support namespace UPCEANExtension2Support { static BitArray::Range DecodeMiddle(const BitArray& row, BitArray::Iterator begin, std::string& resultString) { BitArray::Range next = {begin, row.end()}; const BitArray::Range notFound = {begin, begin}; int lgPatternFound = 0; for (int x = 0; x < 2; x++) { int bestMatch = UPCEANReader::DecodeDigit(&next, UPCEANCommon::L_AND_G_PATTERNS, &resultString); if (bestMatch == -1) return notFound; if (bestMatch >= 10) { lgPatternFound |= 1 << (1 - x); } if (x != 1) { // Read off separator if not last next.begin = row.getNextSet(next.begin); next.begin = row.getNextUnset(next.begin); } } if (std::stoi(resultString) % 4 != lgPatternFound) { return notFound; } return {begin, next.begin}; } static Result DecodeRow(int rowNumber, const BitArray& row, int extStartRangeBegin, int extStartRangeEnd) { std::string resultString;; auto range = DecodeMiddle(row, row.iterAt(extStartRangeEnd), resultString); if (!range) return Result(DecodeStatus::NotFound); float y = static_cast<float>(rowNumber); float x1 = 0.5f * static_cast<float>(extStartRangeBegin + extStartRangeEnd); float x2 = static_cast<float>(range.end - row.begin()); Result result(TextDecoder::FromLatin1(resultString), ByteArray(), { ResultPoint(x1, y), ResultPoint(x2, y) }, BarcodeFormat::UPC_EAN_EXTENSION); if (resultString.length() == 2) { result.metadata().put(ResultMetadata::ISSUE_NUMBER, std::stoi(resultString)); } return result; } } // UPCEANExtension2Support static const std::array<int, 3> EXTENSION_START_PATTERN = { 1,1,2 }; Result UPCEANExtensionSupport::DecodeRow(int rowNumber, const BitArray& row, int rowOffset) { auto extStartRange = UPCEANReader::FindGuardPattern(row, row.iterAt(rowOffset), false, EXTENSION_START_PATTERN); if (!extStartRange) return Result(DecodeStatus::NotFound); Result result = UPCEANExtension5Support::DecodeRow(rowNumber, row, extStartRange.begin - row.begin(), extStartRange.end - row.begin()); if (!result.isValid()) { result = UPCEANExtension2Support::DecodeRow(rowNumber, row, extStartRange.begin - row.begin(), extStartRange.end - row.begin()); } return result; } } // OneD } // ZXing <commit_msg>Add missing currency selectors for UPC/EAN extension<commit_after>/* * Copyright 2016 Nu-book Inc. * Copyright 2016 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "oned/ODUPCEANExtensionSupport.h" #include "oned/ODUPCEANReader.h" #include "oned/ODUPCEANCommon.h" #include "Result.h" #include "BitArray.h" #include "TextDecoder.h" #include "ZXContainerAlgorithms.h" #include "ZXStrConvWorkaround.h" #include <array> #include <sstream> #include <iomanip> namespace ZXing { namespace OneD { /** * @see UPCEANExtension2Support */ namespace UPCEANExtension5Support { static int ExtensionChecksum(const std::string& s) { int length = static_cast<int>(s.length()); int sum = 0; for (int i = length - 2; i >= 0; i -= 2) { sum += (int)s[i] - (int) '0'; } sum *= 3; for (int i = length - 1; i >= 0; i -= 2) { sum += (int)s[i] - (int) '0'; } sum *= 3; return sum % 10; } static BitArray::Range DecodeMiddle(const BitArray& row, BitArray::Iterator begin, std::string& resultString) { BitArray::Range next = {begin, row.end()}; const BitArray::Range notFound = {begin, begin}; int lgPatternFound = 0; for (int x = 0; x < 5; x++) { int bestMatch = UPCEANReader::DecodeDigit(&next, UPCEANCommon::L_AND_G_PATTERNS, &resultString); if (bestMatch == -1) return notFound; if (bestMatch >= 10) { lgPatternFound |= 1 << (4 - x); } if (x != 4) { // Read off separator if not last next.begin = row.getNextSet(next.begin); next.begin = row.getNextUnset(next.begin); } } constexpr int CHECK_DIGIT_ENCODINGS[] = {0x18, 0x14, 0x12, 0x11, 0x0C, 0x06, 0x03, 0x0A, 0x09, 0x05}; if (ExtensionChecksum(resultString) != IndexOf(CHECK_DIGIT_ENCODINGS, lgPatternFound)) return notFound; return {begin, next.begin}; } static std::string ParseExtension5String(const std::string& raw) { std::string currency; switch (raw.front()) { case '0': case '1': currency = "\xa3"; break; case '3': // AUS case '4': // NZ case '5': // US case '6': // CA currency = "$"; break; case '9': // Reference: http://www.jollytech.com if (raw == "90000") { // No suggested retail price return std::string(); } if (raw == "99991") { // Complementary return "0.00"; } if (raw == "99990") { return "Used"; } // Otherwise... unknown currency? currency = ""; break; default: currency = ""; break; } int rawAmount = std::stoi(raw.substr(1)); std::stringstream buf; buf << currency << std::fixed << std::setprecision(2) << (float(rawAmount) / 100); return buf.str(); } /** * @param raw raw content of extension * @return formatted interpretation of raw content as a {@link Map} mapping * one {@link ResultMetadataType} to appropriate value, or {@code null} if not known */ static void ParseExtensionString(const std::string& raw, Result& result) { if (raw.length() == 5) { std::string value = ParseExtension5String(raw); if (!value.empty()) { result.metadata().put(ResultMetadata::SUGGESTED_PRICE, TextDecoder::FromLatin1(value)); } } } static Result DecodeRow(int rowNumber, const BitArray& row, int extStartRangeBegin, int extStartRangeEnd) { std::string resultString; auto range = DecodeMiddle(row, row.iterAt(extStartRangeEnd), resultString); if (!range) return Result(DecodeStatus::NotFound); float y = static_cast<float>(rowNumber); float x1 = 0.5f * static_cast<float>(extStartRangeBegin + extStartRangeEnd); float x2 = static_cast<float>(range.end - row.begin()); Result result(TextDecoder::FromLatin1(resultString), ByteArray(), { ResultPoint(x1, y), ResultPoint(x2, y) }, BarcodeFormat::UPC_EAN_EXTENSION); ParseExtensionString(resultString, result); return result; } } // UPCEANExtension5Support namespace UPCEANExtension2Support { static BitArray::Range DecodeMiddle(const BitArray& row, BitArray::Iterator begin, std::string& resultString) { BitArray::Range next = {begin, row.end()}; const BitArray::Range notFound = {begin, begin}; int lgPatternFound = 0; for (int x = 0; x < 2; x++) { int bestMatch = UPCEANReader::DecodeDigit(&next, UPCEANCommon::L_AND_G_PATTERNS, &resultString); if (bestMatch == -1) return notFound; if (bestMatch >= 10) { lgPatternFound |= 1 << (1 - x); } if (x != 1) { // Read off separator if not last next.begin = row.getNextSet(next.begin); next.begin = row.getNextUnset(next.begin); } } if (std::stoi(resultString) % 4 != lgPatternFound) { return notFound; } return {begin, next.begin}; } static Result DecodeRow(int rowNumber, const BitArray& row, int extStartRangeBegin, int extStartRangeEnd) { std::string resultString;; auto range = DecodeMiddle(row, row.iterAt(extStartRangeEnd), resultString); if (!range) return Result(DecodeStatus::NotFound); float y = static_cast<float>(rowNumber); float x1 = 0.5f * static_cast<float>(extStartRangeBegin + extStartRangeEnd); float x2 = static_cast<float>(range.end - row.begin()); Result result(TextDecoder::FromLatin1(resultString), ByteArray(), { ResultPoint(x1, y), ResultPoint(x2, y) }, BarcodeFormat::UPC_EAN_EXTENSION); if (resultString.length() == 2) { result.metadata().put(ResultMetadata::ISSUE_NUMBER, std::stoi(resultString)); } return result; } } // UPCEANExtension2Support static const std::array<int, 3> EXTENSION_START_PATTERN = { 1,1,2 }; Result UPCEANExtensionSupport::DecodeRow(int rowNumber, const BitArray& row, int rowOffset) { auto extStartRange = UPCEANReader::FindGuardPattern(row, row.iterAt(rowOffset), false, EXTENSION_START_PATTERN); if (!extStartRange) return Result(DecodeStatus::NotFound); Result result = UPCEANExtension5Support::DecodeRow(rowNumber, row, extStartRange.begin - row.begin(), extStartRange.end - row.begin()); if (!result.isValid()) { result = UPCEANExtension2Support::DecodeRow(rowNumber, row, extStartRange.begin - row.begin(), extStartRange.end - row.begin()); } return result; } } // OneD } // ZXing <|endoftext|>
<commit_before>/* * DataMask.cpp * zxing * * Created by Christian Brunschen on 19/05/2008. * Copyright 2008 ZXing 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 <zxing/qrcode/decoder/DataMask.h> #include <zxing/common/IllegalArgumentException.h> namespace zxing { namespace qrcode { using namespace std; DataMask::DataMask() { } DataMask::~DataMask() { } vector<Ref<DataMask> > DataMask::DATA_MASKS; static int N_DATA_MASKS = DataMask::buildDataMasks(); DataMask &DataMask::forReference(int reference) { if (reference < 0 || reference > 7) { throw IllegalArgumentException("reference must be between 0 and 7"); } return *DATA_MASKS[reference]; } void DataMask::unmaskBitMatrix(BitMatrix& bits, size_t dimension) { for (size_t y = 0; y < dimension; y++) { for (size_t x = 0; x < dimension; x++) { // TODO: check why the coordinates have to be swapped if (isMasked(y, x)) { bits.flip(x, y); } } } } /** * 000: mask bits for which (x + y) mod 2 == 0 */ class DataMask000 : public DataMask { public: bool isMasked(size_t x, size_t y) { // return ((x + y) & 0x01) == 0; return ((x + y) % 2) == 0; } }; /** * 001: mask bits for which x mod 2 == 0 */ class DataMask001 : public DataMask { public: bool isMasked(size_t x, size_t) { // return (x & 0x01) == 0; return (x % 2) == 0; } }; /** * 010: mask bits for which y mod 3 == 0 */ class DataMask010 : public DataMask { public: bool isMasked(size_t, size_t y) { return y % 3 == 0; } }; /** * 011: mask bits for which (x + y) mod 3 == 0 */ class DataMask011 : public DataMask { public: bool isMasked(size_t x, size_t y) { return (x + y) % 3 == 0; } }; /** * 100: mask bits for which (x/2 + y/3) mod 2 == 0 */ class DataMask100 : public DataMask { public: bool isMasked(size_t x, size_t y) { // return (((x >> 1) + (y / 3)) & 0x01) == 0; return (((x >> 1) + (y / 3)) % 2) == 0; } }; /** * 101: mask bits for which xy mod 2 + xy mod 3 == 0 */ class DataMask101 : public DataMask { public: bool isMasked(size_t x, size_t y) { size_t temp = x * y; // return (temp & 0x01) + (temp % 3) == 0; return (temp % 2) + (temp % 3) == 0; } }; /** * 110: mask bits for which (xy mod 2 + xy mod 3) mod 2 == 0 */ class DataMask110 : public DataMask { public: bool isMasked(size_t x, size_t y) { size_t temp = x * y; // return (((temp & 0x01) + (temp % 3)) & 0x01) == 0; return (((temp % 2) + (temp % 3)) % 2) == 0; } }; /** * 111: mask bits for which ((x+y)mod 2 + xy mod 3) mod 2 == 0 */ class DataMask111 : public DataMask { public: bool isMasked(size_t x, size_t y) { // return ((((x + y) & 0x01) + ((x * y) % 3)) & 0x01) == 0; return ((((x + y) % 2) + ((x * y) % 3)) % 2) == 0; } }; int DataMask::buildDataMasks() { DATA_MASKS.push_back(Ref<DataMask> (new DataMask000())); DATA_MASKS.push_back(Ref<DataMask> (new DataMask001())); DATA_MASKS.push_back(Ref<DataMask> (new DataMask010())); DATA_MASKS.push_back(Ref<DataMask> (new DataMask011())); DATA_MASKS.push_back(Ref<DataMask> (new DataMask100())); DATA_MASKS.push_back(Ref<DataMask> (new DataMask101())); DATA_MASKS.push_back(Ref<DataMask> (new DataMask110())); DATA_MASKS.push_back(Ref<DataMask> (new DataMask111())); return DATA_MASKS.size(); } } } <commit_msg>Optimize QR data mask recognition<commit_after>/* * DataMask.cpp * zxing * * Created by Christian Brunschen on 19/05/2008. * Copyright 2008 ZXing 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 <zxing/qrcode/decoder/DataMask.h> #include <zxing/common/IllegalArgumentException.h> namespace zxing { namespace qrcode { using namespace std; DataMask::DataMask() { } DataMask::~DataMask() { } vector<Ref<DataMask> > DataMask::DATA_MASKS; static int N_DATA_MASKS = DataMask::buildDataMasks(); DataMask &DataMask::forReference(int reference) { if (reference < 0 || reference > 7) { throw IllegalArgumentException("reference must be between 0 and 7"); } return *DATA_MASKS[reference]; } void DataMask::unmaskBitMatrix(BitMatrix& bits, size_t dimension) { for (size_t y = 0; y < dimension; y++) { for (size_t x = 0; x < dimension; x++) { // TODO: check why the coordinates have to be swapped if (isMasked(y, x)) { bits.flip(x, y); } } } } /** * 000: mask bits for which (x + y) mod 2 == 0 */ class DataMask000 : public DataMask { public: bool isMasked(size_t x, size_t y) { // return ((x + y) & 0x01) == 0; return ((x + y) % 2) == 0; } }; /** * 001: mask bits for which x mod 2 == 0 */ class DataMask001 : public DataMask { public: bool isMasked(size_t x, size_t) { // return (x & 0x01) == 0; return (x % 2) == 0; } }; /** * 010: mask bits for which y mod 3 == 0 */ class DataMask010 : public DataMask { public: bool isMasked(size_t, size_t y) { return y % 3 == 0; } }; /** * 011: mask bits for which (x + y) mod 3 == 0 */ class DataMask011 : public DataMask { public: bool isMasked(size_t x, size_t y) { return (x + y) % 3 == 0; } }; /** * 100: mask bits for which (x/2 + y/3) mod 2 == 0 */ class DataMask100 : public DataMask { public: bool isMasked(size_t x, size_t y) { // return (((x >> 1) + (y / 3)) & 0x01) == 0; return (((x >> 1) + (y / 3)) % 2) == 0; } }; /** * 101: mask bits for which xy mod 2 + xy mod 3 == 0 * equivalently, such that xy mod 6 == 0 */ class DataMask101 : public DataMask { public: bool isMasked(size_t x, size_t y) { return ((x * y) % 6) == 0; } }; /** * 110: mask bits for which (xy mod 2 + xy mod 3) mod 2 == 0 * equivalently, such that xy mod 6 < 3 */ class DataMask110 : public DataMask { public: bool isMasked(size_t x, size_t y) { return ((x * y) % 6) < 3; } }; /** * 111: mask bits for which ((x+y)mod 2 + xy mod 3) mod 2 == 0 * equivalently, such that (x + y + xy mod 3) mod 2 == 0 */ class DataMask111 : public DataMask { public: bool isMasked(size_t x, size_t y) { return ((x + y + ((x * y) % 3)) & 0x01) == 0; } }; int DataMask::buildDataMasks() { DATA_MASKS.push_back(Ref<DataMask> (new DataMask000())); DATA_MASKS.push_back(Ref<DataMask> (new DataMask001())); DATA_MASKS.push_back(Ref<DataMask> (new DataMask010())); DATA_MASKS.push_back(Ref<DataMask> (new DataMask011())); DATA_MASKS.push_back(Ref<DataMask> (new DataMask100())); DATA_MASKS.push_back(Ref<DataMask> (new DataMask101())); DATA_MASKS.push_back(Ref<DataMask> (new DataMask110())); DATA_MASKS.push_back(Ref<DataMask> (new DataMask111())); return DATA_MASKS.size(); } } } <|endoftext|>
<commit_before>/** \brief Utility for converting Dublin Core data downloaded from ICPSR to MARC. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2021 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include "MARC.h" #include "StringUtil.h" #include "TimeUtil.h" #include "util.h" #include "XMLParser.h" bool IsCriminologyRecord(const MARC::Record &record) { for (const auto &field : record.getTagRange("653")) { if (StringUtil::StartsWith(field.getFirstSubfieldWithCode('a'), "crime")) return true; } return false; } // "american_date" is expected to contain the pattern mm-dd-yyyy. std::string AmericanDateToGermanDate(const std::string &american_date) { const auto month(StringUtil::ToUnsigned(american_date.substr(0, 2))); if (unlikely(month == 0 or month > 12)) LOG_ERROR("bad month in \"" + american_date + "\"!"); const auto day(StringUtil::ToUnsigned(american_date.substr(3, 2))); if (unlikely(day == 0 or day > 31)) LOG_ERROR("bad day in \"" + american_date + "\"!"); const auto year(StringUtil::ToUnsigned(american_date.substr(6))); if (unlikely(year < 1000 or year > 2099)) LOG_ERROR("bad year in \"" + american_date + "\"!"); return StringUtil::ToString(day) + "." + StringUtil::ToString(month) + "." + StringUtil::ToString(year); } // Mostly uses the mapping found at https://www.loc.gov/marc/dccross.html to map DC to MARC. bool ParseRecord(XMLParser * const xml_parser, MARC::Writer * const marc_writer) { static unsigned record_number; ++record_number; MARC::Record new_record(MARC::Record::TypeOfRecord::LANGUAGE_MATERIAL, MARC::Record::BibliographicLevel::UNDEFINED, "ICPSR" + StringUtil::ToString(record_number, /* radix = */10, /* width = */6, /* padding_char = */'0')); static const std::string today(TimeUtil::GetCurrentDateAndTime("%y%m%d")); static const std::string current_year(TimeUtil::GetCurrentYear()); static const std::string _008_contents(today + 's' + current_year); new_record.insertField(MARC::Tag("008"), _008_contents); new_record.insertField(MARC::Tag("935"), { { 'a', "icpsr" }, { '2', "LOK" } }); XMLParser::XMLPart xml_part; std::string last_data; while (xml_parser->getNext(&xml_part)) { if (xml_part.type_ == XMLParser::XMLPart::CHARACTERS) xml_part.data_.swap(last_data); else if (xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG and StringUtil::StartsWith(xml_part.data_, "dc:")) { const std::string tag(xml_part.data_.substr(3)); if (tag == "title") new_record.insertField(MARC::Tag("245"), 'a', last_data); else if (tag == "contributor") new_record.insertField(MARC::Tag("720"), 'a', last_data); else if (tag == "creator") new_record.insertField(MARC::Tag("720"), { { 'a', last_data}, { 'e', "author" } }); else if (tag == "description") new_record.insertField(MARC::Tag("520"), 'a', last_data); else if (tag == "identifier") { if (StringUtil::StartsWith(last_data, "http://doi.org/")) { new_record.insertField(MARC::Tag("024"), { { 'a', last_data.substr(__builtin_strlen("http://doi.org/")) }, { '2', "doi" } }); new_record.insertField(MARC::Tag("856"), 'u', last_data); } } else if (tag == "date") new_record.insertField(MARC::Tag("260"), 'c', AmericanDateToGermanDate(last_data)); else if (tag == "type") new_record.insertField(MARC::Tag("655"), 'a', last_data, ' ', '7'); else if (tag == "source") new_record.insertField(MARC::Tag("786"), 'n', last_data, '0', ' '); else if (tag == "coverage") new_record.insertField(MARC::Tag("500"), 'a', last_data); else if (tag == "subject") new_record.insertField(MARC::Tag("653"), 'a', last_data); else LOG_ERROR("Unhandled tag: \"" + xml_part.data_ + "\"!"); } else if (not StringUtil::StartsWith(xml_part.data_, "dc:")) { if (IsCriminologyRecord(new_record)) { marc_writer->write(new_record); return true; } else return false; } } if (IsCriminologyRecord(new_record)) { marc_writer->write(new_record); return true; } else return false; } int Main(int argc, char *argv[]) { if (argc != 3) ::Usage("dc_xml_imput marc_output"); XMLParser xml_parser(argv[1], XMLParser::XML_FILE); const auto marc_writer(MARC::Writer::Factory(argv[2])); unsigned total_record_count(0), selected_record_count(0); while (xml_parser.skipTo(XMLParser::XMLPart::OPENING_TAG, "oai_dc:dc")) { ++total_record_count; if (ParseRecord(&xml_parser, marc_writer.get())) ++selected_record_count; } LOG_INFO("Processed " + std::to_string(total_record_count) + " record(s) of which " + std::to_string(selected_record_count) + " record(s) where selected and converted to MARC."); return EXIT_SUCCESS; } <commit_msg>As requested from the BSZ we now put some keywords not in 500$a but 653$a.<commit_after>/** \brief Utility for converting Dublin Core data downloaded from ICPSR to MARC. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2021 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include "MARC.h" #include "StringUtil.h" #include "TimeUtil.h" #include "util.h" #include "XMLParser.h" bool IsCriminologyRecord(const MARC::Record &record) { for (const auto &field : record.getTagRange("653")) { if (StringUtil::StartsWith(field.getFirstSubfieldWithCode('a'), "crime")) return true; } return false; } // "american_date" is expected to contain the pattern mm-dd-yyyy. std::string AmericanDateToGermanDate(const std::string &american_date) { const auto month(StringUtil::ToUnsigned(american_date.substr(0, 2))); if (unlikely(month == 0 or month > 12)) LOG_ERROR("bad month in \"" + american_date + "\"!"); const auto day(StringUtil::ToUnsigned(american_date.substr(3, 2))); if (unlikely(day == 0 or day > 31)) LOG_ERROR("bad day in \"" + american_date + "\"!"); const auto year(StringUtil::ToUnsigned(american_date.substr(6))); if (unlikely(year < 1000 or year > 2099)) LOG_ERROR("bad year in \"" + american_date + "\"!"); return StringUtil::ToString(day) + "." + StringUtil::ToString(month) + "." + StringUtil::ToString(year); } // Mostly uses the mapping found at https://www.loc.gov/marc/dccross.html to map DC to MARC. bool ParseRecord(XMLParser * const xml_parser, MARC::Writer * const marc_writer) { static unsigned record_number; ++record_number; MARC::Record new_record(MARC::Record::TypeOfRecord::LANGUAGE_MATERIAL, MARC::Record::BibliographicLevel::UNDEFINED, "ICPSR" + StringUtil::ToString(record_number, /* radix = */10, /* width = */6, /* padding_char = */'0')); static const std::string today(TimeUtil::GetCurrentDateAndTime("%y%m%d")); static const std::string current_year(TimeUtil::GetCurrentYear()); static const std::string _008_contents(today + 's' + current_year); new_record.insertField(MARC::Tag("008"), _008_contents); new_record.insertField(MARC::Tag("935"), { { 'a', "icpsr" }, { '2', "LOK" } }); XMLParser::XMLPart xml_part; std::string last_data; while (xml_parser->getNext(&xml_part)) { if (xml_part.type_ == XMLParser::XMLPart::CHARACTERS) xml_part.data_.swap(last_data); else if (xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG and StringUtil::StartsWith(xml_part.data_, "dc:")) { const std::string tag(xml_part.data_.substr(3)); if (tag == "title") new_record.insertField(MARC::Tag("245"), 'a', last_data); else if (tag == "contributor") new_record.insertField(MARC::Tag("720"), 'a', last_data); else if (tag == "creator") new_record.insertField(MARC::Tag("720"), { { 'a', last_data}, { 'e', "author" } }); else if (tag == "description") new_record.insertField(MARC::Tag("520"), 'a', last_data); else if (tag == "identifier") { if (StringUtil::StartsWith(last_data, "http://doi.org/")) { new_record.insertField(MARC::Tag("024"), { { 'a', last_data.substr(__builtin_strlen("http://doi.org/")) }, { '2', "doi" } }); new_record.insertField(MARC::Tag("856"), 'u', last_data); } } else if (tag == "date") new_record.insertField(MARC::Tag("260"), 'c', AmericanDateToGermanDate(last_data)); else if (tag == "type") new_record.insertField(MARC::Tag("655"), 'a', last_data, ' ', '7'); else if (tag == "source") new_record.insertField(MARC::Tag("786"), 'n', last_data, '0', ' '); else if (tag == "coverage" or tag == "subject") new_record.insertField(MARC::Tag("653"), 'a', last_data); else LOG_ERROR("Unhandled tag: \"" + xml_part.data_ + "\"!"); } else if (not StringUtil::StartsWith(xml_part.data_, "dc:")) { if (IsCriminologyRecord(new_record)) { marc_writer->write(new_record); return true; } else return false; } } if (IsCriminologyRecord(new_record)) { marc_writer->write(new_record); return true; } else return false; } int Main(int argc, char *argv[]) { if (argc != 3) ::Usage("dc_xml_imput marc_output"); XMLParser xml_parser(argv[1], XMLParser::XML_FILE); const auto marc_writer(MARC::Writer::Factory(argv[2])); unsigned total_record_count(0), selected_record_count(0); while (xml_parser.skipTo(XMLParser::XMLPart::OPENING_TAG, "oai_dc:dc")) { ++total_record_count; if (ParseRecord(&xml_parser, marc_writer.get())) ++selected_record_count; } LOG_INFO("Processed " + std::to_string(total_record_count) + " record(s) of which " + std::to_string(selected_record_count) + " record(s) where selected and converted to MARC."); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** @file ConnectionSTREAM_UNITE.cpp @author Lime Microsystems @brief Implementation of STREAM+UNITE board connection. */ #include "ConnectionSTREAM_UNITE.h" #include "ErrorReporting.h" using namespace std; namespace lime { ConnectionSTREAM_UNITE::ConnectionSTREAM_UNITE(void* ctx, const std::string &vidpid, const std::string &serial, const unsigned index, const char* comPortName) : ConnectionFX3(ctx, vidpid, serial, index), comPort(nullptr) { if(comPortName && strlen(comPortName)) { comPort = new ConnectionEVB7COM(comPortName, 9600); if(comPort->IsOpen() == false) { delete comPort; comPort = nullptr; return; } } } ConnectionSTREAM_UNITE::~ConnectionSTREAM_UNITE(void) { if(comPort) delete comPort; } DeviceInfo ConnectionSTREAM_UNITE::GetDeviceInfo(void) { DeviceInfo usbInfo = ConnectionFX3::GetDeviceInfo(); if(comPort) { DeviceInfo comInfo; comInfo = comPort->GetDeviceInfo(); usbInfo.deviceName += std::string("+")+comInfo.deviceName; } return usbInfo; } int ConnectionSTREAM_UNITE::TransactSPI(const int addr, const uint32_t *writeData, uint32_t *readData, const size_t size) { if(comPort && (addr == 0x10 || addr == 0x30)) //redirect LMS7002M SPI, ADF4002 { return comPort->TransactSPI(addr, writeData, readData, size); } else return ConnectionFX3::TransactSPI(addr, writeData, readData, size); } int ConnectionSTREAM_UNITE::DeviceReset(int ind) { if(comPort) { int status = comPort->DeviceReset(); if(status != 0) return status; } return ConnectionFX3::DeviceReset(); } int ConnectionSTREAM_UNITE::TransferPacket(GenericPacket &pkt) { if(comPort && (pkt.cmd == CMD_PROG_MCU || pkt.cmd == CMD_LMS7002_WR || pkt.cmd == CMD_LMS7002_RD )) return comPort->TransferPacket(pkt); else return ConnectionFX3::TransferPacket(pkt); } } <commit_msg>Fixed Stream Unite headers build problem.<commit_after>/** @file ConnectionSTREAM_UNITE.cpp @author Lime Microsystems @brief Implementation of STREAM+UNITE board connection. */ #include "ConnectionSTREAM_UNITE.h" using namespace std; namespace lime { ConnectionSTREAM_UNITE::ConnectionSTREAM_UNITE(void* ctx, const std::string &vidpid, const std::string &serial, const unsigned index, const char* comPortName) : ConnectionFX3(ctx, vidpid, serial, index), comPort(nullptr) { if(comPortName && strlen(comPortName)) { comPort = new ConnectionEVB7COM(comPortName, 9600); if(comPort->IsOpen() == false) { delete comPort; comPort = nullptr; return; } } } ConnectionSTREAM_UNITE::~ConnectionSTREAM_UNITE(void) { if(comPort) delete comPort; } DeviceInfo ConnectionSTREAM_UNITE::GetDeviceInfo(void) { DeviceInfo usbInfo = ConnectionFX3::GetDeviceInfo(); if(comPort) { DeviceInfo comInfo; comInfo = comPort->GetDeviceInfo(); usbInfo.deviceName += std::string("+")+comInfo.deviceName; } return usbInfo; } int ConnectionSTREAM_UNITE::TransactSPI(const int addr, const uint32_t *writeData, uint32_t *readData, const size_t size) { if(comPort && (addr == 0x10 || addr == 0x30)) //redirect LMS7002M SPI, ADF4002 { return comPort->TransactSPI(addr, writeData, readData, size); } else return ConnectionFX3::TransactSPI(addr, writeData, readData, size); } int ConnectionSTREAM_UNITE::DeviceReset(int ind) { if(comPort) { int status = comPort->DeviceReset(); if(status != 0) return status; } return ConnectionFX3::DeviceReset(); } int ConnectionSTREAM_UNITE::TransferPacket(GenericPacket &pkt) { if(comPort && (pkt.cmd == CMD_PROG_MCU || pkt.cmd == CMD_LMS7002_WR || pkt.cmd == CMD_LMS7002_RD )) return comPort->TransferPacket(pkt); else return ConnectionFX3::TransferPacket(pkt); } } <|endoftext|>
<commit_before>#ifndef resplunk_util_Cloneable_HeaderPlusPlus #define resplunk_util_Cloneable_HeaderPlusPlus #include <memory> #include <type_traits> namespace resplunk { namespace util { struct Cloneable { Cloneable() = default; Cloneable(Cloneable const &) = default; Cloneable &operator=(Cloneable const &) = delete; Cloneable(Cloneable &&) = default; Cloneable &operator=(Cloneable &&) = delete; virtual ~Cloneable() = default; template<template<typename...> typename Wrapper = std::unique_ptr, typename... Args> static auto Clone(Cloneable const &c) noexcept -> Wrapper<Cloneable, Args...> { return Wrapper<Cloneable, Args...>{c.clone()}; } private: template<typename DerivedT> friend struct CloneImplementor; virtual Cloneable *clone() const noexcept = 0; }; template<typename DerivedT> struct CloneImplementor : virtual Cloneable { using Cloneable_t = DerivedT; using CloneImplementor_t = CloneImplementor; template<template<typename...> typename Wrapper = std::unique_ptr, typename... Args> static auto Clone(Cloneable_t const &ct) noexcept -> Wrapper<Cloneable_t, Args...> { Cloneable const &c = ct; return Wrapper<Cloneable_t, Args...>{dynamic_cast<Cloneable_t *>(c.clone())}; } private: CloneImplementor() = default; friend Cloneable_t; }; template<typename CloneableT, template<typename...> typename Wrapper = std::unique_ptr, typename... Args> struct ClonePtr final : Wrapper<CloneableT, Args...> { static_assert(std::is_base_of<Cloneable, CloneableT>::value); using Cloneable_t = CloneableT; using ClonePtr_t = ClonePtr; using Wrapper_t = Wrapper<CloneableT, Args...>; using Wrapper_t::Wrapper_t; ClonePtr(ClonePtr const &from) noexcept : Wrapper_t{std::move(Cloneable_t::Clone<Wrapper, Args...>(*from))} { } ClonePtr &operator=(ClonePtr const &from) noexcept { return Wrapper_t::operator=(std::move(Cloneable_t::Clone<Wrapper, Args...>(*from))); } ClonePtr(Cloneable_t const &from) noexcept : Wrapper_t{std::move(Cloneable_t::Clone<Wrapper, Args...>(from))} { } ClonePtr &operator=(Cloneable_t const &from) noexcept { return Wrapper_t::operator=(std::move(Cloneable_t::Clone<Wrapper, Args...>(from))); } }; } } #endif <commit_msg>Fix all compilation errors<commit_after>#ifndef resplunk_util_Cloneable_HeaderPlusPlus #define resplunk_util_Cloneable_HeaderPlusPlus #include <memory> #include <type_traits> namespace resplunk { namespace util { struct Cloneable { Cloneable() = default; Cloneable(Cloneable const &) = default; Cloneable &operator=(Cloneable const &) = delete; Cloneable(Cloneable &&) = default; Cloneable &operator=(Cloneable &&) = delete; virtual ~Cloneable() = default; template<template<typename...> typename Wrapper = std::unique_ptr, typename... Args> static auto Clone(Cloneable const &c) noexcept -> Wrapper<Cloneable, Args...> { return Wrapper<Cloneable, Args...>{c.clone()}; } private: template<typename DerivedT> friend struct CloneImplementor; virtual Cloneable *clone() const noexcept = 0; }; template<typename DerivedT> struct CloneImplementor : virtual Cloneable { using Cloneable_t = DerivedT; using CloneImplementor_t = CloneImplementor; template<template<typename...> typename Wrapper = std::unique_ptr, typename... Args> static auto Clone(Cloneable_t const &ct) noexcept -> Wrapper<Cloneable_t, Args...> { Cloneable const &c = ct; return Wrapper<Cloneable_t, Args...>{dynamic_cast<Cloneable_t *>(c.clone())}; } private: CloneImplementor() = default; friend Cloneable_t; }; template<typename CloneableT, template<typename...> typename Wrapper = std::unique_ptr, typename... Args> struct ClonePtr final : Wrapper<CloneableT, Args...> { static_assert(std::is_base_of<Cloneable, CloneableT>::value); using Cloneable_t = CloneableT; using ClonePtr_t = ClonePtr; using Wrapper_t = Wrapper<CloneableT, Args...>; using Wrapper_t::Wrapper_t; ClonePtr(ClonePtr const &from) noexcept : Wrapper_t{std::move(Cloneable_t::template Clone<Wrapper, Args...>(*from))} { } ClonePtr &operator=(ClonePtr const &from) noexcept { return Wrapper_t::operator=(std::move(Cloneable_t::Clone<Wrapper, Args...>(*from))); } ClonePtr(Cloneable_t const &from) noexcept : Wrapper_t{std::move(Cloneable_t::Clone<Wrapper, Args...>(from))} { } ClonePtr &operator=(Cloneable_t const &from) noexcept { return Wrapper_t::operator=(std::move(Cloneable_t::Clone<Wrapper, Args...>(from))); } }; } } #endif <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/atom_browser_client.h" #if defined(OS_WIN) #include <shlobj.h> #endif #include "atom/browser/api/atom_api_app.h" #include "atom/browser/api/atom_api_protocol.h" #include "atom/browser/atom_access_token_store.h" #include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/atom_quota_permission_context.h" #include "atom/browser/atom_resource_dispatcher_host_delegate.h" #include "atom/browser/atom_speech_recognition_manager_delegate.h" #include "atom/browser/native_window.h" #include "atom/browser/web_contents_permission_helper.h" #include "atom/browser/web_contents_preferences.h" #include "atom/browser/window_list.h" #include "atom/common/options_switches.h" #include "base/command_line.h" #include "base/files/file_util.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "chrome/browser/printing/printing_message_filter.h" #include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h" #include "chrome/browser/renderer_host/pepper/widevine_cdm_message_filter.h" #include "chrome/browser/speech/tts_message_filter.h" #include "content/public/browser/browser_ppapi_host.h" #include "content/public/browser/client_certificate_delegate.h" #include "content/public/browser/geolocation_delegate.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/resource_dispatcher_host.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" #include "content/public/common/web_preferences.h" #include "net/ssl/ssl_cert_request_info.h" #include "ppapi/host/ppapi_host.h" #include "ui/base/l10n/l10n_util.h" #include "v8/include/v8.h" namespace atom { namespace { // Next navigation should not restart renderer process. bool g_suppress_renderer_process_restart = false; // Custom schemes to be registered to handle service worker. std::string g_custom_service_worker_schemes = ""; // A provider of Geolocation services to override AccessTokenStore. class AtomGeolocationDelegate : public content::GeolocationDelegate { public: AtomGeolocationDelegate() = default; content::AccessTokenStore* CreateAccessTokenStore() final { return new AtomAccessTokenStore(); } private: DISALLOW_COPY_AND_ASSIGN(AtomGeolocationDelegate); }; void Noop(scoped_refptr<content::SiteInstance>) { } } // namespace // static void AtomBrowserClient::SuppressRendererProcessRestartForOnce() { g_suppress_renderer_process_restart = true; } void AtomBrowserClient::SetCustomServiceWorkerSchemes( const std::vector<std::string>& schemes) { g_custom_service_worker_schemes = base::JoinString(schemes, ","); } AtomBrowserClient::AtomBrowserClient() : delegate_(nullptr) { } AtomBrowserClient::~AtomBrowserClient() { } content::WebContents* AtomBrowserClient::GetWebContentsFromProcessID( int process_id) { // If the process is a pending process, we should use the old one. if (ContainsKey(pending_processes_, process_id)) process_id = pending_processes_[process_id]; // Certain render process will be created with no associated render view, // for example: ServiceWorker. return WebContentsPreferences::GetWebContentsFromProcessID(process_id); } void AtomBrowserClient::RenderProcessWillLaunch( content::RenderProcessHost* host) { int process_id = host->GetID(); host->AddFilter(new printing::PrintingMessageFilter(process_id)); host->AddFilter(new TtsMessageFilter(process_id, host->GetBrowserContext())); host->AddFilter( new WidevineCdmMessageFilter(process_id, host->GetBrowserContext())); } content::SpeechRecognitionManagerDelegate* AtomBrowserClient::CreateSpeechRecognitionManagerDelegate() { return new AtomSpeechRecognitionManagerDelegate; } content::GeolocationDelegate* AtomBrowserClient::CreateGeolocationDelegate() { return new AtomGeolocationDelegate(); } void AtomBrowserClient::OverrideWebkitPrefs( content::RenderViewHost* host, content::WebPreferences* prefs) { prefs->javascript_enabled = true; prefs->web_security_enabled = true; prefs->javascript_can_open_windows_automatically = true; prefs->plugins_enabled = true; prefs->dom_paste_enabled = true; prefs->allow_scripts_to_close_windows = true; prefs->javascript_can_access_clipboard = true; prefs->local_storage_enabled = true; prefs->databases_enabled = true; prefs->application_cache_enabled = true; prefs->allow_universal_access_from_file_urls = true; prefs->allow_file_access_from_file_urls = true; prefs->experimental_webgl_enabled = true; prefs->allow_displaying_insecure_content = false; prefs->allow_running_insecure_content = false; // Custom preferences of guest page. auto web_contents = content::WebContents::FromRenderViewHost(host); WebContentsPreferences::OverrideWebkitPrefs(web_contents, prefs); } std::string AtomBrowserClient::GetApplicationLocale() { return l10n_util::GetApplicationLocale(""); } void AtomBrowserClient::OverrideSiteInstanceForNavigation( content::BrowserContext* browser_context, content::SiteInstance* current_instance, const GURL& url, content::SiteInstance** new_instance) { if (g_suppress_renderer_process_restart) { g_suppress_renderer_process_restart = false; return; } // Restart renderer process for all navigations except "javacript:" scheme. if (url.SchemeIs(url::kJavaScriptScheme)) return; scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(browser_context, url); *new_instance = site_instance.get(); // Make sure the |site_instance| is not freed when this function returns. // FIXME(zcbenz): We should adjust OverrideSiteInstanceForNavigation's // interface to solve this. content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&Noop, base::RetainedRef(site_instance))); // Remember the original renderer process of the pending renderer process. auto current_process = current_instance->GetProcess(); auto pending_process = (*new_instance)->GetProcess(); pending_processes_[pending_process->GetID()] = current_process->GetID(); // Clear the entry in map when process ends. current_process->AddObserver(this); } void AtomBrowserClient::AppendExtraCommandLineSwitches( base::CommandLine* command_line, int process_id) { std::string process_type = command_line->GetSwitchValueASCII("type"); if (process_type != "renderer") return; // Copy following switches to child process. static const char* const kCommonSwitchNames[] = { switches::kStandardSchemes, }; command_line->CopySwitchesFrom( *base::CommandLine::ForCurrentProcess(), kCommonSwitchNames, node::arraysize(kCommonSwitchNames)); // The registered service worker schemes. if (!g_custom_service_worker_schemes.empty()) command_line->AppendSwitchASCII(switches::kRegisterServiceWorkerSchemes, g_custom_service_worker_schemes); #if defined(OS_WIN) // Append --app-user-model-id. PWSTR current_app_id; if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&current_app_id))) { command_line->AppendSwitchNative(switches::kAppUserModelId, current_app_id); CoTaskMemFree(current_app_id); } #endif content::WebContents* web_contents = GetWebContentsFromProcessID(process_id); if (!web_contents) return; WebContentsPreferences::AppendExtraCommandLineSwitches( web_contents, command_line); } void AtomBrowserClient::DidCreatePpapiPlugin( content::BrowserPpapiHost* host) { host->GetPpapiHost()->AddHostFactoryFilter( base::WrapUnique(new chrome::ChromeBrowserPepperHostFactory(host))); } content::QuotaPermissionContext* AtomBrowserClient::CreateQuotaPermissionContext() { return new AtomQuotaPermissionContext; } void AtomBrowserClient::AllowCertificateError( content::WebContents* web_contents, int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, content::ResourceType resource_type, bool overridable, bool strict_enforcement, bool expired_previous_decision, const base::Callback<void(bool)>& callback, content::CertificateRequestResultType* request) { if (delegate_) { delegate_->AllowCertificateError( web_contents, cert_error, ssl_info, request_url, resource_type, overridable, strict_enforcement, expired_previous_decision, callback, request); } } void AtomBrowserClient::SelectClientCertificate( content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, std::unique_ptr<content::ClientCertificateDelegate> delegate) { if (!cert_request_info->client_certs.empty() && delegate_) { delegate_->SelectClientCertificate( web_contents, cert_request_info, std::move(delegate)); } } void AtomBrowserClient::ResourceDispatcherHostCreated() { resource_dispatcher_host_delegate_.reset( new AtomResourceDispatcherHostDelegate); content::ResourceDispatcherHost::Get()->SetDelegate( resource_dispatcher_host_delegate_.get()); } bool AtomBrowserClient::CanCreateWindow( const GURL& opener_url, const GURL& opener_top_level_frame_url, const GURL& source_origin, WindowContainerType container_type, const std::string& frame_name, const GURL& target_url, const content::Referrer& referrer, WindowOpenDisposition disposition, const blink::WebWindowFeatures& features, bool user_gesture, bool opener_suppressed, content::ResourceContext* context, int render_process_id, int opener_render_view_id, int opener_render_frame_id, bool* no_javascript_access) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (delegate_) { content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, base::Bind(&api::App::OnCreateWindow, base::Unretained(static_cast<api::App*>(delegate_)), target_url, frame_name, disposition, render_process_id, opener_render_frame_id)); } return false; } void AtomBrowserClient::GetAdditionalAllowedSchemesForFileSystem( std::vector<std::string>* additional_schemes) { auto schemes_list = api::GetStandardSchemes(); if (!schemes_list.empty()) additional_schemes->insert(additional_schemes->end(), schemes_list.begin(), schemes_list.end()); } brightray::BrowserMainParts* AtomBrowserClient::OverrideCreateBrowserMainParts( const content::MainFunctionParams&) { v8::V8::Initialize(); // Init V8 before creating main parts. return new AtomBrowserMainParts; } void AtomBrowserClient::WebNotificationAllowed( int render_process_id, const base::Callback<void(bool, bool)>& callback) { content::WebContents* web_contents = WebContentsPreferences::GetWebContentsFromProcessID(render_process_id); if (!web_contents) { callback.Run(false, false); return; } auto permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); if (!permission_helper) { callback.Run(false, false); return; } permission_helper->RequestWebNotificationPermission( base::Bind(callback, web_contents->IsAudioMuted())); } void AtomBrowserClient::RenderProcessHostDestroyed( content::RenderProcessHost* host) { int process_id = host->GetID(); for (const auto& entry : pending_processes_) { if (entry.first == process_id || entry.second == process_id) { pending_processes_.erase(entry.first); break; } } } } // namespace atom <commit_msg>only restart node renderer processes possible fix for https://github.com/brave/browser-laptop/issues/2661 and https://github.com/brave/browser-laptop/issues/2744 auditors: @bbondy<commit_after>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/atom_browser_client.h" #if defined(OS_WIN) #include <shlobj.h> #endif #include "atom/browser/api/atom_api_app.h" #include "atom/browser/api/atom_api_protocol.h" #include "atom/browser/atom_access_token_store.h" #include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/atom_quota_permission_context.h" #include "atom/browser/atom_resource_dispatcher_host_delegate.h" #include "atom/browser/atom_speech_recognition_manager_delegate.h" #include "atom/browser/native_window.h" #include "atom/browser/web_contents_permission_helper.h" #include "atom/browser/web_contents_preferences.h" #include "atom/browser/window_list.h" #include "atom/common/options_switches.h" #include "base/command_line.h" #include "base/files/file_util.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "chrome/browser/printing/printing_message_filter.h" #include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h" #include "chrome/browser/renderer_host/pepper/widevine_cdm_message_filter.h" #include "chrome/browser/speech/tts_message_filter.h" #include "content/public/browser/browser_ppapi_host.h" #include "content/public/browser/client_certificate_delegate.h" #include "content/public/browser/geolocation_delegate.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/resource_dispatcher_host.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" #include "content/public/common/web_preferences.h" #include "net/ssl/ssl_cert_request_info.h" #include "ppapi/host/ppapi_host.h" #include "ui/base/l10n/l10n_util.h" #include "v8/include/v8.h" namespace atom { namespace { // Next navigation should not restart renderer process. bool g_suppress_renderer_process_restart = false; // Custom schemes to be registered to handle service worker. std::string g_custom_service_worker_schemes = ""; // A provider of Geolocation services to override AccessTokenStore. class AtomGeolocationDelegate : public content::GeolocationDelegate { public: AtomGeolocationDelegate() = default; content::AccessTokenStore* CreateAccessTokenStore() final { return new AtomAccessTokenStore(); } private: DISALLOW_COPY_AND_ASSIGN(AtomGeolocationDelegate); }; void Noop(scoped_refptr<content::SiteInstance>) { } } // namespace // static void AtomBrowserClient::SuppressRendererProcessRestartForOnce() { g_suppress_renderer_process_restart = true; } void AtomBrowserClient::SetCustomServiceWorkerSchemes( const std::vector<std::string>& schemes) { g_custom_service_worker_schemes = base::JoinString(schemes, ","); } AtomBrowserClient::AtomBrowserClient() : delegate_(nullptr) { } AtomBrowserClient::~AtomBrowserClient() { } content::WebContents* AtomBrowserClient::GetWebContentsFromProcessID( int process_id) { // If the process is a pending process, we should use the old one. if (ContainsKey(pending_processes_, process_id)) process_id = pending_processes_[process_id]; // Certain render process will be created with no associated render view, // for example: ServiceWorker. return WebContentsPreferences::GetWebContentsFromProcessID(process_id); } void AtomBrowserClient::RenderProcessWillLaunch( content::RenderProcessHost* host) { int process_id = host->GetID(); host->AddFilter(new printing::PrintingMessageFilter(process_id)); host->AddFilter(new TtsMessageFilter(process_id, host->GetBrowserContext())); host->AddFilter( new WidevineCdmMessageFilter(process_id, host->GetBrowserContext())); } content::SpeechRecognitionManagerDelegate* AtomBrowserClient::CreateSpeechRecognitionManagerDelegate() { return new AtomSpeechRecognitionManagerDelegate; } content::GeolocationDelegate* AtomBrowserClient::CreateGeolocationDelegate() { return new AtomGeolocationDelegate(); } void AtomBrowserClient::OverrideWebkitPrefs( content::RenderViewHost* host, content::WebPreferences* prefs) { prefs->javascript_enabled = true; prefs->web_security_enabled = true; prefs->javascript_can_open_windows_automatically = true; prefs->plugins_enabled = true; prefs->dom_paste_enabled = true; prefs->allow_scripts_to_close_windows = true; prefs->javascript_can_access_clipboard = true; prefs->local_storage_enabled = true; prefs->databases_enabled = true; prefs->application_cache_enabled = true; prefs->allow_universal_access_from_file_urls = true; prefs->allow_file_access_from_file_urls = true; prefs->experimental_webgl_enabled = true; prefs->allow_displaying_insecure_content = false; prefs->allow_running_insecure_content = false; // Custom preferences of guest page. auto web_contents = content::WebContents::FromRenderViewHost(host); WebContentsPreferences::OverrideWebkitPrefs(web_contents, prefs); } std::string AtomBrowserClient::GetApplicationLocale() { return l10n_util::GetApplicationLocale(""); } void AtomBrowserClient::OverrideSiteInstanceForNavigation( content::BrowserContext* browser_context, content::SiteInstance* current_instance, const GURL& url, content::SiteInstance** new_instance) { content::WebContents* web_contents = GetWebContentsFromProcessID(current_instance->GetProcess()->GetID()); // processes with no disabled may not have a web_contents with the // id that GetWebContentsFromProcessID looks for if (!web_contents) return; WebContentsPreferences* web_contents_prefs = WebContentsPreferences::FromWebContents(web_contents); if (web_contents_prefs) { auto web_preferences = web_contents_prefs->web_preferences(); bool node_integration = true; web_preferences->GetBoolean(options::kNodeIntegration, &node_integration); if (!node_integration) { // only renderers with node integration need to be restarted return; } } if (g_suppress_renderer_process_restart) { g_suppress_renderer_process_restart = false; return; } // Restart renderer process for all navigations except "javacript:" scheme. if (url.SchemeIs(url::kJavaScriptScheme)) return; scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(browser_context, url); *new_instance = site_instance.get(); // Make sure the |site_instance| is not freed when this function returns. // FIXME(zcbenz): We should adjust OverrideSiteInstanceForNavigation's // interface to solve this. content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&Noop, base::RetainedRef(site_instance))); // Remember the original renderer process of the pending renderer process. auto current_process = current_instance->GetProcess(); auto pending_process = (*new_instance)->GetProcess(); pending_processes_[pending_process->GetID()] = current_process->GetID(); // Clear the entry in map when process ends. current_process->AddObserver(this); } void AtomBrowserClient::AppendExtraCommandLineSwitches( base::CommandLine* command_line, int process_id) { std::string process_type = command_line->GetSwitchValueASCII("type"); if (process_type != "renderer") return; // Copy following switches to child process. static const char* const kCommonSwitchNames[] = { switches::kStandardSchemes, }; command_line->CopySwitchesFrom( *base::CommandLine::ForCurrentProcess(), kCommonSwitchNames, node::arraysize(kCommonSwitchNames)); // The registered service worker schemes. if (!g_custom_service_worker_schemes.empty()) command_line->AppendSwitchASCII(switches::kRegisterServiceWorkerSchemes, g_custom_service_worker_schemes); #if defined(OS_WIN) // Append --app-user-model-id. PWSTR current_app_id; if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&current_app_id))) { command_line->AppendSwitchNative(switches::kAppUserModelId, current_app_id); CoTaskMemFree(current_app_id); } #endif content::WebContents* web_contents = GetWebContentsFromProcessID(process_id); if (!web_contents) return; WebContentsPreferences::AppendExtraCommandLineSwitches( web_contents, command_line); } void AtomBrowserClient::DidCreatePpapiPlugin( content::BrowserPpapiHost* host) { host->GetPpapiHost()->AddHostFactoryFilter( base::WrapUnique(new chrome::ChromeBrowserPepperHostFactory(host))); } content::QuotaPermissionContext* AtomBrowserClient::CreateQuotaPermissionContext() { return new AtomQuotaPermissionContext; } void AtomBrowserClient::AllowCertificateError( content::WebContents* web_contents, int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, content::ResourceType resource_type, bool overridable, bool strict_enforcement, bool expired_previous_decision, const base::Callback<void(bool)>& callback, content::CertificateRequestResultType* request) { if (delegate_) { delegate_->AllowCertificateError( web_contents, cert_error, ssl_info, request_url, resource_type, overridable, strict_enforcement, expired_previous_decision, callback, request); } } void AtomBrowserClient::SelectClientCertificate( content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, std::unique_ptr<content::ClientCertificateDelegate> delegate) { if (!cert_request_info->client_certs.empty() && delegate_) { delegate_->SelectClientCertificate( web_contents, cert_request_info, std::move(delegate)); } } void AtomBrowserClient::ResourceDispatcherHostCreated() { resource_dispatcher_host_delegate_.reset( new AtomResourceDispatcherHostDelegate); content::ResourceDispatcherHost::Get()->SetDelegate( resource_dispatcher_host_delegate_.get()); } bool AtomBrowserClient::CanCreateWindow( const GURL& opener_url, const GURL& opener_top_level_frame_url, const GURL& source_origin, WindowContainerType container_type, const std::string& frame_name, const GURL& target_url, const content::Referrer& referrer, WindowOpenDisposition disposition, const blink::WebWindowFeatures& features, bool user_gesture, bool opener_suppressed, content::ResourceContext* context, int render_process_id, int opener_render_view_id, int opener_render_frame_id, bool* no_javascript_access) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (delegate_) { content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, base::Bind(&api::App::OnCreateWindow, base::Unretained(static_cast<api::App*>(delegate_)), target_url, frame_name, disposition, render_process_id, opener_render_frame_id)); } return false; } void AtomBrowserClient::GetAdditionalAllowedSchemesForFileSystem( std::vector<std::string>* additional_schemes) { auto schemes_list = api::GetStandardSchemes(); if (!schemes_list.empty()) additional_schemes->insert(additional_schemes->end(), schemes_list.begin(), schemes_list.end()); } brightray::BrowserMainParts* AtomBrowserClient::OverrideCreateBrowserMainParts( const content::MainFunctionParams&) { v8::V8::Initialize(); // Init V8 before creating main parts. return new AtomBrowserMainParts; } void AtomBrowserClient::WebNotificationAllowed( int render_process_id, const base::Callback<void(bool, bool)>& callback) { content::WebContents* web_contents = WebContentsPreferences::GetWebContentsFromProcessID(render_process_id); if (!web_contents) { callback.Run(false, false); return; } auto permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); if (!permission_helper) { callback.Run(false, false); return; } permission_helper->RequestWebNotificationPermission( base::Bind(callback, web_contents->IsAudioMuted())); } void AtomBrowserClient::RenderProcessHostDestroyed( content::RenderProcessHost* host) { int process_id = host->GetID(); for (const auto& entry : pending_processes_) { if (entry.first == process_id || entry.second == process_id) { pending_processes_.erase(entry.first); break; } } } } // namespace atom <|endoftext|>
<commit_before>#include "Game.h" Game::Game() { renderWindow.create(VideoMode(SCREEN_WIDTH,SCREEN_HEIGHT), "SFML Snake"); renderWindow.setVerticalSyncEnabled(true); gameState = MENU; srand(time(0)); snakeFast = false; canWalkBorder = true; generateWalls = false; gamePaused = false; } void Game::startGame() { if(!font.loadFromFile("font/Xolonium-Bold.otf")) { cerr << "Failed to load Xolonium-Bold.otf!"; return; } updateGame(); } void Game::updateGame() { switch(gameState) { case Game::MENU: drawMenu(); break; case Game::OPTIONS: drawOptions(); break; case Game::STARTED: drawGame(); break; case Game::OVER: gameOver(); break; case Game::ENDED: return; break; } } void Game::drawMenu() { gameName.setFont(font); gameName.setString("SFML Snake"); gameName.setCharacterSize(80); gameName.setPosition(SCREEN_WIDTH/2-gameName.getGlobalBounds().width/2,150); menuStrings[0].setFont(font); menuStrings[0].setString("Start Game"); menuStrings[0].setCharacterSize(40); menuStrings[0].setPosition(SCREEN_WIDTH/2-menuStrings[0].getGlobalBounds().width/2,250); menuStrings[1].setFont(font); menuStrings[1].setString("Options"); menuStrings[1].setCharacterSize(40); menuStrings[1].setPosition(SCREEN_WIDTH/2-menuStrings[1].getGlobalBounds().width/2,300); menuStrings[2].setFont(font); menuStrings[2].setString("Exit"); menuStrings[2].setCharacterSize(40); menuStrings[2].setPosition(SCREEN_WIDTH/2-menuStrings[2].getGlobalBounds().width/2,350); Event event; while(gameState == Game::MENU) { Vector2f mouse(Mouse::getPosition(renderWindow)); while(renderWindow.pollEvent(event)) { //Exit after clicking X on window if(event.type == Event::Closed) gameState = ENDED; //Go to game, options or exit when user selects option in menu if(event.type == Event::MouseButtonReleased) { if(menuStrings[0].getGlobalBounds().contains(mouse) && event.mouseButton.button == Mouse::Left) gameState = STARTED; if(menuStrings[1].getGlobalBounds().contains(mouse) && event.mouseButton.button == Mouse::Left) gameState = OPTIONS; if(menuStrings[2].getGlobalBounds().contains(mouse) && event.mouseButton.button == Mouse::Left) gameState = ENDED; } } renderWindow.clear(); renderWindow.draw(gameName); for(int i = 0; i < 3; i++) renderWindow.draw(menuStrings[i]); for(int i = 0; i < 3; i++) if(menuStrings[i].getGlobalBounds().contains(mouse)) menuStrings[i].setFillColor(Color::Green); else menuStrings[i].setFillColor(Color::White); renderWindow.display(); } updateGame(); } void Game::drawOptions() { optionsStrings[0].setString("OPTIONS"); optionsStrings[1].setString("Snake speed"); optionsStrings[2].setString("Can walk through border"); optionsStrings[3].setString("Generate random wall"); optionsStrings[4].setString("Back"); optionsStrings[5].setString("Slow"); optionsStrings[6].setString("Fast"); optionsStrings[0].setFont(font); optionsStrings[0].setCharacterSize(80); optionsStrings[0].setPosition(SCREEN_WIDTH/2-optionsStrings[0].getGlobalBounds().width/2, 50); //Draw strings for(int i = 1; i < 5; i++) { optionsStrings[i].setFont(font); optionsStrings[i].setCharacterSize(40); optionsStrings[i].setPosition(SCREEN_WIDTH/2-optionsStrings[i].getGlobalBounds().width/2, 100+100*i); } //Set 'Slow' string optionsStrings[5].setFont(font); optionsStrings[5].setCharacterSize(40); optionsStrings[5].setPosition(SCREEN_WIDTH/2-optionsStrings[5].getGlobalBounds().width, 240); //Set 'Fast' string optionsStrings[6].setFont(font); optionsStrings[6].setCharacterSize(40); optionsStrings[6].setPosition(SCREEN_WIDTH/2+optionsStrings[5].getGlobalBounds().width/4, 240); //Set checkboxes borderCheckbox.setSize(Vector2f(20,20)); borderCheckbox.setOutlineColor(Color::Red); borderCheckbox.setFillColor(Color::Black); borderCheckbox.setOutlineThickness(5); borderCheckbox.setPosition(SCREEN_WIDTH/2, 350); wallsCheckbox.setSize(Vector2f(20,20)); wallsCheckbox.setOutlineColor(Color::Red); wallsCheckbox.setFillColor(Color::Black); wallsCheckbox.setOutlineThickness(5); wallsCheckbox.setPosition(SCREEN_WIDTH/2, 450); Event event; while(gameState == Game::OPTIONS) { Vector2f mouse(Mouse::getPosition(renderWindow)); while(renderWindow.pollEvent(event)) { //Back to menu after selecting "Back" in options if(event.type == Event::MouseButtonReleased) if(optionsStrings[4].getGlobalBounds().contains(mouse) && event.mouseButton.button == Mouse::Left) gameState = MENU; //Back to menu when Escape pressed if(event.type == Event::KeyPressed && event.key.code == Keyboard::Escape) gameState = MENU; //Exit game after clicking X on window if(event.type == Event::Closed) gameState = ENDED; //Set slow snake speed after selecting it if(event.type == Event::MouseButtonReleased) if(optionsStrings[5].getGlobalBounds().contains(mouse) && event.mouseButton.button == Mouse::Left && snakeFast) snakeFast = false; //Set fast snake speed after selecting it if(event.type == Event::MouseButtonReleased) if(optionsStrings[6].getGlobalBounds().contains(mouse) && event.mouseButton.button == Mouse::Left && !snakeFast) snakeFast = true; //Set right flag after choosing checkbox if(event.type == Event::MouseButtonReleased) if(borderCheckbox.getGlobalBounds().contains(mouse)) { if(!canWalkBorder) canWalkBorder = true; else canWalkBorder = false; } if(event.type == Event::MouseButtonReleased) if(wallsCheckbox.getGlobalBounds().contains(mouse)) { if(!generateWalls) generateWalls = true; else generateWalls = false; } } if(optionsStrings[4].getGlobalBounds().contains(mouse)) //Change 'Back' string color to green on mouse hover optionsStrings[4].setFillColor(Color::Green); else optionsStrings[4].setFillColor(Color::White); //Highlight string on mouse hover when it is not choosen (yellow) if(optionsStrings[5].getGlobalBounds().contains(mouse) && snakeFast) optionsStrings[5].setFillColor(Color::Green); else optionsStrings[5].setFillColor(Color::White); //Same as before if(optionsStrings[6].getGlobalBounds().contains(mouse) && !snakeFast) optionsStrings[6].setFillColor(Color::Green); else optionsStrings[6].setFillColor(Color::White); //Highlight choosen option in Snake speed if(!snakeFast) optionsStrings[5].setFillColor(Color::Yellow); else optionsStrings[6].setFillColor(Color::Yellow); //Mark or unmark checkbox if(canWalkBorder) borderCheckbox.setFillColor(Color::Yellow); else borderCheckbox.setFillColor(Color::Black); if(generateWalls) wallsCheckbox.setFillColor(Color::Yellow); else wallsCheckbox.setFillColor(Color::Black); renderWindow.clear(); for(int i = 0; i < 7; i++) renderWindow.draw(optionsStrings[i]); renderWindow.draw(borderCheckbox); renderWindow.draw(wallsCheckbox); renderWindow.display(); } updateGame(); } void Game::gameOver() { for(int i = 0; i < 4; i++) { gameOverStrings[i].setFont(font); gameOverStrings[i].setFillColor(Color::White); } //Game over string gameOverStrings[0].setString("Game Over!"); gameOverStrings[0].setCharacterSize(80); gameOverStrings[0].setPosition(SCREEN_WIDTH/2-gameOverStrings[0].getGlobalBounds().width/2,150); gameOverStrings[0].setFillColor(Color::Red); ostringstream buffer; pointsText = "Your points: "; buffer << points; pointsText += buffer.str(); gameOverStrings[1].setCharacterSize(40); gameOverStrings[1].setString(pointsText); gameOverStrings[1].setPosition(SCREEN_WIDTH/2-gameOverStrings[1].getGlobalBounds().width/2,240); //Clear buffer buffer.str(""); buffer.clear(); pointsText = "Your time: "; buffer << playTime; pointsText += buffer.str(); pointsText += "s"; gameOverStrings[2].setCharacterSize(40); gameOverStrings[2].setString(pointsText); gameOverStrings[2].setPosition(SCREEN_WIDTH/2-gameOverStrings[1].getGlobalBounds().width/2,280); buffer.str(""); buffer.clear(); gameOverStrings[3].setString("Back to menu"); gameOverStrings[3].setCharacterSize(40); gameOverStrings[3].setPosition(SCREEN_WIDTH/2-gameOverStrings[3].getGlobalBounds().width/2,340); Event event; while(gameState == Game::OVER) { Vector2f mouse(Mouse::getPosition(renderWindow)); while(renderWindow.pollEvent(event)) { if(event.type == Event::Closed) gameState = ENDED; if(event.type == Event::KeyPressed && event.key.code == Keyboard::Escape) gameState = MENU; if(event.type == Event::MouseButtonReleased) if(event.mouseButton.button == Mouse::Left && gameOverStrings[3].getGlobalBounds().contains(mouse)) gameState = MENU; } if(gameOverStrings[3].getGlobalBounds().contains(mouse)) gameOverStrings[3].setFillColor(Color::Green); else gameOverStrings[3].setFillColor(Color::White); renderWindow.clear(); for(int i = 0; i < 4; i++) renderWindow.draw(gameOverStrings[i]); renderWindow.display(); } updateGame(); } void Game::drawGame() { Snake snake(SCREEN_WIDTH/2/SNAKE_SIZE, SCREEN_HEIGHT/2/SNAKE_SIZE, SCREEN_WIDTH, SCREEN_HEIGHT, canWalkBorder); //Create snake in center of the window Food food(SCREEN_WIDTH, SCREEN_HEIGHT, SNAKE_SIZE); //Draw border - it's a big reactangle with transparent fill gameBorder.setPosition(SNAKE_SIZE,SNAKE_SIZE); gameBorder.setSize(Vector2f(SCREEN_WIDTH-SNAKE_SIZE*2, SCREEN_HEIGHT-SNAKE_SIZE*2)); gameBorder.setFillColor(Color::Black); gameBorder.setOutlineThickness(3); gameBorder.setOutlineColor(Color::Red); snakePoints.setFont(font); snakePoints.setCharacterSize(20); snakePoints.setPosition(SNAKE_SIZE,0); gameTime.setFont(font); gameTime.setCharacterSize(20); gameTime.setPosition(SNAKE_SIZE+150,0); pauseString.setFont(font); pauseString.setCharacterSize(30); pauseString.setFillColor(Color::Magenta); pauseString.setPosition(SNAKE_SIZE+5, SCREEN_HEIGHT/2); pauseString.setString("Game paused (press P to continue)"); points = 0; ostringstream sstreamBuffer; Clock playClock; float elapsedPauseTime = 0; Clock gameClock; float elapsedGameTime = 0.0f; float timeStep; Clock pauseTime; if(!snakeFast) timeStep = 0.50f; //Lower update time means faster snake movement else timeStep = 0.25f; Event event; bool directionChanged = true; while(gameState == Game::STARTED) { while(renderWindow.pollEvent(event)) { if(event.type == Event::KeyPressed && event.key.code == Keyboard::Escape) gameState=MENU; if(event.type == Event::Closed) gameState=ENDED; if(event.type == Event::KeyPressed && event.key.code == Keyboard::P) { if(!gamePaused) { gamePaused = true; pauseTime.restart(); } else { gamePaused = false; elapsedGameTime -= pauseTime.getElapsedTime().asSeconds(); elapsedPauseTime += pauseTime.getElapsedTime().asSeconds(); } } } if(Keyboard::isKeyPressed(Keyboard::Left) && directionChanged && !gamePaused) { snake.setDirection(Snake::LEFT); directionChanged = false; } if(Keyboard::isKeyPressed(Keyboard::Right) && directionChanged && !gamePaused) { snake.setDirection(Snake::RIGHT); directionChanged = false; } if(Keyboard::isKeyPressed(Keyboard::Up) && directionChanged && !gamePaused) { snake.setDirection(Snake::UP); directionChanged = false; } if(Keyboard::isKeyPressed(Keyboard::Down) && directionChanged && !gamePaused) { snake.setDirection(Snake::DOWN); directionChanged = false; } elapsedGameTime += gameClock.restart().asSeconds(); //Dont update game when it's paused if(!gamePaused) { while(elapsedGameTime > timeStep) { //If snake movement fails over game if(!snake.moveSnake()) gameState = OVER; directionChanged = true; elapsedGameTime -= timeStep; } } if(snake.getX() == food.getFoodX() && snake.getY() == food.getFoodY()) { points++; snake.addSegment(food.getFoodX(), food.getFoodY()); food.generateNewFood(); } //Convert int to string by ostringstream, prepare text and set sf::Text pointsText = "Points: "; sstreamBuffer << points; pointsText += sstreamBuffer.str(); snakePoints.setString(pointsText); //Clear buffer sstreamBuffer.str(""); sstreamBuffer.clear(); timeText = "Time: "; //Dont update time when game is paused if(!gamePaused) playTime = playClock.getElapsedTime().asSeconds() - elapsedPauseTime; sstreamBuffer << playTime; timeText += sstreamBuffer.str(); gameTime.setString(timeText); sstreamBuffer.str(""); sstreamBuffer.clear(); renderWindow.clear(); renderWindow.draw(gameBorder); renderWindow.draw(snakePoints); renderWindow.draw(gameTime); snake.drawSnake(renderWindow); food.drawFood(renderWindow); if(gamePaused) renderWindow.draw(pauseString); renderWindow.display(); } updateGame(); } <commit_msg>Code and gameplay improvements<commit_after>#include "Game.h" Game::Game() { renderWindow.create(VideoMode(SCREEN_WIDTH,SCREEN_HEIGHT), "SFML Snake"); renderWindow.setVerticalSyncEnabled(true); gameState = MENU; srand(time(0)); snakeFast = false; canWalkBorder = true; generateWalls = false; gamePaused = false; } void Game::startGame() { if(!font.loadFromFile("font/Xolonium-Bold.otf")) { cerr << "Failed to load Xolonium-Bold.otf!"; return; } updateGame(); } void Game::updateGame() { switch(gameState) { case Game::MENU: drawMenu(); break; case Game::OPTIONS: drawOptions(); break; case Game::STARTED: drawGame(); break; case Game::OVER: gameOver(); break; case Game::ENDED: renderWindow.close(); return; break; } } void Game::drawMenu() { gameName.setFont(font); gameName.setString("SFML Snake"); gameName.setCharacterSize(80); gameName.setPosition(SCREEN_WIDTH/2-gameName.getGlobalBounds().width/2,150); menuStrings[0].setFont(font); menuStrings[0].setString("Start Game"); menuStrings[0].setCharacterSize(40); menuStrings[0].setPosition(SCREEN_WIDTH/2-menuStrings[0].getGlobalBounds().width/2,250); menuStrings[1].setFont(font); menuStrings[1].setString("Options"); menuStrings[1].setCharacterSize(40); menuStrings[1].setPosition(SCREEN_WIDTH/2-menuStrings[1].getGlobalBounds().width/2,300); menuStrings[2].setFont(font); menuStrings[2].setString("Exit"); menuStrings[2].setCharacterSize(40); menuStrings[2].setPosition(SCREEN_WIDTH/2-menuStrings[2].getGlobalBounds().width/2,350); Event event; while(gameState == Game::MENU) { Vector2f mouse(Mouse::getPosition(renderWindow)); while(renderWindow.pollEvent(event)) { //Exit after clicking X on window if(event.type == Event::Closed) gameState = ENDED; //Go to game, options or exit when user selects option in menu if(event.type == Event::MouseButtonReleased) { if(menuStrings[0].getGlobalBounds().contains(mouse) && event.mouseButton.button == Mouse::Left) gameState = STARTED; if(menuStrings[1].getGlobalBounds().contains(mouse) && event.mouseButton.button == Mouse::Left) gameState = OPTIONS; if(menuStrings[2].getGlobalBounds().contains(mouse) && event.mouseButton.button == Mouse::Left) gameState = ENDED; } } renderWindow.clear(); renderWindow.draw(gameName); for(int i = 0; i < 3; i++) renderWindow.draw(menuStrings[i]); for(int i = 0; i < 3; i++) if(menuStrings[i].getGlobalBounds().contains(mouse)) menuStrings[i].setFillColor(Color::Green); else menuStrings[i].setFillColor(Color::White); renderWindow.display(); } updateGame(); } void Game::drawOptions() { optionsStrings[0].setString("OPTIONS"); optionsStrings[1].setString("Snake speed"); optionsStrings[2].setString("Can walk through border"); optionsStrings[3].setString("Generate random wall"); optionsStrings[4].setString("Back"); optionsStrings[5].setString("Slow"); optionsStrings[6].setString("Fast"); optionsStrings[0].setFont(font); optionsStrings[0].setCharacterSize(80); optionsStrings[0].setPosition(SCREEN_WIDTH/2-optionsStrings[0].getGlobalBounds().width/2, 50); //Draw strings for(int i = 1; i < 5; i++) { optionsStrings[i].setFont(font); optionsStrings[i].setCharacterSize(40); optionsStrings[i].setPosition(SCREEN_WIDTH/2-optionsStrings[i].getGlobalBounds().width/2, 100+100*i); } //Set 'Slow' string optionsStrings[5].setFont(font); optionsStrings[5].setCharacterSize(40); optionsStrings[5].setPosition(SCREEN_WIDTH/2-optionsStrings[5].getGlobalBounds().width, 240); //Set 'Fast' string optionsStrings[6].setFont(font); optionsStrings[6].setCharacterSize(40); optionsStrings[6].setPosition(SCREEN_WIDTH/2+optionsStrings[5].getGlobalBounds().width/4, 240); //Set checkboxes borderCheckbox.setSize(Vector2f(20,20)); borderCheckbox.setOutlineColor(Color::Red); borderCheckbox.setFillColor(Color::Black); borderCheckbox.setOutlineThickness(5); borderCheckbox.setPosition(SCREEN_WIDTH/2, 350); wallsCheckbox.setSize(Vector2f(20,20)); wallsCheckbox.setOutlineColor(Color::Red); wallsCheckbox.setFillColor(Color::Black); wallsCheckbox.setOutlineThickness(5); wallsCheckbox.setPosition(SCREEN_WIDTH/2, 450); Event event; while(gameState == Game::OPTIONS) { Vector2f mouse(Mouse::getPosition(renderWindow)); while(renderWindow.pollEvent(event)) { //Back to menu after selecting "Back" in options if(event.type == Event::MouseButtonReleased) if(optionsStrings[4].getGlobalBounds().contains(mouse) && event.mouseButton.button == Mouse::Left) gameState = MENU; //Back to menu when Escape pressed if(event.type == Event::KeyPressed && event.key.code == Keyboard::Escape) gameState = MENU; //Exit game after clicking X on window if(event.type == Event::Closed) gameState = ENDED; //Set slow snake speed after selecting it if(event.type == Event::MouseButtonReleased) if(optionsStrings[5].getGlobalBounds().contains(mouse) && event.mouseButton.button == Mouse::Left && snakeFast) snakeFast = false; //Set fast snake speed after selecting it if(event.type == Event::MouseButtonReleased) if(optionsStrings[6].getGlobalBounds().contains(mouse) && event.mouseButton.button == Mouse::Left && !snakeFast) snakeFast = true; //Set right flag after choosing checkbox if(event.type == Event::MouseButtonReleased) if(borderCheckbox.getGlobalBounds().contains(mouse)) { if(!canWalkBorder) canWalkBorder = true; else canWalkBorder = false; } if(event.type == Event::MouseButtonReleased) if(wallsCheckbox.getGlobalBounds().contains(mouse)) { if(!generateWalls) generateWalls = true; else generateWalls = false; } } if(optionsStrings[4].getGlobalBounds().contains(mouse)) //Change 'Back' string color to green on mouse hover optionsStrings[4].setFillColor(Color::Green); else optionsStrings[4].setFillColor(Color::White); //Highlight string on mouse hover when it is not choosen (yellow) if(optionsStrings[5].getGlobalBounds().contains(mouse) && snakeFast) optionsStrings[5].setFillColor(Color::Green); else optionsStrings[5].setFillColor(Color::White); //Same as before if(optionsStrings[6].getGlobalBounds().contains(mouse) && !snakeFast) optionsStrings[6].setFillColor(Color::Green); else optionsStrings[6].setFillColor(Color::White); //Highlight choosen option in Snake speed if(!snakeFast) optionsStrings[5].setFillColor(Color::Yellow); else optionsStrings[6].setFillColor(Color::Yellow); //Mark or unmark checkbox if(canWalkBorder) borderCheckbox.setFillColor(Color::Yellow); else borderCheckbox.setFillColor(Color::Black); if(generateWalls) wallsCheckbox.setFillColor(Color::Yellow); else wallsCheckbox.setFillColor(Color::Black); renderWindow.clear(); for(int i = 0; i < 7; i++) renderWindow.draw(optionsStrings[i]); renderWindow.draw(borderCheckbox); renderWindow.draw(wallsCheckbox); renderWindow.display(); } updateGame(); } void Game::gameOver() { for(int i = 0; i < 4; i++) { gameOverStrings[i].setFont(font); gameOverStrings[i].setFillColor(Color::White); } //Game over string gameOverStrings[0].setString("Game Over!"); gameOverStrings[0].setCharacterSize(80); gameOverStrings[0].setPosition(SCREEN_WIDTH/2-gameOverStrings[0].getGlobalBounds().width/2,150); gameOverStrings[0].setFillColor(Color::Red); ostringstream buffer; pointsText = "Your points: "; buffer << points; pointsText += buffer.str(); gameOverStrings[1].setCharacterSize(40); gameOverStrings[1].setString(pointsText); gameOverStrings[1].setPosition(SCREEN_WIDTH/2-gameOverStrings[1].getGlobalBounds().width/2,240); //Clear buffer buffer.str(""); buffer.clear(); pointsText = "Your time: "; buffer << playTime; pointsText += buffer.str(); pointsText += "s"; gameOverStrings[2].setCharacterSize(40); gameOverStrings[2].setString(pointsText); gameOverStrings[2].setPosition(SCREEN_WIDTH/2-gameOverStrings[1].getGlobalBounds().width/2,280); buffer.str(""); buffer.clear(); gameOverStrings[3].setString("Back to menu"); gameOverStrings[3].setCharacterSize(40); gameOverStrings[3].setPosition(SCREEN_WIDTH/2-gameOverStrings[3].getGlobalBounds().width/2,340); Event event; while(gameState == Game::OVER) { Vector2f mouse(Mouse::getPosition(renderWindow)); while(renderWindow.pollEvent(event)) { if(event.type == Event::Closed) gameState = ENDED; if(event.type == Event::KeyPressed && event.key.code == Keyboard::Escape) gameState = MENU; if(event.type == Event::MouseButtonReleased) if(event.mouseButton.button == Mouse::Left && gameOverStrings[3].getGlobalBounds().contains(mouse)) gameState = MENU; } if(gameOverStrings[3].getGlobalBounds().contains(mouse)) gameOverStrings[3].setFillColor(Color::Green); else gameOverStrings[3].setFillColor(Color::White); renderWindow.clear(); for(int i = 0; i < 4; i++) renderWindow.draw(gameOverStrings[i]); renderWindow.display(); } updateGame(); } void Game::drawGame() { Snake snake(SCREEN_WIDTH/2/SNAKE_SIZE, SCREEN_HEIGHT/2/SNAKE_SIZE, SCREEN_WIDTH, SCREEN_HEIGHT, canWalkBorder); //Create snake in center of the window Food food(SCREEN_WIDTH, SCREEN_HEIGHT, SNAKE_SIZE); //Draw border - it's a big reactangle with transparent fill gameBorder.setPosition(SNAKE_SIZE,SNAKE_SIZE); gameBorder.setSize(Vector2f(SCREEN_WIDTH-SNAKE_SIZE*2, SCREEN_HEIGHT-SNAKE_SIZE*2)); gameBorder.setFillColor(Color::Black); gameBorder.setOutlineThickness(3); gameBorder.setOutlineColor(Color::Red); snakePoints.setFont(font); snakePoints.setCharacterSize(20); snakePoints.setPosition(SNAKE_SIZE,0); gameTime.setFont(font); gameTime.setCharacterSize(20); gameTime.setPosition(SNAKE_SIZE+150,0); pauseString.setFont(font); pauseString.setCharacterSize(30); pauseString.setFillColor(Color::Magenta); pauseString.setPosition(SNAKE_SIZE+5, SCREEN_HEIGHT/2); pauseString.setString("Game paused (press P to continue)"); points = 0; ostringstream sstreamBuffer; Clock playClock; float elapsedPauseTime = 0; Clock gameClock; float elapsedGameTime = 0.0f; float timeStep; Clock pauseTime; if(!snakeFast) timeStep = 0.35f; //Lower update time means faster snake movement else timeStep = 0.15f; Event event; bool directionChanged = true; while(gameState == Game::STARTED) { while(renderWindow.pollEvent(event)) { if(event.type == Event::KeyPressed && event.key.code == Keyboard::Escape) gameState=MENU; if(event.type == Event::Closed) gameState=ENDED; if(event.type == Event::KeyPressed && event.key.code == Keyboard::P) { if(!gamePaused) { gamePaused = true; pauseTime.restart(); } else { gamePaused = false; elapsedGameTime -= pauseTime.getElapsedTime().asSeconds(); elapsedPauseTime += pauseTime.getElapsedTime().asSeconds(); } } } if(Keyboard::isKeyPressed(Keyboard::Left) && directionChanged && !gamePaused) { snake.setDirection(Snake::LEFT); directionChanged = false; } if(Keyboard::isKeyPressed(Keyboard::Right) && directionChanged && !gamePaused) { snake.setDirection(Snake::RIGHT); directionChanged = false; } if(Keyboard::isKeyPressed(Keyboard::Up) && directionChanged && !gamePaused) { snake.setDirection(Snake::UP); directionChanged = false; } if(Keyboard::isKeyPressed(Keyboard::Down) && directionChanged && !gamePaused) { snake.setDirection(Snake::DOWN); directionChanged = false; } elapsedGameTime += gameClock.restart().asSeconds(); //Dont update game when it's paused while(elapsedGameTime > timeStep && !gamePaused) { //If snake movement fails over game if(!snake.moveSnake()) gameState = OVER; directionChanged = true; elapsedGameTime -= timeStep; } if(snake.getX() == food.getFoodX() && snake.getY() == food.getFoodY()) { points++; snake.addSegment(food.getFoodX(), food.getFoodY()); food.generateNewFood(); } //Convert int to string by ostringstream, prepare text and set sf::Text pointsText = "Points: "; sstreamBuffer << points; pointsText += sstreamBuffer.str(); snakePoints.setString(pointsText); //Clear buffer sstreamBuffer.str(""); sstreamBuffer.clear(); timeText = "Time: "; //Dont update time when game is paused if(!gamePaused) playTime = playClock.getElapsedTime().asSeconds() - elapsedPauseTime; sstreamBuffer << playTime; timeText += sstreamBuffer.str(); gameTime.setString(timeText); sstreamBuffer.str(""); sstreamBuffer.clear(); renderWindow.clear(); renderWindow.draw(gameBorder); renderWindow.draw(snakePoints); renderWindow.draw(gameTime); snake.drawSnake(renderWindow); food.drawFood(renderWindow); if(gamePaused) renderWindow.draw(pauseString); renderWindow.display(); } updateGame(); } <|endoftext|>
<commit_before>/***************************************************************************** * Help.cpp : Help and About dialogs **************************************************************************** * Copyright (C) 2007 the VideoLAN team * $Id$ * * Authors: Jean-Baptiste Kempf <jb (at) videolan.org> * Rémi Duraffort <ivoire (at) via.ecp.fr> * * 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. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_common.h> #include "dialogs/help.hpp" #include <vlc_about.h> #ifdef UPDATE_CHECK #include <vlc_update.h> #endif #include "dialogs_provider.hpp" #include <vlc_intf_strings.h> #include <QTextBrowser> #include <QTabWidget> #include <QFile> #include <QLabel> #include <QString> #include <QDialogButtonBox> #include <QEvent> #include <QFileDialog> #include <QDate> HelpDialog *HelpDialog::instance = NULL; HelpDialog::HelpDialog( intf_thread_t *_p_intf ) : QVLCFrame( _p_intf ) { setWindowTitle( qtr( "Help" ) ); setMinimumSize( 250, 300 ); QGridLayout *layout = new QGridLayout( this ); QTextBrowser *helpBrowser = new QTextBrowser( this ); helpBrowser->setOpenExternalLinks( true ); helpBrowser->setHtml( I_LONGHELP ); QPushButton *closeButton = new QPushButton( qtr( "&Close" ) ); closeButton->setDefault( true ); layout->addWidget( helpBrowser, 0, 0, 1, 0 ); layout->addWidget( closeButton, 1, 3 ); BUTTONACT( closeButton, close() ); readSettings( "Help", QSize( 400, 450 ) ); } HelpDialog::~HelpDialog() { writeSettings( "Help" ); } void HelpDialog::close() { toggleVisible(); } AboutDialog *AboutDialog::instance = NULL; AboutDialog::AboutDialog( QWidget *parent, intf_thread_t *_p_intf) : QVLCDialog( parent, _p_intf ) { setWindowTitle( qtr( "About" ) ); resize( 600, 500 ); setMinimumSize( 600, 500 ); QGridLayout *layout = new QGridLayout( this ); QTabWidget *tab = new QTabWidget( this ); QPushButton *closeButton = new QPushButton( qtr( "&Close" ) ); closeButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); closeButton->setDefault( true ); QLabel *introduction = new QLabel( qtr( "VLC media player" " " VERSION_MESSAGE ) ); QLabel *iconVLC = new QLabel; if( QDate::currentDate().dayOfYear() >= 354 ) iconVLC->setPixmap( QPixmap( ":/vlc48-christmas.png" ) ); else iconVLC->setPixmap( QPixmap( ":/vlc48.png" ) ); layout->addWidget( iconVLC, 0, 0, 1, 1 ); layout->addWidget( introduction, 0, 1, 1, 7 ); layout->addWidget( tab, 1, 0, 1, 8 ); layout->addWidget( closeButton, 2, 6, 1, 2 ); /* Main Introduction */ QWidget *infoWidget = new QWidget( this ); QHBoxLayout *infoLayout = new QHBoxLayout( infoWidget ); QLabel *infoLabel = new QLabel( qtr( "VLC media player is a free media player, " "encoder and streamer that can read from files, " "CDs, DVDs, network streams, capture cards and even more!\n" "VLC uses its internal codecs and works on essentially every " "popular platform.\n\n" ) + qtr( "This version of VLC was compiled by:\n " ) + qfu( VLC_CompileBy() )+ "@" + qfu( VLC_CompileHost() ) + "." + qfu( VLC_CompileDomain() ) + ".\n" + "Compiler: " + qfu( VLC_Compiler() ) + ".\n" + qtr( "Based on Git commit: " ) + qfu( VLC_Changeset() ) + ".\n" + qtr( "You are using the Qt4 Interface.\n\n" ) + qtr( "Copyright (C) " COPYRIGHT_YEARS " by the VideoLAN Team.\n" ) + "vlc@videolan.org, http://www.videolan.org" ); infoLabel->setWordWrap( infoLabel ); QLabel *iconVLC2 = new QLabel; if( QDate::currentDate().dayOfYear() >= 354 ) iconVLC2->setPixmap( QPixmap( ":/vlc128-christmas.png" ) ); else iconVLC2->setPixmap( QPixmap( ":/vlc128.png" ) ); infoLayout->addWidget( iconVLC2 ); infoLayout->addWidget( infoLabel ); /* GPL License */ QTextEdit *licenseEdit = new QTextEdit( this ); licenseEdit->setText( qfu( psz_license ) ); licenseEdit->setReadOnly( true ); /* People who helped */ QWidget *thanksWidget = new QWidget( this ); QVBoxLayout *thanksLayout = new QVBoxLayout( thanksWidget ); QLabel *thanksLabel = new QLabel( qtr( "We would like to thank the whole " "VLC community, the testers, our users and the following people " "(and the missing ones...) for their collaboration to " "create the best free software." ) ); thanksLabel->setWordWrap( true ); thanksLayout->addWidget( thanksLabel ); QTextEdit *thanksEdit = new QTextEdit( this ); thanksEdit->setText( qfu( psz_thanks ) ); thanksEdit->setReadOnly( true ); thanksLayout->addWidget( thanksEdit ); /* People who wrote the software */ QTextEdit *authorsEdit = new QTextEdit( this ); authorsEdit->setText( qfu( psz_authors ) ); authorsEdit->setReadOnly( true ); /* add the tabs to the Tabwidget */ tab->addTab( infoWidget, qtr( "About" ) ); tab->addTab( authorsEdit, qtr( "Authors" ) ); tab->addTab( thanksWidget, qtr("Thanks") ); tab->addTab( licenseEdit, qtr("License") ); BUTTONACT( closeButton, close() ); } AboutDialog::~AboutDialog() { } void AboutDialog::close() { toggleVisible(); } #ifdef UPDATE_CHECK /***************************************************************************** * UpdateDialog *****************************************************************************/ /* callback to get information from the core */ static void UpdateCallback( void *data, bool b_ret ) { UpdateDialog* UDialog = (UpdateDialog *)data; QEvent* event; if( b_ret ) event = new QEvent( (QEvent::Type)UDOkEvent ); else event = new QEvent( (QEvent::Type)UDErrorEvent ); QApplication::postEvent( UDialog, event ); } UpdateDialog *UpdateDialog::instance = NULL; UpdateDialog::UpdateDialog( intf_thread_t *_p_intf ) : QVLCFrame( _p_intf ) { setWindowTitle( qtr( "Update" ) ); QGridLayout *layout = new QGridLayout( this ); QPushButton *closeButton = new QPushButton( qtr( "&Close" ) ); updateButton = new QPushButton( qtr( "&Update List" ) ); updateButton->setDefault( true ); QDialogButtonBox *buttonBox = new QDialogButtonBox( Qt::Horizontal ); buttonBox->addButton( updateButton, QDialogButtonBox::ActionRole ); buttonBox->addButton( closeButton, QDialogButtonBox::AcceptRole ); updateLabel = new QLabel( qtr( "Checking for an update..." ) ); updateLabel->setWordWrap( true ); layout->addWidget( updateLabel, 0, 0 ); layout->addWidget( buttonBox, 1, 0 ); BUTTONACT( updateButton, UpdateOrDownload() ); BUTTONACT( closeButton, close() ); /* Create the update structure */ p_update = update_New( p_intf ); b_checked = false; readSettings( "Update", QSize( 120, 80 ) ); /* Check for updates */ UpdateOrDownload(); } UpdateDialog::~UpdateDialog() { update_Delete( p_update ); writeSettings( "Update" ); } void UpdateDialog::close() { toggleVisible(); } /* Check for updates */ void UpdateDialog::UpdateOrDownload() { if( !b_checked ) { updateButton->setEnabled( false ); msg_Dbg( p_intf, "Launching an update request" ); update_Check( p_update, UpdateCallback, this ); } else { updateButton->setEnabled( false ); QString dest_dir = QFileDialog::getExistingDirectory( this, qtr( "Select a directory..." ), qfu( config_GetHomeDir() ) ); if( dest_dir != "" ) { toggleVisible(); update_Download( p_update, qtu( dest_dir ) ); } else updateButton->setEnabled( true ); } } /* Handle the events */ void UpdateDialog::customEvent( QEvent *event ) { if( event->type() == UDOkEvent ) updateNotify( true ); else updateNotify( false ); } /* Notify the end of the update_Check */ void UpdateDialog::updateNotify( bool b_result ) { /* The update finish without errors */ if( b_result ) { if( update_NeedUpgrade( p_update ) ) { update_release_t *p_release = update_GetRelease( p_update ); assert( p_release ); b_checked = true; updateButton->setText( "Download" ); updateLabel->setText( qtr( "There is a new version of VLC :\n" ) + qfu( p_release->psz_desc ) ); /* Force the dialog to be shown */ this->show(); } else updateLabel->setText( qtr( "You have the latest version of VLC" ) ); } else updateLabel->setText( qtr( "An error occurred while checking for updates" ) ); adjustSize(); updateButton->setEnabled( true ); } #endif <commit_msg>Add a DIR_SEP to the download folder. Close #1776<commit_after>/***************************************************************************** * Help.cpp : Help and About dialogs **************************************************************************** * Copyright (C) 2007 the VideoLAN team * $Id$ * * Authors: Jean-Baptiste Kempf <jb (at) videolan.org> * Rémi Duraffort <ivoire (at) via.ecp.fr> * * 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. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_common.h> #include "dialogs/help.hpp" #include <vlc_about.h> #ifdef UPDATE_CHECK #include <vlc_update.h> #endif #include "dialogs_provider.hpp" #include <vlc_intf_strings.h> #include <QTextBrowser> #include <QTabWidget> #include <QFile> #include <QLabel> #include <QString> #include <QDialogButtonBox> #include <QEvent> #include <QFileDialog> #include <QDate> HelpDialog *HelpDialog::instance = NULL; HelpDialog::HelpDialog( intf_thread_t *_p_intf ) : QVLCFrame( _p_intf ) { setWindowTitle( qtr( "Help" ) ); setMinimumSize( 250, 300 ); QGridLayout *layout = new QGridLayout( this ); QTextBrowser *helpBrowser = new QTextBrowser( this ); helpBrowser->setOpenExternalLinks( true ); helpBrowser->setHtml( I_LONGHELP ); QPushButton *closeButton = new QPushButton( qtr( "&Close" ) ); closeButton->setDefault( true ); layout->addWidget( helpBrowser, 0, 0, 1, 0 ); layout->addWidget( closeButton, 1, 3 ); BUTTONACT( closeButton, close() ); readSettings( "Help", QSize( 400, 450 ) ); } HelpDialog::~HelpDialog() { writeSettings( "Help" ); } void HelpDialog::close() { toggleVisible(); } AboutDialog *AboutDialog::instance = NULL; AboutDialog::AboutDialog( QWidget *parent, intf_thread_t *_p_intf) : QVLCDialog( parent, _p_intf ) { setWindowTitle( qtr( "About" ) ); resize( 600, 500 ); setMinimumSize( 600, 500 ); QGridLayout *layout = new QGridLayout( this ); QTabWidget *tab = new QTabWidget( this ); QPushButton *closeButton = new QPushButton( qtr( "&Close" ) ); closeButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); closeButton->setDefault( true ); QLabel *introduction = new QLabel( qtr( "VLC media player" " " VERSION_MESSAGE ) ); QLabel *iconVLC = new QLabel; if( QDate::currentDate().dayOfYear() >= 354 ) iconVLC->setPixmap( QPixmap( ":/vlc48-christmas.png" ) ); else iconVLC->setPixmap( QPixmap( ":/vlc48.png" ) ); layout->addWidget( iconVLC, 0, 0, 1, 1 ); layout->addWidget( introduction, 0, 1, 1, 7 ); layout->addWidget( tab, 1, 0, 1, 8 ); layout->addWidget( closeButton, 2, 6, 1, 2 ); /* Main Introduction */ QWidget *infoWidget = new QWidget( this ); QHBoxLayout *infoLayout = new QHBoxLayout( infoWidget ); QLabel *infoLabel = new QLabel( qtr( "VLC media player is a free media player, " "encoder and streamer that can read from files, " "CDs, DVDs, network streams, capture cards and even more!\n" "VLC uses its internal codecs and works on essentially every " "popular platform.\n\n" ) + qtr( "This version of VLC was compiled by:\n " ) + qfu( VLC_CompileBy() )+ "@" + qfu( VLC_CompileHost() ) + "." + qfu( VLC_CompileDomain() ) + ".\n" + "Compiler: " + qfu( VLC_Compiler() ) + ".\n" + qtr( "Based on Git commit: " ) + qfu( VLC_Changeset() ) + ".\n" + qtr( "You are using the Qt4 Interface.\n\n" ) + qtr( "Copyright (C) " COPYRIGHT_YEARS " by the VideoLAN Team.\n" ) + "vlc@videolan.org, http://www.videolan.org" ); infoLabel->setWordWrap( infoLabel ); QLabel *iconVLC2 = new QLabel; if( QDate::currentDate().dayOfYear() >= 354 ) iconVLC2->setPixmap( QPixmap( ":/vlc128-christmas.png" ) ); else iconVLC2->setPixmap( QPixmap( ":/vlc128.png" ) ); infoLayout->addWidget( iconVLC2 ); infoLayout->addWidget( infoLabel ); /* GPL License */ QTextEdit *licenseEdit = new QTextEdit( this ); licenseEdit->setText( qfu( psz_license ) ); licenseEdit->setReadOnly( true ); /* People who helped */ QWidget *thanksWidget = new QWidget( this ); QVBoxLayout *thanksLayout = new QVBoxLayout( thanksWidget ); QLabel *thanksLabel = new QLabel( qtr( "We would like to thank the whole " "VLC community, the testers, our users and the following people " "(and the missing ones...) for their collaboration to " "create the best free software." ) ); thanksLabel->setWordWrap( true ); thanksLayout->addWidget( thanksLabel ); QTextEdit *thanksEdit = new QTextEdit( this ); thanksEdit->setText( qfu( psz_thanks ) ); thanksEdit->setReadOnly( true ); thanksLayout->addWidget( thanksEdit ); /* People who wrote the software */ QTextEdit *authorsEdit = new QTextEdit( this ); authorsEdit->setText( qfu( psz_authors ) ); authorsEdit->setReadOnly( true ); /* add the tabs to the Tabwidget */ tab->addTab( infoWidget, qtr( "About" ) ); tab->addTab( authorsEdit, qtr( "Authors" ) ); tab->addTab( thanksWidget, qtr("Thanks") ); tab->addTab( licenseEdit, qtr("License") ); BUTTONACT( closeButton, close() ); } AboutDialog::~AboutDialog() { } void AboutDialog::close() { toggleVisible(); } #ifdef UPDATE_CHECK /***************************************************************************** * UpdateDialog *****************************************************************************/ /* callback to get information from the core */ static void UpdateCallback( void *data, bool b_ret ) { UpdateDialog* UDialog = (UpdateDialog *)data; QEvent* event; if( b_ret ) event = new QEvent( (QEvent::Type)UDOkEvent ); else event = new QEvent( (QEvent::Type)UDErrorEvent ); QApplication::postEvent( UDialog, event ); } UpdateDialog *UpdateDialog::instance = NULL; UpdateDialog::UpdateDialog( intf_thread_t *_p_intf ) : QVLCFrame( _p_intf ) { setWindowTitle( qtr( "Update" ) ); QGridLayout *layout = new QGridLayout( this ); QPushButton *closeButton = new QPushButton( qtr( "&Close" ) ); updateButton = new QPushButton( qtr( "&Update List" ) ); updateButton->setDefault( true ); QDialogButtonBox *buttonBox = new QDialogButtonBox( Qt::Horizontal ); buttonBox->addButton( updateButton, QDialogButtonBox::ActionRole ); buttonBox->addButton( closeButton, QDialogButtonBox::AcceptRole ); updateLabel = new QLabel( qtr( "Checking for an update..." ) ); updateLabel->setWordWrap( true ); layout->addWidget( updateLabel, 0, 0 ); layout->addWidget( buttonBox, 1, 0 ); BUTTONACT( updateButton, UpdateOrDownload() ); BUTTONACT( closeButton, close() ); /* Create the update structure */ p_update = update_New( p_intf ); b_checked = false; readSettings( "Update", QSize( 120, 80 ) ); /* Check for updates */ UpdateOrDownload(); } UpdateDialog::~UpdateDialog() { update_Delete( p_update ); writeSettings( "Update" ); } void UpdateDialog::close() { toggleVisible(); } /* Check for updates */ void UpdateDialog::UpdateOrDownload() { if( !b_checked ) { updateButton->setEnabled( false ); msg_Dbg( p_intf, "Launching an update request" ); update_Check( p_update, UpdateCallback, this ); } else { updateButton->setEnabled( false ); QString dest_dir = QFileDialog::getExistingDirectory( this, qtr( "Select a directory..." ), qfu( config_GetHomeDir() ) ); if( dest_dir != "" ) { #if defined( WIN32 ) || defined( UNDER_CE ) dest_dir += DIR_SEP; #endif msg_Dbg( p_intf, "Downloading to folder: %s", dest_dir ); toggleVisible(); update_Download( p_update, qtu( dest_dir ) ); } else updateButton->setEnabled( true ); } } /* Handle the events */ void UpdateDialog::customEvent( QEvent *event ) { if( event->type() == UDOkEvent ) updateNotify( true ); else updateNotify( false ); } /* Notify the end of the update_Check */ void UpdateDialog::updateNotify( bool b_result ) { /* The update finish without errors */ if( b_result ) { if( update_NeedUpgrade( p_update ) ) { update_release_t *p_release = update_GetRelease( p_update ); assert( p_release ); b_checked = true; updateButton->setText( "Download" ); updateLabel->setText( qtr( "There is a new version of VLC :\n" ) + qfu( p_release->psz_desc ) ); /* Force the dialog to be shown */ this->show(); } else updateLabel->setText( qtr( "You have the latest version of VLC" ) ); } else updateLabel->setText( qtr( "An error occurred while checking for updates" ) ); adjustSize(); updateButton->setEnabled( true ); } #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: b3ivector.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-07 20:55:03 $ * * 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_VECTOR_B3IVECTOR_HXX #include <basegfx/vector/b3ivector.hxx> #endif #ifndef _BGFX_MATRIX_B3DHOMMATRIX_HXX #include <basegfx/matrix/b3dhommatrix.hxx> #endif namespace basegfx { B3IVector& B3IVector::operator*=( const B3DHomMatrix& rMat ) { mnX = fround( rMat.get(0,0)*mnX + rMat.get(0,1)*mnY + rMat.get(0,2)*mnZ ); mnY = fround( rMat.get(1,0)*mnX + rMat.get(1,1)*mnY + rMat.get(1,2)*mnZ ); mnZ = fround( rMat.get(2,0)*mnX + rMat.get(2,1)*mnY + rMat.get(2,2)*mnZ ); return *this; } B3IVector operator*( const B3DHomMatrix& rMat, const B3IVector& rVec ) { B3IVector aRes( rVec ); return aRes*=rMat; } } // end of namespace basegfx // eof <commit_msg>INTEGRATION: CWS pchfix02 (1.2.36); FILE MERGED 2006/09/01 17:16:41 kaib 1.2.36.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: b3ivector.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-09-17 08:08: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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_basegfx.hxx" #ifndef _BGFX_VECTOR_B3IVECTOR_HXX #include <basegfx/vector/b3ivector.hxx> #endif #ifndef _BGFX_MATRIX_B3DHOMMATRIX_HXX #include <basegfx/matrix/b3dhommatrix.hxx> #endif namespace basegfx { B3IVector& B3IVector::operator*=( const B3DHomMatrix& rMat ) { mnX = fround( rMat.get(0,0)*mnX + rMat.get(0,1)*mnY + rMat.get(0,2)*mnZ ); mnY = fround( rMat.get(1,0)*mnX + rMat.get(1,1)*mnY + rMat.get(1,2)*mnZ ); mnZ = fround( rMat.get(2,0)*mnX + rMat.get(2,1)*mnY + rMat.get(2,2)*mnZ ); return *this; } B3IVector operator*( const B3DHomMatrix& rMat, const B3IVector& rVec ) { B3IVector aRes( rVec ); return aRes*=rMat; } } // end of namespace basegfx // eof <|endoftext|>
<commit_before>// illarionserver - server for the game Illarion // Copyright 2011 Illarion e.V. // // This file is part of illarionserver. // // illarionserver 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. // // illarionserver 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 illarionserver. If not, see <http://www.gnu.org/licenses/>. #include "Item.hpp" #include "data/CommonObjectTable.hpp" #include "data/ContainerObjectTable.hpp" #include <sstream> #include <boost/lexical_cast.hpp> extern CommonObjectTable *CommonItems; extern ContainerObjectTable *ContainerItems; Item::Item(id_type id, number_type number, wear_type wear, quality_type quality, const luabind::object &datamap): id(id), number(number), wear(wear), quality(quality), datamap(1) { setData(datamap); } Item::number_type Item::increaseNumberBy(Item::number_type count) { CommonStruct common; if (CommonItems->find(id, common)) { count += getNumber(); if (count >= common.MaxStack) { setNumber(common.MaxStack); count -= common.MaxStack; } else { setNumber(count); count = 0; } } return count; } void Item::setMinQuality(const Item &item) { quality_type minQuality = (quality < item.quality) ? quality : item.quality; minQuality /= 100; quality_type minDurability = (getDurability() < item.getDurability()) ? getDurability() : item.getDurability(); quality = minQuality * 100 + minDurability; } void Item::setData(const luabind::object &datamap) { using namespace luabind; auto mapType = type(datamap); if (mapType == LUA_TTABLE) { for (iterator it(datamap), end; it != end; ++it) { std::string key; try { key = object_cast<std::string>(it.key()); } catch (cast_failed &e) { throw std::logic_error("Usage of invalid data map key. Data map keys must be strings."); } try { std::string value = object_cast<std::string>(*it); setData(key, value); } catch (cast_failed &e) { try { int32_t intValue = object_cast<int32_t>(*it); setData(key, intValue); } catch (cast_failed &e) { throw std::logic_error("Usage of invalid data map value. Data map values must be numbers or strings."); } } } } else if (mapType == LUA_TNIL) { this->datamap.clear(); } else { throw std::logic_error("Usage of invalid data map type. Data maps must be tables or nil."); } } bool Item::hasData(const luabind::object &datamap) { using namespace luabind; auto mapType = type(datamap); if (mapType == LUA_TTABLE) { bool isSameData = true; iterator it(datamap), end; if (it == end) { return hasNoData(); } for (; it != end && isSameData; ++it) { std::string key; try { key = object_cast<std::string>(it.key()); } catch (cast_failed &e) { throw std::logic_error("Usage of invalid data map key. Data map keys must be strings."); } std::string value; try { value = object_cast<std::string>(*it); } catch (cast_failed &e) { try { int32_t intValue = object_cast<int32_t>(*it); std::stringstream ss; ss << intValue; value = ss.str(); } catch (cast_failed &e) { throw std::logic_error("Usage of invalid data map value. Data map values must be numbers or strings."); } } isSameData = (getData(key) == value); } return isSameData; } else if (mapType != LUA_TNIL) { throw std::logic_error("Usage of invalid data map type. Data maps must be tables or nil."); } return true; } bool Item::hasNoData() const { return datamap.size() == 0; } std::string Item::getData(std::string key) { return datamap[key]; } void Item::setData(std::string key, std::string value) { datamap[key] = value; } void Item::setData(std::string key, int32_t value) { std::stringstream ss; ss << value; setData(key, ss.str()); } uint16_t Item::getDepot() { uint16_t depotId; try { depotId = boost::lexical_cast<uint16_t>(getData("depot")); } catch (boost::bad_lexical_cast) { depotId = 1; } return depotId; } void Item::reset() { id = 0; number = 0; wear = 0; quality = 333; datamap.clear(); } void Item::resetWear() { CommonStruct common; if (CommonItems->find(id, common)) { if (!common.rotsInInventory && common.AgeingSpeed > wear) { wear = common.AgeingSpeed; } } } void Item::save(std::ostream *obj) const { obj->write((char *) &id, sizeof(id_type)); obj->write((char *) &number, sizeof(number_type)); obj->write((char *) &wear, sizeof(wear_type)); obj->write((char *) &quality, sizeof(quality_type)); uint8_t mapsize = static_cast<uint8_t>(datamap.size()); obj->write((char *) &mapsize, sizeof(uint8_t)); for (auto it = datamap.begin(); it != datamap.end(); ++it) { uint8_t sz1 = static_cast<uint8_t>(it->first.size()); uint8_t sz2 = static_cast<uint8_t>(it->second.size()); obj->write((char *) &sz1 , sizeof(uint8_t)); obj->write((char *) &sz2 , sizeof(uint8_t)); obj->write((char *) it->first.data() , sz1); obj->write((char *) it->second.data() , sz2); } } void Item::load(std::istream *obj) { obj->read((char *) &id, sizeof(id_type)); obj->read((char *) &number, sizeof(number_type)); obj->read((char *) &wear, sizeof(wear_type)); obj->read((char *) &quality, sizeof(quality_type)); uint8_t tempsize; obj->read((char *) &tempsize, sizeof(uint8_t)); char readStr[255]; for (int i = 0; i < tempsize; ++i) { uint8_t sz1 = 0; uint8_t sz2 = 0; obj->read((char *) &sz1, sizeof(uint8_t)); obj->read((char *) &sz2, sizeof(uint8_t)); obj->read((char *) readStr, sz1); std::string key(readStr,sz1); obj->read((char *) readStr, sz2); std::string value(readStr,sz2); datamap[key] = value; } } bool Item::survivesAgeing() { if (wear != 255 && wear != 0) { --wear; } return wear > 0; } bool Item::isContainer() const { return ContainerItems->find(id); } TYPE_OF_WEIGHT Item::getWeight() const { CommonStruct common; if (CommonItems->find(id, common)) { return common.Weight; } return 0; } TYPE_OF_WORTH Item::getWorth() const { CommonStruct common; if (CommonItems->find(id, common)) { return common.Worth; } return 0; } Item::number_type Item::getMaxStack() const { CommonStruct common; if (CommonItems->find(id, common)) { return common.MaxStack; } return 0; } bool Item::isPermanent() const { return wear == PERMANENT_WEAR; } void Item::makePermanent() { wear = PERMANENT_WEAR; } <commit_msg>Treat empty data strings as missing data<commit_after>// illarionserver - server for the game Illarion // Copyright 2011 Illarion e.V. // // This file is part of illarionserver. // // illarionserver 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. // // illarionserver 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 illarionserver. If not, see <http://www.gnu.org/licenses/>. #include "Item.hpp" #include "data/CommonObjectTable.hpp" #include "data/ContainerObjectTable.hpp" #include <sstream> #include <boost/lexical_cast.hpp> extern CommonObjectTable *CommonItems; extern ContainerObjectTable *ContainerItems; Item::Item(id_type id, number_type number, wear_type wear, quality_type quality, const luabind::object &datamap): id(id), number(number), wear(wear), quality(quality), datamap(1) { setData(datamap); } Item::number_type Item::increaseNumberBy(Item::number_type count) { CommonStruct common; if (CommonItems->find(id, common)) { count += getNumber(); if (count >= common.MaxStack) { setNumber(common.MaxStack); count -= common.MaxStack; } else { setNumber(count); count = 0; } } return count; } void Item::setMinQuality(const Item &item) { quality_type minQuality = (quality < item.quality) ? quality : item.quality; minQuality /= 100; quality_type minDurability = (getDurability() < item.getDurability()) ? getDurability() : item.getDurability(); quality = minQuality * 100 + minDurability; } void Item::setData(const luabind::object &datamap) { using namespace luabind; auto mapType = type(datamap); if (mapType == LUA_TTABLE) { for (iterator it(datamap), end; it != end; ++it) { std::string key; try { key = object_cast<std::string>(it.key()); } catch (cast_failed &e) { throw std::logic_error("Usage of invalid data map key. Data map keys must be strings."); } try { std::string value = object_cast<std::string>(*it); setData(key, value); } catch (cast_failed &e) { try { int32_t intValue = object_cast<int32_t>(*it); setData(key, intValue); } catch (cast_failed &e) { throw std::logic_error("Usage of invalid data map value. Data map values must be numbers or strings."); } } } } else if (mapType == LUA_TNIL) { this->datamap.clear(); } else { throw std::logic_error("Usage of invalid data map type. Data maps must be tables or nil."); } } bool Item::hasData(const luabind::object &datamap) { using namespace luabind; auto mapType = type(datamap); if (mapType == LUA_TTABLE) { bool isSameData = true; iterator it(datamap), end; if (it == end) { return hasNoData(); } for (; it != end && isSameData; ++it) { std::string key; try { key = object_cast<std::string>(it.key()); } catch (cast_failed &e) { throw std::logic_error("Usage of invalid data map key. Data map keys must be strings."); } std::string value; try { value = object_cast<std::string>(*it); } catch (cast_failed &e) { try { int32_t intValue = object_cast<int32_t>(*it); std::stringstream ss; ss << intValue; value = ss.str(); } catch (cast_failed &e) { throw std::logic_error("Usage of invalid data map value. Data map values must be numbers or strings."); } } isSameData = (getData(key) == value); } return isSameData; } else if (mapType != LUA_TNIL) { throw std::logic_error("Usage of invalid data map type. Data maps must be tables or nil."); } return true; } bool Item::hasNoData() const { return datamap.size() == 0; } std::string Item::getData(std::string key) { return datamap[key]; } void Item::setData(std::string key, std::string value) { if (value.length() > 0) { datamap[key] = value; } else { datamap.erase(key); } } void Item::setData(std::string key, int32_t value) { std::stringstream ss; ss << value; setData(key, ss.str()); } uint16_t Item::getDepot() { uint16_t depotId; try { depotId = boost::lexical_cast<uint16_t>(getData("depot")); } catch (boost::bad_lexical_cast) { depotId = 1; } return depotId; } void Item::reset() { id = 0; number = 0; wear = 0; quality = 333; datamap.clear(); } void Item::resetWear() { CommonStruct common; if (CommonItems->find(id, common)) { if (!common.rotsInInventory && common.AgeingSpeed > wear) { wear = common.AgeingSpeed; } } } void Item::save(std::ostream *obj) const { obj->write((char *) &id, sizeof(id_type)); obj->write((char *) &number, sizeof(number_type)); obj->write((char *) &wear, sizeof(wear_type)); obj->write((char *) &quality, sizeof(quality_type)); uint8_t mapsize = static_cast<uint8_t>(datamap.size()); obj->write((char *) &mapsize, sizeof(uint8_t)); for (auto it = datamap.begin(); it != datamap.end(); ++it) { uint8_t sz1 = static_cast<uint8_t>(it->first.size()); uint8_t sz2 = static_cast<uint8_t>(it->second.size()); obj->write((char *) &sz1 , sizeof(uint8_t)); obj->write((char *) &sz2 , sizeof(uint8_t)); obj->write((char *) it->first.data() , sz1); obj->write((char *) it->second.data() , sz2); } } void Item::load(std::istream *obj) { obj->read((char *) &id, sizeof(id_type)); obj->read((char *) &number, sizeof(number_type)); obj->read((char *) &wear, sizeof(wear_type)); obj->read((char *) &quality, sizeof(quality_type)); uint8_t tempsize; obj->read((char *) &tempsize, sizeof(uint8_t)); char readStr[255]; for (int i = 0; i < tempsize; ++i) { uint8_t sz1 = 0; uint8_t sz2 = 0; obj->read((char *) &sz1, sizeof(uint8_t)); obj->read((char *) &sz2, sizeof(uint8_t)); obj->read((char *) readStr, sz1); std::string key(readStr,sz1); obj->read((char *) readStr, sz2); std::string value(readStr,sz2); datamap[key] = value; } } bool Item::survivesAgeing() { if (wear != 255 && wear != 0) { --wear; } return wear > 0; } bool Item::isContainer() const { return ContainerItems->find(id); } TYPE_OF_WEIGHT Item::getWeight() const { CommonStruct common; if (CommonItems->find(id, common)) { return common.Weight; } return 0; } TYPE_OF_WORTH Item::getWorth() const { CommonStruct common; if (CommonItems->find(id, common)) { return common.Worth; } return 0; } Item::number_type Item::getMaxStack() const { CommonStruct common; if (CommonItems->find(id, common)) { return common.MaxStack; } return 0; } bool Item::isPermanent() const { return wear == PERMANENT_WEAR; } void Item::makePermanent() { wear = PERMANENT_WEAR; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ImageRegionIteratorWithIndex.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // \index{Iterators!speed} // The ``WithIndex'' family of iterators was designed for algorithms that // depend on the image index locations of values they work with. Unlike // \doxygen{ImageRegionIterator}, which calculates an index only if and when // it is asked for, \doxygen{ImageRegionIteratorWithIndex} maintains its // index location as a member variable that is updated each time the iterator // is incremented or decremented. A penalty is therefore introduced on the // iteration speed, but the iterator is more efficient in cases where it is // heavily queried for the index. // // \index{itk::ImageRegionIteratorWithIndex!example of using|(} // // The following example illustrates the use of // \doxygen{ImageRegionIteratorWithIndex}. This algorithm mirrors // a 2D image across its $x$-axis (see \doxygen{FlipImageAxis} for an ND // version). The algorithm makes extensive use of the \code{GetIndex()} // method. // // Start by including the proper header file. // // Software Guide : EndLatex #include "itkImage.h" #include "itkRGBPixel.h" // Software Guide : BeginCodeSnippet #include "itkImageRegionIteratorWithIndex.h" // Software Guide : EndCodeSnippet #include "itkImageFileReader.h" #include "itkImageFileWriter.h" int main( int argc, char ** argv ) { // Verify the number of parameters on the command line. if ( argc < 3 ) { std::cerr << "Missing parameters. " << std::endl; std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " inputImageFile outputImageFile" << std::endl; return -1; } // Software Guide : BeginLatex // // For this example, we will use an RGB pixel type so that we can process color // images. Like most other ITK image iterator, // \doxygen{ImageRegionIteratorWithIndex} class expects the image type as its // single template parameter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const unsigned int Dimension = 2; typedef itk::RGBPixel< unsigned char > RGBPixelType; typedef itk::Image< RGBPixelType, Dimension > ImageType; typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType; // Software Guide : EndCodeSnippet typedef itk::ImageFileReader< ImageType > ReaderType; typedef itk::ImageFileWriter< ImageType > WriterType; ImageType::ConstPointer inputImage; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); try { reader->Update(); inputImage = reader->GetOutput(); } catch ( itk::ExceptionObject &err) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } // Software Guide : BeginLatex // // An \code{ImageType} smart pointer called \code{inputImage} points to the // output of the image reader. After updating the image reader, we can // allocate an output image of the same size, spacing, and origin as the // input image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ImageType::Pointer outputImage = ImageType::New(); outputImage->SetRegions( inputImage->GetRequestedRegion() ); outputImage->CopyInformation( inputImage ); outputImage->Allocate(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Next we create the iterator that walks the output image. Instead of using // an iterator on the input, we will copy the values directly using image // indicies. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet IteratorType outputIt( outputImage, outputImage->GetRequestedRegion() ); // Software Guide : EndCodeSnippet // Software Guide: BeginLatex // // This axis flipping algorithm works by iterating through the output image, querying // the iterator for its index, and copying the value from the input at an index // mirrored across the $x$-axis. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ImageType::IndexType requestedIndex = outputImage->GetRequestedRegion().GetIndex(); ImageType::SizeType requestedSize = outputImage->GetRequestedRegion().GetSize(); for ( outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++outputIt) { ImageType::IndexType idx = outputIt.GetIndex(); idx[0] = requestedIndex[0] + requestedSize[0] - idx[0]; outputIt.Set( inputImage->GetPixel(idx) ); } // Software Guide : EndCodeSnippet WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); writer->SetInput(outputImage); try { writer->Update(); } catch ( itk::ExceptionObject &err) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } // Software Guide : BeginLatex // // Let's run this example on the image \code{VisibleWomanEyeSlice.png} found in // the \code{Insight/Examples/Data} directory. // Figure~\ref{fig:ImageRegionIteratorWithIndexExample} shows how the original // image has been mirrored across its $x$-axis in the output. // // \begin{figure} \center // \includegraphics[width=4cm]{VisibleWomanEyeSlice.eps} // \includegraphics[width=4cm]{ImageRegionIteratorWithIndexOutput.eps} // \caption[Using the ImageRegionIteratorWithIndex]{Results of using ImageRegionIteratorWithIndex to mirror an image // across an axis. The original image is shown at left. The mirrored output is // shown at right.} // \label{fig:ImageRegionIteratorWithIndexExample} // \end{figure} // // \index{itk::ImageRegionIteratorWithIndex!example of using|)} // // Software Guide : EndLatex return 0; } <commit_msg>DOC: FlipImageAxis should be FlipImageFilter.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ImageRegionIteratorWithIndex.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // \index{Iterators!speed} // The ``WithIndex'' family of iterators was designed for algorithms that // depend on the image index locations of values they work with. Unlike // \doxygen{ImageRegionIterator}, which calculates an index only if and when // it is asked for, \doxygen{ImageRegionIteratorWithIndex} maintains its // index location as a member variable that is updated each time the iterator // is incremented or decremented. A penalty is therefore introduced on the // iteration speed, but the iterator is more efficient in cases where it is // heavily queried for the index. // // \index{itk::ImageRegionIteratorWithIndex!example of using|(} // // The following example illustrates the use of // \doxygen{ImageRegionIteratorWithIndex}. This algorithm mirrors // a 2D image across its $x$-axis (see \doxygen{FlipImageFilter} for an ND // version). The algorithm makes extensive use of the \code{GetIndex()} // method. // // Start by including the proper header file. // // Software Guide : EndLatex #include "itkImage.h" #include "itkRGBPixel.h" // Software Guide : BeginCodeSnippet #include "itkImageRegionIteratorWithIndex.h" // Software Guide : EndCodeSnippet #include "itkImageFileReader.h" #include "itkImageFileWriter.h" int main( int argc, char ** argv ) { // Verify the number of parameters on the command line. if ( argc < 3 ) { std::cerr << "Missing parameters. " << std::endl; std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " inputImageFile outputImageFile" << std::endl; return -1; } // Software Guide : BeginLatex // // For this example, we will use an RGB pixel type so that we can process color // images. Like most other ITK image iterator, // \doxygen{ImageRegionIteratorWithIndex} class expects the image type as its // single template parameter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const unsigned int Dimension = 2; typedef itk::RGBPixel< unsigned char > RGBPixelType; typedef itk::Image< RGBPixelType, Dimension > ImageType; typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType; // Software Guide : EndCodeSnippet typedef itk::ImageFileReader< ImageType > ReaderType; typedef itk::ImageFileWriter< ImageType > WriterType; ImageType::ConstPointer inputImage; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); try { reader->Update(); inputImage = reader->GetOutput(); } catch ( itk::ExceptionObject &err) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } // Software Guide : BeginLatex // // An \code{ImageType} smart pointer called \code{inputImage} points to the // output of the image reader. After updating the image reader, we can // allocate an output image of the same size, spacing, and origin as the // input image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ImageType::Pointer outputImage = ImageType::New(); outputImage->SetRegions( inputImage->GetRequestedRegion() ); outputImage->CopyInformation( inputImage ); outputImage->Allocate(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Next we create the iterator that walks the output image. Instead of using // an iterator on the input, we will copy the values directly using image // indicies. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet IteratorType outputIt( outputImage, outputImage->GetRequestedRegion() ); // Software Guide : EndCodeSnippet // Software Guide: BeginLatex // // This axis flipping algorithm works by iterating through the output image, querying // the iterator for its index, and copying the value from the input at an index // mirrored across the $x$-axis. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ImageType::IndexType requestedIndex = outputImage->GetRequestedRegion().GetIndex(); ImageType::SizeType requestedSize = outputImage->GetRequestedRegion().GetSize(); for ( outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++outputIt) { ImageType::IndexType idx = outputIt.GetIndex(); idx[0] = requestedIndex[0] + requestedSize[0] - idx[0]; outputIt.Set( inputImage->GetPixel(idx) ); } // Software Guide : EndCodeSnippet WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); writer->SetInput(outputImage); try { writer->Update(); } catch ( itk::ExceptionObject &err) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } // Software Guide : BeginLatex // // Let's run this example on the image \code{VisibleWomanEyeSlice.png} found in // the \code{Insight/Examples/Data} directory. // Figure~\ref{fig:ImageRegionIteratorWithIndexExample} shows how the original // image has been mirrored across its $x$-axis in the output. // // \begin{figure} \center // \includegraphics[width=4cm]{VisibleWomanEyeSlice.eps} // \includegraphics[width=4cm]{ImageRegionIteratorWithIndexOutput.eps} // \caption[Using the ImageRegionIteratorWithIndex]{Results of using ImageRegionIteratorWithIndex to mirror an image // across an axis. The original image is shown at left. The mirrored output is // shown at right.} // \label{fig:ImageRegionIteratorWithIndexExample} // \end{figure} // // \index{itk::ImageRegionIteratorWithIndex!example of using|)} // // Software Guide : EndLatex return 0; } <|endoftext|>
<commit_before>#include "Halide.h" #include "halide_benchmark.h" using namespace Halide; using namespace Halide::Tools; Var x("x"), y("y"); // Downsample with a 1 3 3 1 filter Func downsample(Func f) { Func downx("downx"), downy("downy"); downx(x, y, _) = (f(2*x-1, y, _) + 3.0f * (f(2*x, y, _) + f(2*x+1, y, _)) + f(2*x+2, y, _)) / 8.0f; downy(x, y, _) = (downx(x, 2*y-1, _) + 3.0f * (downx(x, 2*y, _) + downx(x, 2*y+1, _)) + downx(x, 2*y+2, _)) / 8.0f; return downy; } // Upsample using bilinear interpolation Func upsample(Func f) { Func upx("upx"), upy("upy"); upx(x, y, _) = 0.25f * f((x/2) - 1 + 2*(x % 2), y, _) + 0.75f * f(x/2, y, _); upy(x, y, _) = 0.25f * upx(x, (y/2) - 1 + 2*(y % 2), _) + 0.75f * upx(x, y/2, _); return upy; } int main(int argc, char **argv) { /* THE ALGORITHM */ // Number of pyramid levels int J = 8; const int maxJ = 20; ImageParam input(UInt(16), 3, "input"); Param<int> levels; Param<float> alpha; Param<float> beta; // loop variables Var c("c"), k("k"); // Make the remapping function as a lookup table. Func remap("remap"); Expr fx = cast<float>(x) / 256.0f; remap(x) = alpha*fx*exp(-fx*fx/2.0f); // Set a boundary condition Func clamped = BoundaryConditions::repeat_edge(input); // Convert to floating point Func floating("floating"); floating(x, y, c) = clamped(x, y, c) / 65535.0f; // Get the luminance channel Func gray("gray"); gray(x, y) = 0.299f * floating(x, y, 0) + 0.587f * floating(x, y, 1) + 0.114f * floating(x, y, 2); // Make the processed Gaussian pyramid. std::vector<Func> gPyramid; for (int i = 0; i < maxJ; i++) { Func gP("gPyramid_" + std::to_string(i)); gPyramid.push_back(gP); } // Do a lookup into a lut with 256 entires per intensity level Expr level = k * (1.0f / (levels - 1)); Expr idx = gray(x, y)*cast<float>(levels-1)*256.0f; idx = clamp(cast<int>(idx), 0, (levels-1)*256); gPyramid[0](x, y, k) = beta*(gray(x, y) - level) + level + remap(idx - 256*k); for (int j = 1; j < J; j++) { Func down = downsample(gPyramid[j-1]); gPyramid[j](x, y, k) = down(x, y, k); } // Get its laplacian pyramid std::vector<Func> lPyramid; for (int i = 0; i < maxJ; i++) { Func lP("lPyramid_" + std::to_string(i)); lPyramid.push_back(lP); } lPyramid[J-1](x, y, k) = gPyramid[J-1](x, y, k); for (int j = J-2; j >= 0; j--) { Func up = upsample(gPyramid[j+1]); lPyramid[j](x, y, k) = gPyramid[j](x, y, k) - up(x, y, k); } // Make the Gaussian pyramid of the input std::vector<Func> inGPyramid; for (int i = 0; i < maxJ; i++) { Func inGP("inGPyramid_" + std::to_string(i)); inGPyramid.push_back(inGP); } inGPyramid[0](x, y) = gray(x, y); for (int j = 1; j < J; j++) { inGPyramid[j](x, y) = downsample(inGPyramid[j-1])(x, y); } // Make the laplacian pyramid of the output std::vector<Func> outLPyramid; for (int i = 0; i < maxJ; i++) { Func outLP("outLPyramid_" + std::to_string(i)); outLPyramid.push_back(outLP); } for (int j = 0; j < J; j++) { // Split input pyramid value into integer and floating parts Expr level = inGPyramid[j](x, y) * cast<float>(levels-1); Expr li = clamp(cast<int>(level), 0, levels-2); Expr lf = level - cast<float>(li); // Linearly interpolate between the nearest processed pyramid levels outLPyramid[j](x, y) = (1.0f - lf) * lPyramid[j](x, y, li) + lf * lPyramid[j](x, y, li+1); } // Make the Gaussian pyramid of the output std::vector<Func> outGPyramid; for (int i = 0; i < maxJ; i++) { Func outGP("outGPyramid_" + std::to_string(i)); outGPyramid.push_back(outGP); } outGPyramid[J-1](x, y) = outLPyramid[J-1](x, y); for (int j = J-2; j >= 0; j--) { outGPyramid[j](x, y) = upsample(outGPyramid[j+1])(x, y) + outLPyramid[j](x, y); } // Reintroduce color (Connelly: use eps to avoid scaling up noise w/ apollo3.png input) Func color("color"); float eps = 0.01f; color(x, y, c) = outGPyramid[0](x, y) * (floating(x, y, c)+eps) / (gray(x, y)+eps); Func output("local_laplacian"); // Convert back to 16-bit output(x, y, c) = cast<uint16_t>(clamp(color(x, y, c), 0.0f, 1.0f) * 65535.0f); Target target = get_target_from_environment(); if (target.has_gpu_feature()) { Var xi("xi"), yi("yi"); output.compute_root().gpu_tile(x, y, xi, yi, 16, 8); for (int j = 0; j < J; j++) { int blockw = 16, blockh = 8; if (j > 3) { blockw = 2; blockh = 2; } if (j > 0) { inGPyramid[j].compute_root().gpu_tile(x, y, xi, yi, blockw, blockh); gPyramid[j].compute_root().reorder(k, x, y).gpu_tile(x, y, xi, yi, blockw, blockh); } outGPyramid[j].compute_root().gpu_tile(x, y, xi, yi, blockw, blockh); } } else { // CPU schedule Var yi("yi"); output.parallel(y, 32).vectorize(x, 8); gray.compute_root().parallel(y, 32).vectorize(x, 8); for (int j = 0; j < J; j++) { if (j > 0) { inGPyramid[j].compute_root() .parallel(y, 32) .vectorize(x, 8); gPyramid[j].compute_root() .reorder(k, y) .parallel(y, 8) .vectorize(x, 8); //.reorder_storage(x, k, y); } outGPyramid[j].compute_root().parallel(y, 32).vectorize(x, 8); } for (int j = 4; j < J; j++) { inGPyramid[j].compute_root(); gPyramid[j].compute_root().parallel(k); outGPyramid[j].compute_root(); } } output.compile_to_object("build/generated_fct_laplacian_ref.o", {input}, "laplacian_ref"); output.compile_to_lowered_stmt("build/generated_fct_laplacian_ref.txt", {input}, Text); return 0; } <commit_msg>Update laplacian ref<commit_after>#include "Halide.h" #include "halide_benchmark.h" using namespace Halide; using namespace Halide::Tools; Var x("x"), y("y"); // Downsample with a 1 3 3 1 filter Func downsample(Func f) { Func downx("downx"), downy("downy"); downx(x, y, _) = (f(2*x-1, y, _) + 3.0f * (f(2*x, y, _) + f(2*x+1, y, _)) + f(2*x+2, y, _)) / 8.0f; downy(x, y, _) = (downx(x, 2*y-1, _) + 3.0f * (downx(x, 2*y, _) + downx(x, 2*y+1, _)) + downx(x, 2*y+2, _)) / 8.0f; return downy; } // Upsample using bilinear interpolation Func upsample(Func f) { Func upx("upx"), upy("upy"); upx(x, y, _) = 0.25f * f((x/2) - 1 + 2*(x % 2), y, _) + 0.75f * f(x/2, y, _); upy(x, y, _) = 0.25f * upx(x, (y/2) - 1 + 2*(y % 2), _) + 0.75f * upx(x, y/2, _); return upy; } int main(int argc, char **argv) { /* THE ALGORITHM */ // Number of pyramid levels int J = 8; const int maxJ = 20; ImageParam input(UInt(16), 3, "input"); Param<int> levels; Param<float> alpha; Param<float> beta; // loop variables Var c("c"), k("k"); // Make the remapping function as a lookup table. Func remap("remap"); Expr fx = cast<float>(x) / 256.0f; remap(x) = alpha*fx*exp(-fx*fx/2.0f); // Set a boundary condition Func clamped = BoundaryConditions::repeat_edge(input); // Convert to floating point Func floating("floating"); floating(x, y, c) = clamped(x, y, c) / 65535.0f; // Get the luminance channel Func gray("gray"); gray(x, y) = 0.299f * floating(x, y, 0) + 0.587f * floating(x, y, 1) + 0.114f * floating(x, y, 2); // Make the processed Gaussian pyramid. std::vector<Func> gPyramid; for (int i = 0; i < maxJ; i++) { Func gP("gPyramid_" + std::to_string(i)); gPyramid.push_back(gP); } // Do a lookup into a lut with 256 entires per intensity level Expr level = k * (1.0f / (levels - 1)); Expr idx = gray(x, y)*cast<float>(levels-1)*256.0f; idx = clamp(cast<int>(idx), 0, (levels-1)*256); gPyramid[0](x, y, k) = beta*(gray(x, y) - level) + level + remap(idx - 256*k); for (int j = 1; j < J; j++) { Func down = downsample(gPyramid[j-1]); gPyramid[j](x, y, k) = down(x, y, k); } // Get its laplacian pyramid std::vector<Func> lPyramid; for (int i = 0; i < maxJ; i++) { Func lP("lPyramid_" + std::to_string(i)); lPyramid.push_back(lP); } lPyramid[J-1](x, y, k) = gPyramid[J-1](x, y, k); for (int j = J-2; j >= 0; j--) { Func up = upsample(gPyramid[j+1]); lPyramid[j](x, y, k) = gPyramid[j](x, y, k) - up(x, y, k); } // Make the Gaussian pyramid of the input std::vector<Func> inGPyramid; for (int i = 0; i < maxJ; i++) { Func inGP("inGPyramid_" + std::to_string(i)); inGPyramid.push_back(inGP); } inGPyramid[0](x, y) = gray(x, y); for (int j = 1; j < J; j++) { inGPyramid[j](x, y) = downsample(inGPyramid[j-1])(x, y); } // Make the laplacian pyramid of the output std::vector<Func> outLPyramid; for (int i = 0; i < maxJ; i++) { Func outLP("outLPyramid_" + std::to_string(i)); outLPyramid.push_back(outLP); } for (int j = 0; j < J; j++) { // Split input pyramid value into integer and floating parts Expr level = inGPyramid[j](x, y) * cast<float>(levels-1); Expr li = clamp(cast<int>(level), 0, levels-2); Expr lf = level - cast<float>(li); // Linearly interpolate between the nearest processed pyramid levels outLPyramid[j](x, y) = (1.0f - lf) * lPyramid[j](x, y, li) + lf * lPyramid[j](x, y, li+1); } // Make the Gaussian pyramid of the output std::vector<Func> outGPyramid; for (int i = 0; i < maxJ; i++) { Func outGP("outGPyramid_" + std::to_string(i)); outGPyramid.push_back(outGP); } outGPyramid[J-1](x, y) = outLPyramid[J-1](x, y); for (int j = J-2; j >= 0; j--) { outGPyramid[j](x, y) = upsample(outGPyramid[j+1])(x, y) + outLPyramid[j](x, y); } // Reintroduce color (Connelly: use eps to avoid scaling up noise w/ apollo3.png input) Func color("color"); float eps = 0.01f; color(x, y, c) = outGPyramid[0](x, y) * (floating(x, y, c)+eps) / (gray(x, y)+eps); Func output("local_laplacian"); // Convert back to 16-bit output(x, y, c) = cast<uint16_t>(clamp(color(x, y, c), 0.0f, 1.0f) * 65535.0f); Target target = get_target_from_environment(); if (target.has_gpu_feature()) { Var xi("xi"), yi("yi"); output.compute_root().gpu_tile(x, y, xi, yi, 16, 8); for (int j = 0; j < J; j++) { int blockw = 16, blockh = 8; if (j > 3) { blockw = 2; blockh = 2; } if (j > 0) { inGPyramid[j].compute_root().gpu_tile(x, y, xi, yi, blockw, blockh); gPyramid[j].compute_root().reorder(k, x, y).gpu_tile(x, y, xi, yi, blockw, blockh); } outGPyramid[j].compute_root().gpu_tile(x, y, xi, yi, blockw, blockh); } } else { // CPU schedule Var yi("yi"); output.parallel(y, 32).vectorize(x, 8); gray.compute_root().parallel(y, 32).vectorize(x, 8); for (int j = 0; j < J; j++) { if (j > 0) { inGPyramid[j].compute_root() .parallel(y, 32) .vectorize(x, 8); gPyramid[j].compute_root() .reorder(k, y) .parallel(y, 8) .vectorize(x, 8); //.reorder_storage(x, k, y); } outGPyramid[j].compute_root().parallel(y, 32).vectorize(x, 8); } for (int j = 4; j < J; j++) { inGPyramid[j].compute_root(); gPyramid[j].compute_root().parallel(k); outGPyramid[j].compute_root(); } } output.compile_to_object("build/generated_fct_laplacian_ref.o", {input, levels, alpha, beta}, "laplacian_ref"); output.compile_to_lowered_stmt("build/generated_fct_laplacian_ref.txt", {input, levels, alpha, beta}, Text); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <stdexcept> #include <string> #include <vector> #include <sstream> #include <algorithm> #include <functional> #include "std_is_missing_stuff.h" #include "global.h" #include "operators.h" #include "tokens.h" #include "nodes.h" class Parser { private: std::vector<Token> tokens {}; inline void skipCharacters(unsigned int &i, int by) {i += by;} // If we're already at the next character, but the loop will increment i by 1 inline void preventIncrement(unsigned int &i) {i--;} std::vector<std::string> typeIdentifiers {"Integer"}; std::vector<std::string> variables {}; std::vector<std::string> keywords {"var", "if", "while", "for"}; public: nodes::AST tree = nodes::AST(); Parser(std::string code) { try { tokenize(code); buildTree(); if (PARSER_PRINT_TOKENS) for (auto tok : tokens) print(tok.data, " --> TokenType ", tok.type, "\n"); if (PARSER_PRINT_AS_EXPR) for (auto tok : nodes::ExpressionNode(tokens).getRPNOutput()) printnb(tok.data << ' ') } catch (SyntaxError &e) { print(e.getMessage(), "\n"); } } Parser() {} void tokenize(std::string code) { unsigned int lines = 0; for (unsigned int i = 0; i < code.length(); ++i) { if (code[i] == '\n') lines++; // Ignore whitespace if (isspace(code[i])) continue; // Block begin/end // Parenthesis // Semicolumns if (code[i] == '{' || code[i] == '}' || code[i] == '(' || code[i] == ')' || code[i] == ';') { tokens.push_back(Token(to_string(code[i]), CONSTRUCT, lines)); continue; } // Operators auto initTokSize = tokens.size(); std::for_each(ops::opList.begin(), ops::opList.end(), [this, initTokSize, code, i, lines](ops::Operator& op) { if (initTokSize < tokens.size()) return; // If there are more tokens than before for_each, the operator was already added, so return. if (op.getName().length() + i > code.length()) return; // If the operator is longer than the source string, ignore it. if (op.getName() == code.substr(i, op.getName().length())) { ops::Operator& tmp = op; // TODO: apply DRY on these ifs if (tmp.getName() == "++" || tmp.getName() == "--") { // Prefix version if (tokens.back().type == OPERATOR || tokens.back().type == CONSTRUCT) tmp = ops::Operator(tmp.getName(), 12, ops::ASSOCIATE_FROM_RIGHT, ops::UNARY); // Postfix version else tmp = ops::Operator(tmp.getName(), 13, ops::ASSOCIATE_FROM_RIGHT, ops::UNARY); } if (tmp.getName() == "+" || tmp.getName() == "-") { // Unary version if (tokens.back().type == OPERATOR || tokens.back().type == CONSTRUCT) tmp = ops::Operator(tmp.getName(), 12, ops::ASSOCIATE_FROM_RIGHT, ops::UNARY); // Binary version else tmp = ops::Operator(tmp.getName(), 10); } if (PARSER_PRINT_OPERATOR_TOKENS) print("Parser found Token with Operator ", tmp, ", at address ", &tmp, "\n"); tokens.push_back(Token(tmp, OPERATOR, lines)); } }); if (initTokSize < tokens.size()) { skipCharacters(i, tokens.back().data.length() - 1); continue; // Token added, continue. } // Numbers if (isdigit(code[i])) { // TODO: understand 0xDEADBEEF hexadecimal and 0b10101 binary, maybe 0o765432 octal std::string current = ""; bool isFloat = false; while (isdigit(code[i]) || code[i] == '.') { current += code[i]; if (code[i] == '.') { if (isFloat) throw SyntaxError("Malformed float, multiple decimal points: \"" + current + "\"", lines); isFloat = true; } skipCharacters(i, 1); } preventIncrement(i); if (current[current.length() - 1] == '.') throw SyntaxError("Malformed float, missing digits after decimal point: \"" + current + "\"", lines); tokens.push_back(Token(current, isFloat ? FLOAT : INTEGER, lines)); continue; } // String literals if (code[i] == '"') { skipCharacters(i, 1); // Skip the double quote std::string current = ""; while (code[i] != '"') { // TODO: add escape sequences current += code[i]; skipCharacters(i, 1); } // Don't call preventIncrement here so the other double quote is skipped tokens.push_back(Token(current, STRING, lines)); continue; } // Others Token token = Token(); while (!isspace(code[i])) { if (ops::isReservedChar(code[i]) || code[i] == '\0') break; token.data += code[i]; skipCharacters(i, 1); } // Check if the thing is a keyword if (contains(token.data, keywords)) token.type = KEYWORD; preventIncrement(i); token.line = lines; tokens.push_back(token); } } void buildTree() { // TODO: start building the AST here } }; int main() { switch (TEST_INPUT) { case 1: Parser("a = ++b"); break; case 2: Parser("(1 + 2) * 3 / (2 << 1)"); break; case 3: Parser("var a = \"abc123\";"); break; case 4: Parser("var a = 132;\na+=1+123*(1 + 32/2);"); break; case 5: Parser("1+ a*(-19-1++)==Integer.MAX_INT"); break; case 6: Parser("var a = 1 + 2 * (76 - 123 - (43 + 12) / 5) % 10;\nInteger n = 1;"); break; case 7: Parser("1 + 2 * 3 << 2"); break; case 8: Parser("Test.test.abc.df23.asdasf ()"); break; default: break; } return 0; } <commit_msg>Updated inputs and print method<commit_after>#include <iostream> #include <stdexcept> #include <string> #include <vector> #include <sstream> #include <algorithm> #include <functional> #include "std_is_missing_stuff.h" #include "global.h" #include "operators.h" #include "tokens.h" #include "nodes.h" class Parser { private: std::vector<Token> tokens {}; inline void skipCharacters(unsigned int &i, int by) {i += by;} // If we're already at the next character, but the loop will increment i by 1 inline void preventIncrement(unsigned int &i) {i--;} std::vector<std::string> typeIdentifiers {"Integer"}; std::vector<std::string> variables {}; std::vector<std::string> keywords {"var", "if", "while", "for"}; public: nodes::AST tree = nodes::AST(); Parser(std::string code) { try { tokenize(code); buildTree(); if (PARSER_PRINT_TOKENS) for (auto tok : tokens) print(tok.data, " --> TokenType ", tok.type, "\n"); if (PARSER_PRINT_AS_EXPR) for (auto tok : nodes::ExpressionNode(tokens).getRPNOutput()) print(tok.data, " "); } catch (SyntaxError &e) { print(e.getMessage(), "\n"); } } Parser() {} void tokenize(std::string code) { unsigned int lines = 0; for (unsigned int i = 0; i < code.length(); ++i) { if (code[i] == '\n') lines++; // Ignore whitespace if (isspace(code[i])) continue; // Block begin/end // Parenthesis // Semicolumns if (code[i] == '{' || code[i] == '}' || code[i] == '(' || code[i] == ')' || code[i] == ';') { tokens.push_back(Token(to_string(code[i]), CONSTRUCT, lines)); continue; } // Operators auto initTokSize = tokens.size(); std::for_each(ops::opList.begin(), ops::opList.end(), [this, initTokSize, code, i, lines](ops::Operator& op) { if (initTokSize < tokens.size()) return; // If there are more tokens than before for_each, the operator was already added, so return. if (op.getName().length() + i > code.length()) return; // If the operator is longer than the source string, ignore it. if (op.getName() == code.substr(i, op.getName().length())) { ops::Operator& tmp = op; // TODO: apply DRY on these ifs if (tmp.getName() == "++" || tmp.getName() == "--") { // Prefix version if (tokens.back().type == OPERATOR || tokens.back().type == CONSTRUCT) tmp = ops::Operator(tmp.getName(), 12, ops::ASSOCIATE_FROM_RIGHT, ops::UNARY); // Postfix version else tmp = ops::Operator(tmp.getName(), 13, ops::ASSOCIATE_FROM_RIGHT, ops::UNARY); } if (tmp.getName() == "+" || tmp.getName() == "-") { // Unary version if (tokens.back().type == OPERATOR || tokens.back().type == CONSTRUCT) tmp = ops::Operator(tmp.getName(), 12, ops::ASSOCIATE_FROM_RIGHT, ops::UNARY); // Binary version else tmp = ops::Operator(tmp.getName(), 10); } if (PARSER_PRINT_OPERATOR_TOKENS) print("Parser found Token with Operator ", tmp, ", at address ", &tmp, "\n"); tokens.push_back(Token(tmp, OPERATOR, lines)); } }); if (initTokSize < tokens.size()) { skipCharacters(i, tokens.back().data.length() - 1); continue; // Token added, continue. } // Numbers if (isdigit(code[i])) { // TODO: understand 0xDEADBEEF hexadecimal and 0b10101 binary, maybe 0o765432 octal std::string current = ""; bool isFloat = false; while (isdigit(code[i]) || code[i] == '.') { current += code[i]; if (code[i] == '.') { if (isFloat) throw SyntaxError("Malformed float, multiple decimal points: \"" + current + "\"", lines); isFloat = true; } skipCharacters(i, 1); } preventIncrement(i); if (current[current.length() - 1] == '.') throw SyntaxError("Malformed float, missing digits after decimal point: \"" + current + "\"", lines); tokens.push_back(Token(current, isFloat ? FLOAT : INTEGER, lines)); continue; } // String literals if (code[i] == '"') { skipCharacters(i, 1); // Skip the double quote std::string current = ""; while (code[i] != '"') { // TODO: add escape sequences current += code[i]; skipCharacters(i, 1); } // Don't call preventIncrement here so the other double quote is skipped tokens.push_back(Token(current, STRING, lines)); continue; } // Others Token token = Token(); while (!isspace(code[i])) { if (ops::isReservedChar(code[i]) || code[i] == '\0') break; token.data += code[i]; skipCharacters(i, 1); } // Check if the thing is a keyword if (contains(token.data, keywords)) token.type = KEYWORD; preventIncrement(i); token.line = lines; tokens.push_back(token); } } void buildTree() { // TODO: start building the AST here } std::vector<Token> getTokens() { return tokens; } }; int main() { switch (TEST_INPUT) { case 1: Parser("a = (a + 1)"); break; case 2: Parser("(1 + 2) * 3 / (2 << 1)"); break;// TODO: Causes segfault because it's starting with "(" case 3: Parser("var a = \"abc123\";"); break; case 4: Parser("var a = 132;\na+=1+123*(1 + 32/2);"); break; case 5: Parser("1+ a*(-19-1++)==Integer.MAX_INT"); break; case 6: Parser("var a = 1 + 2 * (76 - 123 - (43 + 12) / 5) % 10;\nInteger n = 1;"); break; case 7: Parser("1 + 2 * 3 << 2"); break; case 8: Parser("Test.test.abc.df23.asdasf ()"); break; case 9: Parser("(1+3)*1+ a*(19-1)"); break; default: break; } return 0; } <|endoftext|>
<commit_before>#include "arguments.hpp" #include "call_frame.hpp" #include "memory.hpp" #include "metrics.hpp" #include "builtin/array.hpp" #include "builtin/class.hpp" #include "builtin/exception.hpp" #include "builtin/fiber.hpp" #include "builtin/lookup_table.hpp" #include "builtin/object.hpp" #include "memory/gc.hpp" namespace rubinius { void Fiber::bootstrap(STATE) { GO(fiber).set(state->memory()->new_class<Class, Fiber>( state, G(rubinius), "Fiber")); #ifdef RBX_FIBER_ENABLED G(fiber)->set_const(state, "ENABLED", cTrue); #else G(fiber)->set_const(state, "ENABLED", cFalse); #endif } Fiber* Fiber::current(STATE) { #ifdef RBX_FIBER_ENABLED Fiber* fib = state->vm()->current_fiber.get(); // Lazily allocate a root fiber. if(fib->nil_p()) { fib = state->memory()->new_object<Fiber>(state, G(fiber)); fib->root(true); fib->status(Fiber::eRunning); fib->data(state->vm()->new_fiber_data(true, fib->stack_size()->to_native())); fib->data()->set_call_frame(state->vm()->call_frame()); state->memory()->native_finalizer(state, fib, (memory::FinalizerFunction)&Fiber::finalize); state->vm()->current_fiber.set(fib); state->vm()->root_fiber.set(fib); } return fib; #else Exception::raise_not_implemented_error(state, "Fibers not supported on this platform"); #endif } void Fiber::start_on_stack() { #ifdef RBX_FIBER_ENABLED VM* vm = VM::current(); State state_obj(vm), *state = &state_obj; Fiber* fib = Fiber::current(state); // Reset the current fiber again to reset the stack limits so // we can properly detect stack overflows vm->set_current_fiber(fib); Array* result = nil<Array>(); Object* obj = fib->starter()->send(state, G(sym_call), fib->value(), cNil, false); // GC has run! Don't use stack vars! fib = Fiber::current(state); fib->status(Fiber::eDead); fib->dead(cTrue); fib->set_call_frame(state, 0); Fiber* dest = fib->prev(); // If this fiber has already been cleaned up, just ignore this if(!dest->data()) return; assert(!dest->nil_p()); // Box this up so it's in a standard format at the point // of returning, so we can deal with it in the same way // as *args from #yield, #resume, and #transfer if(obj) { result = Array::create(state, 1); result->set(state, 0, obj); } else { if(state->vm()->thread_state()->raise_reason() == cException) { dest->exception(state, state->vm()->thread_state()->current_exception()); } } vm->metrics().system.fibers_destroyed++; dest->run(state); dest->value(state, result); dest->data()->switch_and_orphan(state, fib->data()); // TODO: CallFrame: return from this function rubinius::bug("returning from Fiber::start_on_stack"); #else rubinius::bug("Fibers not supported on this platform"); #endif } Fiber* Fiber::create(STATE, Object* self, Object* stack_size, Object* callable) { #ifdef RBX_FIBER_ENABLED Fiber* fib = state->memory()->new_object<Fiber>(state, as<Class>(self)); fib->starter(state, callable); if(Fixnum* size = try_as<Fixnum>(stack_size)) { state->vm()->validate_stack_size(state, size->to_native()); fib->stack_size(state, size); } state->vm()->metrics().system.fibers_created++; state->memory()->native_finalizer(state, fib, (memory::FinalizerFunction)&Fiber::finalize); return fib; #else Exception::raise_not_implemented_error(state, "Fibers not supported on this platform"); #endif } Object* Fiber::resume(STATE, Arguments& args) { #ifdef RBX_FIBER_ENABLED if(!data()) { data(state->vm()->new_fiber_data(stack_size()->to_native())); } if(status() == Fiber::eDead || data()->dead_p()) { Exception::raise_fiber_error(state, "dead fiber called"); } if(!prev()->nil_p()) { Exception::raise_fiber_error(state, "double resume"); } if(data()->thread() && data()->thread() != state->vm()) { Exception::raise_fiber_error(state, "cross thread fiber resuming is illegal"); } Array* val = args.as_array(state); value(state, val); Fiber* cur = Fiber::current(state); prev(state, cur); cur->sleep(state); run(state); data()->switch_to(state, cur->data()); // Back here when someone yields back to us! // Beware here, because the GC has probably run so GC pointers on the C++ stack // can't be accessed. cur = Fiber::current(state); // TODO: clean up this and the following conditional. if(state->vm()->thread_interrupted_p(state)) { return NULL; } if(!cur->exception()->nil_p()) { state->raise_exception(cur->exception()); cur->exception(state, nil<Exception>()); return NULL; } Array* ret = cur->value(); if(ret->nil_p()) return cNil; switch(ret->size()) { case 0: return cNil; case 1: return ret->get(state, 0); default: return ret; } #else Exception::raise_not_implemented_error(state, "Fibers not supported on this platform"); #endif } Object* Fiber::transfer(STATE, Arguments& args) { #ifdef RBX_FIBER_ENABLED if(!data()) { data(state->vm()->new_fiber_data(stack_size()->to_native())); } if(status() == Fiber::eDead || data()->dead_p()) { Exception::raise_fiber_error(state, "dead fiber called"); } if(data()->thread() && data()->thread() != state->vm()) { Exception::raise_fiber_error(state, "cross thread fiber resuming is illegal"); } Array* val = args.as_array(state); value(state, val); Fiber* cur = Fiber::current(state); Fiber* root = state->vm()->root_fiber.get(); assert(root); prev(state, root); cur->sleep(state); run(state); data()->switch_to(state, cur->data()); // Back here when someone transfers back to us! // Beware here, because the GC has probably run so GC pointers on the C++ stack // can't be accessed. cur = Fiber::current(state); if(!cur->exception()->nil_p()) { state->raise_exception(cur->exception()); cur->exception(state, nil<Exception>()); return 0; } Array* ret = cur->value(); if(ret->nil_p()) return cNil; switch(ret->size()) { case 0: return cNil; case 1: return ret->get(state, 0); default: return ret; } #else Exception::raise_not_implemented_error(state, "Fibers not supported on this platform"); #endif } Object* Fiber::s_yield(STATE, Arguments& args) { #ifdef RBX_FIBER_ENABLED Fiber* cur = Fiber::current(state); Fiber* dest_fib = cur->prev(); assert(cur != dest_fib); if(cur->root()) { Exception::raise_fiber_error(state, "can't yield from root fiber"); } cur->prev(state, nil<Fiber>()); Array* val = args.as_array(state); dest_fib->value(state, val); cur->sleep(state); dest_fib->run(state); dest_fib->data()->switch_to(state, cur->data()); // Back here when someone yields back to us! // Beware here, because the GC has probably run so GC pointers on the C++ stack // can't be accessed. cur = Fiber::current(state); Array* ret = cur->value(); if(ret->nil_p()) return cNil; switch(ret->size()) { case 0: return cNil; case 1: return ret->get(state, 0); default: return ret; } #else Exception::raise_not_implemented_error(state, "Fibers not supported on this platform"); #endif } void Fiber::finalize(STATE, Fiber* fib) { #ifdef RBX_FIBER_ENABLED logger::write("finalizer: fiber: %ld", (intptr_t)fib); if(!fib->data()) return; fib->data()->orphan(state); delete fib->data(); fib->data(NULL); #endif } void Fiber::Info::mark(Object* obj, memory::ObjectMark& mark) { auto_mark(obj, mark); Fiber* fib = force_as<Fiber>(obj); FiberData* data = fib->data(); if(!data || data->dead_p()) return; data->set_mark(); } } <commit_msg>Another Travis test.<commit_after>#include "arguments.hpp" #include "call_frame.hpp" #include "memory.hpp" #include "metrics.hpp" #include "builtin/array.hpp" #include "builtin/class.hpp" #include "builtin/exception.hpp" #include "builtin/fiber.hpp" #include "builtin/lookup_table.hpp" #include "builtin/object.hpp" #include "memory/gc.hpp" namespace rubinius { void Fiber::bootstrap(STATE) { GO(fiber).set(state->memory()->new_class<Class, Fiber>( state, G(rubinius), "Fiber")); #ifdef RBX_FIBER_ENABLED G(fiber)->set_const(state, "ENABLED", cTrue); #else G(fiber)->set_const(state, "ENABLED", cFalse); #endif } Fiber* Fiber::current(STATE) { #ifdef RBX_FIBER_ENABLED Fiber* fib = state->vm()->current_fiber.get(); // Lazily allocate a root fiber. if(fib->nil_p()) { fib = state->memory()->new_object<Fiber>(state, G(fiber)); fib->root(true); fib->status(Fiber::eRunning); fib->data(state->vm()->new_fiber_data(true, fib->stack_size()->to_native())); fib->data()->set_call_frame(state->vm()->call_frame()); state->memory()->native_finalizer(state, fib, (memory::FinalizerFunction)&Fiber::finalize); state->vm()->current_fiber.set(fib); state->vm()->root_fiber.set(fib); } return fib; #else Exception::raise_not_implemented_error(state, "Fibers not supported on this platform"); #endif } void Fiber::start_on_stack() { #ifdef RBX_FIBER_ENABLED VM* vm = VM::current(); State state_obj(vm), *state = &state_obj; Fiber* fib = Fiber::current(state); // Reset the current fiber again to reset the stack limits so // we can properly detect stack overflows vm->set_current_fiber(fib); Array* result = nil<Array>(); Object* obj = fib->starter()->send(state, G(sym_call), fib->value(), cNil, false); // GC has run! Don't use stack vars! fib = Fiber::current(state); fib->status(Fiber::eDead); fib->dead(cTrue); fib->set_call_frame(state, 0); Fiber* dest = fib->prev(); // If this fiber has already been cleaned up, just ignore this if(!dest->data()) return; assert(!dest->nil_p()); // Box this up so it's in a standard format at the point // of returning, so we can deal with it in the same way // as *args from #yield, #resume, and #transfer if(obj) { result = Array::create(state, 1); result->set(state, 0, obj); } else { if(state->vm()->thread_state()->raise_reason() == cException) { dest->exception(state, state->vm()->thread_state()->current_exception()); } } vm->metrics().system.fibers_destroyed++; dest->run(state); dest->value(state, result); dest->data()->switch_and_orphan(state, fib->data()); // TODO: CallFrame: return from this function rubinius::bug("returning from Fiber::start_on_stack"); #else rubinius::bug("Fibers not supported on this platform"); #endif } Fiber* Fiber::create(STATE, Object* self, Object* stack_size, Object* callable) { #ifdef RBX_FIBER_ENABLED Fiber* fib = state->memory()->new_object<Fiber>(state, as<Class>(self)); fib->starter(state, callable); if(Fixnum* size = try_as<Fixnum>(stack_size)) { state->vm()->validate_stack_size(state, size->to_native()); fib->stack_size(state, size); } state->vm()->metrics().system.fibers_created++; state->memory()->native_finalizer(state, fib, (memory::FinalizerFunction)&Fiber::finalize); return fib; #else Exception::raise_not_implemented_error(state, "Fibers not supported on this platform"); #endif } Object* Fiber::resume(STATE, Arguments& args) { #ifdef RBX_FIBER_ENABLED if(!data()) { data(state->vm()->new_fiber_data(stack_size()->to_native())); } if(status() == Fiber::eDead || data()->dead_p()) { Exception::raise_fiber_error(state, "dead fiber called"); } if(!prev()->nil_p()) { Exception::raise_fiber_error(state, "double resume"); } if(data()->thread() && data()->thread() != state->vm()) { Exception::raise_fiber_error(state, "cross thread fiber resuming is illegal"); } Array* val = args.as_array(state); value(state, val); Fiber* cur = Fiber::current(state); prev(state, cur); cur->sleep(state); run(state); data()->switch_to(state, cur->data()); // Back here when someone yields back to us! // Beware here, because the GC has probably run so GC pointers on the C++ stack // can't be accessed. cur = Fiber::current(state); // TODO: clean up this and the following conditional. if(state->vm()->thread_interrupted_p(state)) { return NULL; } if(!cur->exception()->nil_p()) { state->raise_exception(cur->exception()); cur->exception(state, nil<Exception>()); return NULL; } Array* ret = cur->value(); if(ret->nil_p()) return cNil; switch(ret->size()) { case 0: return cNil; case 1: return ret->get(state, 0); default: return ret; } #else Exception::raise_not_implemented_error(state, "Fibers not supported on this platform"); #endif } Object* Fiber::transfer(STATE, Arguments& args) { #ifdef RBX_FIBER_ENABLED if(!data()) { data(state->vm()->new_fiber_data(stack_size()->to_native())); } if(status() == Fiber::eDead || data()->dead_p()) { Exception::raise_fiber_error(state, "dead fiber called"); } if(data()->thread() && data()->thread() != state->vm()) { Exception::raise_fiber_error(state, "cross thread fiber resuming is illegal"); } Array* val = args.as_array(state); value(state, val); Fiber* cur = Fiber::current(state); Fiber* root = state->vm()->root_fiber.get(); assert(root); prev(state, root); cur->sleep(state); run(state); data()->switch_to(state, cur->data()); // Back here when someone transfers back to us! // Beware here, because the GC has probably run so GC pointers on the C++ stack // can't be accessed. cur = Fiber::current(state); if(!cur->exception()->nil_p()) { state->raise_exception(cur->exception()); cur->exception(state, nil<Exception>()); return 0; } Array* ret = cur->value(); if(ret->nil_p()) return cNil; switch(ret->size()) { case 0: return cNil; case 1: return ret->get(state, 0); default: return ret; } #else Exception::raise_not_implemented_error(state, "Fibers not supported on this platform"); #endif } Object* Fiber::s_yield(STATE, Arguments& args) { #ifdef RBX_FIBER_ENABLED Fiber* cur = Fiber::current(state); Fiber* dest_fib = cur->prev(); assert(cur != dest_fib); if(cur->root()) { Exception::raise_fiber_error(state, "can't yield from root fiber"); } cur->prev(state, nil<Fiber>()); Array* val = args.as_array(state); dest_fib->value(state, val); cur->sleep(state); dest_fib->run(state); dest_fib->data()->switch_to(state, cur->data()); // Back here when someone yields back to us! // Beware here, because the GC has probably run so GC pointers on the C++ stack // can't be accessed. cur = Fiber::current(state); Array* ret = cur->value(); if(ret->nil_p()) return cNil; switch(ret->size()) { case 0: return cNil; case 1: return ret->get(state, 0); default: return ret; } #else Exception::raise_not_implemented_error(state, "Fibers not supported on this platform"); #endif } void Fiber::finalize(STATE, Fiber* fib) { #ifdef RBX_FIBER_ENABLED // Debugging Travis CI run. return; logger::write("finalizer: fiber: %ld", (intptr_t)fib); if(!fib->data()) return; fib->data()->orphan(state); delete fib->data(); fib->data(NULL); #endif } void Fiber::Info::mark(Object* obj, memory::ObjectMark& mark) { auto_mark(obj, mark); Fiber* fib = force_as<Fiber>(obj); FiberData* data = fib->data(); if(!data || data->dead_p()) return; data->set_mark(); } } <|endoftext|>
<commit_before>#include "cnn/init.h" #include "cnn/aligned-mem-pool.h" #include "cnn/cnn.h" #include "cnn/model.h" #include <iostream> #include <random> #include <cmath> #if HAVE_CUDA #include "cnn/cuda.h" #include <device_launch_parameters.h> #endif using namespace std; namespace cnn { AlignedMemoryPool<ALIGN>* fxs = nullptr; AlignedMemoryPool<ALIGN>* dEdfs = nullptr; AlignedMemoryPool<ALIGN>* mem_nodes= nullptr; /// for nodes allocation/delocation. operation of new/delete of each node has been overwritten to use this memory pool for speed-up AlignedMemoryPool<ALIGN>* glb_temp_working_mem = nullptr; mt19937* rndeng = nullptr; char* getCmdOption(char ** begin, char ** end, const std::string & option) { char ** itr = std::find(begin, end, option); if (itr != end && ++itr != end) { return *itr; } return 0; } static void RemoveArgs(int& argc, char**& argv, int& argi, int n) { for (int i = argi + n; i < argc; ++i) argv[i - n] = argv[i]; argc -= n; assert(argc >= 0); } bool cmdOptionExists(char** begin, char** end, const std::string& option) { return std::find(begin, end, option) != end; } void Initialize(int& argc, char**& argv, unsigned random_seed, bool demo) { cerr << "Initializing...\n"; #if HAVE_CUDA Initialize_GPU(argc, argv); #else kSCALAR_MINUSONE = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_MINUSONE = -1; kSCALAR_ONE = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_ONE = 1; kSCALAR_ZERO = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_ZERO = 0; #endif if (random_seed == 0) { if (cmdOptionExists(argv, argv + argc, "--seed")) { string seed = getCmdOption(argv, argv + argc, "--seed"); stringstream(seed) >> random_seed; } else { random_device rd; random_seed = rd(); } } rndeng = new mt19937(random_seed); cerr << "Allocating memory...\n"; unsigned long num_mb = 512UL; mem_nodes = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20), true); glb_temp_working_mem = new AlignedMemoryPool<ALIGN>(1UL << 16); if (demo) { fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); } else { #ifdef HAVE_CUDA fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); #else fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 22)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 22)); #endif } cerr << "Done.\n"; } void Free() { cerr << "Freeing memory ...\n"; cnn_mm_free(kSCALAR_MINUSONE); cnn_mm_free(kSCALAR_ONE); cnn_mm_free(kSCALAR_ZERO); delete (rndeng); delete (fxs); delete (dEdfs); delete (mem_nodes); delete (glb_temp_working_mem); for (auto p : kSCALAR_ONE_OVER_INT) cnn_mm_free(p); #ifdef HAVE_CUDA Free_GPU(); #endif cerr << "Done.\n"; } } // namespace cnn <commit_msg>allocate larger space, to 512 * 2^22 space for GPU<commit_after>#include "cnn/init.h" #include "cnn/aligned-mem-pool.h" #include "cnn/cnn.h" #include "cnn/model.h" #include <iostream> #include <random> #include <cmath> #if HAVE_CUDA #include "cnn/cuda.h" #include <device_launch_parameters.h> #endif using namespace std; namespace cnn { AlignedMemoryPool<ALIGN>* fxs = nullptr; AlignedMemoryPool<ALIGN>* dEdfs = nullptr; AlignedMemoryPool<ALIGN>* mem_nodes= nullptr; /// for nodes allocation/delocation. operation of new/delete of each node has been overwritten to use this memory pool for speed-up AlignedMemoryPool<ALIGN>* glb_temp_working_mem = nullptr; mt19937* rndeng = nullptr; char* getCmdOption(char ** begin, char ** end, const std::string & option) { char ** itr = std::find(begin, end, option); if (itr != end && ++itr != end) { return *itr; } return 0; } static void RemoveArgs(int& argc, char**& argv, int& argi, int n) { for (int i = argi + n; i < argc; ++i) argv[i - n] = argv[i]; argc -= n; assert(argc >= 0); } bool cmdOptionExists(char** begin, char** end, const std::string& option) { return std::find(begin, end, option) != end; } void Initialize(int& argc, char**& argv, unsigned random_seed, bool demo) { cerr << "Initializing...\n"; #if HAVE_CUDA Initialize_GPU(argc, argv); #else kSCALAR_MINUSONE = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_MINUSONE = -1; kSCALAR_ONE = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_ONE = 1; kSCALAR_ZERO = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_ZERO = 0; #endif if (random_seed == 0) { if (cmdOptionExists(argv, argv + argc, "--seed")) { string seed = getCmdOption(argv, argv + argc, "--seed"); stringstream(seed) >> random_seed; } else { random_device rd; random_seed = rd(); } } rndeng = new mt19937(random_seed); cerr << "Allocating memory...\n"; unsigned long num_mb = 512UL; mem_nodes = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20), true); glb_temp_working_mem = new AlignedMemoryPool<ALIGN>(1UL << 16); if (demo) { fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); } else { #ifdef HAVE_CUDA fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 22)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 22)); #else fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 22)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 22)); #endif } cerr << "Done.\n"; } void Free() { cerr << "Freeing memory ...\n"; cnn_mm_free(kSCALAR_MINUSONE); cnn_mm_free(kSCALAR_ONE); cnn_mm_free(kSCALAR_ZERO); delete (rndeng); delete (fxs); delete (dEdfs); delete (mem_nodes); delete (glb_temp_working_mem); for (auto p : kSCALAR_ONE_OVER_INT) cnn_mm_free(p); #ifdef HAVE_CUDA Free_GPU(); #endif cerr << "Done.\n"; } } // namespace cnn <|endoftext|>
<commit_before>// @(#)root/pyroot:$Id$ // Author: Wim Lavrijsen, Jan 2005 // Bindings #include "PyROOT.h" #include "PyStrings.h" #include "ObjectProxy.h" #include "Utility.h" // ROOT #include "TObject.h" #include "TBufferFile.h" // for pickling //- data _______________________________________________________________________ R__EXTERN PyObject* gRootModule; //____________________________________________________________________________ void PyROOT::op_dealloc_nofree( ObjectProxy* pyobj ) { if ( pyobj->fObject && ( pyobj->fFlags & ObjectProxy::kIsOwner ) ) { pyobj->ObjectIsA()->Destructor( pyobj->fObject ); } } //____________________________________________________________________________ namespace PyROOT { namespace { //= PyROOT object proxy nullness checking ==================================== PyObject* op_nonzero( ObjectProxy* self, void* ) { return PyInt_FromLong( self->GetObject() ? 1 : 0 ); } //= PyROOT object proxy pickle support ======================================= PyObject* op_reduce( ObjectProxy* self ) { // Turn the object proxy instance into a character stream and return for // pickle, together with the callable object that can restore the stream // into the object proxy instance. // keep a borrowed reference around to the callable function for expanding; // because it is borrowed, it means that there can be no pickling during the // shutdown of the libPyROOT module static PyObject* s_expand = PyDict_GetItemString( PyModule_GetDict( gRootModule ), const_cast< char* >( "_ObjectProxy__expand__" ) ); // TBuffer and its derived classes can't write themselves, but can be created // directly from the buffer, so handle them in a special case static TClassRef s_bfClass( "TBufferFile" ); TBufferFile* buff = 0; if ( s_bfClass == self->ObjectIsA() ) { buff = (TBufferFile*)self->GetObject(); } else { // no cast is needed, but WriteObject taking a TClass argument is protected, // so use WriteObjectAny() static TBufferFile s_buff( TBuffer::kWrite ); s_buff.Reset(); if ( s_buff.WriteObjectAny( self->GetObject(), self->ObjectIsA() ) != 1 ) { PyErr_Format( PyExc_IOError, "could not stream object of type %s", self->ObjectIsA()->GetName() ); return 0; } buff = &s_buff; } // use a string for the serialized result, as a python buffer will not copy // the buffer contents; use a string for the class name, used when casting // on reading back in (see RootModule.cxx:TObjectExpand) PyObject* res2 = PyTuple_New( 2 ); PyTuple_SET_ITEM( res2, 0, PyString_FromStringAndSize( buff->Buffer(), buff->Length() ) ); PyTuple_SET_ITEM( res2, 1, PyString_FromString( self->ObjectIsA()->GetName() ) ); PyObject* result = PyTuple_New( 2 ); Py_INCREF( s_expand ); PyTuple_SET_ITEM( result, 0, s_expand ); PyTuple_SET_ITEM( result, 1, res2 ); return result; } //____________________________________________________________________________ PyMethodDef op_methods[] = { { (char*)"__nonzero__", (PyCFunction)op_nonzero, METH_NOARGS, NULL }, { (char*)"__reduce__", (PyCFunction)op_reduce, METH_NOARGS, NULL }, { (char*)NULL, NULL, 0, NULL } }; //= PyROOT object proxy construction/destruction ============================= ObjectProxy* op_new( PyTypeObject* subtype, PyObject*, PyObject* ) { ObjectProxy* pyobj = (ObjectProxy*)subtype->tp_alloc( subtype, 0 ); pyobj->fObject = NULL; pyobj->fFlags = 0; return pyobj; } //____________________________________________________________________________ void op_dealloc( ObjectProxy* pyobj ) { op_dealloc_nofree( pyobj ); pyobj->ob_type->tp_free( (PyObject*)pyobj ); } //____________________________________________________________________________ PyObject* op_richcompare( ObjectProxy* self, ObjectProxy* other, int op ) { if ( op != Py_EQ && op != Py_NE ) { Py_INCREF( Py_NotImplemented ); return Py_NotImplemented; } bool bIsEq = false; // special case for None to compare True to a null-pointer if ( (PyObject*)other == Py_None && ! self->fObject ) bIsEq = true; // type + held pointer value defines identity (will cover if other is not // actually an ObjectProxy, as ob_type will be unequal) else if ( self->ob_type == other->ob_type && self->fObject == other->fObject ) bIsEq = true; if ( ( op == Py_EQ && bIsEq ) || ( op == Py_NE && ! bIsEq ) ) { Py_INCREF( Py_True ); return Py_True; } Py_INCREF( Py_False ); return Py_False; } //____________________________________________________________________________ PyObject* op_repr( ObjectProxy* pyobj ) { TClass* klass = pyobj->ObjectIsA(); std::string clName = klass ? klass->GetName() : "<unknown>"; if ( pyobj->fFlags & ObjectProxy::kIsReference ) clName.append( "*" ); // need to prevent accidental derefs when just printing (usually unsafe) if ( ! PyObject_HasAttr( (PyObject*)pyobj, PyStrings::gDeref ) ) { PyObject* name = PyObject_CallMethod( (PyObject*)pyobj, const_cast< char* >( "GetName" ), const_cast< char* >( "" ) ); if ( name ) { if ( PyString_GET_SIZE( name ) != 0 ) { PyObject* repr = PyString_FromFormat( "<ROOT.%s object (\"%s\") at %p>", clName.c_str(), PyString_AS_STRING( name ), pyobj->fObject ); Py_DECREF( name ); return repr; } Py_DECREF( name ); } else PyErr_Clear(); } // get here if object has no method GetName() or name = "" return PyString_FromFormat( const_cast< char* >( "<ROOT.%s object at %p>" ), clName.c_str(), pyobj->fObject ); } //= PyROOT type number stubs to allow dynamic overrides ====================== #define PYROOT_STUB( name, op, pystring ) \ PyObject* op_##name##_stub( PyObject* self, PyObject* other ) \ { \ /* place holder to lazily install __name__ if a global overload is available */ \ if ( ! Utility::AddBinaryOperator( self, other, #op, "__"#name"__" ) ) {\ Py_INCREF( Py_NotImplemented ); \ return Py_NotImplemented; \ } \ \ /* redo the call, which will now go to the newly installed method */ \ return PyObject_CallMethodObjArgs( self, pystring, other, NULL ); \ } PYROOT_STUB( add, +, PyStrings::gAdd ) PYROOT_STUB( sub, -, PyStrings::gSub ) PYROOT_STUB( mul, *, PyStrings::gMul ) PYROOT_STUB( div, /, PyStrings::gDiv ) //____________________________________________________________________________ PyNumberMethods op_as_number = { (binaryfunc)op_add_stub, // nb_add (binaryfunc)op_sub_stub, // nb_subtract (binaryfunc)op_mul_stub, // nb_multiply (binaryfunc)op_div_stub, // nb_divide 0, // nb_remainder 0, // nb_divmod 0, // nb_power 0, // nb_negative 0, // tp_positive 0, // tp_absolute 0, // tp_nonzero 0, // nb_invert 0, // nb_lshift 0, // nb_rshift 0, // nb_and 0, // nb_xor 0, // nb_or 0, // nb_coerce 0, // nb_int 0, // nb_long 0, // nb_float 0, // nb_oct 0, // nb_hex 0, // nb_inplace_add 0, // nb_inplace_subtract 0, // nb_inplace_multiply 0, // nb_inplace_divide 0, // nb_inplace_remainder 0, // nb_inplace_power 0, // nb_inplace_lshift 0, // nb_inplace_rshift 0, // nb_inplace_and 0, // nb_inplace_xor 0 // nb_inplace_or #if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 2 , 0 // nb_floor_divide , 0 // nb_true_divide , 0 // nb_inplace_floor_divide , 0 // nb_inplace_true_divide #endif #if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 5 , 0 // nb_index #endif }; } // unnamed namespace //= PyROOT object proxy type ================================================= PyTypeObject ObjectProxy_Type = { PyObject_HEAD_INIT( &PyRootType_Type ) 0, // ob_size (char*)"ROOT.ObjectProxy", // tp_name sizeof(ObjectProxy), // tp_basicsize 0, // tp_itemsize (destructor)op_dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare (reprfunc)op_repr, // tp_repr 0, //&op_as_number, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, // tp_flags (char*)"PyROOT object proxy (internal)", // tp_doc 0, // tp_traverse 0, // tp_clear (richcmpfunc)op_richcompare, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext op_methods, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc (newfunc)op_new, // tp_new 0, // tp_free 0, // tp_is_gc 0, // tp_bases 0, // tp_mro 0, // tp_cache 0, // tp_subclasses 0 // tp_weaklist #if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 3 , 0 // tp_del #endif #if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 6 , 0 // tp_version_tag #endif }; } // namespace PyROOT <commit_msg>finalie implementation of global overloads<commit_after>// @(#)root/pyroot:$Id$ // Author: Wim Lavrijsen, Jan 2005 // Bindings #include "PyROOT.h" #include "PyStrings.h" #include "ObjectProxy.h" #include "Utility.h" // ROOT #include "TObject.h" #include "TBufferFile.h" // for pickling //- data _______________________________________________________________________ R__EXTERN PyObject* gRootModule; //____________________________________________________________________________ void PyROOT::op_dealloc_nofree( ObjectProxy* pyobj ) { if ( pyobj->fObject && ( pyobj->fFlags & ObjectProxy::kIsOwner ) ) { pyobj->ObjectIsA()->Destructor( pyobj->fObject ); } } //____________________________________________________________________________ namespace PyROOT { namespace { //= PyROOT object proxy nullness checking ==================================== PyObject* op_nonzero( ObjectProxy* self, void* ) { return PyInt_FromLong( self->GetObject() ? 1 : 0 ); } //= PyROOT object proxy pickle support ======================================= PyObject* op_reduce( ObjectProxy* self ) { // Turn the object proxy instance into a character stream and return for // pickle, together with the callable object that can restore the stream // into the object proxy instance. // keep a borrowed reference around to the callable function for expanding; // because it is borrowed, it means that there can be no pickling during the // shutdown of the libPyROOT module static PyObject* s_expand = PyDict_GetItemString( PyModule_GetDict( gRootModule ), const_cast< char* >( "_ObjectProxy__expand__" ) ); // TBuffer and its derived classes can't write themselves, but can be created // directly from the buffer, so handle them in a special case static TClassRef s_bfClass( "TBufferFile" ); TBufferFile* buff = 0; if ( s_bfClass == self->ObjectIsA() ) { buff = (TBufferFile*)self->GetObject(); } else { // no cast is needed, but WriteObject taking a TClass argument is protected, // so use WriteObjectAny() static TBufferFile s_buff( TBuffer::kWrite ); s_buff.Reset(); if ( s_buff.WriteObjectAny( self->GetObject(), self->ObjectIsA() ) != 1 ) { PyErr_Format( PyExc_IOError, "could not stream object of type %s", self->ObjectIsA()->GetName() ); return 0; } buff = &s_buff; } // use a string for the serialized result, as a python buffer will not copy // the buffer contents; use a string for the class name, used when casting // on reading back in (see RootModule.cxx:TObjectExpand) PyObject* res2 = PyTuple_New( 2 ); PyTuple_SET_ITEM( res2, 0, PyString_FromStringAndSize( buff->Buffer(), buff->Length() ) ); PyTuple_SET_ITEM( res2, 1, PyString_FromString( self->ObjectIsA()->GetName() ) ); PyObject* result = PyTuple_New( 2 ); Py_INCREF( s_expand ); PyTuple_SET_ITEM( result, 0, s_expand ); PyTuple_SET_ITEM( result, 1, res2 ); return result; } //____________________________________________________________________________ PyMethodDef op_methods[] = { { (char*)"__nonzero__", (PyCFunction)op_nonzero, METH_NOARGS, NULL }, { (char*)"__reduce__", (PyCFunction)op_reduce, METH_NOARGS, NULL }, { (char*)NULL, NULL, 0, NULL } }; //= PyROOT object proxy construction/destruction ============================= ObjectProxy* op_new( PyTypeObject* subtype, PyObject*, PyObject* ) { ObjectProxy* pyobj = (ObjectProxy*)subtype->tp_alloc( subtype, 0 ); pyobj->fObject = NULL; pyobj->fFlags = 0; return pyobj; } //____________________________________________________________________________ void op_dealloc( ObjectProxy* pyobj ) { op_dealloc_nofree( pyobj ); pyobj->ob_type->tp_free( (PyObject*)pyobj ); } //____________________________________________________________________________ PyObject* op_richcompare( ObjectProxy* self, ObjectProxy* other, int op ) { if ( op != Py_EQ && op != Py_NE ) { Py_INCREF( Py_NotImplemented ); return Py_NotImplemented; } bool bIsEq = false; // special case for None to compare True to a null-pointer if ( (PyObject*)other == Py_None && ! self->fObject ) bIsEq = true; // type + held pointer value defines identity (will cover if other is not // actually an ObjectProxy, as ob_type will be unequal) else if ( self->ob_type == other->ob_type && self->fObject == other->fObject ) bIsEq = true; if ( ( op == Py_EQ && bIsEq ) || ( op == Py_NE && ! bIsEq ) ) { Py_INCREF( Py_True ); return Py_True; } Py_INCREF( Py_False ); return Py_False; } //____________________________________________________________________________ PyObject* op_repr( ObjectProxy* pyobj ) { TClass* klass = pyobj->ObjectIsA(); std::string clName = klass ? klass->GetName() : "<unknown>"; if ( pyobj->fFlags & ObjectProxy::kIsReference ) clName.append( "*" ); // need to prevent accidental derefs when just printing (usually unsafe) if ( ! PyObject_HasAttr( (PyObject*)pyobj, PyStrings::gDeref ) ) { PyObject* name = PyObject_CallMethod( (PyObject*)pyobj, const_cast< char* >( "GetName" ), const_cast< char* >( "" ) ); if ( name ) { if ( PyString_GET_SIZE( name ) != 0 ) { PyObject* repr = PyString_FromFormat( "<ROOT.%s object (\"%s\") at %p>", clName.c_str(), PyString_AS_STRING( name ), pyobj->fObject ); Py_DECREF( name ); return repr; } Py_DECREF( name ); } else PyErr_Clear(); } // get here if object has no method GetName() or name = "" return PyString_FromFormat( const_cast< char* >( "<ROOT.%s object at %p>" ), clName.c_str(), pyobj->fObject ); } //= PyROOT type number stubs to allow dynamic overrides ====================== #define PYROOT_STUB( name, op, pystring ) \ PyObject* op_##name##_stub( PyObject* self, PyObject* other ) \ { \ /* place holder to lazily install __name__ if a global overload is available */ \ if ( ! Utility::AddBinaryOperator( self, other, #op, "__"#name"__" ) ) {\ Py_INCREF( Py_NotImplemented ); \ return Py_NotImplemented; \ } \ \ /* redo the call, which will now go to the newly installed method */ \ return PyObject_CallMethodObjArgs( self, pystring, other, NULL ); \ } PYROOT_STUB( add, +, PyStrings::gAdd ) PYROOT_STUB( sub, -, PyStrings::gSub ) PYROOT_STUB( mul, *, PyStrings::gMul ) PYROOT_STUB( div, /, PyStrings::gDiv ) //____________________________________________________________________________ PyNumberMethods op_as_number = { (binaryfunc)op_add_stub, // nb_add (binaryfunc)op_sub_stub, // nb_subtract (binaryfunc)op_mul_stub, // nb_multiply (binaryfunc)op_div_stub, // nb_divide 0, // nb_remainder 0, // nb_divmod 0, // nb_power 0, // nb_negative 0, // tp_positive 0, // tp_absolute 0, // tp_nonzero 0, // nb_invert 0, // nb_lshift 0, // nb_rshift 0, // nb_and 0, // nb_xor 0, // nb_or 0, // nb_coerce 0, // nb_int 0, // nb_long 0, // nb_float 0, // nb_oct 0, // nb_hex 0, // nb_inplace_add 0, // nb_inplace_subtract 0, // nb_inplace_multiply 0, // nb_inplace_divide 0, // nb_inplace_remainder 0, // nb_inplace_power 0, // nb_inplace_lshift 0, // nb_inplace_rshift 0, // nb_inplace_and 0, // nb_inplace_xor 0 // nb_inplace_or #if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 2 , 0 // nb_floor_divide , 0 // nb_true_divide , 0 // nb_inplace_floor_divide , 0 // nb_inplace_true_divide #endif #if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 5 , 0 // nb_index #endif }; } // unnamed namespace //= PyROOT object proxy type ================================================= PyTypeObject ObjectProxy_Type = { PyObject_HEAD_INIT( &PyRootType_Type ) 0, // ob_size (char*)"ROOT.ObjectProxy", // tp_name sizeof(ObjectProxy), // tp_basicsize 0, // tp_itemsize (destructor)op_dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare (reprfunc)op_repr, // tp_repr &op_as_number, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES, // tp_flags (char*)"PyROOT object proxy (internal)", // tp_doc 0, // tp_traverse 0, // tp_clear (richcmpfunc)op_richcompare, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext op_methods, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc (newfunc)op_new, // tp_new 0, // tp_free 0, // tp_is_gc 0, // tp_bases 0, // tp_mro 0, // tp_cache 0, // tp_subclasses 0 // tp_weaklist #if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 3 , 0 // tp_del #endif #if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 6 , 0 // tp_version_tag #endif }; } // namespace PyROOT <|endoftext|>
<commit_before>// Copyright Daniel Wallin 2007. Use, modification and distribution is // subject to 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) #include <libtorrent/extensions.hpp> #include <libtorrent/entry.hpp> #include <libtorrent/peer_request.hpp> #include <libtorrent/disk_buffer_holder.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; namespace { struct peer_plugin_wrap : peer_plugin, wrapper<peer_plugin> { void add_handshake(entry& e) { if (override f = this->get_override("add_handshake")) e = call<entry>(f.ptr(), e); else peer_plugin::add_handshake(e); } void default_add_handshake(entry& e) { this->peer_plugin::add_handshake(e); } bool on_handshake() { if (override f = this->get_override("on_handshake")) return f(); else return peer_plugin::on_handshake(); } bool default_on_handshake() { return this->peer_plugin::on_handshake(); } bool on_extension_handshake(entry const& e) { if (override f = this->get_override("on_extension_handshake")) return f(e); else return peer_plugin::on_extension_handshake(e); } bool default_on_extension_handshake(entry const& e) { return this->peer_plugin::on_extension_handshake(e); } bool on_choke() { if (override f = this->get_override("on_choke")) return f(); else return peer_plugin::on_choke(); } bool default_on_choke() { return this->peer_plugin::on_choke(); } bool on_unchoke() { if (override f = this->get_override("on_unchoke")) return f(); else return peer_plugin::on_unchoke(); } bool default_on_unchoke() { return this->peer_plugin::on_unchoke(); } bool on_interested() { if (override f = this->get_override("on_interested")) return f(); else return peer_plugin::on_interested(); } bool default_on_interested() { return this->peer_plugin::on_interested(); } bool on_not_interested() { if (override f = this->get_override("on_not_interested")) return f(); else return peer_plugin::on_not_interested(); } bool default_on_not_interested() { return this->peer_plugin::on_not_interested(); } bool on_have(int index) { if (override f = this->get_override("on_have")) return f(index); else return peer_plugin::on_have(index); } bool default_on_have(int index) { return this->peer_plugin::on_have(index); } bool on_bitfield(std::vector<bool> const& bitfield) { if (override f = this->get_override("on_bitfield")) return f(bitfield); else return peer_plugin::on_bitfield(bitfield); } bool default_on_bitfield(std::vector<bool> const& bitfield) { return this->peer_plugin::on_bitfield(bitfield); } bool on_request(peer_request const& req) { if (override f = this->get_override("on_request")) return f(req); else return peer_plugin::on_request(req); } bool default_on_request(peer_request const& req) { return this->peer_plugin::on_request(req); } bool on_piece(peer_request const& piece, disk_buffer_holder& data) { if (override f = this->get_override("on_piece")) return f(piece, data); else return peer_plugin::on_piece(piece, data); } bool default_on_piece(peer_request const& piece, disk_buffer_holder& data) { return this->peer_plugin::on_piece(piece, data); } bool on_cancel(peer_request const& req) { if (override f = this->get_override("on_cancel")) return f(req); else return peer_plugin::on_cancel(req); } bool default_on_cancel(peer_request const& req) { return this->peer_plugin::on_cancel(req); } bool on_extended(int length, int msg, buffer::const_interval body) { if (override f = this->get_override("on_extended")) return f(length, msg, body); else return peer_plugin::on_extended(length, msg, body); } bool default_on_extended(int length, int msg, buffer::const_interval body) { return this->peer_plugin::on_extended(length, msg, body); } bool on_unknown_message(int length, int msg, buffer::const_interval body) { if (override f = this->get_override("on_unknown_message")) return f(length, msg, body); else return peer_plugin::on_unknown_message(length, msg, body); } bool default_on_unknown_message(int length, int msg, buffer::const_interval body) { return this->peer_plugin::on_unknown_message(length, msg, body); } void on_piece_pass(int index) { if (override f = this->get_override("on_piece_pass")) f(index); else peer_plugin::on_piece_pass(index); } void default_on_piece_pass(int index) { this->peer_plugin::on_piece_pass(index); } void on_piece_failed(int index) { if (override f = this->get_override("on_piece_failed")) f(index); else peer_plugin::on_piece_failed(index); } void default_on_piece_failed(int index) { this->peer_plugin::on_piece_failed(index); } void tick() { if (override f = this->get_override("tick")) f(); else peer_plugin::tick(); } void default_tick() { this->peer_plugin::tick(); } bool write_request(peer_request const& req) { if (override f = this->get_override("write_request")) return f(req); else return peer_plugin::write_request(req); } bool default_write_request(peer_request const& req) { return this->peer_plugin::write_request(req); } }; object get_buffer() { static char const data[] = "foobar"; return object(handle<>(PyBuffer_FromMemory((void*)data, 6))); } } // namespace unnamed void bind_peer_plugin() { class_< peer_plugin_wrap, boost::shared_ptr<peer_plugin_wrap>, boost::noncopyable >("peer_plugin") .def( "add_handshake" , &peer_plugin::add_handshake, &peer_plugin_wrap::default_add_handshake ) .def( "on_handshake" , &peer_plugin::on_handshake, &peer_plugin_wrap::default_on_handshake ) .def( "on_extension_handshake" , &peer_plugin::on_extension_handshake , &peer_plugin_wrap::default_on_extension_handshake ) .def( "on_choke" , &peer_plugin::on_choke, &peer_plugin_wrap::default_on_choke ) .def( "on_unchoke" , &peer_plugin::on_unchoke, &peer_plugin_wrap::default_on_unchoke ) .def( "on_interested" , &peer_plugin::on_interested, &peer_plugin_wrap::default_on_interested ) .def( "on_not_interested" , &peer_plugin::on_not_interested, &peer_plugin_wrap::default_on_not_interested ) .def( "on_have" , &peer_plugin::on_have, &peer_plugin_wrap::default_on_have ) .def( "on_bitfield" , &peer_plugin::on_bitfield, &peer_plugin_wrap::default_on_bitfield ) .def( "on_request" , &peer_plugin::on_request, &peer_plugin_wrap::default_on_request ) .def( "on_piece" , &peer_plugin::on_piece, &peer_plugin_wrap::default_on_piece ) .def( "on_cancel" , &peer_plugin::on_cancel, &peer_plugin_wrap::default_on_cancel ) .def( "on_piece_pass" , &peer_plugin::on_piece_pass, &peer_plugin_wrap::default_on_piece_pass ) .def( "on_piece_failed" , &peer_plugin::on_piece_failed, &peer_plugin_wrap::default_on_piece_failed ) .def( "tick" , &peer_plugin::tick, &peer_plugin_wrap::default_tick ) .def( "write_request" , &peer_plugin::write_request, &peer_plugin_wrap::default_write_request ) // These seem to make VC7.1 freeze. Needs special handling. /*.def( "on_extended" , &peer_plugin::on_extended, &peer_plugin_wrap::default_on_extended ) .def( "on_unknown_message" , &peer_plugin::on_unknown_message, &peer_plugin_wrap::default_on_unknown_message )*/ ; def("get_buffer", &get_buffer); } <commit_msg>python binding fixes<commit_after>// Copyright Daniel Wallin 2007. Use, modification and distribution is // subject to 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) #include <libtorrent/extensions.hpp> #include <libtorrent/entry.hpp> #include <libtorrent/peer_request.hpp> #include <libtorrent/disk_buffer_holder.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; namespace { struct peer_plugin_wrap : peer_plugin, wrapper<peer_plugin> { void add_handshake(entry& e) { if (override f = this->get_override("add_handshake")) e = call<entry>(f.ptr(), e); else peer_plugin::add_handshake(e); } void default_add_handshake(entry& e) { this->peer_plugin::add_handshake(e); } bool on_handshake(char const* reserved_bits) { if (override f = this->get_override("on_handshake")) return f(); else return peer_plugin::on_handshake(reserved_bits); } bool default_on_handshake(char const* reserved_bits) { return this->peer_plugin::on_handshake(reserved_bits); } bool on_extension_handshake(entry const& e) { if (override f = this->get_override("on_extension_handshake")) return f(e); else return peer_plugin::on_extension_handshake(e); } bool default_on_extension_handshake(entry const& e) { return this->peer_plugin::on_extension_handshake(e); } bool on_choke() { if (override f = this->get_override("on_choke")) return f(); else return peer_plugin::on_choke(); } bool default_on_choke() { return this->peer_plugin::on_choke(); } bool on_unchoke() { if (override f = this->get_override("on_unchoke")) return f(); else return peer_plugin::on_unchoke(); } bool default_on_unchoke() { return this->peer_plugin::on_unchoke(); } bool on_interested() { if (override f = this->get_override("on_interested")) return f(); else return peer_plugin::on_interested(); } bool default_on_interested() { return this->peer_plugin::on_interested(); } bool on_not_interested() { if (override f = this->get_override("on_not_interested")) return f(); else return peer_plugin::on_not_interested(); } bool default_on_not_interested() { return this->peer_plugin::on_not_interested(); } bool on_have(int index) { if (override f = this->get_override("on_have")) return f(index); else return peer_plugin::on_have(index); } bool default_on_have(int index) { return this->peer_plugin::on_have(index); } bool on_bitfield(std::vector<bool> const& bitfield) { if (override f = this->get_override("on_bitfield")) return f(bitfield); else return peer_plugin::on_bitfield(bitfield); } bool default_on_bitfield(std::vector<bool> const& bitfield) { return this->peer_plugin::on_bitfield(bitfield); } bool on_request(peer_request const& req) { if (override f = this->get_override("on_request")) return f(req); else return peer_plugin::on_request(req); } bool default_on_request(peer_request const& req) { return this->peer_plugin::on_request(req); } bool on_piece(peer_request const& piece, disk_buffer_holder& data) { if (override f = this->get_override("on_piece")) return f(piece, data); else return peer_plugin::on_piece(piece, data); } bool default_on_piece(peer_request const& piece, disk_buffer_holder& data) { return this->peer_plugin::on_piece(piece, data); } bool on_cancel(peer_request const& req) { if (override f = this->get_override("on_cancel")) return f(req); else return peer_plugin::on_cancel(req); } bool default_on_cancel(peer_request const& req) { return this->peer_plugin::on_cancel(req); } bool on_extended(int length, int msg, buffer::const_interval body) { if (override f = this->get_override("on_extended")) return f(length, msg, body); else return peer_plugin::on_extended(length, msg, body); } bool default_on_extended(int length, int msg, buffer::const_interval body) { return this->peer_plugin::on_extended(length, msg, body); } bool on_unknown_message(int length, int msg, buffer::const_interval body) { if (override f = this->get_override("on_unknown_message")) return f(length, msg, body); else return peer_plugin::on_unknown_message(length, msg, body); } bool default_on_unknown_message(int length, int msg, buffer::const_interval body) { return this->peer_plugin::on_unknown_message(length, msg, body); } void on_piece_pass(int index) { if (override f = this->get_override("on_piece_pass")) f(index); else peer_plugin::on_piece_pass(index); } void default_on_piece_pass(int index) { this->peer_plugin::on_piece_pass(index); } void on_piece_failed(int index) { if (override f = this->get_override("on_piece_failed")) f(index); else peer_plugin::on_piece_failed(index); } void default_on_piece_failed(int index) { this->peer_plugin::on_piece_failed(index); } void tick() { if (override f = this->get_override("tick")) f(); else peer_plugin::tick(); } void default_tick() { this->peer_plugin::tick(); } bool write_request(peer_request const& req) { if (override f = this->get_override("write_request")) return f(req); else return peer_plugin::write_request(req); } bool default_write_request(peer_request const& req) { return this->peer_plugin::write_request(req); } }; object get_buffer() { static char const data[] = "foobar"; return object(handle<>(PyBuffer_FromMemory((void*)data, 6))); } } // namespace unnamed void bind_peer_plugin() { class_< peer_plugin_wrap, boost::shared_ptr<peer_plugin_wrap>, boost::noncopyable >("peer_plugin") .def( "add_handshake" , &peer_plugin::add_handshake, &peer_plugin_wrap::default_add_handshake ) .def( "on_handshake" , &peer_plugin::on_handshake, &peer_plugin_wrap::default_on_handshake ) .def( "on_extension_handshake" , &peer_plugin::on_extension_handshake , &peer_plugin_wrap::default_on_extension_handshake ) .def( "on_choke" , &peer_plugin::on_choke, &peer_plugin_wrap::default_on_choke ) .def( "on_unchoke" , &peer_plugin::on_unchoke, &peer_plugin_wrap::default_on_unchoke ) .def( "on_interested" , &peer_plugin::on_interested, &peer_plugin_wrap::default_on_interested ) .def( "on_not_interested" , &peer_plugin::on_not_interested, &peer_plugin_wrap::default_on_not_interested ) .def( "on_have" , &peer_plugin::on_have, &peer_plugin_wrap::default_on_have ) .def( "on_bitfield" , &peer_plugin::on_bitfield, &peer_plugin_wrap::default_on_bitfield ) .def( "on_request" , &peer_plugin::on_request, &peer_plugin_wrap::default_on_request ) .def( "on_piece" , &peer_plugin::on_piece, &peer_plugin_wrap::default_on_piece ) .def( "on_cancel" , &peer_plugin::on_cancel, &peer_plugin_wrap::default_on_cancel ) .def( "on_piece_pass" , &peer_plugin::on_piece_pass, &peer_plugin_wrap::default_on_piece_pass ) .def( "on_piece_failed" , &peer_plugin::on_piece_failed, &peer_plugin_wrap::default_on_piece_failed ) .def( "tick" , &peer_plugin::tick, &peer_plugin_wrap::default_tick ) .def( "write_request" , &peer_plugin::write_request, &peer_plugin_wrap::default_write_request ) // These seem to make VC7.1 freeze. Needs special handling. /*.def( "on_extended" , &peer_plugin::on_extended, &peer_plugin_wrap::default_on_extended ) .def( "on_unknown_message" , &peer_plugin::on_unknown_message, &peer_plugin_wrap::default_on_unknown_message )*/ ; def("get_buffer", &get_buffer); } <|endoftext|>
<commit_before>// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved // Please see LICENSE.md in repository root for license information // https://github.com/AtomicGameEngine/AtomicGameEngine #include "AtomicEditor.h" #include <rapidjson/document.h> #include "rapidjson/prettywriter.h" #include "rapidjson/filestream.h" #include <Atomic/Core/Context.h> #include <Atomic/IO/FileSystem.h> #include <Atomic/IO/Log.h> #include <Atomic/IO/File.h> #include <Atomic/Graphics/Graphics.h> #include "AEEvents.h" #include "AEPreferences.h" using namespace rapidjson; namespace AtomicEditor { AEPreferences::AEPreferences(Context* context) : Object(context) { context->RegisterSubsystem(this); SubscribeToEvent(E_EDITORSHUTDOWN, HANDLER(AEPreferences, HandleEditorShutdown)); Read(); } AEPreferences::~AEPreferences() { } String AEPreferences::GetPreferencesFullPath() { FileSystem* fs = GetSubsystem<FileSystem>(); String filepath = fs->GetAppPreferencesDir("AtomicEditor", "Preferences"); filepath += "prefs.json"; return filepath; } void AEPreferences::Clear() { recentProjects_.Clear(); } void AEPreferences::Read() { rapidjson::Document document; String filepath = GetPreferencesFullPath(); File jsonFile(context_, filepath); if (!jsonFile.IsOpen()) return; String json; jsonFile.ReadText(json); if (!json.Length()) return; if (document.Parse<0>(json.CString()).HasParseError()) { LOGERRORF("Could not parse JSON data from %s", filepath.CString()); return; } Clear(); const Value::Member* recent_files = document.FindMember("recent_files"); if (recent_files && recent_files->value.IsArray()) { for (Value::ConstValueIterator itr = recent_files->value.Begin(); itr != recent_files->value.End(); itr++) { if (!(*itr).IsString()) continue; String path(itr->GetString()); recentProjects_.Push(path.CString()); } } const Value::Member* android_sdk_path = document.FindMember("android_sdk_path"); if (android_sdk_path && android_sdk_path->value.IsString()) androidSDKPath_ = android_sdk_path->value.GetString(); const Value::Member* jdk_root_path = document.FindMember("jdk_root_path"); if (jdk_root_path && jdk_root_path->value.IsString()) jdkRootPath_ = jdk_root_path->value.GetString(); const Value::Member* ant_path = document.FindMember("ant_path"); if (ant_path && ant_path->value.IsString()) antPath_ = ant_path->value.GetString(); UpdateRecentFiles(false); } void AEPreferences::Write() { String filepath = GetPreferencesFullPath(); FILE* file = fopen(filepath.CString(), "w"); if (!file) return; Graphics* graphics = GetSubsystem<Graphics>(); IntVector2 pos(-1, -1); int width = -1; int height = -1; if (graphics && !graphics->GetFullscreen()) { pos = graphics->GetWindowPosition(); width = graphics->GetWidth(); height = graphics->GetHeight(); } rapidjson::FileStream s(file); rapidjson::PrettyWriter<rapidjson::FileStream> writer(s); writer.StartObject(); // recent files writer.String("recent_files"); writer.StartArray(); for (unsigned i = 0; i < recentProjects_.Size(); i++) writer.String(recentProjects_[i].CString()); writer.EndArray(); writer.String("android_sdk_path"); writer.String(androidSDKPath_.CString()); writer.String("jdk_root_path"); writer.String(jdkRootPath_.CString()); writer.String("ant_path"); writer.String(antPath_.CString()); writer.String("window_pos_x"); writer.Int(pos.x_); writer.String("window_pos_y"); writer.Int(pos.y_); writer.String("window_width"); writer.Int(width); writer.String("window_height"); writer.Int(height); writer.EndObject(); fclose(file); } void AEPreferences::UpdateRecentFiles(bool write) { FileSystem* fileSystem = GetSubsystem<FileSystem>(); Vector<String> recentProjects; for (unsigned i = 0; i < recentProjects_.Size(); i++) { String path = recentProjects_[i]; if (!fileSystem->FileExists(path)) continue; recentProjects.Push(path); if (recentProjects.Size() == 10) break; } recentProjects_ = recentProjects; if (write) Write(); } void AEPreferences::RegisterRecentProject(const String& fullpath) { if (recentProjects_.Contains(fullpath)) { recentProjects_.Remove(fullpath); } recentProjects_.Insert(0, fullpath); UpdateRecentFiles(); } bool AEPreferences::ReadStartupPrefs(Context *context, StartupPreferences& prefs) { FileSystem* fileSystem = context->GetSubsystem<FileSystem>(); String filepath = fileSystem->GetAppPreferencesDir("AtomicEditor", "Preferences"); filepath += "prefs.json"; if (!fileSystem->FileExists(filepath)) return false; SharedPtr<File> file(new File(context, filepath, FILE_READ)); if (!file->IsOpen()) return false; String json; file->ReadText(json); if (!json.Length()) return false; rapidjson::Document document; if (document.Parse<0>(json.CString()).HasParseError()) { return false; } bool success = true; const Value::Member* imember = document.FindMember("window_pos_x"); if (imember && imember->value.IsInt()) { prefs.windowPos.x_ = imember->value.GetInt(); } else { success = false; } imember = document.FindMember("window_pos_y"); if (imember && imember->value.IsInt()) { prefs.windowPos.y_ = imember->value.GetInt(); } else { success = false; } imember = document.FindMember("window_width"); if (imember && imember->value.IsInt()) { prefs.windowWidth = imember->value.GetInt(); } else { success = false; } imember = document.FindMember("window_height"); if (imember && imember->value.IsInt()) { prefs.windowHeight = imember->value.GetInt(); } else { success = false; } if (prefs.windowHeight < 128 || prefs.windowWidth < 128) return false; return success; } void AEPreferences::HandleEditorShutdown(StringHash eventType, VariantMap& eventData) { context_->RemoveSubsystem(GetType()); } } <commit_msg>fix #537<commit_after>// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved // Please see LICENSE.md in repository root for license information // https://github.com/AtomicGameEngine/AtomicGameEngine #include "AtomicEditor.h" #include <rapidjson/document.h> #include "rapidjson/prettywriter.h" #include "rapidjson/filestream.h" #include <Atomic/Core/Context.h> #include <Atomic/IO/FileSystem.h> #include <Atomic/IO/Log.h> #include <Atomic/IO/File.h> #include <Atomic/Graphics/Graphics.h> #include "AEEvents.h" #include "AEPreferences.h" using namespace rapidjson; namespace AtomicEditor { AEPreferences::AEPreferences(Context* context) : Object(context) { context->RegisterSubsystem(this); SubscribeToEvent(E_EDITORSHUTDOWN, HANDLER(AEPreferences, HandleEditorShutdown)); Read(); } AEPreferences::~AEPreferences() { } String AEPreferences::GetPreferencesFullPath() { FileSystem* fs = GetSubsystem<FileSystem>(); String filepath = fs->GetAppPreferencesDir("AtomicEditor", "Preferences"); filepath += "prefs.json"; return filepath; } void AEPreferences::Clear() { recentProjects_.Clear(); } void AEPreferences::Read() { rapidjson::Document document; String filepath = GetPreferencesFullPath(); File jsonFile(context_, filepath); if (!jsonFile.IsOpen()) return; String json; jsonFile.ReadText(json); if (!json.Length()) return; if (document.Parse<0>(json.CString()).HasParseError()) { LOGERRORF("Could not parse JSON data from %s", filepath.CString()); return; } Clear(); const Value::Member* recent_files = document.FindMember("recent_files"); if (recent_files && recent_files->value.IsArray()) { for (Value::ConstValueIterator itr = recent_files->value.Begin(); itr != recent_files->value.End(); itr++) { if (!(*itr).IsString()) continue; String path(itr->GetString()); recentProjects_.Push(path.CString()); } } const Value::Member* android_sdk_path = document.FindMember("android_sdk_path"); if (android_sdk_path && android_sdk_path->value.IsString()) androidSDKPath_ = android_sdk_path->value.GetString(); const Value::Member* jdk_root_path = document.FindMember("jdk_root_path"); if (jdk_root_path && jdk_root_path->value.IsString()) jdkRootPath_ = jdk_root_path->value.GetString(); const Value::Member* ant_path = document.FindMember("ant_path"); if (ant_path && ant_path->value.IsString()) antPath_ = ant_path->value.GetString(); UpdateRecentFiles(false); } void AEPreferences::Write() { String filepath = GetPreferencesFullPath(); FILE* file = fopen(filepath.CString(), "w"); if (!file) return; Graphics* graphics = GetSubsystem<Graphics>(); IntVector2 pos(-1, -1); int width = -1; int height = -1; if (graphics && !graphics->GetFullscreen()) { pos = graphics->GetWindowPosition(); width = graphics->GetWidth(); height = graphics->GetHeight(); } rapidjson::FileStream s(file); rapidjson::PrettyWriter<rapidjson::FileStream> writer(s); writer.StartObject(); // recent files writer.String("recent_files"); writer.StartArray(); for (unsigned i = 0; i < recentProjects_.Size(); i++) writer.String(recentProjects_[i].CString()); writer.EndArray(); writer.String("android_sdk_path"); writer.String(androidSDKPath_.CString()); writer.String("jdk_root_path"); writer.String(jdkRootPath_.CString()); writer.String("ant_path"); writer.String(antPath_.CString()); writer.String("window_pos_x"); writer.Int(pos.x_); writer.String("window_pos_y"); writer.Int(pos.y_); writer.String("window_width"); writer.Int(width); writer.String("window_height"); writer.Int(height); writer.EndObject(); fclose(file); } void AEPreferences::UpdateRecentFiles(bool write) { FileSystem* fileSystem = GetSubsystem<FileSystem>(); Vector<String> recentProjects; for (unsigned i = 0; i < recentProjects_.Size(); i++) { String path = recentProjects_[i]; if (!fileSystem->FileExists(path)) continue; recentProjects.Push(path); if (recentProjects.Size() > 0 && recentProjects.Size() <= 15) break; } recentProjects_ = recentProjects; if (write) Write(); } void AEPreferences::RegisterRecentProject(const String& fullpath) { if (recentProjects_.Contains(fullpath)) { recentProjects_.Remove(fullpath); } recentProjects_.Insert(0, fullpath); UpdateRecentFiles(); } bool AEPreferences::ReadStartupPrefs(Context *context, StartupPreferences& prefs) { FileSystem* fileSystem = context->GetSubsystem<FileSystem>(); String filepath = fileSystem->GetAppPreferencesDir("AtomicEditor", "Preferences"); filepath += "prefs.json"; if (!fileSystem->FileExists(filepath)) return false; SharedPtr<File> file(new File(context, filepath, FILE_READ)); if (!file->IsOpen()) return false; String json; file->ReadText(json); if (!json.Length()) return false; rapidjson::Document document; if (document.Parse<0>(json.CString()).HasParseError()) { return false; } bool success = true; const Value::Member* imember = document.FindMember("window_pos_x"); if (imember && imember->value.IsInt()) { prefs.windowPos.x_ = imember->value.GetInt(); } else { success = false; } imember = document.FindMember("window_pos_y"); if (imember && imember->value.IsInt()) { prefs.windowPos.y_ = imember->value.GetInt(); } else { success = false; } imember = document.FindMember("window_width"); if (imember && imember->value.IsInt()) { prefs.windowWidth = imember->value.GetInt(); } else { success = false; } imember = document.FindMember("window_height"); if (imember && imember->value.IsInt()) { prefs.windowHeight = imember->value.GetInt(); } else { success = false; } if (prefs.windowHeight < 128 || prefs.windowWidth < 128) return false; return success; } void AEPreferences::HandleEditorShutdown(StringHash eventType, VariantMap& eventData) { context_->RemoveSubsystem(GetType()); } } <|endoftext|>
<commit_before>// // AHDSHREnvelope.cpp // AudioKit // // Created by Jeff Cooper on 5/21/20. // Copyright © 2020 AudioKit. All rights reserved. // #include "AHDSHREnvelope.hpp" #include <cmath> namespace AudioKitCore { AHDSHREnvelopeParameters::AHDSHREnvelopeParameters() : sampleRateHz(44100.0f) // a guess, will be overridden later by a call to init(,,,,) { init(0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f); } void AHDSHREnvelopeParameters::init(float attackSeconds, float holdSeconds, float decaySeconds, float susFraction, float releaseHoldSeconds, float releaseSeconds) { attackSamples = attackSeconds * sampleRateHz; holdSamples = holdSeconds * sampleRateHz; decaySamples = decaySeconds * sampleRateHz; sustainFraction = susFraction; releaseHoldSamples = releaseHoldSeconds * sampleRateHz; releaseSamples = releaseSeconds * sampleRateHz; } void AHDSHREnvelopeParameters::init(float newSampleRateHz, float attackSeconds, float holdSeconds, float decaySeconds, float susFraction, float releaseHoldSeconds, float releaseSeconds) { sampleRateHz = newSampleRateHz; init(attackSeconds, holdSeconds, decaySeconds, susFraction, releaseHoldSeconds, releaseSeconds); } void AHDSHREnvelopeParameters::updateSampleRate(float newSampleRateHz) { float scaleFactor = newSampleRateHz / sampleRateHz; sampleRateHz = newSampleRateHz; attackSamples *= scaleFactor; holdSamples *= scaleFactor; decaySamples *= scaleFactor; releaseHoldSamples *= scaleFactor; releaseSamples *= scaleFactor; } void AHDSHREnvelope::init(CurvatureType curvatureType) { int silenceSamples = int(0.01 * pParameters->sampleRateHz); // always 10 mSec int attackSamples = int(pParameters->attackSamples); int holdSamples = int(pParameters->holdSamples); int decaySamples = int(pParameters->decaySamples); double sustainFraction = double(pParameters->sustainFraction); int releaseHoldSamples = int(pParameters->releaseHoldSamples); int releaseSamples = int(pParameters->releaseSamples); envDesc.clear(); envDesc.push_back({ 0.0, 0.0, 0.0, -1 }); // kIdle: 0 forever envDesc.push_back({ 1.0, 0.0, 0.0, silenceSamples }); // kSilence in 10 mSec if (curvatureType == kAnalogLike) { envDesc.push_back({ 0.0, 1.0, exp(-1.5), attackSamples }); // kAttack envDesc.push_back({ 1.0, 1.0, 0.0, holdSamples }); // kHold envDesc.push_back({ 1.0, sustainFraction, exp(-4.95), decaySamples }); // kDecay envDesc.push_back({ sustainFraction, sustainFraction, 0.0, -1 }); // kSustain envDesc.push_back({ sustainFraction, sustainFraction, 0.0, releaseHoldSamples }); // kReleaseHold envDesc.push_back({ sustainFraction, 0.0, exp(-4.95), releaseSamples }); // kRelease } else if (curvatureType == kLinearInDb) { envDesc.push_back({ 0.0, 1.0, 0.99999, attackSamples }); // kAttack envDesc.push_back({ 1.0, 1.0, 0.0, holdSamples }); // kHold envDesc.push_back({ 1.0, sustainFraction, exp(-11.05), decaySamples }); // kDecay envDesc.push_back({ sustainFraction, sustainFraction, 0.0, -1 }); // kSustain envDesc.push_back({ sustainFraction, sustainFraction, 0.0, releaseHoldSamples }); // kReleaseHold envDesc.push_back({ sustainFraction, 0.0, exp(-11.05), releaseSamples }); // kRelease } else { envDesc.push_back({ 0.0, 1.0, 0.0, attackSamples }); // kAttack envDesc.push_back({ 1.0, 1.0, 0.0, holdSamples }); // kHold envDesc.push_back({ 1.0, sustainFraction, 0.0, decaySamples }); // kDecay envDesc.push_back({ sustainFraction, sustainFraction, 0.0, -1 }); // kSustain envDesc.push_back({ sustainFraction, sustainFraction, 0.0, releaseHoldSamples }); // kReleaseHold envDesc.push_back({ sustainFraction, 0.0, 0.0, releaseSamples }); // kRelease } env.reset(&envDesc); } void AHDSHREnvelope::updateParams() { if (envDesc.size() < 8) return; double sustainFraction = double(pParameters->sustainFraction); envDesc[kAttack].lengthSamples = int(pParameters->attackSamples); envDesc[kHold].initialValue = sustainFraction; envDesc[kHold].finalValue = sustainFraction; envDesc[kHold].lengthSamples = int(pParameters->holdSamples); envDesc[kDecay].finalValue = sustainFraction; envDesc[kDecay].lengthSamples = int(pParameters->decaySamples); envDesc[kSustain].initialValue = envDesc[kSustain].finalValue = sustainFraction; envDesc[kReleaseHold].initialValue = sustainFraction; envDesc[kReleaseHold].finalValue = sustainFraction; envDesc[kReleaseHold].lengthSamples = int(pParameters->releaseHoldSamples); envDesc[kRelease].initialValue = sustainFraction; envDesc[kRelease].lengthSamples = int(pParameters->releaseSamples); } void AHDSHREnvelope::start() { env.advanceToSegment(kAttack); } void AHDSHREnvelope::restart() { env.advanceToSegment(kSilence); } void AHDSHREnvelope::release() { env.advanceToSegment(kReleaseHold); } void AHDSHREnvelope::reset() { env.reset(&envDesc); } } <commit_msg>set hold value to 1 instead of fraction value<commit_after>// // AHDSHREnvelope.cpp // AudioKit // // Created by Jeff Cooper on 5/21/20. // Copyright © 2020 AudioKit. All rights reserved. // #include "AHDSHREnvelope.hpp" #include <cmath> namespace AudioKitCore { AHDSHREnvelopeParameters::AHDSHREnvelopeParameters() : sampleRateHz(44100.0f) // a guess, will be overridden later by a call to init(,,,,) { init(0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f); } void AHDSHREnvelopeParameters::init(float attackSeconds, float holdSeconds, float decaySeconds, float susFraction, float releaseHoldSeconds, float releaseSeconds) { attackSamples = attackSeconds * sampleRateHz; holdSamples = holdSeconds * sampleRateHz; decaySamples = decaySeconds * sampleRateHz; sustainFraction = susFraction; releaseHoldSamples = releaseHoldSeconds * sampleRateHz; releaseSamples = releaseSeconds * sampleRateHz; } void AHDSHREnvelopeParameters::init(float newSampleRateHz, float attackSeconds, float holdSeconds, float decaySeconds, float susFraction, float releaseHoldSeconds, float releaseSeconds) { sampleRateHz = newSampleRateHz; init(attackSeconds, holdSeconds, decaySeconds, susFraction, releaseHoldSeconds, releaseSeconds); } void AHDSHREnvelopeParameters::updateSampleRate(float newSampleRateHz) { float scaleFactor = newSampleRateHz / sampleRateHz; sampleRateHz = newSampleRateHz; attackSamples *= scaleFactor; holdSamples *= scaleFactor; decaySamples *= scaleFactor; releaseHoldSamples *= scaleFactor; releaseSamples *= scaleFactor; } void AHDSHREnvelope::init(CurvatureType curvatureType) { int silenceSamples = int(0.01 * pParameters->sampleRateHz); // always 10 mSec int attackSamples = int(pParameters->attackSamples); int holdSamples = int(pParameters->holdSamples); int decaySamples = int(pParameters->decaySamples); double sustainFraction = double(pParameters->sustainFraction); int releaseHoldSamples = int(pParameters->releaseHoldSamples); int releaseSamples = int(pParameters->releaseSamples); envDesc.clear(); envDesc.push_back({ 0.0, 0.0, 0.0, -1 }); // kIdle: 0 forever envDesc.push_back({ 1.0, 0.0, 0.0, silenceSamples }); // kSilence in 10 mSec if (curvatureType == kAnalogLike) { envDesc.push_back({ 0.0, 1.0, exp(-1.5), attackSamples }); // kAttack envDesc.push_back({ 1.0, 1.0, 0.0, holdSamples }); // kHold envDesc.push_back({ 1.0, sustainFraction, exp(-4.95), decaySamples }); // kDecay envDesc.push_back({ sustainFraction, sustainFraction, 0.0, -1 }); // kSustain envDesc.push_back({ sustainFraction, sustainFraction, 0.0, releaseHoldSamples }); // kReleaseHold envDesc.push_back({ sustainFraction, 0.0, exp(-4.95), releaseSamples }); // kRelease } else if (curvatureType == kLinearInDb) { envDesc.push_back({ 0.0, 1.0, 0.99999, attackSamples }); // kAttack envDesc.push_back({ 1.0, 1.0, 0.0, holdSamples }); // kHold envDesc.push_back({ 1.0, sustainFraction, exp(-11.05), decaySamples }); // kDecay envDesc.push_back({ sustainFraction, sustainFraction, 0.0, -1 }); // kSustain envDesc.push_back({ sustainFraction, sustainFraction, 0.0, releaseHoldSamples }); // kReleaseHold envDesc.push_back({ sustainFraction, 0.0, exp(-11.05), releaseSamples }); // kRelease } else { envDesc.push_back({ 0.0, 1.0, 0.0, attackSamples }); // kAttack envDesc.push_back({ 1.0, 1.0, 0.0, holdSamples }); // kHold envDesc.push_back({ 1.0, sustainFraction, 0.0, decaySamples }); // kDecay envDesc.push_back({ sustainFraction, sustainFraction, 0.0, -1 }); // kSustain envDesc.push_back({ sustainFraction, sustainFraction, 0.0, releaseHoldSamples }); // kReleaseHold envDesc.push_back({ sustainFraction, 0.0, 0.0, releaseSamples }); // kRelease } env.reset(&envDesc); } void AHDSHREnvelope::updateParams() { if (envDesc.size() < 8) return; double sustainFraction = double(pParameters->sustainFraction); envDesc[kAttack].lengthSamples = int(pParameters->attackSamples); envDesc[kHold].initialValue = 1.0; envDesc[kHold].finalValue = 1.0; envDesc[kHold].lengthSamples = int(pParameters->holdSamples); envDesc[kDecay].finalValue = sustainFraction; envDesc[kDecay].lengthSamples = int(pParameters->decaySamples); envDesc[kSustain].initialValue = envDesc[kSustain].finalValue = sustainFraction; envDesc[kReleaseHold].initialValue = sustainFraction; envDesc[kReleaseHold].finalValue = sustainFraction; envDesc[kReleaseHold].lengthSamples = int(pParameters->releaseHoldSamples); envDesc[kRelease].initialValue = sustainFraction; envDesc[kRelease].lengthSamples = int(pParameters->releaseSamples); } void AHDSHREnvelope::start() { env.advanceToSegment(kAttack); } void AHDSHREnvelope::restart() { env.advanceToSegment(kSilence); } void AHDSHREnvelope::release() { env.advanceToSegment(kReleaseHold); } void AHDSHREnvelope::reset() { env.reset(&envDesc); } } <|endoftext|>
<commit_before>#include "Stabilization.h" #include <sofa/core/ObjectFactory.h> #include "../utils/map.h" namespace sofa { namespace component { namespace odesolver { SOFA_DECL_CLASS(Stabilization); int StabilizationClass = core::RegisterObject("Kinematic constraint stabilization").add< Stabilization >(); Stabilization::Stabilization( mstate_type* mstate ) : BaseConstraintValue( mstate ) , mask(initData(&mask, "mask", "dofs to be stabilized")) { } void Stabilization::correction(SReal* dst, unsigned n) const { assert( mstate ); assert( mask.empty() || mask.size() == n ); mstate->copyToBuffer(dst, core::VecCoordId::position(), n); // TODO needed ? map(dst, n) = -map(dst, n) / this->getContext()->getDt(); const mask_type& mask = this->mask.getValue(); // non-zero for stabilized unsigned i = 0; for(SReal* last = dst + n; dst < last; ++dst, ++i) { if( !mask.empty() && !mask[i] ) *dst = 0; } } void Stabilization::dynamics(SReal* dst, unsigned n) const { assert( mstate ); assert( mask.empty() || mask.size() == n ); mstate->copyToBuffer(dst, core::VecCoordId::position(), n); map(dst, n) = -map(dst, n) / this->getContext()->getDt(); const mask_type& mask = this->mask.getValue(); // zero for stabilized, since the position error will be handled by the correction unsigned i = 0; for(SReal* last = dst + n; dst < last; ++dst, ++i) { if( mask.empty() || mask[i] ) *dst = 0; } } } } } <commit_msg>r10438/sofa : fix compilation<commit_after>#include "Stabilization.h" #include <sofa/core/ObjectFactory.h> #include "../utils/map.h" namespace sofa { namespace component { namespace odesolver { SOFA_DECL_CLASS(Stabilization); int StabilizationClass = core::RegisterObject("Kinematic constraint stabilization").add< Stabilization >(); Stabilization::Stabilization( mstate_type* mstate ) : BaseConstraintValue( mstate ) , mask(initData(&mask, "mask", "dofs to be stabilized")) { } void Stabilization::correction(SReal* dst, unsigned n) const { assert( mstate ); assert( mask.getValue().empty() || mask.getValue().size() == n ); mstate->copyToBuffer(dst, core::VecCoordId::position(), n); // TODO needed ? map(dst, n) = -map(dst, n) / this->getContext()->getDt(); const mask_type& mask = this->mask.getValue(); // non-zero for stabilized unsigned i = 0; for(SReal* last = dst + n; dst < last; ++dst, ++i) { if( !mask.empty() && !mask[i] ) *dst = 0; } } void Stabilization::dynamics(SReal* dst, unsigned n) const { assert( mstate ); assert( mask.getValue().empty() || mask.getValue().size() == n ); mstate->copyToBuffer(dst, core::VecCoordId::position(), n); map(dst, n) = -map(dst, n) / this->getContext()->getDt(); const mask_type& mask = this->mask.getValue(); // zero for stabilized, since the position error will be handled by the correction unsigned i = 0; for(SReal* last = dst + n; dst < last; ++dst, ++i) { if( mask.empty() || mask[i] ) *dst = 0; } } } } } <|endoftext|>
<commit_before>// // Created by Sam on 3/29/2018. // #include "../../../../include/Network/Response/Game/CreatureAttackedMessage.h" #include "../../../../include/Game/Player.h" #include "../../../../include/Game/Card/Creature.h" CreatureAttackedMessage::CreatureAttackedMessage(CreatureAttackedEvent creatureAttackedEvent) { auto target = creatureAttackedEvent.target; auto attacker = creatureAttackedEvent.attacker; rawJSON[TYPE_KEY] = Message::CREATURE_ATTACKED; rawJSON[DATA_KEY]["target"] = target->getJSON(); rawJSON[DATA_KEY]["attacker"] = attacker->getJSON(); rawJSON[DATA_KEY]["attackerOwner"] = creatureAttackedEvent.attacker->player->getJSON(); } CreatureAttackedMessage::~CreatureAttackedMessage() = default; <commit_msg>Changed the CreatureAttacked message to be more inline with that the client is expecting<commit_after>// // Created by Sam on 3/29/2018. // #include "../../../../include/Network/Response/Game/CreatureAttackedMessage.h" #include "../../../../include/Game/Player.h" #include "../../../../include/Game/Card/Creature.h" CreatureAttackedMessage::CreatureAttackedMessage(CreatureAttackedEvent creatureAttackedEvent) { auto target = creatureAttackedEvent.target; auto attacker = creatureAttackedEvent.attacker; rawJSON[TYPE_KEY] = Message::CREATURE_ATTACKED; rawJSON[DATA_KEY]["targetCardTag"] = target->tag; rawJSON[DATA_KEY]["attackerCardTag"] = attacker->tag; rawJSON[DATA_KEY]["attackerOwnerTag"] = creatureAttackedEvent.attacker->player->tag; } CreatureAttackedMessage::~CreatureAttackedMessage() = default; <|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) 2015-2017 Francois Beaune, The appleseedhq Organization // // 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 "renderersettings.h" // appleseed-max headers. #include "appleseedrenderer/datachunks.h" #include "utilities.h" // appleseed.renderer headers. #include "renderer/api/project.h" #include "renderer/api/utility.h" // 3ds Max headers. #include <ioapi.h> namespace asr = renderer; namespace { struct DefaultRendererSettings : public RendererSettings { DefaultRendererSettings() { m_pixel_samples = 16; m_passes = 1; m_tile_size = 64; m_gi = true; m_caustics = false; m_bounces = 8; m_max_ray_intensity_set = false; m_max_ray_intensity = 0.0f; m_background_emits_light = true; m_background_alpha = 0.0f; m_output_mode = OutputMode::RenderOnly; m_scale_multiplier = 1.0f; m_rendering_threads = 0; // 0 = as many as there are logical cores m_low_priority_mode = true; m_use_max_procedural_maps = false; } }; } const RendererSettings& RendererSettings::defaults() { static DefaultRendererSettings default_settings; return default_settings; } void RendererSettings::apply(asr::Project& project) const { apply_common_settings(project, "final"); apply_common_settings(project, "interactive"); apply_settings_to_final_config(project); apply_settings_to_interactive_config(project); } void RendererSettings::apply_common_settings(asr::Project& project, const char* config_name) const { asr::ParamArray& params = project.configurations().get_by_name(config_name)->get_parameters(); params.insert_path("sampling_mode", "qmc"); if (!m_gi) params.insert_path("pt.max_diffuse_bounces", 0); params.insert_path("pt.max_bounces", m_bounces); params.insert_path("pt.enable_ibl", m_background_emits_light); params.insert_path("pt.enable_caustics", m_caustics); if (m_max_ray_intensity_set) params.insert_path("pt.max_ray_intensity", m_max_ray_intensity); if (m_rendering_threads == 0) params.insert_path("rendering_threads", "auto"); else params.insert_path("rendering_threads", m_rendering_threads); //params.insert_path("shading_engine.override_shading.mode", "shading_normal"); } void RendererSettings::apply_settings_to_final_config(asr::Project& project) const { asr::ParamArray& params = project.configurations().get_by_name("final")->get_parameters(); params.insert_path("generic_frame_renderer.tile_ordering", "spiral"); params.insert_path("generic_frame_renderer.passes", m_passes); params.insert_path("shading_result_framebuffer", m_passes == 1 ? "ephemeral" : "permanent"); params.insert_path("uniform_pixel_renderer.samples", m_pixel_samples); if (m_pixel_samples == 1) params.insert_path("uniform_pixel_renderer.force_antialiasing", true); } void RendererSettings::apply_settings_to_interactive_config(asr::Project& project) const { asr::ParamArray& params = project.configurations().get_by_name("interactive")->get_parameters(); params.insert_path("frame_renderer", "progressive"); params.insert_path("sample_generator", "generic"); params.insert_path("sample_renderer", "generic"); } bool RendererSettings::save(ISave* isave) const { bool success = true; // // Image Sampling settings. // isave->BeginChunk(ChunkSettingsImageSampling); isave->BeginChunk(ChunkSettingsImageSamplingPixelSamples); success &= write<int>(isave, m_pixel_samples); isave->EndChunk(); isave->BeginChunk(ChunkSettingsImageSamplingPasses); success &= write<int>(isave, m_passes); isave->EndChunk(); isave->BeginChunk(ChunkSettingsImageSamplingTileSize); success &= write<int>(isave, m_tile_size); isave->EndChunk(); isave->EndChunk(); // // Lighting settings. // isave->BeginChunk(ChunkSettingsLighting); isave->BeginChunk(ChunkSettingsLightingGI); success &= write<bool>(isave, m_gi); isave->EndChunk(); isave->BeginChunk(ChunkSettingsLightingCaustics); success &= write<bool>(isave, m_caustics); isave->EndChunk(); isave->BeginChunk(ChunkSettingsLightingBounces); success &= write<int>(isave, m_bounces); isave->EndChunk(); isave->BeginChunk(ChunkSettingsLightingMaxRayIntensitySet); success &= write<bool>(isave, m_max_ray_intensity_set); isave->EndChunk(); isave->BeginChunk(ChunkSettingsLightingMaxRayIntensity); success &= write<float>(isave, m_max_ray_intensity); isave->EndChunk(); isave->BeginChunk(ChunkSettingsLightingBackgroundEmitsLight); success &= write<bool>(isave, m_background_emits_light); isave->EndChunk(); isave->BeginChunk(ChunkSettingsLightingBackgroundAlpha); success &= write<float>(isave, m_background_alpha); isave->EndChunk(); isave->EndChunk(); // // Output settings. // isave->BeginChunk(ChunkSettingsOutput); isave->BeginChunk(ChunkSettingsOutputMode); switch (m_output_mode) { case OutputMode::RenderOnly: success &= write<BYTE>(isave, 0x00); break; case OutputMode::SaveProjectOnly: success &= write<BYTE>(isave, 0x01); break; case OutputMode::SaveProjectAndRender: success &= write<BYTE>(isave, 0x02); break; } isave->EndChunk(); isave->BeginChunk(ChunkSettingsOutputProjectFilePath); success &= write(isave, m_project_file_path); isave->EndChunk(); isave->BeginChunk(ChunkSettingsOutputScaleMultiplier); success &= write<float>(isave, m_scale_multiplier); isave->EndChunk(); isave->EndChunk(); // // System settings. // isave->BeginChunk(ChunkSettingsSystem); isave->BeginChunk(ChunkSettingsSystemRenderingThreads); success &= write<int>(isave, m_rendering_threads); isave->EndChunk(); isave->BeginChunk(ChunkSettingsSystemLowPriorityMode); success &= write<bool>(isave, m_low_priority_mode); isave->EndChunk(); isave->BeginChunk(ChunkSettingsSystemUseMaxProceduralMaps); success &= write<bool>(isave, m_use_max_procedural_maps); isave->EndChunk(); isave->EndChunk(); return success; } IOResult RendererSettings::load(ILoad* iload) { IOResult result = IO_OK; while (true) { result = iload->OpenChunk(); if (result == IO_END) return IO_OK; if (result != IO_OK) break; switch (iload->CurChunkID()) { case ChunkSettingsImageSampling: result = load_image_sampling_settings(iload); break; case ChunkSettingsLighting: result = load_lighting_settings(iload); break; case ChunkSettingsOutput: result = load_output_settings(iload); break; case ChunkSettingsSystem: result = load_system_settings(iload); break; } if (result != IO_OK) break; result = iload->CloseChunk(); if (result != IO_OK) break; } return result; } IOResult RendererSettings::load_image_sampling_settings(ILoad* iload) { IOResult result = IO_OK; while (true) { result = iload->OpenChunk(); if (result == IO_END) return IO_OK; if (result != IO_OK) break; switch (iload->CurChunkID()) { case ChunkSettingsImageSamplingPixelSamples: result = read<int>(iload, &m_pixel_samples); break; case ChunkSettingsImageSamplingPasses: result = read<int>(iload, &m_passes); break; case ChunkSettingsImageSamplingTileSize: result = read<int>(iload, &m_tile_size); break; } if (result != IO_OK) break; result = iload->CloseChunk(); if (result != IO_OK) break; } return result; } IOResult RendererSettings::load_lighting_settings(ILoad* iload) { IOResult result = IO_OK; while (true) { result = iload->OpenChunk(); if (result == IO_END) return IO_OK; if (result != IO_OK) break; switch (iload->CurChunkID()) { case ChunkSettingsLightingGI: result = read<bool>(iload, &m_gi); break; case ChunkSettingsLightingCaustics: result = read<bool>(iload, &m_caustics); break; case ChunkSettingsLightingBounces: result = read<int>(iload, &m_bounces); break; case ChunkSettingsLightingMaxRayIntensitySet: result = read<bool>(iload, &m_max_ray_intensity_set); break; case ChunkSettingsLightingMaxRayIntensity: result = read<float>(iload, &m_max_ray_intensity); break; case ChunkSettingsLightingBackgroundEmitsLight: result = read<bool>(iload, &m_background_emits_light); break; case ChunkSettingsLightingBackgroundAlpha: result = read<float>(iload, &m_background_alpha); break; } if (result != IO_OK) break; result = iload->CloseChunk(); if (result != IO_OK) break; } return result; } IOResult RendererSettings::load_output_settings(ILoad* iload) { IOResult result = IO_OK; while (true) { result = iload->OpenChunk(); if (result == IO_END) return IO_OK; if (result != IO_OK) break; switch (iload->CurChunkID()) { case ChunkSettingsOutputMode: { BYTE mode; result = read<BYTE>(iload, &mode); if (result == IO_OK) { switch (mode) { case 0x00: m_output_mode = OutputMode::RenderOnly; break; case 0x01: m_output_mode = OutputMode::SaveProjectOnly; break; case 0x02: m_output_mode = OutputMode::SaveProjectAndRender; break; default: result = IO_ERROR; break; } } } break; case ChunkSettingsOutputProjectFilePath: result = read(iload, &m_project_file_path); break; case ChunkSettingsOutputScaleMultiplier: result = read(iload, &m_scale_multiplier); break; } if (result != IO_OK) break; result = iload->CloseChunk(); if (result != IO_OK) break; } return result; } IOResult RendererSettings::load_system_settings(ILoad* iload) { IOResult result = IO_OK; while (true) { result = iload->OpenChunk(); if (result == IO_END) return IO_OK; if (result != IO_OK) break; switch (iload->CurChunkID()) { case ChunkSettingsSystemRenderingThreads: result = read<int>(iload, &m_rendering_threads); break; case ChunkSettingsSystemLowPriorityMode: result = read<bool>(iload, &m_low_priority_mode); break; case ChunkSettingsSystemUseMaxProceduralMaps: result = read<bool>(iload, &m_use_max_procedural_maps); break; } if (result != IO_OK) break; result = iload->CloseChunk(); if (result != IO_OK) break; } return result; } <commit_msg>Set default Max Ray Intensity to 1 (remains disabled by default)<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) 2015-2017 Francois Beaune, The appleseedhq Organization // // 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 "renderersettings.h" // appleseed-max headers. #include "appleseedrenderer/datachunks.h" #include "utilities.h" // appleseed.renderer headers. #include "renderer/api/project.h" #include "renderer/api/utility.h" // 3ds Max headers. #include <ioapi.h> namespace asr = renderer; namespace { struct DefaultRendererSettings : public RendererSettings { DefaultRendererSettings() { m_pixel_samples = 16; m_passes = 1; m_tile_size = 64; m_gi = true; m_caustics = false; m_bounces = 8; m_max_ray_intensity_set = false; m_max_ray_intensity = 1.0f; m_background_emits_light = true; m_background_alpha = 0.0f; m_output_mode = OutputMode::RenderOnly; m_scale_multiplier = 1.0f; m_rendering_threads = 0; // 0 = as many as there are logical cores m_low_priority_mode = true; m_use_max_procedural_maps = false; } }; } const RendererSettings& RendererSettings::defaults() { static DefaultRendererSettings default_settings; return default_settings; } void RendererSettings::apply(asr::Project& project) const { apply_common_settings(project, "final"); apply_common_settings(project, "interactive"); apply_settings_to_final_config(project); apply_settings_to_interactive_config(project); } void RendererSettings::apply_common_settings(asr::Project& project, const char* config_name) const { asr::ParamArray& params = project.configurations().get_by_name(config_name)->get_parameters(); params.insert_path("sampling_mode", "qmc"); if (!m_gi) params.insert_path("pt.max_diffuse_bounces", 0); params.insert_path("pt.max_bounces", m_bounces); params.insert_path("pt.enable_ibl", m_background_emits_light); params.insert_path("pt.enable_caustics", m_caustics); if (m_max_ray_intensity_set) params.insert_path("pt.max_ray_intensity", m_max_ray_intensity); if (m_rendering_threads == 0) params.insert_path("rendering_threads", "auto"); else params.insert_path("rendering_threads", m_rendering_threads); //params.insert_path("shading_engine.override_shading.mode", "shading_normal"); } void RendererSettings::apply_settings_to_final_config(asr::Project& project) const { asr::ParamArray& params = project.configurations().get_by_name("final")->get_parameters(); params.insert_path("generic_frame_renderer.tile_ordering", "spiral"); params.insert_path("generic_frame_renderer.passes", m_passes); params.insert_path("shading_result_framebuffer", m_passes == 1 ? "ephemeral" : "permanent"); params.insert_path("uniform_pixel_renderer.samples", m_pixel_samples); if (m_pixel_samples == 1) params.insert_path("uniform_pixel_renderer.force_antialiasing", true); } void RendererSettings::apply_settings_to_interactive_config(asr::Project& project) const { asr::ParamArray& params = project.configurations().get_by_name("interactive")->get_parameters(); params.insert_path("frame_renderer", "progressive"); params.insert_path("sample_generator", "generic"); params.insert_path("sample_renderer", "generic"); } bool RendererSettings::save(ISave* isave) const { bool success = true; // // Image Sampling settings. // isave->BeginChunk(ChunkSettingsImageSampling); isave->BeginChunk(ChunkSettingsImageSamplingPixelSamples); success &= write<int>(isave, m_pixel_samples); isave->EndChunk(); isave->BeginChunk(ChunkSettingsImageSamplingPasses); success &= write<int>(isave, m_passes); isave->EndChunk(); isave->BeginChunk(ChunkSettingsImageSamplingTileSize); success &= write<int>(isave, m_tile_size); isave->EndChunk(); isave->EndChunk(); // // Lighting settings. // isave->BeginChunk(ChunkSettingsLighting); isave->BeginChunk(ChunkSettingsLightingGI); success &= write<bool>(isave, m_gi); isave->EndChunk(); isave->BeginChunk(ChunkSettingsLightingCaustics); success &= write<bool>(isave, m_caustics); isave->EndChunk(); isave->BeginChunk(ChunkSettingsLightingBounces); success &= write<int>(isave, m_bounces); isave->EndChunk(); isave->BeginChunk(ChunkSettingsLightingMaxRayIntensitySet); success &= write<bool>(isave, m_max_ray_intensity_set); isave->EndChunk(); isave->BeginChunk(ChunkSettingsLightingMaxRayIntensity); success &= write<float>(isave, m_max_ray_intensity); isave->EndChunk(); isave->BeginChunk(ChunkSettingsLightingBackgroundEmitsLight); success &= write<bool>(isave, m_background_emits_light); isave->EndChunk(); isave->BeginChunk(ChunkSettingsLightingBackgroundAlpha); success &= write<float>(isave, m_background_alpha); isave->EndChunk(); isave->EndChunk(); // // Output settings. // isave->BeginChunk(ChunkSettingsOutput); isave->BeginChunk(ChunkSettingsOutputMode); switch (m_output_mode) { case OutputMode::RenderOnly: success &= write<BYTE>(isave, 0x00); break; case OutputMode::SaveProjectOnly: success &= write<BYTE>(isave, 0x01); break; case OutputMode::SaveProjectAndRender: success &= write<BYTE>(isave, 0x02); break; } isave->EndChunk(); isave->BeginChunk(ChunkSettingsOutputProjectFilePath); success &= write(isave, m_project_file_path); isave->EndChunk(); isave->BeginChunk(ChunkSettingsOutputScaleMultiplier); success &= write<float>(isave, m_scale_multiplier); isave->EndChunk(); isave->EndChunk(); // // System settings. // isave->BeginChunk(ChunkSettingsSystem); isave->BeginChunk(ChunkSettingsSystemRenderingThreads); success &= write<int>(isave, m_rendering_threads); isave->EndChunk(); isave->BeginChunk(ChunkSettingsSystemLowPriorityMode); success &= write<bool>(isave, m_low_priority_mode); isave->EndChunk(); isave->BeginChunk(ChunkSettingsSystemUseMaxProceduralMaps); success &= write<bool>(isave, m_use_max_procedural_maps); isave->EndChunk(); isave->EndChunk(); return success; } IOResult RendererSettings::load(ILoad* iload) { IOResult result = IO_OK; while (true) { result = iload->OpenChunk(); if (result == IO_END) return IO_OK; if (result != IO_OK) break; switch (iload->CurChunkID()) { case ChunkSettingsImageSampling: result = load_image_sampling_settings(iload); break; case ChunkSettingsLighting: result = load_lighting_settings(iload); break; case ChunkSettingsOutput: result = load_output_settings(iload); break; case ChunkSettingsSystem: result = load_system_settings(iload); break; } if (result != IO_OK) break; result = iload->CloseChunk(); if (result != IO_OK) break; } return result; } IOResult RendererSettings::load_image_sampling_settings(ILoad* iload) { IOResult result = IO_OK; while (true) { result = iload->OpenChunk(); if (result == IO_END) return IO_OK; if (result != IO_OK) break; switch (iload->CurChunkID()) { case ChunkSettingsImageSamplingPixelSamples: result = read<int>(iload, &m_pixel_samples); break; case ChunkSettingsImageSamplingPasses: result = read<int>(iload, &m_passes); break; case ChunkSettingsImageSamplingTileSize: result = read<int>(iload, &m_tile_size); break; } if (result != IO_OK) break; result = iload->CloseChunk(); if (result != IO_OK) break; } return result; } IOResult RendererSettings::load_lighting_settings(ILoad* iload) { IOResult result = IO_OK; while (true) { result = iload->OpenChunk(); if (result == IO_END) return IO_OK; if (result != IO_OK) break; switch (iload->CurChunkID()) { case ChunkSettingsLightingGI: result = read<bool>(iload, &m_gi); break; case ChunkSettingsLightingCaustics: result = read<bool>(iload, &m_caustics); break; case ChunkSettingsLightingBounces: result = read<int>(iload, &m_bounces); break; case ChunkSettingsLightingMaxRayIntensitySet: result = read<bool>(iload, &m_max_ray_intensity_set); break; case ChunkSettingsLightingMaxRayIntensity: result = read<float>(iload, &m_max_ray_intensity); break; case ChunkSettingsLightingBackgroundEmitsLight: result = read<bool>(iload, &m_background_emits_light); break; case ChunkSettingsLightingBackgroundAlpha: result = read<float>(iload, &m_background_alpha); break; } if (result != IO_OK) break; result = iload->CloseChunk(); if (result != IO_OK) break; } return result; } IOResult RendererSettings::load_output_settings(ILoad* iload) { IOResult result = IO_OK; while (true) { result = iload->OpenChunk(); if (result == IO_END) return IO_OK; if (result != IO_OK) break; switch (iload->CurChunkID()) { case ChunkSettingsOutputMode: { BYTE mode; result = read<BYTE>(iload, &mode); if (result == IO_OK) { switch (mode) { case 0x00: m_output_mode = OutputMode::RenderOnly; break; case 0x01: m_output_mode = OutputMode::SaveProjectOnly; break; case 0x02: m_output_mode = OutputMode::SaveProjectAndRender; break; default: result = IO_ERROR; break; } } } break; case ChunkSettingsOutputProjectFilePath: result = read(iload, &m_project_file_path); break; case ChunkSettingsOutputScaleMultiplier: result = read(iload, &m_scale_multiplier); break; } if (result != IO_OK) break; result = iload->CloseChunk(); if (result != IO_OK) break; } return result; } IOResult RendererSettings::load_system_settings(ILoad* iload) { IOResult result = IO_OK; while (true) { result = iload->OpenChunk(); if (result == IO_END) return IO_OK; if (result != IO_OK) break; switch (iload->CurChunkID()) { case ChunkSettingsSystemRenderingThreads: result = read<int>(iload, &m_rendering_threads); break; case ChunkSettingsSystemLowPriorityMode: result = read<bool>(iload, &m_low_priority_mode); break; case ChunkSettingsSystemUseMaxProceduralMaps: result = read<bool>(iload, &m_use_max_procedural_maps); break; } if (result != IO_OK) break; result = iload->CloseChunk(); if (result != IO_OK) break; } return result; } <|endoftext|>
<commit_before>#include "addtype.h" #include "ui_addtype.h" AddType::AddType(QWidget *parent) : QDialog(parent), ui(new Ui::AddType) { ui->setupUi(this); } AddType::~AddType() { delete ui; } void AddType::on_button_Save_Type_clicked() { //If validation fails these are used bool canCreateType = true; //If validation fails this is set as false bool nameTypeFail = false; QString nameType = ui-> lineEdit_addComputerType->text(); if(nameType == "") { canCreateType = false; nameTypeFail = true; } if(canCreateType) { ComputerType newType; _newType = newType; //_newType.getName(nameType.toStdString()); this->setResult(QDialog::Accepted); } else { QString errorMessage = "Please enter a computer type!"; ui->label_addTypeErrorField->setText("<span style = 'color : red>" + errorMessage+ "</span>"); this->setResult(QDialog::Rejected); } //this->close(); //this->setResult(QDialog::Accepted); } void AddType::on_button_clear_fields_clicked() { this->close(); this->setResult(QDialog::Rejected); } <commit_msg>addType done except for mainwindow/service connection<commit_after>#include "addtype.h" #include "ui_addtype.h" AddType::AddType(QWidget *parent) : QDialog(parent), ui(new Ui::AddType) { ui->setupUi(this); } AddType::~AddType() { delete ui; } void AddType::on_button_Save_Type_clicked() { //If validation fails these are used bool canCreateType = true; //If validation fails this is set as false bool nameTypeFail = false; QString nameType = ui->lineEdit_addComputerType->text(); if(nameType == "") { canCreateType = false; nameTypeFail = true; } if(canCreateType) { ComputerType newType; _newType = newType; std::string newName = nameType.toStdString(); int id = newType.getID(); _newType.setTypeValues(newName, id); this->setResult(QDialog::Accepted); } else { QString errorMessage = "Please enter a computer type!"; ui->label_addTypeErrorField->setText("<span style = 'color : red>" + errorMessage+ "</span>"); this->setResult(QDialog::Rejected); } //this->close(); //this->setResult(QDialog::Accepted); } void AddType::on_button_clear_fields_clicked() { //Clear the input fields ui->lineEdit_addComputerType->clear(); //this->close(); //this->setResult(QDialog::Rejected); } <|endoftext|>
<commit_before>#include <string.h> #include <stdbool.h> #include <iostream> using namespace std; #define ctab "\t" #include "tests.h" #include "basetypes.h" #include "command.h" #include "main.h" // COMMAND WORD /////////////// class CommandWord { public: char word[1000], *walker; int wordcount; CommandWord (const char * input) { word[0] = word[1] = '\0'; walker = NULL; wordcount = 0; Set(input); } CommandWord () { word[0] = word[1] = '\0'; walker = NULL; wordcount = 0; } inline char * Str () { return walker; } void Set (); void Set (const char *); bool operator== (const char * sample); bool operator!= (const char * sample); bool operator++ (int); }; void CommandWord::Set () { wordcount = 0; walker = word; while ((*walker = getchar()) != '\n') { if (*walker == ' ') { *walker = '\0'; if ((walker > word) && walker[-1] != '\0') { walker ++; wordcount++; } } else { walker++; } } walker[0] = '\0'; walker[1] = '\0'; if (walker == word) walker = NULL; else walker = word; } void CommandWord::Set (const char * queue) { wordcount = 0; walker = word; while ((*walker = *queue) != '\n') { if (*walker == ' ') { *walker = '\0'; if ((walker > word) && walker[-1] != '\0') { walker ++; wordcount++; } } else { walker++; } queue++; } walker[0] = '\0'; walker[1] = '\0'; if (walker == word) walker = NULL; else walker = word; } bool CommandWord::operator== (const char * sample) { if (walker) { if (strcmp(walker,sample) == 0) return true; } return false; } bool CommandWord::operator!= (const char * sample) { return !(*this == sample); } bool CommandWord::operator++ (int) { if (walker == NULL) walker = word; else while (*walker != '\0') walker++; walker++; wordcount--; if (*walker == '\0') walker = NULL; return walker; } // COMMAND LINE USER INTERFACE ////////////////////////////// typedef enum { QUIT_APPLICATION = 0, VIEW_MANUAL, SUGEST_MANUAL } UI_STATES; typedef enum { NAME_INPUT = (0x1 << 0), PASS1_INPUT = (0x1 << 1), PASS2_INPUT = (0x1 << 2), ID_INPUT = (0x1 << 3), STATE_INPUT = (0x1 << 4) } INPUT_MODES; class CLTUI: public MethaUI { class CommandWord * Word; class Developer * Dev; class password * password; public: CLTUI (int FLAGS) { PrintFile("welcome.txt"); SQLInterface::instance(FLAGS); Dev = new class Developer; password = new class password; if (FLAGS & TSTMODE) Word = new class CommandWord ("tst && q"); else Word = new class CommandWord; } void Run(); void PrintScope (); void ParseOpt (); void ParseUsr (); void PrintFile (const char *); void GetFields (int); ~CLTUI () { delete Word; delete Dev; delete password; delete SQLINTERFACE::instance(); delete TESTENVIROMENT::instance(); } }; void CLTUI::PrintScope () { cout << "| "; } void CLTUI::PrintFile (const char * path) { FILE *pFile = fopen (path, "r"); char cache; if (pFile) while ((cache = getc(pFile)) != EOF) putchar(cache); // cout << "Word:" << setw(15) << hash->key << // " Count:" << hash->value << endl; } void CLTUI::GetFields (int mode) { char field[31]; if (mode & NAME_INPUT) { try { cout << "NAME: "; cin.getline(field,31); Dev->name.set(field); } catch (dev_name_error) { cout << ctab << "INVALID NAME" << endl; GetFields(NAME_INPUT); } } if (mode & PASS1_INPUT) { try { cout << "PASSWORD: "; cin.getline(field,31); Dev->password.set(field); } catch (password_error) { cout << ctab << "INVALID PASSWORD" << endl; GetFields(PASS1_INPUT); } } if (mode & PASS2_INPUT) { try { cout << "PASSWORD: "; cin.getline(field,31); password->set(field); if (!(Dev->password == *password)) { cout << ctab << "PASSWORDS NOT MATCHIN" << endl; GetFields(PASS2_INPUT); } } catch (password_error) { cout << ctab << "INVALID PASSWORD" << endl; GetFields(PASS2_INPUT); } } } void CLTUI::ParseUsr () { if (!((*Word)++) || (*Word) == "&&") { cout << ctab << "LOGGED OUT" << endl; } else if ((*Word) == "new") { if ((*Word)++) { try { Dev->email.set(Word->Str()); GetFields( NAME_INPUT | PASS1_INPUT | PASS2_INPUT); cout << ctab << "USER ADDED" << endl; (*Word)++; } catch (email_error) { cout << ctab << "INVALID EMAIL" << endl; } } else throw SUGEST_MANUAL; } else if ((*Word) == "rm") { if ((*Word)++) { try { Dev->email.set(Word->Str()); cout << ctab << "USER REMOVED" << endl; (*Word)++; } catch (email_error) { cout << ctab << "INVALID EMAIL" << endl; } } else throw SUGEST_MANUAL; } else { try { Dev->email.set(Word->Str()); GetFields( PASS1_INPUT); if (SQLINTERFACE::instance()->Login(Dev)) { cout << ctab << "LOGGED IN" << endl; } else cout << ctab << "WRONG INPUT" << endl; (*Word)++; } catch (email_error) { cout << ctab << "INVALID EMAIL" << endl; } } } void CLTUI::ParseOpt () { if (((*Word) == "quit") || ((*Word) == "q")) { if ((*Word)++) throw SUGEST_MANUAL; else throw QUIT_APPLICATION; } else if (((*Word) == "?") || ((*Word) == "help")) { throw VIEW_MANUAL; (*Word)++; } else if (((*Word) == "test") || ((*Word) == "tst")) { if (!((*Word)++) || (*Word) == "&&") TESTENVIROMENT::instance()->RunTests(); else throw SUGEST_MANUAL; } else if (((*Word) == "list") || ((*Word) == "ls")) { if (!((*Word)++) || (*Word) == "&&") cout << ctab << "List items on scope." << endl; else throw SUGEST_MANUAL; } else // USER ACTIONS if (((*Word) == "usr") || ((*Word) == "user")) ParseUsr(); else { if (Word->Str()) throw SUGEST_MANUAL; } if ((*Word) == "&&") { (*Word)++; ParseOpt(); } } void CLTUI::Run () { while (true) { try { if (Word->Str()) ParseOpt(); else { PrintScope(); Word->Set(); ParseOpt(); } } catch (UI_STATES state) { if (state == QUIT_APPLICATION) return; else if (state == VIEW_MANUAL) PrintFile("manual.txt"); else if (state == SUGEST_MANUAL) cout << ctab << "Use ? to seek help." << endl; } } } // SINGLETON STATEMENTS /////////////////////// MethaUI * MethaUI::p_instance = 0; MethaUI * MethaUI::instance (int FLAGS) { if (p_instance) delete p_instance; if (FLAGS & CLTMODE) p_instance = new class CLTUI (FLAGS); else p_instance = new class CLTUI (FLAGS); return p_instance; } MethaUI * MethaUI::instance () { if (p_instance) return p_instance; return instance (0); } <commit_msg>Declaração de módulo web<commit_after>#include <string.h> #include <stdbool.h> #include <iostream> using namespace std; #define ctab "\t" #include "tests.h" #include "basetypes.h" #include "command.h" #include "main.h" // WEB SERVER USER INTERFACE //////////////////////////// class WEBUI: public MethaUI { class Developer * Dev; class password * password; public: WEBUI (int FLAGS) { SQLInterface::instance(FLAGS); Dev = new class Developer; password = new class password; } void Run() {} ~WEBUI () { delete Dev; delete password; delete SQLINTERFACE::instance(); } }; // COMMAND WORD /////////////// class CommandWord { public: char word[1000], *walker; int wordcount; CommandWord (const char * input) { word[0] = word[1] = '\0'; walker = NULL; wordcount = 0; Set(input); } CommandWord () { word[0] = word[1] = '\0'; walker = NULL; wordcount = 0; } inline char * Str () { return walker; } void Set (); void Set (const char *); bool operator== (const char * sample); bool operator!= (const char * sample); bool operator++ (int); }; void CommandWord::Set () { wordcount = 0; walker = word; while ((*walker = getchar()) != '\n') { if (*walker == ' ') { *walker = '\0'; if ((walker > word) && walker[-1] != '\0') { walker ++; wordcount++; } } else { walker++; } } walker[0] = '\0'; walker[1] = '\0'; if (walker == word) walker = NULL; else walker = word; } void CommandWord::Set (const char * queue) { wordcount = 0; walker = word; while ((*walker = *queue) != '\n') { if (*walker == ' ') { *walker = '\0'; if ((walker > word) && walker[-1] != '\0') { walker ++; wordcount++; } } else { walker++; } queue++; } walker[0] = '\0'; walker[1] = '\0'; if (walker == word) walker = NULL; else walker = word; } bool CommandWord::operator== (const char * sample) { if (walker) { if (strcmp(walker,sample) == 0) return true; } return false; } bool CommandWord::operator!= (const char * sample) { return !(*this == sample); } bool CommandWord::operator++ (int) { if (walker == NULL) walker = word; else while (*walker != '\0') walker++; walker++; wordcount--; if (*walker == '\0') walker = NULL; return walker; } // COMMAND LINE USER INTERFACE ////////////////////////////// typedef enum { QUIT_APPLICATION = 0, VIEW_MANUAL, SUGEST_MANUAL } UI_STATES; typedef enum { NAME_INPUT = (0x1 << 0), PASS1_INPUT = (0x1 << 1), PASS2_INPUT = (0x1 << 2), ID_INPUT = (0x1 << 3), STATE_INPUT = (0x1 << 4) } INPUT_MODES; class CLTUI: public MethaUI { class CommandWord * Word; class Developer * Dev; class password * password; public: CLTUI (int FLAGS) { PrintFile("welcome.txt"); SQLInterface::instance(FLAGS); Dev = new class Developer; password = new class password; if (FLAGS & TSTMODE) Word = new class CommandWord ("tst && q"); else Word = new class CommandWord; } void Run(); void PrintScope (); void ParseOpt (); void ParseUsr (); void PrintFile (const char *); void GetFields (int); ~CLTUI () { delete Word; delete Dev; delete password; delete SQLINTERFACE::instance(); delete TESTENVIROMENT::instance(); } }; void CLTUI::PrintScope () { cout << "| "; } void CLTUI::PrintFile (const char * path) { FILE *pFile = fopen (path, "r"); char cache; if (pFile) while ((cache = getc(pFile)) != EOF) putchar(cache); // cout << "Word:" << setw(15) << hash->key << // " Count:" << hash->value << endl; } void CLTUI::GetFields (int mode) { char field[31]; if (mode & NAME_INPUT) { try { cout << "NAME: "; cin.getline(field,31); Dev->name.set(field); } catch (dev_name_error) { cout << ctab << "INVALID NAME" << endl; GetFields(NAME_INPUT); } } if (mode & PASS1_INPUT) { try { cout << "PASSWORD: "; cin.getline(field,31); Dev->password.set(field); } catch (password_error) { cout << ctab << "INVALID PASSWORD" << endl; GetFields(PASS1_INPUT); } } if (mode & PASS2_INPUT) { try { cout << "PASSWORD: "; cin.getline(field,31); password->set(field); if (!(Dev->password == *password)) { cout << ctab << "PASSWORDS NOT MATCHIN" << endl; GetFields(PASS2_INPUT); } } catch (password_error) { cout << ctab << "INVALID PASSWORD" << endl; GetFields(PASS2_INPUT); } } } void CLTUI::ParseUsr () { if (!((*Word)++) || (*Word) == "&&") { cout << ctab << "LOGGED OUT" << endl; } else if ((*Word) == "new") { if ((*Word)++) { try { Dev->email.set(Word->Str()); GetFields( NAME_INPUT | PASS1_INPUT | PASS2_INPUT); cout << ctab << "USER ADDED" << endl; (*Word)++; } catch (email_error) { cout << ctab << "INVALID EMAIL" << endl; } } else throw SUGEST_MANUAL; } else if ((*Word) == "rm") { if ((*Word)++) { try { Dev->email.set(Word->Str()); cout << ctab << "USER REMOVED" << endl; (*Word)++; } catch (email_error) { cout << ctab << "INVALID EMAIL" << endl; } } else throw SUGEST_MANUAL; } else { try { Dev->email.set(Word->Str()); GetFields( PASS1_INPUT); if (SQLINTERFACE::instance()->Login(Dev)) { cout << ctab << "LOGGED IN" << endl; } else cout << ctab << "WRONG INPUT" << endl; (*Word)++; } catch (email_error) { cout << ctab << "INVALID EMAIL" << endl; } } } void CLTUI::ParseOpt () { if (((*Word) == "quit") || ((*Word) == "q")) { if ((*Word)++) throw SUGEST_MANUAL; else throw QUIT_APPLICATION; } else if (((*Word) == "?") || ((*Word) == "help")) { throw VIEW_MANUAL; (*Word)++; } else if (((*Word) == "test") || ((*Word) == "tst")) { if (!((*Word)++) || (*Word) == "&&") TESTENVIROMENT::instance()->RunTests(); else throw SUGEST_MANUAL; } else if (((*Word) == "list") || ((*Word) == "ls")) { if (!((*Word)++) || (*Word) == "&&") cout << ctab << "List items on scope." << endl; else throw SUGEST_MANUAL; } else // USER ACTIONS if (((*Word) == "usr") || ((*Word) == "user")) ParseUsr(); else { if (Word->Str()) throw SUGEST_MANUAL; } if ((*Word) == "&&") { (*Word)++; ParseOpt(); } } void CLTUI::Run () { while (true) { try { if (Word->Str()) ParseOpt(); else { PrintScope(); Word->Set(); ParseOpt(); } } catch (UI_STATES state) { if (state == QUIT_APPLICATION) return; else if (state == VIEW_MANUAL) PrintFile("manual.txt"); else if (state == SUGEST_MANUAL) cout << ctab << "Use ? to seek help." << endl; } } } // SINGLETON STATEMENTS /////////////////////// MethaUI * MethaUI::p_instance = 0; MethaUI * MethaUI::instance (int FLAGS) { if (p_instance) delete p_instance; if (FLAGS & CLTMODE) p_instance = new class CLTUI (FLAGS); else p_instance = new class CLTUI (FLAGS); return p_instance; } MethaUI * MethaUI::instance () { if (p_instance) return p_instance; return instance (0); } <|endoftext|>
<commit_before>#pragma once #include "application_launcher.hpp" #include "configuration_monitor.hpp" namespace krbn { class menu_process_manager final { public: menu_process_manager(const menu_process_manager&) = delete; menu_process_manager(std::shared_ptr<configuration_monitor> configuration_monitor) { // core_configuration_updated { auto c = configuration_monitor->core_configuration_updated.connect([](auto&& core_configuration) { if (core_configuration->get_global_configuration().get_show_in_menu_bar() || core_configuration->get_global_configuration().get_show_profile_name_in_menu_bar()) { application_launcher::launch_menu(); } else { application_launcher::kill_menu(); } }); connections_.push_back(std::make_unique<boost::signals2::scoped_connection>(c)); } } private: std::vector<std::unique_ptr<boost::signals2::scoped_connection>> connections_; }; } // namespace krbn <commit_msg>update menu_process_manager<commit_after>#pragma once #include "application_launcher.hpp" #include "boost_utility.hpp" #include "configuration_monitor.hpp" namespace krbn { class menu_process_manager final { public: menu_process_manager(const menu_process_manager&) = delete; menu_process_manager(std::weak_ptr<configuration_monitor> weak_configuration_monitor) : weak_configuration_monitor_(weak_configuration_monitor) { if (auto configuration_monitor = weak_configuration_monitor_.lock()) { // core_configuration_updated { auto c = configuration_monitor->core_configuration_updated.connect([](auto&& weak_core_configuration) { if (auto core_configuration = weak_core_configuration.lock()) { if (core_configuration->get_global_configuration().get_show_in_menu_bar() || core_configuration->get_global_configuration().get_show_profile_name_in_menu_bar()) { application_launcher::launch_menu(); } else { application_launcher::kill_menu(); } } }); configuration_monitor_connections_.push_back(c); } } } ~menu_process_manager(void) { // Disconnect `configuration_monitor_connections_`. if (auto configuration_monitor = weak_configuration_monitor_.lock()) { configuration_monitor->get_run_loop_thread()->enqueue(^{ configuration_monitor_connections_.disconnect_all_connections(); }); } else { configuration_monitor_connections_.disconnect_all_connections(); } configuration_monitor_connections_.wait_disconnect_all_connections(); } private: std::weak_ptr<configuration_monitor> weak_configuration_monitor_; boost_utility::signals2_connections configuration_monitor_connections_; }; } // namespace krbn <|endoftext|>
<commit_before>/*! * \carl_joy_teleop.cpp * \brief Allows for control of CARL with a joystick. * * carl_joy_teleop creates a ROS node that allows the control of CARL with a joystick. * This node listens to a /joy topic and sends messages to the /cmd_vel topic. * * * \author Russell Toris, WPI - rctoris@wpi.edu * \date May 21, 2013 * * \author Steven Kordell, WPI - spkordell@wpi.edu * \date May 23, 2014 * */ #include <geometry_msgs/Twist.h> #include <ros/ros.h> #include <sensor_msgs/Joy.h> #include <carl_teleop/carl_joy_teleop.h> ros::Time T; bool receivedmsg = false; using namespace std; carl_joy_teleop::carl_joy_teleop() { // create the ROS topics cmd_vel = node.advertise < geometry_msgs::Twist > ("cmd_vel", 10); joy_sub = node.subscribe < sensor_msgs::Joy > ("joy", 10, &carl_joy_teleop::joy_cback, this); //read in throttle value double temp; if (node.getParam("/carl_joy_teleop/linear_throttle_factor", temp)) linear_throttle_factor = (float)temp; else linear_throttle_factor = 1.0; if (node.getParam("/carl_joy_teleop/angular_throttle_factor", temp)) angular_throttle_factor = (float)temp; else angular_throttle_factor = 1.0; ROS_INFO("Carl Joystick Teleop Started"); } void carl_joy_teleop::joy_cback(const sensor_msgs::Joy::ConstPtr& joy) { if (!receivedmsg) { receivedmsg = true; } T = ros::Time::now(); // create the twist message geometry_msgs::Twist twist; twist.linear.y = 0; twist.linear.z = 0; twist.angular.x = 0; twist.angular.y = 0; if (joy->buttons.at(4) == 1) { // left joystick controls the linear and angular movement twist.linear.x = joy->axes.at(1) * MAX_TRANS_VEL * linear_throttle_factor; twist.angular.z = joy->axes.at(0) * MAX_ANG_VEL * angular_throttle_factor; } else { twist.linear.x = 0; twist.angular.z = 0; } //boost button if (joy->buttons.at(5) == 1) { twist.linear.x *= 2; twist.angular.z *= 2; } // send the twist command cmd_vel.publish(twist); } void carl_joy_teleop::joy_check() { if ((receivedmsg) && ((ros::Time::now().toSec() - T.toSec()) > .15)) { geometry_msgs::Twist zero; cmd_vel.publish(zero); } } int main(int argc, char **argv) { // initialize ROS and the node ros::init(argc, argv, "carl_joy_teleop"); //initialize the joystick controller carl_joy_teleop controller; // continue until a ctrl-c has occurred /*while(ros::ok()) { controller.joy_check(); ros::spinOnce(); }*/ ros::spin(); } <commit_msg>Now using right joystick for angular control<commit_after>/*! * \carl_joy_teleop.cpp * \brief Allows for control of CARL with a joystick. * * carl_joy_teleop creates a ROS node that allows the control of CARL with a joystick. * This node listens to a /joy topic and sends messages to the /cmd_vel topic. * * * \author Russell Toris, WPI - rctoris@wpi.edu * \date May 21, 2013 * * \author Steven Kordell, WPI - spkordell@wpi.edu * \date May 23, 2014 * */ #include <geometry_msgs/Twist.h> #include <ros/ros.h> #include <sensor_msgs/Joy.h> #include <carl_teleop/carl_joy_teleop.h> ros::Time T; bool receivedmsg = false; using namespace std; carl_joy_teleop::carl_joy_teleop() { // create the ROS topics cmd_vel = node.advertise < geometry_msgs::Twist > ("cmd_vel", 10); joy_sub = node.subscribe < sensor_msgs::Joy > ("joy", 10, &carl_joy_teleop::joy_cback, this); //read in throttle value double temp; if (node.getParam("/carl_joy_teleop/linear_throttle_factor", temp)) linear_throttle_factor = (float)temp; else linear_throttle_factor = 1.0; if (node.getParam("/carl_joy_teleop/angular_throttle_factor", temp)) angular_throttle_factor = (float)temp; else angular_throttle_factor = 1.0; ROS_INFO("Carl Joystick Teleop Started"); } void carl_joy_teleop::joy_cback(const sensor_msgs::Joy::ConstPtr& joy) { if (!receivedmsg) { receivedmsg = true; } T = ros::Time::now(); // create the twist message geometry_msgs::Twist twist; twist.linear.y = 0; twist.linear.z = 0; twist.angular.x = 0; twist.angular.y = 0; if (joy->buttons.at(4) == 1) { // left joystick controls the linear and angular movement twist.linear.x = joy->axes.at(1) * MAX_TRANS_VEL * linear_throttle_factor; twist.angular.z = -joy->axes.at(2) * MAX_ANG_VEL * angular_throttle_factor; } else { twist.linear.x = 0; twist.angular.z = 0; } //boost button if (joy->buttons.at(5) == 1) { twist.linear.x *= 2; twist.angular.z *= 2; } // send the twist command cmd_vel.publish(twist); } void carl_joy_teleop::joy_check() { if ((receivedmsg) && ((ros::Time::now().toSec() - T.toSec()) > .15)) { geometry_msgs::Twist zero; cmd_vel.publish(zero); } } int main(int argc, char **argv) { // initialize ROS and the node ros::init(argc, argv, "carl_joy_teleop"); //initialize the joystick controller carl_joy_teleop controller; ros::spin(); } <|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. // // Broker RPC Server implementation. #include "ceee/ie/broker/broker_rpc_server.h" #include "base/atomic_sequence_num.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/process_util.h" #include "broker_rpc_lib.h" // NOLINT #include "ceee/common/com_utils.h" #include "ceee/ie/broker/broker_module_util.h" #include "ceee/ie/broker/broker_rpc_utils.h" #include "ceee/ie/broker/chrome_postman.h" namespace { // This lock ensures that histograms created by the broker are thread safe. // The histograms created here can be initialized on multiple threads. Lock g_metrics_lock; RPC_STATUS PrepareEndpoint(std::wstring endpoint) { std::wstring protocol = kRpcProtocol; DCHECK(!protocol.empty()); DCHECK(!endpoint.empty()); if (protocol.empty() || endpoint.empty()) return false; VLOG(1) << "RPC server is starting. Endpoint: " << endpoint; // Tell RPC runtime to use local interprocess communication for given // end point. RPC_STATUS status = ::RpcServerUseProtseqEp( reinterpret_cast<RPC_WSTR>(&protocol[0]), RPC_C_PROTSEQ_MAX_REQS_DEFAULT, reinterpret_cast<RPC_WSTR>(&endpoint[0]), NULL); LOG_IF(ERROR, RPC_S_OK != status && RPC_S_DUPLICATE_ENDPOINT != status) << "Failed to set protocol for RPC end point. RPC_STATUS=0x" << com::LogWe(status); // This is not an error because unittest may start several servers. For // ceee_broker this is an error because we should not have several instances // of broker for the same endpoint. However BrokerRpcServer will fail anyway // while starting to listen. if (RPC_S_DUPLICATE_ENDPOINT == status) status = RPC_S_OK; return status; } } // namespace BrokerRpcServer::BrokerRpcServer() : is_started_(false), current_thread_(::GetCurrentThreadId()) { } BrokerRpcServer::~BrokerRpcServer() { DCHECK(current_thread_ == ::GetCurrentThreadId()); Stop(); } bool BrokerRpcServer::Start() { DCHECK(current_thread_ == ::GetCurrentThreadId()); if (is_started()) return true; std::wstring endpoint = GetRpcEndpointAddress(); RPC_STATUS status = PrepareEndpoint(endpoint); if (RPC_S_OK == status) { // Register RPC interface with the RPC runtime. status = ::RpcServerRegisterIfEx(BrokerRpcServer_CeeeBroker_v1_1_s_ifspec, NULL, NULL, 0, RPC_C_LISTEN_MAX_CALLS_DEFAULT, NULL); LOG_IF(ERROR, RPC_S_OK != status) << "Failed to register RPC interface. RPC_STATUS=0x" << com::LogWe(status); if (RPC_S_OK == status) { // Start listen for RPC calls. status = ::RpcServerListen(1, RPC_C_LISTEN_MAX_CALLS_DEFAULT, TRUE); LOG_IF(ERROR, RPC_S_OK != status) << "Failed to start listening. RPC_STATUS=0x" << com::LogWe(status); if (RPC_S_OK == status) { VLOG(1) << "RPC server is started. Endpoint: " << endpoint; is_started_ = true; } } } if (!is_started()) Stop(); return is_started(); } bool BrokerRpcServer::Stop() { DCHECK(current_thread_ == ::GetCurrentThreadId()); is_started_ = false; // Stop server listening for RPC. RPC_STATUS status = ::RpcMgmtStopServerListening(NULL); LOG_IF(WARNING, RPC_S_OK != status && RPC_S_NOT_LISTENING != status) << "Failed to stop listening. RPC_STATUS=0x" << com::LogWe(status); // Wait while server stops listening threads. status = ::RpcMgmtWaitServerListen(); LOG_IF(WARNING, RPC_S_OK != status && RPC_S_NOT_LISTENING != status) << "Failed to wait server listen. RPC_STATUS=0x" << com::LogWe(status); // Unregister RPC interface. status = ::RpcServerUnregisterIf( BrokerRpcServer_CeeeBroker_v1_1_s_ifspec, NULL, FALSE); LOG_IF(WARNING, RPC_S_OK != status || RPC_S_UNKNOWN_MGR_TYPE != status || RPC_S_UNKNOWN_IF != status) << "Failed to unregister interface. RPC_STATUS=0x" << com::LogWe(status); return RPC_S_OK == status; } bool BrokerRpcServer::is_started() const { DCHECK(current_thread_ == ::GetCurrentThreadId()); return is_started_; } static base::AtomicSequenceNumber current_broker_rpc_context( base::LINKER_INITIALIZED); BrokerContextHandle BrokerRpcServer_Connect(handle_t binding_handle) { // TODO(vitalybuka@google.com): Add client identity check. ceee_module_util::LockModule(); return reinterpret_cast<void*>(current_broker_rpc_context.GetNext() + 1); } void BrokerRpcServer_Disconnect( handle_t binding_handle, BrokerContextHandle* context) { DCHECK(context != NULL); if (context) *context = NULL; ceee_module_util::UnlockModule(); } // Called when client process terminated without releasing context handle. void __RPC_USER BrokerContextHandle_rundown(BrokerContextHandle context) { DCHECK(context != NULL); ceee_module_util::UnlockModule(); } void BrokerRpcServer_FireEvent( handle_t binding_handle, BrokerContextHandle context, const char* event_name, const char* event_args) { DCHECK(ChromePostman::GetInstance()); if (ChromePostman::GetInstance()) ChromePostman::GetInstance()->FireEvent(event_name, event_args); } void BrokerRpcServer_SendUmaHistogramTimes(handle_t binding_handle, const char* name, int sample) { // We can't unfortunately use the HISTOGRAM_*_TIMES here because they use // static variables to save time. AutoLock lock(g_metrics_lock); scoped_refptr<base::Histogram> counter = base::Histogram::FactoryTimeGet(name, base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromSeconds(10), 50, base::Histogram::kUmaTargetedHistogramFlag); DCHECK_EQ(name, counter->histogram_name()); if (counter.get()) counter->AddTime(base::TimeDelta::FromMilliseconds(sample)); } void BrokerRpcServer_SendUmaHistogramData(handle_t binding_handle, const char* name, int sample, int min, int max, int bucket_count) { // We can't unfortunately use the HISTOGRAM_*_COUNT here because they use // static variables to save time. AutoLock lock(g_metrics_lock); scoped_refptr<base::Histogram> counter = base::Histogram::FactoryGet(name, min, max, bucket_count, base::Histogram::kUmaTargetedHistogramFlag); DCHECK_EQ(name, counter->histogram_name()); if (counter.get()) counter->AddTime(base::TimeDelta::FromMilliseconds(sample)); } <commit_msg>Fix LOG_IF check.<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. // // Broker RPC Server implementation. #include "ceee/ie/broker/broker_rpc_server.h" #include "base/atomic_sequence_num.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/process_util.h" #include "broker_rpc_lib.h" // NOLINT #include "ceee/common/com_utils.h" #include "ceee/ie/broker/broker_module_util.h" #include "ceee/ie/broker/broker_rpc_utils.h" #include "ceee/ie/broker/chrome_postman.h" namespace { // This lock ensures that histograms created by the broker are thread safe. // The histograms created here can be initialized on multiple threads. Lock g_metrics_lock; RPC_STATUS PrepareEndpoint(std::wstring endpoint) { std::wstring protocol = kRpcProtocol; DCHECK(!protocol.empty()); DCHECK(!endpoint.empty()); if (protocol.empty() || endpoint.empty()) return false; VLOG(1) << "RPC server is starting. Endpoint: " << endpoint; // Tell RPC runtime to use local interprocess communication for given // end point. RPC_STATUS status = ::RpcServerUseProtseqEp( reinterpret_cast<RPC_WSTR>(&protocol[0]), RPC_C_PROTSEQ_MAX_REQS_DEFAULT, reinterpret_cast<RPC_WSTR>(&endpoint[0]), NULL); LOG_IF(ERROR, RPC_S_OK != status && RPC_S_DUPLICATE_ENDPOINT != status) << "Failed to set protocol for RPC end point. RPC_STATUS=0x" << com::LogWe(status); // This is not an error because unittest may start several servers. For // ceee_broker this is an error because we should not have several instances // of broker for the same endpoint. However BrokerRpcServer will fail anyway // while starting to listen. if (RPC_S_DUPLICATE_ENDPOINT == status) status = RPC_S_OK; return status; } } // namespace BrokerRpcServer::BrokerRpcServer() : is_started_(false), current_thread_(::GetCurrentThreadId()) { } BrokerRpcServer::~BrokerRpcServer() { DCHECK(current_thread_ == ::GetCurrentThreadId()); Stop(); } bool BrokerRpcServer::Start() { DCHECK(current_thread_ == ::GetCurrentThreadId()); if (is_started()) return true; std::wstring endpoint = GetRpcEndpointAddress(); RPC_STATUS status = PrepareEndpoint(endpoint); if (RPC_S_OK == status) { // Register RPC interface with the RPC runtime. status = ::RpcServerRegisterIfEx(BrokerRpcServer_CeeeBroker_v1_1_s_ifspec, NULL, NULL, 0, RPC_C_LISTEN_MAX_CALLS_DEFAULT, NULL); LOG_IF(ERROR, RPC_S_OK != status) << "Failed to register RPC interface. RPC_STATUS=0x" << com::LogWe(status); if (RPC_S_OK == status) { // Start listen for RPC calls. status = ::RpcServerListen(1, RPC_C_LISTEN_MAX_CALLS_DEFAULT, TRUE); LOG_IF(ERROR, RPC_S_OK != status) << "Failed to start listening. RPC_STATUS=0x" << com::LogWe(status); if (RPC_S_OK == status) { VLOG(1) << "RPC server is started. Endpoint: " << endpoint; is_started_ = true; } } } if (!is_started()) Stop(); return is_started(); } bool BrokerRpcServer::Stop() { DCHECK(current_thread_ == ::GetCurrentThreadId()); is_started_ = false; // Stop server listening for RPC. RPC_STATUS status = ::RpcMgmtStopServerListening(NULL); LOG_IF(WARNING, RPC_S_OK != status && RPC_S_NOT_LISTENING != status) << "Failed to stop listening. RPC_STATUS=0x" << com::LogWe(status); // Wait while server stops listening threads. status = ::RpcMgmtWaitServerListen(); LOG_IF(WARNING, RPC_S_OK != status && RPC_S_NOT_LISTENING != status) << "Failed to wait server listen. RPC_STATUS=0x" << com::LogWe(status); // Unregister RPC interface. status = ::RpcServerUnregisterIf( BrokerRpcServer_CeeeBroker_v1_1_s_ifspec, NULL, FALSE); LOG_IF(WARNING, RPC_S_OK != status && RPC_S_UNKNOWN_MGR_TYPE != status && RPC_S_UNKNOWN_IF != status) << "Failed to unregister interface. RPC_STATUS=0x" << com::LogWe(status); return RPC_S_OK == status; } bool BrokerRpcServer::is_started() const { DCHECK(current_thread_ == ::GetCurrentThreadId()); return is_started_; } static base::AtomicSequenceNumber current_broker_rpc_context( base::LINKER_INITIALIZED); BrokerContextHandle BrokerRpcServer_Connect(handle_t binding_handle) { // TODO(vitalybuka@google.com): Add client identity check. ceee_module_util::LockModule(); return reinterpret_cast<void*>(current_broker_rpc_context.GetNext() + 1); } void BrokerRpcServer_Disconnect( handle_t binding_handle, BrokerContextHandle* context) { DCHECK(context != NULL); if (context) *context = NULL; ceee_module_util::UnlockModule(); } // Called when client process terminated without releasing context handle. void __RPC_USER BrokerContextHandle_rundown(BrokerContextHandle context) { DCHECK(context != NULL); ceee_module_util::UnlockModule(); } void BrokerRpcServer_FireEvent( handle_t binding_handle, BrokerContextHandle context, const char* event_name, const char* event_args) { DCHECK(ChromePostman::GetInstance()); if (ChromePostman::GetInstance()) ChromePostman::GetInstance()->FireEvent(event_name, event_args); } void BrokerRpcServer_SendUmaHistogramTimes(handle_t binding_handle, const char* name, int sample) { // We can't unfortunately use the HISTOGRAM_*_TIMES here because they use // static variables to save time. AutoLock lock(g_metrics_lock); scoped_refptr<base::Histogram> counter = base::Histogram::FactoryTimeGet(name, base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromSeconds(10), 50, base::Histogram::kUmaTargetedHistogramFlag); DCHECK_EQ(name, counter->histogram_name()); if (counter.get()) counter->AddTime(base::TimeDelta::FromMilliseconds(sample)); } void BrokerRpcServer_SendUmaHistogramData(handle_t binding_handle, const char* name, int sample, int min, int max, int bucket_count) { // We can't unfortunately use the HISTOGRAM_*_COUNT here because they use // static variables to save time. AutoLock lock(g_metrics_lock); scoped_refptr<base::Histogram> counter = base::Histogram::FactoryGet(name, min, max, bucket_count, base::Histogram::kUmaTargetedHistogramFlag); DCHECK_EQ(name, counter->histogram_name()); if (counter.get()) counter->AddTime(base::TimeDelta::FromMilliseconds(sample)); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/accessibility/accessibility_util.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/logging.h" #include "chrome/browser/accessibility/accessibility_extension_api.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/component_loader.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/file_reader.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/speech/extension_api/tts_extension_api_platform.h" #include "chrome/common/extensions/extension_messages.h" #include "chrome/common/extensions/extension_resource.h" #include "chrome/common/pref_names.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" using content::RenderViewHost; namespace chromeos { namespace accessibility { // Helper class that directly loads an extension's content scripts into // all of the frames corresponding to a given RenderViewHost. class ContentScriptLoader { public: // Initialize the ContentScriptLoader with the ID of the extension // and the RenderViewHost where the scripts should be loaded. ContentScriptLoader(const std::string& extension_id, RenderViewHost* render_view_host) : extension_id_(extension_id), render_view_host_(render_view_host) {} // Call this once with the ExtensionResource corresponding to each // content script to be loaded. void AppendScript(ExtensionResource resource) { resources_.push(resource); } // Fianlly, call this method once to fetch all of the resources and // load them. This method will delete this object when done. void Run() { if (resources_.empty()) { delete this; return; } ExtensionResource resource = resources_.front(); resources_.pop(); scoped_refptr<FileReader> reader(new FileReader(resource, base::Bind( &ContentScriptLoader::OnFileLoaded, base::Unretained(this)))); reader->Start(); } private: void OnFileLoaded(bool success, const std::string& data) { if (success) { ExtensionMsg_ExecuteCode_Params params; params.request_id = 0; params.extension_id = extension_id_; params.is_javascript = true; params.code = data; params.all_frames = true; params.in_main_world = false; render_view_host_->Send(new ExtensionMsg_ExecuteCode( render_view_host_->GetRoutingID(), params)); } Run(); } std::string extension_id_; RenderViewHost* render_view_host_; std::queue<ExtensionResource> resources_; }; void EnableSpokenFeedback(bool enabled, content::WebUI* login_web_ui) { bool spoken_feedback_enabled = g_browser_process && g_browser_process->local_state()->GetBoolean( prefs::kSpokenFeedbackEnabled); if (spoken_feedback_enabled == enabled) { DLOG(INFO) << "Spoken feedback is already " << (enabled ? "enabled" : "disabled") << ". Going to do nothing."; return; } g_browser_process->local_state()->SetBoolean( prefs::kSpokenFeedbackEnabled, enabled); g_browser_process->local_state()->CommitPendingWrite(); ExtensionAccessibilityEventRouter::GetInstance()-> SetAccessibilityEnabled(enabled); BrowserAccessibilityState::GetInstance()->OnAccessibilityEnabledManually(); Speak(l10n_util::GetStringUTF8( enabled ? IDS_CHROMEOS_ACC_SPOKEN_FEEDBACK_ENABLED : IDS_CHROMEOS_ACC_SPOKEN_FEEDBACK_DISABLED).c_str()); // Load/Unload ChromeVox Profile* profile = ProfileManager::GetDefaultProfile(); ExtensionService* extension_service = profile->GetExtensionService(); FilePath path = FilePath(extension_misc::kAccessExtensionPath) .AppendASCII(extension_misc::kChromeVoxDirectoryName); if (enabled) { // Load ChromeVox const Extension* extension = extension_service->component_loader()->Add(IDR_CHROMEVOX_MANIFEST, path); if (login_web_ui) { RenderViewHost* render_view_host = login_web_ui->GetWebContents()->GetRenderViewHost(); // Set a flag to tell ChromeVox that it's just been enabled, // so that it won't interrupt our speech feedback enabled message. ExtensionMsg_ExecuteCode_Params params; params.request_id = 0; params.extension_id = extension->id(); params.is_javascript = true; params.code = "window.INJECTED_AFTER_LOAD = true;"; params.all_frames = true; params.in_main_world = false; render_view_host->Send(new ExtensionMsg_ExecuteCode( render_view_host->GetRoutingID(), params)); // Inject ChromeVox' content scripts. ContentScriptLoader* loader = new ContentScriptLoader( extension->id(), render_view_host); for (size_t i = 0; i < extension->content_scripts().size(); i++) { const UserScript& script = extension->content_scripts()[i]; for (size_t j = 0; j < script.js_scripts().size(); ++j) { const UserScript::File &file = script.js_scripts()[j]; ExtensionResource resource = extension->GetResource( file.relative_path()); loader->AppendScript(resource); } } loader->Run(); // It cleans itself up when done. } DLOG(INFO) << "ChromeVox was Loaded."; } else { // Unload ChromeVox extension_service->component_loader()->Remove(path); DLOG(INFO) << "ChromeVox was Unloaded."; } } void EnableHighContrast(bool enabled) { PrefService* pref_service = g_browser_process->local_state(); pref_service->SetBoolean(prefs::kHighContrastEnabled, enabled); pref_service->CommitPendingWrite(); } void EnableScreenMagnifier(bool enabled) { PrefService* pref_service = g_browser_process->local_state(); pref_service->SetBoolean(prefs::kScreenMagnifierEnabled, enabled); pref_service->CommitPendingWrite(); } void EnableVirtualKeyboard(bool enabled) { PrefService* pref_service = g_browser_process->local_state(); pref_service->SetBoolean(prefs::kVirtualKeyboardEnabled, enabled); pref_service->CommitPendingWrite(); } void ToggleSpokenFeedback(content::WebUI* login_web_ui) { bool spoken_feedback_enabled = g_browser_process && g_browser_process->local_state()->GetBoolean( prefs::kSpokenFeedbackEnabled); spoken_feedback_enabled = !spoken_feedback_enabled; EnableSpokenFeedback(spoken_feedback_enabled, login_web_ui); }; void Speak(const std::string& utterance) { UtteranceContinuousParameters params; ExtensionTtsPlatformImpl::GetInstance()->Speak( -1, // No utterance ID because we don't need a callback when it finishes. utterance.c_str(), g_browser_process->GetApplicationLocale(), params); } bool IsSpokenFeedbackEnabled() { if (!g_browser_process) { return false; } PrefService* prefs = g_browser_process->local_state(); bool spoken_feedback_enabled = prefs && prefs->GetBoolean(prefs::kSpokenFeedbackEnabled); return spoken_feedback_enabled; } void MaybeSpeak(const std::string& utterance) { if (IsSpokenFeedbackEnabled()) Speak(utterance); } } // namespace accessibility } // namespace chromeos <commit_msg>Revert 109851 - Tell BrowserAccessibilityState when Chrome OS accessibility is turned on. This will improve feedback for a couple of toolbar controls that check this state, and also start collecting UMA statistics on accessibility usage in Chrome OS.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/accessibility/accessibility_util.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/logging.h" #include "chrome/browser/accessibility/accessibility_extension_api.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/component_loader.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/file_reader.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/speech/extension_api/tts_extension_api_platform.h" #include "chrome/common/extensions/extension_messages.h" #include "chrome/common/extensions/extension_resource.h" #include "chrome/common/pref_names.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" using content::RenderViewHost; namespace chromeos { namespace accessibility { // Helper class that directly loads an extension's content scripts into // all of the frames corresponding to a given RenderViewHost. class ContentScriptLoader { public: // Initialize the ContentScriptLoader with the ID of the extension // and the RenderViewHost where the scripts should be loaded. ContentScriptLoader(const std::string& extension_id, RenderViewHost* render_view_host) : extension_id_(extension_id), render_view_host_(render_view_host) {} // Call this once with the ExtensionResource corresponding to each // content script to be loaded. void AppendScript(ExtensionResource resource) { resources_.push(resource); } // Fianlly, call this method once to fetch all of the resources and // load them. This method will delete this object when done. void Run() { if (resources_.empty()) { delete this; return; } ExtensionResource resource = resources_.front(); resources_.pop(); scoped_refptr<FileReader> reader(new FileReader(resource, base::Bind( &ContentScriptLoader::OnFileLoaded, base::Unretained(this)))); reader->Start(); } private: void OnFileLoaded(bool success, const std::string& data) { if (success) { ExtensionMsg_ExecuteCode_Params params; params.request_id = 0; params.extension_id = extension_id_; params.is_javascript = true; params.code = data; params.all_frames = true; params.in_main_world = false; render_view_host_->Send(new ExtensionMsg_ExecuteCode( render_view_host_->GetRoutingID(), params)); } Run(); } std::string extension_id_; RenderViewHost* render_view_host_; std::queue<ExtensionResource> resources_; }; void EnableSpokenFeedback(bool enabled, content::WebUI* login_web_ui) { bool spoken_feedback_enabled = g_browser_process && g_browser_process->local_state()->GetBoolean( prefs::kSpokenFeedbackEnabled); if (spoken_feedback_enabled == enabled) { DLOG(INFO) << "Spoken feedback is already " << (enabled ? "enabled" : "disabled") << ". Going to do nothing."; return; } g_browser_process->local_state()->SetBoolean( prefs::kSpokenFeedbackEnabled, enabled); g_browser_process->local_state()->CommitPendingWrite(); ExtensionAccessibilityEventRouter::GetInstance()-> SetAccessibilityEnabled(enabled); Speak(l10n_util::GetStringUTF8( enabled ? IDS_CHROMEOS_ACC_SPOKEN_FEEDBACK_ENABLED : IDS_CHROMEOS_ACC_SPOKEN_FEEDBACK_DISABLED).c_str()); // Load/Unload ChromeVox Profile* profile = ProfileManager::GetDefaultProfile(); ExtensionService* extension_service = profile->GetExtensionService(); FilePath path = FilePath(extension_misc::kAccessExtensionPath) .AppendASCII(extension_misc::kChromeVoxDirectoryName); if (enabled) { // Load ChromeVox const Extension* extension = extension_service->component_loader()->Add(IDR_CHROMEVOX_MANIFEST, path); if (login_web_ui) { RenderViewHost* render_view_host = login_web_ui->GetWebContents()->GetRenderViewHost(); // Set a flag to tell ChromeVox that it's just been enabled, // so that it won't interrupt our speech feedback enabled message. ExtensionMsg_ExecuteCode_Params params; params.request_id = 0; params.extension_id = extension->id(); params.is_javascript = true; params.code = "window.INJECTED_AFTER_LOAD = true;"; params.all_frames = true; params.in_main_world = false; render_view_host->Send(new ExtensionMsg_ExecuteCode( render_view_host->GetRoutingID(), params)); // Inject ChromeVox' content scripts. ContentScriptLoader* loader = new ContentScriptLoader( extension->id(), render_view_host); for (size_t i = 0; i < extension->content_scripts().size(); i++) { const UserScript& script = extension->content_scripts()[i]; for (size_t j = 0; j < script.js_scripts().size(); ++j) { const UserScript::File &file = script.js_scripts()[j]; ExtensionResource resource = extension->GetResource( file.relative_path()); loader->AppendScript(resource); } } loader->Run(); // It cleans itself up when done. } DLOG(INFO) << "ChromeVox was Loaded."; } else { // Unload ChromeVox extension_service->component_loader()->Remove(path); DLOG(INFO) << "ChromeVox was Unloaded."; } } void EnableHighContrast(bool enabled) { PrefService* pref_service = g_browser_process->local_state(); pref_service->SetBoolean(prefs::kHighContrastEnabled, enabled); pref_service->CommitPendingWrite(); } void EnableScreenMagnifier(bool enabled) { PrefService* pref_service = g_browser_process->local_state(); pref_service->SetBoolean(prefs::kScreenMagnifierEnabled, enabled); pref_service->CommitPendingWrite(); } void EnableVirtualKeyboard(bool enabled) { PrefService* pref_service = g_browser_process->local_state(); pref_service->SetBoolean(prefs::kVirtualKeyboardEnabled, enabled); pref_service->CommitPendingWrite(); } void ToggleSpokenFeedback(content::WebUI* login_web_ui) { bool spoken_feedback_enabled = g_browser_process && g_browser_process->local_state()->GetBoolean( prefs::kSpokenFeedbackEnabled); spoken_feedback_enabled = !spoken_feedback_enabled; EnableSpokenFeedback(spoken_feedback_enabled, login_web_ui); }; void Speak(const std::string& utterance) { UtteranceContinuousParameters params; ExtensionTtsPlatformImpl::GetInstance()->Speak( -1, // No utterance ID because we don't need a callback when it finishes. utterance.c_str(), g_browser_process->GetApplicationLocale(), params); } bool IsSpokenFeedbackEnabled() { if (!g_browser_process) { return false; } PrefService* prefs = g_browser_process->local_state(); bool spoken_feedback_enabled = prefs && prefs->GetBoolean(prefs::kSpokenFeedbackEnabled); return spoken_feedback_enabled; } void MaybeSpeak(const std::string& utterance) { if (IsSpokenFeedbackEnabled()) Speak(utterance); } } // namespace accessibility } // namespace chromeos <|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. // // Implementation of the SafeBrowsingBlockingPage class. #include "chrome/browser/safe_browsing/safe_browsing_blocking_page.h" #include "chrome/app/locales/locale_settings.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_resources.h" #include "chrome/browser/dom_operation_notification_details.h" #include "chrome/browser/google_util.h" #include "chrome/browser/navigation_controller.h" #include "chrome/browser/navigation_entry.h" #include "chrome/browser/tab_util.h" #include "chrome/browser/web_contents.h" #include "chrome/common/jstemplate_builder.h" #include "chrome/common/l10n_util.h" #include "chrome/common/resource_bundle.h" #include "generated_resources.h" #include "net/base/escape.h" // For malware interstitial pages, we link the problematic URL to Google's // diagnostic page. #if defined(GOOGLE_CHROME_BUILD) static const char* const kSbDiagnosticUrl = "http://safebrowsing.clients.google.com/safebrowsing/diagnostic?site=%ls&client=googlechrome"; #else static const char* const kSbDiagnosticUrl = "http://safebrowsing.clients.google.com/safebrowsing/diagnostic?site=%ls&client=chromium"; #endif static const char* const kSbReportPhishingUrl = "http://www.google.com/safebrowsing/report_error/"; static const wchar_t* const kSbDiagnosticHtml = L"<a href=\"\" onClick=\"sendCommand(4); return false;\">%ls</a>"; // Created on the io_thread. SafeBrowsingBlockingPage::SafeBrowsingBlockingPage( SafeBrowsingService* sb_service, SafeBrowsingService::Client* client, int render_process_host_id, int render_view_id, const GURL& url, ResourceType::Type resource_type, SafeBrowsingService::UrlCheckResult result) : sb_service_(sb_service), client_(client), render_process_host_id_(render_process_host_id), render_view_id_(render_view_id), url_(url), result_(result), proceed_(false), tab_(NULL), controller_(NULL), delete_pending_(false), is_main_frame_(resource_type == ResourceType::MAIN_FRAME), created_temporary_entry_(false) { } // Deleted on the io_thread. SafeBrowsingBlockingPage::~SafeBrowsingBlockingPage() { } void SafeBrowsingBlockingPage::DisplayBlockingPage() { TabContents* tab = tab_util::GetTabContentsByID(render_process_host_id_, render_view_id_); if (!tab || tab->type() != TAB_CONTENTS_WEB) { NotifyDone(); return; } tab_ = tab; controller_ = tab->controller(); // Register for notifications of events from this tab. NotificationService* ns = NotificationService::current(); DCHECK(ns); ns->AddObserver(this, NOTIFY_TAB_CLOSING, Source<NavigationController>(controller_)); ns->AddObserver(this, NOTIFY_DOM_OPERATION_RESPONSE, Source<TabContents>(tab_)); // Hold an extra reference to ourself until the interstitial is gone. AddRef(); WebContents* web_contents = tab->AsWebContents(); // Load the HTML page and create the template components. DictionaryValue strings; ResourceBundle& rb = ResourceBundle::GetSharedInstance(); std::string html; if (result_ == SafeBrowsingService::URL_MALWARE) { std::wstring link = StringPrintf(kSbDiagnosticHtml, l10n_util::GetString(IDS_SAFE_BROWSING_MALWARE_DIAGNOSTIC_PAGE).c_str()); strings.SetString(L"badURL", UTF8ToWide(url_.host())); strings.SetString(L"title", l10n_util::GetString(IDS_SAFE_BROWSING_MALWARE_TITLE)); strings.SetString(L"headLine", l10n_util::GetString(IDS_SAFE_BROWSING_MALWARE_HEADLINE)); // Check to see if we're blocking the main page, or a sub-resource on the // main page. if (is_main_frame_) { strings.SetString(L"description1", l10n_util::GetStringF(IDS_SAFE_BROWSING_MALWARE_DESCRIPTION1, UTF8ToWide(url_.host()))); strings.SetString(L"description2", l10n_util::GetStringF(IDS_SAFE_BROWSING_MALWARE_DESCRIPTION2, link, UTF8ToWide(url_.host()))); } else { strings.SetString(L"description1", l10n_util::GetStringF(IDS_SAFE_BROWSING_MALWARE_DESCRIPTION4, UTF8ToWide(tab_->GetURL().host()), UTF8ToWide(url_.host()))); strings.SetString(L"description2", l10n_util::GetStringF(IDS_SAFE_BROWSING_MALWARE_DESCRIPTION5, link, UTF8ToWide(url_.host()))); } strings.SetString(L"description3", l10n_util::GetString(IDS_SAFE_BROWSING_MALWARE_DESCRIPTION3)); strings.SetString(L"confirm_text", l10n_util::GetString(IDS_SAFE_BROWSING_MALWARE_DESCRIPTION_AGREE)); strings.SetString(L"continue_button", l10n_util::GetString(IDS_SAFE_BROWSING_MALWARE_PROCEED_BUTTON)); strings.SetString(L"back_button", l10n_util::GetString(IDS_SAFE_BROWSING_MALWARE_BACK_BUTTON)); strings.SetString(L"textdirection", (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) ? L"rtl" : L"ltr"); html = rb.GetDataResource(IDR_SAFE_BROWSING_MALWARE_BLOCK); } else { strings.SetString(L"title", l10n_util::GetString(IDS_SAFE_BROWSING_PHISHING_TITLE)); strings.SetString(L"headLine", l10n_util::GetString(IDS_SAFE_BROWSING_PHISHING_HEADLINE)); strings.SetString(L"description1", l10n_util::GetStringF(IDS_SAFE_BROWSING_PHISHING_DESCRIPTION1, UTF8ToWide(url_.host()))); strings.SetString(L"description2", l10n_util::GetStringF(IDS_SAFE_BROWSING_PHISHING_DESCRIPTION2, UTF8ToWide(url_.host()))); strings.SetString(L"continue_button", l10n_util::GetString(IDS_SAFE_BROWSING_PHISHING_PROCEED_BUTTON)); strings.SetString(L"back_button", l10n_util::GetString(IDS_SAFE_BROWSING_PHISHING_BACK_BUTTON)); strings.SetString(L"report_error", l10n_util::GetString(IDS_SAFE_BROWSING_PHISHING_REPORT_ERROR)); strings.SetString(L"textdirection", (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) ? L"rtl" : L"ltr"); html = rb.GetDataResource(IDR_SAFE_BROWSING_PHISHING_BLOCK); } std::string html_page(jstemplate_builder::GetTemplateHtml(html, &strings, "template_root")); // If the malware is the actual main frame and we have no pending entry // (typically the navigation was initiated by the page), we create a fake // navigation entry (so the location bar shows the page's URL). if (is_main_frame_ && tab_->controller()->GetPendingEntryIndex() == -1) { NavigationEntry new_entry(TAB_CONTENTS_WEB); new_entry.set_url(url_); new_entry.set_page_type(NavigationEntry::INTERSTITIAL_PAGE); tab_->controller()->AddDummyEntryForInterstitial(new_entry); created_temporary_entry_ = true; } // Show the interstitial page. web_contents->ShowInterstitialPage(html_page, this); } void SafeBrowsingBlockingPage::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type) { case NOTIFY_TAB_CLOSING: HandleClose(); break; case NOTIFY_DOM_OPERATION_RESPONSE: Continue(Details<DomOperationNotificationDetails>(details)->json()); break; default: NOTREACHED(); } } void SafeBrowsingBlockingPage::InterstitialClosed() { HandleClose(); } bool SafeBrowsingBlockingPage::GoBack() { WebContents* web_contents = tab_->AsWebContents(); NavigationEntry* prev_entry = web_contents->controller()->GetEntryAtOffset(-1); if (!prev_entry) { // Nothing to go to, default to about:blank. Navigating will cause the // interstitial to hide which will trigger "this" to be deleted. tab_->controller()->LoadURL(GURL("about:blank"), PageTransition::AUTO_BOOKMARK); } else if (prev_entry->tab_type() != TAB_CONTENTS_WEB || prev_entry->restored() || !is_main_frame_) { // We do navigate back if any of these is true: // - the page is not a WebContents, its TabContents might have to be // recreated. // - we have not yet visited that navigation entry (typically session // restore), in which case the page is not already available. // - the interstitial was triggered by a sub-resource. In that case we // really need to navigate, just hiding the interstitial would show the // page containing the bad resource, and we don't want that. web_contents->controller()->GoBack(); } else { // Otherwise, the user was viewing a page and navigated to a URL that was // interrupted by an interstitial. Thus, we can just hide the interstitial // and show the page the user was on before. web_contents->HideInterstitialPage(false, false); } // WARNING: at this point we are now either deleted or pending deletion from // the IO thread. // Remove the navigation entry for the malware page. Note that we always // remove the entry even if we did not create it as it has been flagged as // malware and we don't want the user navigating back to it. web_contents->controller()->RemoveLastEntryForInterstitial(); return true; } void SafeBrowsingBlockingPage::Continue(const std::string& user_action) { TabContents* tab = tab_util::GetTabContentsByID(render_process_host_id_, render_view_id_); DCHECK(tab); WebContents* web = tab->AsWebContents(); if (user_action == "2") { // User pressed "Learn more". GURL url; if (result_ == SafeBrowsingService::URL_MALWARE) { url = GURL(l10n_util::GetString(IDS_LEARN_MORE_MALWARE_URL)); } else if (result_ == SafeBrowsingService::URL_PHISHING) { url = GURL(l10n_util::GetString(IDS_LEARN_MORE_PHISHING_URL)); } else { NOTREACHED(); } web->OpenURL(url, CURRENT_TAB, PageTransition::LINK); return; } if (user_action == "3") { // User pressed "Report error" for a phishing site. // Note that we cannot just put a link in the interstitial at this point. // It is not OK to navigate in the context of an interstitial page. DCHECK(result_ == SafeBrowsingService::URL_PHISHING); GURL report_url = safe_browsing_util::GeneratePhishingReportUrl(kSbReportPhishingUrl, url_.spec()); web->OpenURL(report_url, CURRENT_TAB, PageTransition::LINK); return; } if (user_action == "4") { // We're going to take the user to Google's SafeBrowsing diagnostic page. std::string diagnostic = StringPrintf(kSbDiagnosticUrl, EscapeQueryParamValue(url_.spec()).c_str()); GURL diagnostic_url(diagnostic); diagnostic_url = google_util::AppendGoogleLocaleParam(diagnostic_url); DCHECK(result_ == SafeBrowsingService::URL_MALWARE); web->OpenURL(diagnostic_url, CURRENT_TAB, PageTransition::LINK); return; } proceed_ = user_action == "1"; if (proceed_) { // We are continuing, if we have created a temporary navigation entry, // delete it as a new will be created on navigation. if (created_temporary_entry_) web->controller()->RemoveLastEntryForInterstitial(); if (is_main_frame_) web->HideInterstitialPage(true, true); else web->HideInterstitialPage(false, false); } else { GoBack(); } NotifyDone(); } void SafeBrowsingBlockingPage::HandleClose() { NotificationService* ns = NotificationService::current(); DCHECK(ns); ns->RemoveObserver(this, NOTIFY_TAB_CLOSING, Source<NavigationController>(controller_)); ns->RemoveObserver(this, NOTIFY_DOM_OPERATION_RESPONSE, Source<TabContents>(tab_)); NotifyDone(); Release(); } void SafeBrowsingBlockingPage::NotifyDone() { if (delete_pending_) return; delete_pending_ = true; if (tab_ && tab_->AsWebContents()) { // Ensure the WebContents does not keep a pointer to us. tab_->AsWebContents()->set_interstitial_delegate(NULL); } base::Thread* io_thread = g_browser_process->io_thread(); if (!io_thread) return; io_thread->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( sb_service_, &SafeBrowsingService::OnBlockingPageDone, this, client_, proceed_)); } <commit_msg>Clicking the diagnostic link on the malware page would triggers a DCHECK. The diagnostic URL was not formatted properly and we would load an empty URL.<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. // // Implementation of the SafeBrowsingBlockingPage class. #include "chrome/browser/safe_browsing/safe_browsing_blocking_page.h" #include "chrome/app/locales/locale_settings.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_resources.h" #include "chrome/browser/dom_operation_notification_details.h" #include "chrome/browser/google_util.h" #include "chrome/browser/navigation_controller.h" #include "chrome/browser/navigation_entry.h" #include "chrome/browser/tab_util.h" #include "chrome/browser/web_contents.h" #include "chrome/common/jstemplate_builder.h" #include "chrome/common/l10n_util.h" #include "chrome/common/resource_bundle.h" #include "generated_resources.h" #include "net/base/escape.h" // For malware interstitial pages, we link the problematic URL to Google's // diagnostic page. #if defined(GOOGLE_CHROME_BUILD) static const char* const kSbDiagnosticUrl = "http://safebrowsing.clients.google.com/safebrowsing/diagnostic?site=%s&client=googlechrome"; #else static const char* const kSbDiagnosticUrl = "http://safebrowsing.clients.google.com/safebrowsing/diagnostic?site=%s&client=chromium"; #endif static const char* const kSbReportPhishingUrl = "http://www.google.com/safebrowsing/report_error/"; static const wchar_t* const kSbDiagnosticHtml = L"<a href=\"\" onClick=\"sendCommand(4); return false;\">%ls</a>"; // Created on the io_thread. SafeBrowsingBlockingPage::SafeBrowsingBlockingPage( SafeBrowsingService* sb_service, SafeBrowsingService::Client* client, int render_process_host_id, int render_view_id, const GURL& url, ResourceType::Type resource_type, SafeBrowsingService::UrlCheckResult result) : sb_service_(sb_service), client_(client), render_process_host_id_(render_process_host_id), render_view_id_(render_view_id), url_(url), result_(result), proceed_(false), tab_(NULL), controller_(NULL), delete_pending_(false), is_main_frame_(resource_type == ResourceType::MAIN_FRAME), created_temporary_entry_(false) { } // Deleted on the io_thread. SafeBrowsingBlockingPage::~SafeBrowsingBlockingPage() { } void SafeBrowsingBlockingPage::DisplayBlockingPage() { TabContents* tab = tab_util::GetTabContentsByID(render_process_host_id_, render_view_id_); if (!tab || tab->type() != TAB_CONTENTS_WEB) { NotifyDone(); return; } tab_ = tab; controller_ = tab->controller(); // Register for notifications of events from this tab. NotificationService* ns = NotificationService::current(); DCHECK(ns); ns->AddObserver(this, NOTIFY_TAB_CLOSING, Source<NavigationController>(controller_)); ns->AddObserver(this, NOTIFY_DOM_OPERATION_RESPONSE, Source<TabContents>(tab_)); // Hold an extra reference to ourself until the interstitial is gone. AddRef(); WebContents* web_contents = tab->AsWebContents(); // Load the HTML page and create the template components. DictionaryValue strings; ResourceBundle& rb = ResourceBundle::GetSharedInstance(); std::string html; if (result_ == SafeBrowsingService::URL_MALWARE) { std::wstring link = StringPrintf(kSbDiagnosticHtml, l10n_util::GetString(IDS_SAFE_BROWSING_MALWARE_DIAGNOSTIC_PAGE).c_str()); strings.SetString(L"badURL", UTF8ToWide(url_.host())); strings.SetString(L"title", l10n_util::GetString(IDS_SAFE_BROWSING_MALWARE_TITLE)); strings.SetString(L"headLine", l10n_util::GetString(IDS_SAFE_BROWSING_MALWARE_HEADLINE)); // Check to see if we're blocking the main page, or a sub-resource on the // main page. if (is_main_frame_) { strings.SetString(L"description1", l10n_util::GetStringF(IDS_SAFE_BROWSING_MALWARE_DESCRIPTION1, UTF8ToWide(url_.host()))); strings.SetString(L"description2", l10n_util::GetStringF(IDS_SAFE_BROWSING_MALWARE_DESCRIPTION2, link, UTF8ToWide(url_.host()))); } else { strings.SetString(L"description1", l10n_util::GetStringF(IDS_SAFE_BROWSING_MALWARE_DESCRIPTION4, UTF8ToWide(tab_->GetURL().host()), UTF8ToWide(url_.host()))); strings.SetString(L"description2", l10n_util::GetStringF(IDS_SAFE_BROWSING_MALWARE_DESCRIPTION5, link, UTF8ToWide(url_.host()))); } strings.SetString(L"description3", l10n_util::GetString(IDS_SAFE_BROWSING_MALWARE_DESCRIPTION3)); strings.SetString(L"confirm_text", l10n_util::GetString(IDS_SAFE_BROWSING_MALWARE_DESCRIPTION_AGREE)); strings.SetString(L"continue_button", l10n_util::GetString(IDS_SAFE_BROWSING_MALWARE_PROCEED_BUTTON)); strings.SetString(L"back_button", l10n_util::GetString(IDS_SAFE_BROWSING_MALWARE_BACK_BUTTON)); strings.SetString(L"textdirection", (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) ? L"rtl" : L"ltr"); html = rb.GetDataResource(IDR_SAFE_BROWSING_MALWARE_BLOCK); } else { strings.SetString(L"title", l10n_util::GetString(IDS_SAFE_BROWSING_PHISHING_TITLE)); strings.SetString(L"headLine", l10n_util::GetString(IDS_SAFE_BROWSING_PHISHING_HEADLINE)); strings.SetString(L"description1", l10n_util::GetStringF(IDS_SAFE_BROWSING_PHISHING_DESCRIPTION1, UTF8ToWide(url_.host()))); strings.SetString(L"description2", l10n_util::GetStringF(IDS_SAFE_BROWSING_PHISHING_DESCRIPTION2, UTF8ToWide(url_.host()))); strings.SetString(L"continue_button", l10n_util::GetString(IDS_SAFE_BROWSING_PHISHING_PROCEED_BUTTON)); strings.SetString(L"back_button", l10n_util::GetString(IDS_SAFE_BROWSING_PHISHING_BACK_BUTTON)); strings.SetString(L"report_error", l10n_util::GetString(IDS_SAFE_BROWSING_PHISHING_REPORT_ERROR)); strings.SetString(L"textdirection", (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) ? L"rtl" : L"ltr"); html = rb.GetDataResource(IDR_SAFE_BROWSING_PHISHING_BLOCK); } std::string html_page(jstemplate_builder::GetTemplateHtml(html, &strings, "template_root")); // If the malware is the actual main frame and we have no pending entry // (typically the navigation was initiated by the page), we create a fake // navigation entry (so the location bar shows the page's URL). if (is_main_frame_ && tab_->controller()->GetPendingEntryIndex() == -1) { NavigationEntry new_entry(TAB_CONTENTS_WEB); new_entry.set_url(url_); new_entry.set_page_type(NavigationEntry::INTERSTITIAL_PAGE); tab_->controller()->AddDummyEntryForInterstitial(new_entry); created_temporary_entry_ = true; } // Show the interstitial page. web_contents->ShowInterstitialPage(html_page, this); } void SafeBrowsingBlockingPage::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type) { case NOTIFY_TAB_CLOSING: HandleClose(); break; case NOTIFY_DOM_OPERATION_RESPONSE: Continue(Details<DomOperationNotificationDetails>(details)->json()); break; default: NOTREACHED(); } } void SafeBrowsingBlockingPage::InterstitialClosed() { HandleClose(); } bool SafeBrowsingBlockingPage::GoBack() { WebContents* web_contents = tab_->AsWebContents(); NavigationEntry* prev_entry = web_contents->controller()->GetEntryAtOffset(-1); if (!prev_entry) { // Nothing to go to, default to about:blank. Navigating will cause the // interstitial to hide which will trigger "this" to be deleted. tab_->controller()->LoadURL(GURL("about:blank"), PageTransition::AUTO_BOOKMARK); } else if (prev_entry->tab_type() != TAB_CONTENTS_WEB || prev_entry->restored() || !is_main_frame_) { // We do navigate back if any of these is true: // - the page is not a WebContents, its TabContents might have to be // recreated. // - we have not yet visited that navigation entry (typically session // restore), in which case the page is not already available. // - the interstitial was triggered by a sub-resource. In that case we // really need to navigate, just hiding the interstitial would show the // page containing the bad resource, and we don't want that. web_contents->controller()->GoBack(); } else { // Otherwise, the user was viewing a page and navigated to a URL that was // interrupted by an interstitial. Thus, we can just hide the interstitial // and show the page the user was on before. web_contents->HideInterstitialPage(false, false); } // WARNING: at this point we are now either deleted or pending deletion from // the IO thread. // Remove the navigation entry for the malware page. Note that we always // remove the entry even if we did not create it as it has been flagged as // malware and we don't want the user navigating back to it. web_contents->controller()->RemoveLastEntryForInterstitial(); return true; } void SafeBrowsingBlockingPage::Continue(const std::string& user_action) { TabContents* tab = tab_util::GetTabContentsByID(render_process_host_id_, render_view_id_); DCHECK(tab); WebContents* web = tab->AsWebContents(); if (user_action == "2") { // User pressed "Learn more". GURL url; if (result_ == SafeBrowsingService::URL_MALWARE) { url = GURL(l10n_util::GetString(IDS_LEARN_MORE_MALWARE_URL)); } else if (result_ == SafeBrowsingService::URL_PHISHING) { url = GURL(l10n_util::GetString(IDS_LEARN_MORE_PHISHING_URL)); } else { NOTREACHED(); } web->OpenURL(url, CURRENT_TAB, PageTransition::LINK); return; } if (user_action == "3") { // User pressed "Report error" for a phishing site. // Note that we cannot just put a link in the interstitial at this point. // It is not OK to navigate in the context of an interstitial page. DCHECK(result_ == SafeBrowsingService::URL_PHISHING); GURL report_url = safe_browsing_util::GeneratePhishingReportUrl(kSbReportPhishingUrl, url_.spec()); web->OpenURL(report_url, CURRENT_TAB, PageTransition::LINK); return; } if (user_action == "4") { // We're going to take the user to Google's SafeBrowsing diagnostic page. std::string diagnostic = StringPrintf(kSbDiagnosticUrl, EscapeQueryParamValue(url_.spec()).c_str()); GURL diagnostic_url(diagnostic); diagnostic_url = google_util::AppendGoogleLocaleParam(diagnostic_url); DCHECK(result_ == SafeBrowsingService::URL_MALWARE); web->OpenURL(diagnostic_url, CURRENT_TAB, PageTransition::LINK); return; } proceed_ = user_action == "1"; if (proceed_) { // We are continuing, if we have created a temporary navigation entry, // delete it as a new will be created on navigation. if (created_temporary_entry_) web->controller()->RemoveLastEntryForInterstitial(); if (is_main_frame_) web->HideInterstitialPage(true, true); else web->HideInterstitialPage(false, false); } else { GoBack(); } NotifyDone(); } void SafeBrowsingBlockingPage::HandleClose() { NotificationService* ns = NotificationService::current(); DCHECK(ns); ns->RemoveObserver(this, NOTIFY_TAB_CLOSING, Source<NavigationController>(controller_)); ns->RemoveObserver(this, NOTIFY_DOM_OPERATION_RESPONSE, Source<TabContents>(tab_)); NotifyDone(); Release(); } void SafeBrowsingBlockingPage::NotifyDone() { if (delete_pending_) return; delete_pending_ = true; if (tab_ && tab_->AsWebContents()) { // Ensure the WebContents does not keep a pointer to us. tab_->AsWebContents()->set_interstitial_delegate(NULL); } base::Thread* io_thread = g_browser_process->io_thread(); if (!io_thread) return; io_thread->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( sb_service_, &SafeBrowsingService::OnBlockingPageDone, this, client_, proceed_)); } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #ifndef _Stroika_Foundation_Memory_Common_inl_ #define _Stroika_Foundation_Memory_Common_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ namespace Stroika::Foundation::Memory { /* ******************************************************************************** ********************* Memory::GlobalAllocationStatistics *********************** ******************************************************************************** */ inline GlobalAllocationStatistics::GlobalAllocationStatistics () : fTotalOutstandingAllocations{0} , fTotalOutstandingBytesAllocated{0} , fPageFaultCount{0} , fWorkingSetSize{0} , fPagefileUsage{0} { } /* ******************************************************************************** ********************************* Memory::MemCmp ******************************* ******************************************************************************** */ template <> constexpr int MemCmp (const uint8_t* lhs, const uint8_t* rhs, std::size_t count) { //Require (count == 0 or lhs != nullptr); //Require (count == 0 or rhs != nullptr); const uint8_t* li = lhs; const uint8_t* ri = rhs; for (; count--; li++, ri++) { if (int cmp = static_cast<int> (*li) - static_cast<int> (*ri)) { return cmp; } } return 0; } template <typename T> constexpr int MemCmp (const T* lhs, const T* rhs, size_t count) { return MemCmp (reinterpret_cast<const uint8_t*> (lhs), reinterpret_cast<const uint8_t*> (rhs), count * sizeof (T)); } #if qSilenceAnnoyingCompilerWarnings && _MSC_VER namespace Private { template <class _InIt, class _OutIt> inline void VC_BWA_std_copy (_InIt _First, _InIt _Last, _OutIt _Dest) { auto o = _Dest; for (auto i = _First; i != _Last; ++i, ++o) { *o = *i; } } } #endif namespace PRIVATE_ { // @see https://gist.github.com/graphitemaster/494f21190bb2c63c5516 for more info on maybe how to // get this working with constexpr and without static object template <typename T1, typename T2> struct OffsetOfRequiringDefaultConstructibleObjectType_ { #if qCompilerAndStdLib_default_constructor_initialization_issueWithExplicit_Buggy static inline /*constexpr*/ T2 sObj_{T2{}}; #else static inline /*constexpr*/ T2 sObj_{}; #endif static constexpr size_t offset (T1 T2::*member) { /* * UNDEFINED BEHAVIOR: it is undefined, but for the following reason: expr.add-5.sentence-2 // "If the expressions P and Q point to, respectively, elements x[i] and x[j] of // the same array object x, the expression P - Q has the value i - j; otherwise, the behavior is undefined."] */ return size_t (&(OffsetOfRequiringDefaultConstructibleObjectType_<T1, T2>::sObj_.*member)) - size_t (&OffsetOfRequiringDefaultConstructibleObjectType_<T1, T2>::sObj_); } }; } template <typename FIELD_VALUE_TYPE, typename OWNING_OBJECT> inline size_t constexpr OffsetOf_Constexpr (FIELD_VALUE_TYPE OWNING_OBJECT::*member) { return PRIVATE_::OffsetOfRequiringDefaultConstructibleObjectType_<FIELD_VALUE_TYPE, OWNING_OBJECT>::offset (member); } template <typename FIELD_VALUE_TYPE, typename OWNING_OBJECT> inline size_t OffsetOf (FIELD_VALUE_TYPE OWNING_OBJECT::*member) { #if 0 auto o = declval<OWNING_OBJECT> (); // function only valid in unevaluated contexts - produces link errors auto result = size_t (reinterpret_cast<const char*> (&(o.*member)) - reinterpret_cast<const char*> (&o)); #elif 0 // gcc doesn't allow reinterpret_cast of nullptr: invalid cast from type �std::nullptr_t� to type �const ...*� DISABLE_COMPILER_CLANG_WARNING_START ("clang diagnostic ignored \"-Wnull-dereference\"") const OWNING_OBJECT& o = *reinterpret_cast<const OWNING_OBJECT*> (nullptr); DISABLE_COMPILER_CLANG_WARNING_END ("clang diagnostic ignored \"-Wnull-dereference\"") auto result = size_t (reinterpret_cast<const char*> (&(o.*member)) - reinterpret_cast<const char*> (&o)); #elif 0 //TSAN detects undefined behavior const OWNING_OBJECT& o = *reinterpret_cast<const OWNING_OBJECT*> (0); auto result = size_t (reinterpret_cast<const char*> (&(o.*member)) - reinterpret_cast<const char*> (&o)); #else // Still not totally legal for non-std-layout classes, but seems to work, and I haven't found a better way // --LGP 2021-05-27 alignas (OWNING_OBJECT) std::byte buf[sizeof (OWNING_OBJECT)]{}; const OWNING_OBJECT& o = *reinterpret_cast<const OWNING_OBJECT*> (&buf); auto result = size_t (reinterpret_cast<const char*> (&(o.*member)) - reinterpret_cast<const char*> (&o)); #endif // Avoid #include - Ensure (result <= sizeof (OWNING_OBJECT)); return result; } } #endif /*_Stroika_Foundation_Memory_Common_inl_*/ <commit_msg>re-enable constexpr stuff for constexpr test (not working) of OffsetOf<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #ifndef _Stroika_Foundation_Memory_Common_inl_ #define _Stroika_Foundation_Memory_Common_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ namespace Stroika::Foundation::Memory { /* ******************************************************************************** ********************* Memory::GlobalAllocationStatistics *********************** ******************************************************************************** */ inline GlobalAllocationStatistics::GlobalAllocationStatistics () : fTotalOutstandingAllocations{0} , fTotalOutstandingBytesAllocated{0} , fPageFaultCount{0} , fWorkingSetSize{0} , fPagefileUsage{0} { } /* ******************************************************************************** ********************************* Memory::MemCmp ******************************* ******************************************************************************** */ template <> constexpr int MemCmp (const uint8_t* lhs, const uint8_t* rhs, std::size_t count) { //Require (count == 0 or lhs != nullptr); //Require (count == 0 or rhs != nullptr); const uint8_t* li = lhs; const uint8_t* ri = rhs; for (; count--; li++, ri++) { if (int cmp = static_cast<int> (*li) - static_cast<int> (*ri)) { return cmp; } } return 0; } template <typename T> constexpr int MemCmp (const T* lhs, const T* rhs, size_t count) { return MemCmp (reinterpret_cast<const uint8_t*> (lhs), reinterpret_cast<const uint8_t*> (rhs), count * sizeof (T)); } #if qSilenceAnnoyingCompilerWarnings && _MSC_VER namespace Private { template <class _InIt, class _OutIt> inline void VC_BWA_std_copy (_InIt _First, _InIt _Last, _OutIt _Dest) { auto o = _Dest; for (auto i = _First; i != _Last; ++i, ++o) { *o = *i; } } } #endif namespace PRIVATE_ { // @see https://gist.github.com/graphitemaster/494f21190bb2c63c5516 for more info on maybe how to // get this working with constexpr and without static object template <typename T1, typename T2> struct OffsetOfRequiringDefaultConstructibleObjectType_ { #if qCompilerAndStdLib_default_constructor_initialization_issueWithExplicit_Buggy static inline constexpr T2 sObj_{T2{}}; #else static inline constexpr T2 sObj_{}; #endif static constexpr size_t offset (T1 T2::*member) { /* * UNDEFINED BEHAVIOR: it is undefined, but for the following reason: expr.add-5.sentence-2 * "If the expressions P and Q point to, respectively, elements x[i] and x[j] of * the same array object x, the expression P - Q has the value i - j; otherwise, the behavior is undefined."] */ return size_t (&(OffsetOfRequiringDefaultConstructibleObjectType_<T1, T2>::sObj_.*member)) - size_t (&OffsetOfRequiringDefaultConstructibleObjectType_<T1, T2>::sObj_); } }; } template <typename FIELD_VALUE_TYPE, typename OWNING_OBJECT> inline size_t constexpr OffsetOf_Constexpr (FIELD_VALUE_TYPE OWNING_OBJECT::*member) { return PRIVATE_::OffsetOfRequiringDefaultConstructibleObjectType_<FIELD_VALUE_TYPE, OWNING_OBJECT>::offset (member); } template <typename FIELD_VALUE_TYPE, typename OWNING_OBJECT> inline size_t OffsetOf (FIELD_VALUE_TYPE OWNING_OBJECT::*member) { #if 0 auto o = declval<OWNING_OBJECT> (); // function only valid in unevaluated contexts - produces link errors auto result = size_t (reinterpret_cast<const char*> (&(o.*member)) - reinterpret_cast<const char*> (&o)); #elif 0 // gcc doesn't allow reinterpret_cast of nullptr: invalid cast from type �std::nullptr_t� to type �const ...*� DISABLE_COMPILER_CLANG_WARNING_START ("clang diagnostic ignored \"-Wnull-dereference\"") const OWNING_OBJECT& o = *reinterpret_cast<const OWNING_OBJECT*> (nullptr); DISABLE_COMPILER_CLANG_WARNING_END ("clang diagnostic ignored \"-Wnull-dereference\"") auto result = size_t (reinterpret_cast<const char*> (&(o.*member)) - reinterpret_cast<const char*> (&o)); #elif 0 //TSAN detects undefined behavior const OWNING_OBJECT& o = *reinterpret_cast<const OWNING_OBJECT*> (0); auto result = size_t (reinterpret_cast<const char*> (&(o.*member)) - reinterpret_cast<const char*> (&o)); #else // Still not totally legal for non-std-layout classes, but seems to work, and I haven't found a better way // --LGP 2021-05-27 alignas (OWNING_OBJECT) std::byte buf[sizeof (OWNING_OBJECT)]{}; const OWNING_OBJECT& o = *reinterpret_cast<const OWNING_OBJECT*> (&buf); auto result = size_t (reinterpret_cast<const char*> (&(o.*member)) - reinterpret_cast<const char*> (&o)); #endif // Avoid #include - Ensure (result <= sizeof (OWNING_OBJECT)); return result; } } #endif /*_Stroika_Foundation_Memory_Common_inl_*/ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TitleHelper.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 01:35:17 $ * * 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 * ************************************************************************/ #include "TitleHelper.hxx" #include "ChartModelHelper.hxx" #include "macros.hxx" #include "ContextHelper.hxx" #include "MeterHelper.hxx" #ifndef _COM_SUN_STAR_CHART2_XCHARTDOCUMENT_HPP_ #include <com/sun/star/chart2/XChartDocument.hpp> #endif //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; using namespace ::com::sun::star::chart2; rtl::OUString TitleHelper::getIdentifierForTitle( TitleHelper::eTitleType nTitleIndex ) { switch( nTitleIndex ) { case MAIN_TITLE: { static rtl::OUString m_aIdentifier( C2U( "@main-title" ) ); return m_aIdentifier; } case SUB_TITLE: { static rtl::OUString m_aIdentifier( C2U( "@sub-title" ) ); return m_aIdentifier; } case X_AXIS_TITLE: { static rtl::OUString m_aIdentifier( C2U( "@xaxis-title" ) ); return m_aIdentifier; } case Y_AXIS_TITLE: { static rtl::OUString m_aIdentifier( C2U( "@yaxis-title" ) ); return m_aIdentifier; } case Z_AXIS_TITLE: { static rtl::OUString m_aIdentifier( C2U( "@zaxis-title" ) ); return m_aIdentifier; } default: OSL_ENSURE( false, "Unsupported Title-Type requested" ); return ::rtl::OUString(); } } uno::Reference< XTitled > lcl_getTitleParent( TitleHelper::eTitleType nTitleIndex , const uno::Reference< frame::XModel >& xModel ) { uno::Reference< XTitled > xResult; uno::Reference< XChartDocument > xChartDoc( xModel, uno::UNO_QUERY ); uno::Reference< XDiagram > xDiagram; if( xChartDoc.is()) xDiagram.set( xChartDoc->getDiagram()); switch( nTitleIndex ) { case TitleHelper::MAIN_TITLE: xResult.set( xModel, uno::UNO_QUERY ); break; case TitleHelper::SUB_TITLE: if( xDiagram.is()) xResult.set( xDiagram, uno::UNO_QUERY ); break; case TitleHelper::X_AXIS_TITLE: if( xDiagram.is()) xResult.set( MeterHelper::getAxis( 0, true, xDiagram ), uno::UNO_QUERY ); break; case TitleHelper::Y_AXIS_TITLE: if( xDiagram.is()) xResult.set( MeterHelper::getAxis( 1, true, xDiagram ), uno::UNO_QUERY ); break; case TitleHelper::Z_AXIS_TITLE: if( xDiagram.is()) xResult.set( MeterHelper::getAxis( 2, true, xDiagram ), uno::UNO_QUERY ); break; default: OSL_ENSURE( false, "Unsupported Title-Type requested" ); break; } return xResult; } uno::Reference< XTitle > TitleHelper::getTitle( TitleHelper::eTitleType nTitleIndex , const uno::Reference< frame::XModel >& xModel ) { uno::Reference< XTitled > xTitled( lcl_getTitleParent( nTitleIndex, xModel ) ); if( xTitled.is()) return xTitled->getTitle(); return NULL; } uno::Reference< XTitle > TitleHelper::createTitle( TitleHelper::eTitleType nTitleIndex , const rtl::OUString& rTitleText , const uno::Reference< frame::XModel >& xModel , const uno::Reference< uno::XComponentContext > & xContext ) { if( !rTitleText.getLength() ) return NULL; uno::Reference< XTitle > xTitle(NULL); uno::Reference< XTitled > xTitled( lcl_getTitleParent( nTitleIndex, xModel ) ); ContextHelper::tContextEntryMapType aContextValues( ContextHelper::MakeContextEntryMap( C2U( "Identifier" ) , uno::makeAny( TitleHelper::getIdentifierForTitle(nTitleIndex) )) ); uno::Reference< uno::XComponentContext > xNewContext( ContextHelper::createContext( aContextValues, xContext ) ); if(xNewContext.is() && xTitled.is()) { xTitle.set( xContext->getServiceManager()->createInstanceWithContext( C2U( "com.sun.star.chart2.Title" ), xNewContext ), uno::UNO_QUERY ); if(xTitle.is()) { setCompleteString( rTitleText, xTitle, xNewContext ); xTitled->setTitle( xTitle ); } } return xTitle; } rtl::OUString TitleHelper::getCompleteString( const uno::Reference< XTitle >& xTitle ) { rtl::OUString aRet; if(!xTitle.is()) return aRet; uno::Sequence< uno::Reference< XFormattedString > > aStringList = xTitle->getText(); for( sal_Int32 nN=0; nN<aStringList.getLength();nN++ ) aRet += aStringList[nN]->getString(); return aRet; } void TitleHelper::setCompleteString( const rtl::OUString& rNewText , const uno::Reference< XTitle >& xTitle , const uno::Reference< uno::XComponentContext > & xContext ) { //the format of the first old text portion will be maintained if there is any if(!xTitle.is()) return; uno::Sequence< uno::Reference< XFormattedString > > aNewStringList(1); uno::Sequence< uno::Reference< XFormattedString > > aOldStringList = xTitle->getText(); if( aOldStringList.getLength() ) { aNewStringList[0].set( aOldStringList[0] ); aNewStringList[0]->setString( rNewText ); } else { uno::Reference< uno::XInterface > xI( xContext->getServiceManager()->createInstanceWithContext( C2U( "com.sun.star.chart2.FormattedString" ), xContext ) ); uno::Reference< XFormattedString > xFormattedString( xI, uno::UNO_QUERY ); if(xFormattedString.is()) { xFormattedString->setString( rNewText ); aNewStringList[0].set( xFormattedString ); } } xTitle->setText( aNewStringList ); } void TitleHelper::removeTitle( TitleHelper::eTitleType nTitleIndex , const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& xModel ) { uno::Reference< XTitled > xTitled( lcl_getTitleParent( nTitleIndex, xModel ) ); if( xTitled.is()) { xTitled->setTitle(NULL); } } //............................................................................. } //namespace chart //............................................................................. <commit_msg>INTEGRATION: CWS pchfix02 (1.5.80); FILE MERGED 2006/09/01 17:18:55 kaib 1.5.80.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TitleHelper.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-09-17 13:30:07 $ * * 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_chart2.hxx" #include "TitleHelper.hxx" #include "ChartModelHelper.hxx" #include "macros.hxx" #include "ContextHelper.hxx" #include "MeterHelper.hxx" #ifndef _COM_SUN_STAR_CHART2_XCHARTDOCUMENT_HPP_ #include <com/sun/star/chart2/XChartDocument.hpp> #endif //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; using namespace ::com::sun::star::chart2; rtl::OUString TitleHelper::getIdentifierForTitle( TitleHelper::eTitleType nTitleIndex ) { switch( nTitleIndex ) { case MAIN_TITLE: { static rtl::OUString m_aIdentifier( C2U( "@main-title" ) ); return m_aIdentifier; } case SUB_TITLE: { static rtl::OUString m_aIdentifier( C2U( "@sub-title" ) ); return m_aIdentifier; } case X_AXIS_TITLE: { static rtl::OUString m_aIdentifier( C2U( "@xaxis-title" ) ); return m_aIdentifier; } case Y_AXIS_TITLE: { static rtl::OUString m_aIdentifier( C2U( "@yaxis-title" ) ); return m_aIdentifier; } case Z_AXIS_TITLE: { static rtl::OUString m_aIdentifier( C2U( "@zaxis-title" ) ); return m_aIdentifier; } default: OSL_ENSURE( false, "Unsupported Title-Type requested" ); return ::rtl::OUString(); } } uno::Reference< XTitled > lcl_getTitleParent( TitleHelper::eTitleType nTitleIndex , const uno::Reference< frame::XModel >& xModel ) { uno::Reference< XTitled > xResult; uno::Reference< XChartDocument > xChartDoc( xModel, uno::UNO_QUERY ); uno::Reference< XDiagram > xDiagram; if( xChartDoc.is()) xDiagram.set( xChartDoc->getDiagram()); switch( nTitleIndex ) { case TitleHelper::MAIN_TITLE: xResult.set( xModel, uno::UNO_QUERY ); break; case TitleHelper::SUB_TITLE: if( xDiagram.is()) xResult.set( xDiagram, uno::UNO_QUERY ); break; case TitleHelper::X_AXIS_TITLE: if( xDiagram.is()) xResult.set( MeterHelper::getAxis( 0, true, xDiagram ), uno::UNO_QUERY ); break; case TitleHelper::Y_AXIS_TITLE: if( xDiagram.is()) xResult.set( MeterHelper::getAxis( 1, true, xDiagram ), uno::UNO_QUERY ); break; case TitleHelper::Z_AXIS_TITLE: if( xDiagram.is()) xResult.set( MeterHelper::getAxis( 2, true, xDiagram ), uno::UNO_QUERY ); break; default: OSL_ENSURE( false, "Unsupported Title-Type requested" ); break; } return xResult; } uno::Reference< XTitle > TitleHelper::getTitle( TitleHelper::eTitleType nTitleIndex , const uno::Reference< frame::XModel >& xModel ) { uno::Reference< XTitled > xTitled( lcl_getTitleParent( nTitleIndex, xModel ) ); if( xTitled.is()) return xTitled->getTitle(); return NULL; } uno::Reference< XTitle > TitleHelper::createTitle( TitleHelper::eTitleType nTitleIndex , const rtl::OUString& rTitleText , const uno::Reference< frame::XModel >& xModel , const uno::Reference< uno::XComponentContext > & xContext ) { if( !rTitleText.getLength() ) return NULL; uno::Reference< XTitle > xTitle(NULL); uno::Reference< XTitled > xTitled( lcl_getTitleParent( nTitleIndex, xModel ) ); ContextHelper::tContextEntryMapType aContextValues( ContextHelper::MakeContextEntryMap( C2U( "Identifier" ) , uno::makeAny( TitleHelper::getIdentifierForTitle(nTitleIndex) )) ); uno::Reference< uno::XComponentContext > xNewContext( ContextHelper::createContext( aContextValues, xContext ) ); if(xNewContext.is() && xTitled.is()) { xTitle.set( xContext->getServiceManager()->createInstanceWithContext( C2U( "com.sun.star.chart2.Title" ), xNewContext ), uno::UNO_QUERY ); if(xTitle.is()) { setCompleteString( rTitleText, xTitle, xNewContext ); xTitled->setTitle( xTitle ); } } return xTitle; } rtl::OUString TitleHelper::getCompleteString( const uno::Reference< XTitle >& xTitle ) { rtl::OUString aRet; if(!xTitle.is()) return aRet; uno::Sequence< uno::Reference< XFormattedString > > aStringList = xTitle->getText(); for( sal_Int32 nN=0; nN<aStringList.getLength();nN++ ) aRet += aStringList[nN]->getString(); return aRet; } void TitleHelper::setCompleteString( const rtl::OUString& rNewText , const uno::Reference< XTitle >& xTitle , const uno::Reference< uno::XComponentContext > & xContext ) { //the format of the first old text portion will be maintained if there is any if(!xTitle.is()) return; uno::Sequence< uno::Reference< XFormattedString > > aNewStringList(1); uno::Sequence< uno::Reference< XFormattedString > > aOldStringList = xTitle->getText(); if( aOldStringList.getLength() ) { aNewStringList[0].set( aOldStringList[0] ); aNewStringList[0]->setString( rNewText ); } else { uno::Reference< uno::XInterface > xI( xContext->getServiceManager()->createInstanceWithContext( C2U( "com.sun.star.chart2.FormattedString" ), xContext ) ); uno::Reference< XFormattedString > xFormattedString( xI, uno::UNO_QUERY ); if(xFormattedString.is()) { xFormattedString->setString( rNewText ); aNewStringList[0].set( xFormattedString ); } } xTitle->setText( aNewStringList ); } void TitleHelper::removeTitle( TitleHelper::eTitleType nTitleIndex , const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& xModel ) { uno::Reference< XTitled > xTitled( lcl_getTitleParent( nTitleIndex, xModel ) ); if( xTitled.is()) { xTitled->setTitle(NULL); } } //............................................................................. } //namespace chart //............................................................................. <|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 <string> #include <vector> #include "base/memory/scoped_ptr.h" #include "base/rand_util.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/sessions/session_types.h" #include "chrome/browser/sync/glue/synced_session_tracker.h" #include "testing/gtest/include/gtest/gtest.h" namespace browser_sync { typedef testing::Test SyncedSessionTrackerTest; TEST_F(SyncedSessionTrackerTest, GetSession) { SyncedSessionTracker tracker; SyncedSession* session1 = tracker.GetSession("tag"); SyncedSession* session2 = tracker.GetSession("tag2"); ASSERT_EQ(session1, tracker.GetSession("tag")); ASSERT_NE(session1, session2); // Should clean up memory on it's own. } TEST_F(SyncedSessionTrackerTest, GetTabUnmapped) { SyncedSessionTracker tracker; SessionTab* tab = tracker.GetTab("tag", 0); ASSERT_EQ(tab, tracker.GetTab("tag", 0)); // Should clean up memory on it's own. } TEST_F(SyncedSessionTrackerTest, PutWindowInSession) { SyncedSessionTracker tracker; tracker.PutWindowInSession("tag", 0); SyncedSession* session = tracker.GetSession("tag"); ASSERT_EQ(1U, session->windows.size()); // Should clean up memory on it's own. } TEST_F(SyncedSessionTrackerTest, PutTabInWindow) { SyncedSessionTracker tracker; tracker.PutWindowInSession("tag", 10); tracker.PutTabInWindow("tag", 10, 15, 0); // win id 10, tab id 15, tab ind 0. SyncedSession* session = tracker.GetSession("tag"); ASSERT_EQ(1U, session->windows.size()); ASSERT_EQ(1U, session->windows[10]->tabs.size()); ASSERT_EQ(tracker.GetTab("tag", 15), session->windows[10]->tabs[0]); // Should clean up memory on it's own. } TEST_F(SyncedSessionTrackerTest, LookupAllForeignSessions) { SyncedSessionTracker tracker; std::vector<const SyncedSession*> sessions; ASSERT_FALSE(tracker.LookupAllForeignSessions(&sessions)); tracker.GetSession("tag1"); tracker.GetSession("tag2"); tracker.PutWindowInSession("tag1", 0); tracker.PutTabInWindow("tag1", 0, 15, 0); SessionTab* tab = tracker.GetTab("tag1", 15); ASSERT_TRUE(tab); tab->navigations.push_back(TabNavigation( 0, GURL("valid_url"), GURL("referrer"), string16(ASCIIToUTF16("title")), std::string("state"), content::PageTransitionFromInt(0))); ASSERT_TRUE(tracker.LookupAllForeignSessions(&sessions)); // Only the session with a valid window and tab gets returned. ASSERT_EQ(1U, sessions.size()); ASSERT_EQ("tag1", sessions[0]->session_tag); } TEST_F(SyncedSessionTrackerTest, LookupSessionWindows) { SyncedSessionTracker tracker; std::vector<const SessionWindow*> windows; ASSERT_FALSE(tracker.LookupSessionWindows("tag1", &windows)); tracker.GetSession("tag1"); tracker.PutWindowInSession("tag1", 0); tracker.PutWindowInSession("tag1", 2); tracker.GetSession("tag2"); tracker.PutWindowInSession("tag2", 0); tracker.PutWindowInSession("tag2", 2); ASSERT_TRUE(tracker.LookupSessionWindows("tag1", &windows)); ASSERT_EQ(2U, windows.size()); // Only windows from tag1 session. ASSERT_NE((SessionWindow*)NULL, windows[0]); ASSERT_NE((SessionWindow*)NULL, windows[1]); ASSERT_NE(windows[1], windows[0]); } TEST_F(SyncedSessionTrackerTest, LookupSessionTab) { SyncedSessionTracker tracker; const SessionTab* tab; ASSERT_FALSE(tracker.LookupSessionTab("tag1", 5, &tab)); tracker.GetSession("tag1"); tracker.PutWindowInSession("tag1", 0); tracker.PutTabInWindow("tag1", 0, 5, 0); ASSERT_TRUE(tracker.LookupSessionTab("tag1", 5, &tab)); ASSERT_NE((SessionTab*)NULL, tab); } TEST_F(SyncedSessionTrackerTest, Complex) { const std::string tag1 = "tag"; const std::string tag2 = "tag2"; const std::string tag3 = "tag3"; SyncedSessionTracker tracker; std::vector<SessionTab*> tabs1, tabs2; SessionTab* temp_tab; ASSERT_TRUE(tracker.Empty()); ASSERT_EQ(0U, tracker.num_synced_sessions()); ASSERT_EQ(0U, tracker.num_synced_tabs(tag1)); tabs1.push_back(tracker.GetTab(tag1, 0)); tabs1.push_back(tracker.GetTab(tag1, 1)); tabs1.push_back(tracker.GetTab(tag1, 2)); ASSERT_EQ(3U, tracker.num_synced_tabs(tag1)); ASSERT_EQ(0U, tracker.num_synced_sessions()); temp_tab = tracker.GetTab(tag1, 0); // Already created. ASSERT_EQ(3U, tracker.num_synced_tabs(tag1)); ASSERT_EQ(0U, tracker.num_synced_sessions()); ASSERT_EQ(tabs1[0], temp_tab); tabs2.push_back(tracker.GetTab(tag2, 0)); ASSERT_EQ(1U, tracker.num_synced_tabs(tag2)); ASSERT_EQ(0U, tracker.num_synced_sessions()); ASSERT_FALSE(tracker.DeleteSession(tag3)); SyncedSession* session = tracker.GetSession(tag1); SyncedSession* session2 = tracker.GetSession(tag2); SyncedSession* session3 = tracker.GetSession(tag3); ASSERT_EQ(3U, tracker.num_synced_sessions()); ASSERT_TRUE(session); ASSERT_TRUE(session2); ASSERT_TRUE(session3); ASSERT_NE(session, session2); ASSERT_NE(session2, session3); ASSERT_TRUE(tracker.DeleteSession(tag3)); ASSERT_EQ(2U, tracker.num_synced_sessions()); tracker.PutWindowInSession(tag1, 0); // Create a window. tracker.PutTabInWindow(tag1, 0, 2, 0); // No longer unmapped. ASSERT_EQ(3U, tracker.num_synced_tabs(tag1)); // Has not changed. const SessionTab *tab_ptr; ASSERT_TRUE(tracker.LookupSessionTab(tag1, 0, &tab_ptr)); ASSERT_EQ(tab_ptr, tabs1[0]); ASSERT_TRUE(tracker.LookupSessionTab(tag1, 2, &tab_ptr)); ASSERT_EQ(tab_ptr, tabs1[2]); ASSERT_FALSE(tracker.LookupSessionTab(tag1, 3, &tab_ptr)); ASSERT_EQ(static_cast<const SessionTab*>(NULL), tab_ptr); std::vector<const SessionWindow*> windows; ASSERT_TRUE(tracker.LookupSessionWindows(tag1, &windows)); ASSERT_EQ(1U, windows.size()); ASSERT_TRUE(tracker.LookupSessionWindows(tag2, &windows)); ASSERT_EQ(0U, windows.size()); // The sessions don't have valid tabs, lookup should not succeed. std::vector<const SyncedSession*> sessions; ASSERT_FALSE(tracker.LookupAllForeignSessions(&sessions)); tracker.Clear(); ASSERT_EQ(0U, tracker.num_synced_tabs(tag1)); ASSERT_EQ(0U, tracker.num_synced_tabs(tag2)); ASSERT_EQ(0U, tracker.num_synced_sessions()); } TEST_F(SyncedSessionTrackerTest, ManyGetTabs) { SyncedSessionTracker tracker; ASSERT_TRUE(tracker.Empty()); const int kMaxSessions = 10; const int kMaxTabs = 1000; const int kMaxAttempts = 10000; char tag_buf[20]; for (int j=0; j<kMaxSessions; ++j) { snprintf(tag_buf, sizeof(tag_buf), "tag%d", j); std::string tag(tag_buf); for (int i=0; i<kMaxAttempts; ++i) { // More attempts than tabs means we'll sometimes get the same tabs, // sometimes have to allocate new tabs. int rand_tab_num = base::RandInt(0, kMaxTabs); SessionTab* tab = tracker.GetTab(tag, rand_tab_num); ASSERT_TRUE(tab); } } } TEST_F(SyncedSessionTrackerTest, SessionTracking) { SyncedSessionTracker tracker; ASSERT_TRUE(tracker.Empty()); std::string tag1 = "tag1"; std::string tag2 = "tag2"; // Create some session information that is stale. SyncedSession* session1= tracker.GetSession(tag1); tracker.PutWindowInSession(tag1, 0); tracker.PutTabInWindow(tag1, 0, 0, 0); tracker.PutTabInWindow(tag1, 0, 1, 1); tracker.GetTab(tag1, 2)->window_id.set_id(0); // Will be an unmapped tab. tracker.GetTab(tag1, 3)->window_id.set_id(0); // Will be an unmapped tab. tracker.PutWindowInSession(tag1, 1); tracker.PutTabInWindow(tag1, 1, 4, 0); tracker.PutTabInWindow(tag1, 1, 5, 1); ASSERT_EQ(2U, session1->windows.size()); ASSERT_EQ(2U, session1->windows[0]->tabs.size()); ASSERT_EQ(2U, session1->windows[1]->tabs.size()); ASSERT_EQ(6U, tracker.num_synced_tabs(tag1)); // Create a session that should not be affected. SyncedSession* session2 = tracker.GetSession(tag2); tracker.PutWindowInSession(tag2, 2); tracker.PutTabInWindow(tag2, 2, 1, 0); ASSERT_EQ(1U, session2->windows.size()); ASSERT_EQ(1U, session2->windows[2]->tabs.size()); ASSERT_EQ(1U, tracker.num_synced_tabs(tag2)); // Reset tracking and get the current windows/tabs. // We simulate moving a tab from one window to another, then closing the first // window (including it's one remaining tab), and opening a new tab on the // remaining window. tracker.GetTab(tag1, 6); // New tab, arrived before meta node so unmapped. tracker.ResetSessionTracking(tag1); tracker.PutWindowInSession(tag1, 0); tracker.PutTabInWindow(tag1, 0, 0, 0); // Tab 1 is closed. tracker.PutTabInWindow(tag1, 0, 2, 1); // No longer unmapped. // Tab 3 was unmapped and does not get used. tracker.PutTabInWindow(tag1, 0, 4, 2); // Moved from window 1. // Window 1 was closed, along with tab 5. tracker.PutTabInWindow(tag1, 0, 6, 3); // No longer unmapped. // Session 2 should not be affected. tracker.CleanupSession(tag1); // Verify that only those parts of the session not owned have been removed. ASSERT_EQ(1U, session1->windows.size()); ASSERT_EQ(4U, session1->windows[0]->tabs.size()); ASSERT_EQ(1U, session2->windows.size()); ASSERT_EQ(1U, session2->windows[2]->tabs.size()); ASSERT_EQ(2U, tracker.num_synced_sessions()); ASSERT_EQ(4U, tracker.num_synced_tabs(tag1)); ASSERT_EQ(1U, tracker.num_synced_tabs(tag2)); // All memory should be properly deallocated by destructor for the // SyncedSessionTracker. } } // namespace browser_sync <commit_msg>Revert 108858 - Hotfix SyncedSessionTrackerTest.ManyGetTabs to pass under AddressSanitizer. and 108859 - Hotfix the hotfix for SyncedSessionTrackerTest.ManyGetTabs (r108858) to compile on Windows.<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 <string> #include <vector> #include "base/memory/scoped_ptr.h" #include "base/rand_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/sessions/session_types.h" #include "chrome/browser/sync/glue/synced_session_tracker.h" #include "testing/gtest/include/gtest/gtest.h" namespace browser_sync { typedef testing::Test SyncedSessionTrackerTest; TEST_F(SyncedSessionTrackerTest, GetSession) { SyncedSessionTracker tracker; SyncedSession* session1 = tracker.GetSession("tag"); SyncedSession* session2 = tracker.GetSession("tag2"); ASSERT_EQ(session1, tracker.GetSession("tag")); ASSERT_NE(session1, session2); // Should clean up memory on it's own. } TEST_F(SyncedSessionTrackerTest, GetTabUnmapped) { SyncedSessionTracker tracker; SessionTab* tab = tracker.GetTab("tag", 0); ASSERT_EQ(tab, tracker.GetTab("tag", 0)); // Should clean up memory on it's own. } TEST_F(SyncedSessionTrackerTest, PutWindowInSession) { SyncedSessionTracker tracker; tracker.PutWindowInSession("tag", 0); SyncedSession* session = tracker.GetSession("tag"); ASSERT_EQ(1U, session->windows.size()); // Should clean up memory on it's own. } TEST_F(SyncedSessionTrackerTest, PutTabInWindow) { SyncedSessionTracker tracker; tracker.PutWindowInSession("tag", 10); tracker.PutTabInWindow("tag", 10, 15, 0); // win id 10, tab id 15, tab ind 0. SyncedSession* session = tracker.GetSession("tag"); ASSERT_EQ(1U, session->windows.size()); ASSERT_EQ(1U, session->windows[10]->tabs.size()); ASSERT_EQ(tracker.GetTab("tag", 15), session->windows[10]->tabs[0]); // Should clean up memory on it's own. } TEST_F(SyncedSessionTrackerTest, LookupAllForeignSessions) { SyncedSessionTracker tracker; std::vector<const SyncedSession*> sessions; ASSERT_FALSE(tracker.LookupAllForeignSessions(&sessions)); tracker.GetSession("tag1"); tracker.GetSession("tag2"); tracker.PutWindowInSession("tag1", 0); tracker.PutTabInWindow("tag1", 0, 15, 0); SessionTab* tab = tracker.GetTab("tag1", 15); ASSERT_TRUE(tab); tab->navigations.push_back(TabNavigation( 0, GURL("valid_url"), GURL("referrer"), string16(ASCIIToUTF16("title")), std::string("state"), content::PageTransitionFromInt(0))); ASSERT_TRUE(tracker.LookupAllForeignSessions(&sessions)); // Only the session with a valid window and tab gets returned. ASSERT_EQ(1U, sessions.size()); ASSERT_EQ("tag1", sessions[0]->session_tag); } TEST_F(SyncedSessionTrackerTest, LookupSessionWindows) { SyncedSessionTracker tracker; std::vector<const SessionWindow*> windows; ASSERT_FALSE(tracker.LookupSessionWindows("tag1", &windows)); tracker.GetSession("tag1"); tracker.PutWindowInSession("tag1", 0); tracker.PutWindowInSession("tag1", 2); tracker.GetSession("tag2"); tracker.PutWindowInSession("tag2", 0); tracker.PutWindowInSession("tag2", 2); ASSERT_TRUE(tracker.LookupSessionWindows("tag1", &windows)); ASSERT_EQ(2U, windows.size()); // Only windows from tag1 session. ASSERT_NE((SessionWindow*)NULL, windows[0]); ASSERT_NE((SessionWindow*)NULL, windows[1]); ASSERT_NE(windows[1], windows[0]); } TEST_F(SyncedSessionTrackerTest, LookupSessionTab) { SyncedSessionTracker tracker; const SessionTab* tab; ASSERT_FALSE(tracker.LookupSessionTab("tag1", 5, &tab)); tracker.GetSession("tag1"); tracker.PutWindowInSession("tag1", 0); tracker.PutTabInWindow("tag1", 0, 5, 0); ASSERT_TRUE(tracker.LookupSessionTab("tag1", 5, &tab)); ASSERT_NE((SessionTab*)NULL, tab); } TEST_F(SyncedSessionTrackerTest, Complex) { const std::string tag1 = "tag"; const std::string tag2 = "tag2"; const std::string tag3 = "tag3"; SyncedSessionTracker tracker; std::vector<SessionTab*> tabs1, tabs2; SessionTab* temp_tab; ASSERT_TRUE(tracker.Empty()); ASSERT_EQ(0U, tracker.num_synced_sessions()); ASSERT_EQ(0U, tracker.num_synced_tabs(tag1)); tabs1.push_back(tracker.GetTab(tag1, 0)); tabs1.push_back(tracker.GetTab(tag1, 1)); tabs1.push_back(tracker.GetTab(tag1, 2)); ASSERT_EQ(3U, tracker.num_synced_tabs(tag1)); ASSERT_EQ(0U, tracker.num_synced_sessions()); temp_tab = tracker.GetTab(tag1, 0); // Already created. ASSERT_EQ(3U, tracker.num_synced_tabs(tag1)); ASSERT_EQ(0U, tracker.num_synced_sessions()); ASSERT_EQ(tabs1[0], temp_tab); tabs2.push_back(tracker.GetTab(tag2, 0)); ASSERT_EQ(1U, tracker.num_synced_tabs(tag2)); ASSERT_EQ(0U, tracker.num_synced_sessions()); ASSERT_FALSE(tracker.DeleteSession(tag3)); SyncedSession* session = tracker.GetSession(tag1); SyncedSession* session2 = tracker.GetSession(tag2); SyncedSession* session3 = tracker.GetSession(tag3); ASSERT_EQ(3U, tracker.num_synced_sessions()); ASSERT_TRUE(session); ASSERT_TRUE(session2); ASSERT_TRUE(session3); ASSERT_NE(session, session2); ASSERT_NE(session2, session3); ASSERT_TRUE(tracker.DeleteSession(tag3)); ASSERT_EQ(2U, tracker.num_synced_sessions()); tracker.PutWindowInSession(tag1, 0); // Create a window. tracker.PutTabInWindow(tag1, 0, 2, 0); // No longer unmapped. ASSERT_EQ(3U, tracker.num_synced_tabs(tag1)); // Has not changed. const SessionTab *tab_ptr; ASSERT_TRUE(tracker.LookupSessionTab(tag1, 0, &tab_ptr)); ASSERT_EQ(tab_ptr, tabs1[0]); ASSERT_TRUE(tracker.LookupSessionTab(tag1, 2, &tab_ptr)); ASSERT_EQ(tab_ptr, tabs1[2]); ASSERT_FALSE(tracker.LookupSessionTab(tag1, 3, &tab_ptr)); ASSERT_EQ(static_cast<const SessionTab*>(NULL), tab_ptr); std::vector<const SessionWindow*> windows; ASSERT_TRUE(tracker.LookupSessionWindows(tag1, &windows)); ASSERT_EQ(1U, windows.size()); ASSERT_TRUE(tracker.LookupSessionWindows(tag2, &windows)); ASSERT_EQ(0U, windows.size()); // The sessions don't have valid tabs, lookup should not succeed. std::vector<const SyncedSession*> sessions; ASSERT_FALSE(tracker.LookupAllForeignSessions(&sessions)); tracker.Clear(); ASSERT_EQ(0U, tracker.num_synced_tabs(tag1)); ASSERT_EQ(0U, tracker.num_synced_tabs(tag2)); ASSERT_EQ(0U, tracker.num_synced_sessions()); } TEST_F(SyncedSessionTrackerTest, ManyGetTabs) { SyncedSessionTracker tracker; ASSERT_TRUE(tracker.Empty()); const int kMaxSessions = 10; const int kMaxTabs = 1000; const int kMaxAttempts = 10000; for (int j=0; j<kMaxSessions; ++j) { std::string tag = "tag" + j; for (int i=0; i<kMaxAttempts; ++i) { // More attempts than tabs means we'll sometimes get the same tabs, // sometimes have to allocate new tabs. int rand_tab_num = base::RandInt(0, kMaxTabs); SessionTab* tab = tracker.GetTab(tag, rand_tab_num); ASSERT_TRUE(tab); } } } TEST_F(SyncedSessionTrackerTest, SessionTracking) { SyncedSessionTracker tracker; ASSERT_TRUE(tracker.Empty()); std::string tag1 = "tag1"; std::string tag2 = "tag2"; // Create some session information that is stale. SyncedSession* session1= tracker.GetSession(tag1); tracker.PutWindowInSession(tag1, 0); tracker.PutTabInWindow(tag1, 0, 0, 0); tracker.PutTabInWindow(tag1, 0, 1, 1); tracker.GetTab(tag1, 2)->window_id.set_id(0); // Will be an unmapped tab. tracker.GetTab(tag1, 3)->window_id.set_id(0); // Will be an unmapped tab. tracker.PutWindowInSession(tag1, 1); tracker.PutTabInWindow(tag1, 1, 4, 0); tracker.PutTabInWindow(tag1, 1, 5, 1); ASSERT_EQ(2U, session1->windows.size()); ASSERT_EQ(2U, session1->windows[0]->tabs.size()); ASSERT_EQ(2U, session1->windows[1]->tabs.size()); ASSERT_EQ(6U, tracker.num_synced_tabs(tag1)); // Create a session that should not be affected. SyncedSession* session2 = tracker.GetSession(tag2); tracker.PutWindowInSession(tag2, 2); tracker.PutTabInWindow(tag2, 2, 1, 0); ASSERT_EQ(1U, session2->windows.size()); ASSERT_EQ(1U, session2->windows[2]->tabs.size()); ASSERT_EQ(1U, tracker.num_synced_tabs(tag2)); // Reset tracking and get the current windows/tabs. // We simulate moving a tab from one window to another, then closing the first // window (including it's one remaining tab), and opening a new tab on the // remaining window. tracker.GetTab(tag1, 6); // New tab, arrived before meta node so unmapped. tracker.ResetSessionTracking(tag1); tracker.PutWindowInSession(tag1, 0); tracker.PutTabInWindow(tag1, 0, 0, 0); // Tab 1 is closed. tracker.PutTabInWindow(tag1, 0, 2, 1); // No longer unmapped. // Tab 3 was unmapped and does not get used. tracker.PutTabInWindow(tag1, 0, 4, 2); // Moved from window 1. // Window 1 was closed, along with tab 5. tracker.PutTabInWindow(tag1, 0, 6, 3); // No longer unmapped. // Session 2 should not be affected. tracker.CleanupSession(tag1); // Verify that only those parts of the session not owned have been removed. ASSERT_EQ(1U, session1->windows.size()); ASSERT_EQ(4U, session1->windows[0]->tabs.size()); ASSERT_EQ(1U, session2->windows.size()); ASSERT_EQ(1U, session2->windows[2]->tabs.size()); ASSERT_EQ(2U, tracker.num_synced_sessions()); ASSERT_EQ(4U, tracker.num_synced_tabs(tag1)); ASSERT_EQ(1U, tracker.num_synced_tabs(tag2)); // All memory should be properly deallocated by destructor for the // SyncedSessionTracker. } } // namespace browser_sync <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #ifndef _Stroika_Foundation_Memory_Common_inl_ #define _Stroika_Foundation_Memory_Common_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ namespace Stroika::Foundation::Memory { /* ******************************************************************************** ********************* Memory::GlobalAllocationStatistics *********************** ******************************************************************************** */ inline GlobalAllocationStatistics::GlobalAllocationStatistics () : fTotalOutstandingAllocations{0} , fTotalOutstandingBytesAllocated{0} , fPageFaultCount{0} , fWorkingSetSize{0} , fPagefileUsage{0} { } /* ******************************************************************************** ********************************* Memory::MemCmp ******************************* ******************************************************************************** */ template <> constexpr int MemCmp (const uint8_t* lhs, const uint8_t* rhs, std::size_t count) { //Require (count == 0 or lhs != nullptr); //Require (count == 0 or rhs != nullptr); const uint8_t* li = lhs; const uint8_t* ri = rhs; for (; count--; li++, ri++) { if (int cmp = static_cast<int> (*li) - static_cast<int> (*ri)) { return cmp; } } return 0; } template <typename T> constexpr int MemCmp (const T* lhs, const T* rhs, size_t count) { return MemCmp (reinterpret_cast<const uint8_t*> (lhs), reinterpret_cast<const uint8_t*> (rhs), count * sizeof (T)); } #if qSilenceAnnoyingCompilerWarnings && _MSC_VER namespace Private { template <class _InIt, class _OutIt> inline void VC_BWA_std_copy (_InIt _First, _InIt _Last, _OutIt _Dest) { auto o = _Dest; for (auto i = _First; i != _Last; ++i, ++o) { *o = *i; } } } #endif namespace PRIVATE_ { template <typename T1, typename T2> struct OffsetOfRequiringDefaultConstexprObjectType_ { static inline constexpr T2 object; static constexpr size_t offset (T1 T2::*member) { return size_t (&(OffsetOfRequiringDefaultConstexprObjectType_<T1, T2>::object.*member)) - size_t (&OffsetOfRequiringDefaultConstexprObjectType_<T1, T2>::object); } }; } template <typename FIELD_VALUE_TYPE, typename OWNING_OBJECT, enable_if_t<is_default_constructible_v<OWNING_OBJECT>>*> inline size_t constexpr OffsetOf (FIELD_VALUE_TYPE OWNING_OBJECT::*member) { return PRIVATE_::OffsetOfRequiringDefaultConstexprObjectType_<FIELD_VALUE_TYPE, OWNING_OBJECT>::offset (member); } template <typename FIELD_VALUE_TYPE, typename OWNING_OBJECT, enable_if_t<not is_default_constructible_v<OWNING_OBJECT>>*> inline size_t OffsetOf (FIELD_VALUE_TYPE OWNING_OBJECT::*member) { #if 0 auto o = declval<OWNING_OBJECT> (); // function only valid in unevaluated contexts - produces link errors #elif 0 // gcc doesn't allow reinterpret_cast of nullptr: invalid cast from type std::nullptr_t to type const ...* DISABLE_COMPILER_CLANG_WARNING_START ("clang diagnostic ignored \"-Wnull-dereference\"") const OWNING_OBJECT& o = *reinterpret_cast<const OWNING_OBJECT*> (nullptr); DISABLE_COMPILER_CLANG_WARNING_END ("clang diagnostic ignored \"-Wnull-dereference\"") #elif 0 //TSAN detects undefined behavior const OWNING_OBJECT& o = *reinterpret_cast<const OWNING_OBJECT*> (0); #else // Still not totally legal for non-std-layout classes, but seems to work, and I haven't found a better way // --LGP 2021-05-27 alignas (OWNING_OBJECT) std::byte buf[sizeof (OWNING_OBJECT)]{}; const OWNING_OBJECT& o = *reinterpret_cast<const OWNING_OBJECT*> (&buf); #endif auto result = size_t (reinterpret_cast<const char*> (&(o.*member)) - reinterpret_cast<const char*> (&o)); // Avoid #include - Ensure (result <= sizeof (OWNING_OBJECT)); return result; } } #endif /*_Stroika_Foundation_Memory_Common_inl_*/ <commit_msg>more tweaks to OffsetOf() code<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #ifndef _Stroika_Foundation_Memory_Common_inl_ #define _Stroika_Foundation_Memory_Common_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ namespace Stroika::Foundation::Memory { /* ******************************************************************************** ********************* Memory::GlobalAllocationStatistics *********************** ******************************************************************************** */ inline GlobalAllocationStatistics::GlobalAllocationStatistics () : fTotalOutstandingAllocations{0} , fTotalOutstandingBytesAllocated{0} , fPageFaultCount{0} , fWorkingSetSize{0} , fPagefileUsage{0} { } /* ******************************************************************************** ********************************* Memory::MemCmp ******************************* ******************************************************************************** */ template <> constexpr int MemCmp (const uint8_t* lhs, const uint8_t* rhs, std::size_t count) { //Require (count == 0 or lhs != nullptr); //Require (count == 0 or rhs != nullptr); const uint8_t* li = lhs; const uint8_t* ri = rhs; for (; count--; li++, ri++) { if (int cmp = static_cast<int> (*li) - static_cast<int> (*ri)) { return cmp; } } return 0; } template <typename T> constexpr int MemCmp (const T* lhs, const T* rhs, size_t count) { return MemCmp (reinterpret_cast<const uint8_t*> (lhs), reinterpret_cast<const uint8_t*> (rhs), count * sizeof (T)); } #if qSilenceAnnoyingCompilerWarnings && _MSC_VER namespace Private { template <class _InIt, class _OutIt> inline void VC_BWA_std_copy (_InIt _First, _InIt _Last, _OutIt _Dest) { auto o = _Dest; for (auto i = _First; i != _Last; ++i, ++o) { *o = *i; } } } #endif namespace PRIVATE_ { template <typename T1, typename T2> struct OffsetOfRequiringDefaultConstexprObjectType_ { static inline /*constexpr*/ T2 sObj_{}; static constexpr size_t offset (T1 T2::*member) { return size_t (&(OffsetOfRequiringDefaultConstexprObjectType_<T1, T2>::sObj_.*member)) - size_t (&OffsetOfRequiringDefaultConstexprObjectType_<T1, T2>::sObj_); } }; } template <typename FIELD_VALUE_TYPE, typename OWNING_OBJECT, enable_if_t<is_default_constructible_v<OWNING_OBJECT>>*> inline size_t constexpr OffsetOf (FIELD_VALUE_TYPE OWNING_OBJECT::*member) { return PRIVATE_::OffsetOfRequiringDefaultConstexprObjectType_<FIELD_VALUE_TYPE, OWNING_OBJECT>::offset (member); } template <typename FIELD_VALUE_TYPE, typename OWNING_OBJECT, enable_if_t<not is_default_constructible_v<OWNING_OBJECT>>*> inline size_t OffsetOf (FIELD_VALUE_TYPE OWNING_OBJECT::*member) { #if 0 auto o = declval<OWNING_OBJECT> (); // function only valid in unevaluated contexts - produces link errors auto result = size_t (reinterpret_cast<const char*> (&(o.*member)) - reinterpret_cast<const char*> (&o)); #elif 0 // gcc doesn't allow reinterpret_cast of nullptr: invalid cast from type �std::nullptr_t� to type �const ...*� DISABLE_COMPILER_CLANG_WARNING_START ("clang diagnostic ignored \"-Wnull-dereference\"") const OWNING_OBJECT& o = *reinterpret_cast<const OWNING_OBJECT*> (nullptr); DISABLE_COMPILER_CLANG_WARNING_END ("clang diagnostic ignored \"-Wnull-dereference\"") auto result = size_t (reinterpret_cast<const char*> (&(o.*member)) - reinterpret_cast<const char*> (&o)); #elif 0 //TSAN detects undefined behavior const OWNING_OBJECT& o = *reinterpret_cast<const OWNING_OBJECT*> (0); auto result = size_t (reinterpret_cast<const char*> (&(o.*member)) - reinterpret_cast<const char*> (&o)); #else // Still not totally legal for non-std-layout classes, but seems to work, and I haven't found a better way // --LGP 2021-05-27 alignas (OWNING_OBJECT) std::byte buf[sizeof (OWNING_OBJECT)]{}; const OWNING_OBJECT& o = *reinterpret_cast<const OWNING_OBJECT*> (&buf); auto result = size_t (reinterpret_cast<const char*> (&(o.*member)) - reinterpret_cast<const char*> (&o)); #endif // Avoid #include - Ensure (result <= sizeof (OWNING_OBJECT)); return result; } } #endif /*_Stroika_Foundation_Memory_Common_inl_*/ <|endoftext|>
<commit_before>// Copyright (c) The University of Cincinnati. // All rights reserved. // UC MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF // THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE, OR NON-INFRINGEMENT. UC SHALL NOT BE LIABLE // FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, // RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS // DERIVATIVES. // By using or copying this Software, Licensee agrees to abide by the // intellectual property laws, and all other applicable laws of the // U.S., and the terms of this license. #include <iostream> #include <sstream> #include <string> #include <vector> #include <map> #include <fstream> #include <stdlib.h> #include <string.h> #define LINE_LENGTH 256 #define LINE_NUMBER 8 #define OBJECT_DELAY 1 using namespace std; // the struct for storing the circuit node information class CircuitNode{ public: string nodeNum; string nodeName; int inputPortId; CircuitNode *nextNode; }; int extractNodeId(string nName); //void genConfigLine(CircuitNode* first,ofstream& outputStream,string& ioType,vector<int>* numInputs,int lineId); void genConfigLine(int position, vector<CircuitNode* >* nodesVec,ofstream& outputStream,vector<int>* numInputs,int lineId,string path); int main (int argc, char* argv[]){ char oneLine[LINE_LENGTH]; ifstream isacsBenchMark; ofstream simModelConfig; // ids for NOT,AND,OR,NAND,NOR and XOR gates int andNum =0; int orNum =0; int nandNum =0; int xorNum =0; int notNum =0; int norNum =0; int numOfFiles = 0; int numOfGates = 0; map<int,string> numNameMap; int nId; isacsBenchMark.open(argv[1]); simModelConfig.open(argv[2]); if(!isacsBenchMark.is_open()){ cout <<"Fail to open the input file !" <<endl; exit (-1); } if(!simModelConfig.is_open()){ cout<<"Fail to open the output file !"<<endl; exit(-1); } vector <CircuitNode* > *nodes = new vector<CircuitNode* >; vector <int> *numOfInputsVec = new vector<int>;//record the input number of each object. //gates, input and output files are objects. //each input file has 0 input. while(isacsBenchMark.getline(oneLine,LINE_LENGTH)){ //for each line in the isacs85 benchmark int lineCount = 0; int lineLength = strlen(oneLine); bool havePid = false; for(int i =0; i<lineLength;i++){ //strip space and () in isacs85 benchmark if (oneLine[i] =='(') oneLine[i]=' '; if (oneLine[i] ==')') oneLine[i]=' '; if (oneLine[i] =='=') oneLine[i]=' '; if (oneLine[i] == ',') oneLine[i]=' '; } /* check for the striping cout<<"strip space and ( )"<<endl; istringstream thisLine(oneLine,istringstream::in); string aa = thisLine.str(); cout<<aa<<endl; */ CircuitNode* currentNode = new CircuitNode(); string thisNodeName; //for INPUT and the OUTPUT istringstream thisLine(oneLine,istringstream::in); thisLine>>thisNodeName; if(thisNodeName == "INPUT"){ //construct the node with the type INPUT numOfFiles++; currentNode->nodeName =thisNodeName; string thisNodeNum; thisLine>>thisNodeNum; nId = extractNodeId(thisNodeNum); numNameMap[nId] = thisNodeNum; currentNode->nodeNum = thisNodeNum; currentNode->inputPortId=0; currentNode->nextNode = NULL; nodes->push_back(currentNode); //cout<<"this is the INPUT node !"<<endl; } else if(thisNodeName == "OUTPUT"){//construct the node with the type OUTPUT numOfFiles++; currentNode->nodeName =thisNodeName; string thisNodeNum; thisLine>>thisNodeNum; nId = extractNodeId(thisNodeNum); numNameMap[nId] = thisNodeNum; currentNode->nodeNum = thisNodeNum; currentNode->inputPortId=0; currentNode->nextNode = NULL; nodes->push_back(currentNode); //cout<<"this is the OUTPUT node!"<<endl; } else{ // construct other gates string thisNodeNum = thisNodeName;//this value hold the node number for any gate currentNode->nodeNum = thisNodeNum; nId = extractNodeId(thisNodeNum); string gateName; thisLine>>gateName; stringstream out; //cout<<"this is the gate!"<<endl; //check the gate name,and count how many gates in the benchmark if("AND"==gateName) { numOfGates++; andNum++; out<<andNum; string curNum = out.str(); gateName = gateName + curNum; numNameMap[nId]=gateName; } if("OR"==gateName){ numOfGates++; orNum++; out<<orNum; string curNum = out.str(); gateName = gateName + curNum; numNameMap[nId]=gateName; } if("NAND"==gateName){ numOfGates++; nandNum++; out<<nandNum; string curNum = out.str(); gateName = gateName + curNum; numNameMap[nId]=gateName; } if("NOR"==gateName){ numOfGates++; norNum++; out<<norNum; string curNum = out.str(); gateName = gateName + curNum; numNameMap[nId]=gateName; } if("NOT"==gateName){ numOfGates++; notNum++; out<<notNum; string curNum = out.str(); gateName = gateName + curNum; numNameMap[nId]=gateName; } if("XOR"==gateName){ numOfGates++; xorNum++; out<<xorNum; string curNum = out.str(); gateName = gateName + curNum; numNameMap[nId]=gateName; } currentNode->nodeName = gateName; currentNode->inputPortId = 0;//this Id should always be 0 when the node is at the beginning at //the linklist currentNode->nextNode = NULL; nodes->push_back(currentNode); string inputGateNum; int portId = 0; while(thisLine>>inputGateNum){ //attach the information of the current gate to its input gates //cout<<"the inputGateNum is"<<inputGateNum<<endl; CircuitNode* inputNode = new CircuitNode(); inputNode->nodeNum =thisNodeNum; nId=extractNodeId(thisNodeNum); inputNode->nodeName = numNameMap[nId]; int n =0 ; //cout<<"the first while !"<<endl; while(n<nodes->size()){ if((*nodes)[n]->nodeNum == inputGateNum){ CircuitNode* nextNodePt = (*nodes)[n]->nextNode; CircuitNode* currentPt =nextNodePt; if(nextNodePt==NULL){ (*nodes)[n]->nextNode = inputNode; inputNode->inputPortId = portId+1; inputNode->nextNode = NULL; } else{ while(nextNodePt != NULL){//go to the end of the linklist which begines with node[n] currentPt = nextNodePt; nextNodePt = nextNodePt->nextNode; } currentPt->nextNode=inputNode; inputNode->inputPortId =portId+1; inputNode->nextNode=NULL; } } n++; } portId++; } //while //bool havePid = false; numOfInputsVec->push_back(portId);//wrong havePid = true; }//else if(false==havePid){// numOfInputsVec->push_back(0);//wrong } else{havePid=false;} lineCount++; }//while // cout<<"out of the while !"<<endl; int j= 0; while(j<nodes->size()){ cout<<(*nodes)[j]->nodeNum<<" "; CircuitNode* nextGate = (*nodes)[j]->nextNode; CircuitNode* currentGate = new CircuitNode(); while(nextGate != NULL){ currentGate = nextGate; cout<< currentGate->nodeNum<<" "; cout<< currentGate->nodeName<<" "; cout<< currentGate->inputPortId<<" "; nextGate = nextGate->nextNode; } cout<<endl; j++; } simModelConfig<<numOfFiles<<endl; simModelConfig<<numOfGates<<endl; string filePath = "circuitsimulationmodels/iscas85/iscas85Sim/c5315/"; int capacity = 0; int linenum = 0; while(capacity<nodes->size()){ //genConfigLine(capacity,(*nodes)[capacity],simModelConfig,(*nodes)[capacity]->nodeName,numOfInputsVec,linenum); genConfigLine(capacity,nodes,simModelConfig,numOfInputsVec,linenum,filePath); capacity++; linenum++; } isacsBenchMark.close(); simModelConfig.close(); }//main void genConfigLine(int position,vector<CircuitNode*> *nodesVec,ofstream& outputStream, vector<int>* numInputs,int lineId,string path){ // int lineNum = 8; // vector<int> inPortId; vector<string> gatesName; CircuitNode* first = (*nodesVec)[position]; string ioType = first->nodeName; if(ioType!="OUTPUT"){ int listLength = 0; CircuitNode* next = first->nextNode; CircuitNode* current = new CircuitNode(); while(next!=NULL){ listLength++; current=next; gatesName.push_back(current->nodeName); inPortId.push_back(current->inputPortId); next=next->nextNode; cout<<"list length is :"<<listLength<<endl;//} }//while if("INPUT"==ioType){ // generate one line for the configuration file, the information is for the input file. outputStream<<first->nodeNum<<" "; outputStream<<listLength<<" "<<"I"<<" "; for(int i = 0; i < listLength;i++){ outputStream<<inPortId[i]<<" ";} for(int i = 0; i < listLength;i++){ outputStream<<gatesName[i]<<" ";} outputStream<<LINE_NUMBER<<endl; } else{ bool isToFile=false; for(int i = position-1;i >= 0;i--){ if(first->nodeNum==(*nodesVec)[i]->nodeNum){// find an output gate isToFile = true; outputStream<<first->nodeName<<" "; outputStream<<(*numInputs)[lineId]<<" "; outputStream<<"1"<<" "; outputStream<<path+(*nodesVec)[i]->nodeNum<<" "; //output file name outputStream<<"0"<<" "<<OBJECT_DELAY<<endl;} } if(isToFile==false){ outputStream<<first->nodeName<<" "<<(*numInputs)[lineId]<<" "<<listLength<<" "; for(int i = 0; i < listLength;i++){ outputStream<<gatesName[i]<<" ";} for(int i = 0; i < listLength;i++){ outputStream<<inPortId[i]<<" ";} outputStream<<OBJECT_DELAY<<endl;}} }//if else{ outputStream<<first->nodeNum<<" "<<0<<" "<<"O"<<" "; outputStream<<0<<" "<<"null"<<" "<<LINE_NUMBER<<endl;} } int extractNodeId(string nName){ string tempstr = nName; tempstr.erase(0,1); stringstream sstream; int nodeId; sstream<<tempstr; sstream>>nodeId; return nodeId; } <commit_msg>remove the old translator<commit_after><|endoftext|>
<commit_before><commit_msg>Initialize salt_ to zero in VisitedLinkCommon.<commit_after><|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Qmitk #include "QmitkDicomLocalStorageWidget.h" //#include <mitkLogMacros.h> // Qt #include <QLabel> #include <QProgressDialog> #include <QVariant> #include <QMessageBox> const std::string QmitkDicomLocalStorageWidget::Widget_ID = "org.mitk.Widgets.QmitkDicomLocalStorageWidget"; QmitkDicomLocalStorageWidget::QmitkDicomLocalStorageWidget(QWidget *parent) : QWidget(parent) , m_Controls(0) , m_LocalIndexer(new ctkDICOMIndexer(parent)) { CreateQtPartControl(this); } QmitkDicomLocalStorageWidget::~QmitkDicomLocalStorageWidget() { m_LocalDatabase->closeDatabase(); } void QmitkDicomLocalStorageWidget::CreateQtPartControl( QWidget *parent ) { if ( !m_Controls ) { m_Controls = new Ui::QmitkDicomLocalStorageWidgetControls; m_Controls->setupUi( parent ); this->SetupProgressDialog(this); connect(m_Controls->deleteButton,SIGNAL(clicked()),this,SLOT(OnDeleteButtonClicked())); connect(m_Controls->viewInternalDataButton, SIGNAL(clicked()), this , SLOT(OnViewButtonClicked())); connect(m_Controls->ctkDicomBrowser, SIGNAL(seriesSelectionChanged(const QStringList&)), this, SLOT(OnSeriesSelectionChanged(const QStringList&))); connect(m_Controls->ctkDicomBrowser, SIGNAL(seriesSelectionChanged(const QStringList&)), this, SLOT(OnSeriesSelectionChanged(const QStringList&))); connect(m_Controls->ctkDicomBrowser, SIGNAL(seriesDoubleClicked(const QModelIndex&)), this, SLOT(OnViewButtonClicked())); connect(m_LocalIndexer, SIGNAL(indexingComplete()),this, SLOT(OnFinishedImport())); connect(m_LocalIndexer, SIGNAL(indexingComplete()),this, SIGNAL(SignalFinishedImport())); connect(m_LocalIndexer, SIGNAL(indexingComplete()),this, SLOT(OnFinishedImport())); connect(m_LocalIndexer, SIGNAL(indexingFilePath(const QString&)), m_ProgressDialogLabel, SLOT(setText(const QString&))); connect(m_LocalIndexer, SIGNAL(progress(int)), m_ProgressDialog, SLOT(setValue(int))); connect(m_ProgressDialog, SIGNAL(canceled()), m_LocalIndexer, SLOT(cancel())); m_Controls->ctkDicomBrowser->setTableOrientation(Qt::Vertical); } } void QmitkDicomLocalStorageWidget::OnStartDicomImport(const QString& dicomData) { if(m_LocalDatabase->isOpen()) { m_LocalIndexer->addDirectory(*m_LocalDatabase,dicomData,m_LocalDatabase->databaseDirectory()); } } void QmitkDicomLocalStorageWidget::OnStartDicomImport(const QStringList& dicomData) { if(m_LocalDatabase->isOpen()) { m_ProgressDialog->show(); m_LocalIndexer->addListOfFiles(*m_LocalDatabase,dicomData,m_LocalDatabase->databaseDirectory()); } } void QmitkDicomLocalStorageWidget::OnFinishedImport() { m_ProgressDialog->setValue(m_ProgressDialog->maximum()); } void QmitkDicomLocalStorageWidget::OnDeleteButtonClicked() { if (!this->DeletePatients()) { if (!this->DeleteStudies()) { this->DeleteSeries(); } } m_Controls->ctkDicomBrowser->updateTableViews(); } bool QmitkDicomLocalStorageWidget::DeletePatients() { auto selectedPatientUIDs = m_Controls->ctkDicomBrowser->currentPatientsSelection(); if (!selectedPatientUIDs.empty()) { QStringList studyUIDs; for (const auto& patientUID : selectedPatientUIDs) studyUIDs.append(m_LocalDatabase->studiesForPatient(patientUID)); QStringList seriesUIDs; for (const auto& studyUID : studyUIDs) seriesUIDs.append(m_LocalDatabase->seriesForStudy(studyUID)); auto answer = QMessageBox::question(nullptr, "Delete Patients", QString("Do you really want to delete %1 %2, containing %3 series in %4 %5?") .arg(selectedPatientUIDs.count()) .arg(selectedPatientUIDs.count() != 1 ? "patients" : "patient") .arg(seriesUIDs.count()) .arg(studyUIDs.count()) .arg(studyUIDs.count() != 1 ? "studies" : "study")); if (answer == QMessageBox::Ok) { for (const auto& patientUID : selectedPatientUIDs) m_LocalDatabase->removePatient(patientUID); } return true; } return false; } bool QmitkDicomLocalStorageWidget::DeleteStudies() { auto selectedStudyUIDs = m_Controls->ctkDicomBrowser->currentStudiesSelection(); if (!selectedStudyUIDs.empty()) { QStringList seriesUIDs; for (const auto& studyUID : selectedStudyUIDs) seriesUIDs.append(m_LocalDatabase->seriesForStudy(studyUID)); auto answer = QMessageBox::question(nullptr, "Delete Studies", QString("Do you really want to delete %1 %2, containing %3 series?") .arg(selectedStudyUIDs.count()) .arg(selectedStudyUIDs.count() != 1 ? "studies" : "study") .arg(seriesUIDs.count())); if (answer == QMessageBox::Ok) { for (const auto& studyUID : selectedStudyUIDs) m_LocalDatabase->removeStudy(studyUID); } return true; } return false; } bool QmitkDicomLocalStorageWidget::DeleteSeries() { auto selectedSeriesUIDs = m_Controls->ctkDicomBrowser->currentSeriesSelection(); if (!selectedSeriesUIDs.empty()) { auto answer = QMessageBox::question(nullptr, "Delete Series", QString("Do you really want to delete %1 series?") .arg(selectedSeriesUIDs.count())); if (answer == QMessageBox::Ok) { for (const auto& seriesUID : selectedSeriesUIDs) m_LocalDatabase->removeSeries(seriesUID); } return true; } return false; } void QmitkDicomLocalStorageWidget::OnViewButtonClicked() { QStringList uids = m_Controls->ctkDicomBrowser->currentSeriesSelection(); QString uid; foreach (uid, uids) { QStringList filesForSeries = m_LocalDatabase->filesForSeries(uid); QHash<QString, QVariant> eventProperty; eventProperty.insert("FilesForSeries", filesForSeries); emit SignalDicomToDataManager(eventProperty); } } void QmitkDicomLocalStorageWidget::SetDatabaseDirectory(QString newDatatbaseDirectory) { QDir databaseDirecory = QDir(newDatatbaseDirectory); if(!databaseDirecory.exists()) { databaseDirecory.mkpath(databaseDirecory.absolutePath()); } QString newDatatbaseFile = databaseDirecory.absolutePath() + QString("/ctkDICOM.sql"); this->SetDatabase(newDatatbaseFile); } void QmitkDicomLocalStorageWidget::SetDatabase(QString databaseFile) { m_LocalDatabase = new ctkDICOMDatabase(databaseFile); m_LocalDatabase->setParent(this); m_Controls->ctkDicomBrowser->setDICOMDatabase(m_LocalDatabase); } void QmitkDicomLocalStorageWidget::OnSeriesSelectionChanged(const QStringList &s) { m_Controls->viewInternalDataButton->setEnabled((s.size() != 0)); } void QmitkDicomLocalStorageWidget::SetupProgressDialog(QWidget* parent) { m_ProgressDialog = new QProgressDialog("DICOM Import", "Cancel", 0, 100, parent,Qt::WindowTitleHint | Qt::WindowSystemMenuHint); m_ProgressDialogLabel = new QLabel("Initialization...", m_ProgressDialog); m_ProgressDialog->setLabel(m_ProgressDialogLabel); m_ProgressDialog->setWindowModality(Qt::ApplicationModal); m_ProgressDialog->setMinimumDuration(0); } <commit_msg>Explicitly specify Yes and No buttons in Delete message boxes.<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Qmitk #include "QmitkDicomLocalStorageWidget.h" //#include <mitkLogMacros.h> // Qt #include <QLabel> #include <QProgressDialog> #include <QVariant> #include <QMessageBox> const std::string QmitkDicomLocalStorageWidget::Widget_ID = "org.mitk.Widgets.QmitkDicomLocalStorageWidget"; QmitkDicomLocalStorageWidget::QmitkDicomLocalStorageWidget(QWidget *parent) : QWidget(parent) , m_Controls(0) , m_LocalIndexer(new ctkDICOMIndexer(parent)) { CreateQtPartControl(this); } QmitkDicomLocalStorageWidget::~QmitkDicomLocalStorageWidget() { m_LocalDatabase->closeDatabase(); } void QmitkDicomLocalStorageWidget::CreateQtPartControl( QWidget *parent ) { if ( !m_Controls ) { m_Controls = new Ui::QmitkDicomLocalStorageWidgetControls; m_Controls->setupUi( parent ); this->SetupProgressDialog(this); connect(m_Controls->deleteButton,SIGNAL(clicked()),this,SLOT(OnDeleteButtonClicked())); connect(m_Controls->viewInternalDataButton, SIGNAL(clicked()), this , SLOT(OnViewButtonClicked())); connect(m_Controls->ctkDicomBrowser, SIGNAL(seriesSelectionChanged(const QStringList&)), this, SLOT(OnSeriesSelectionChanged(const QStringList&))); connect(m_Controls->ctkDicomBrowser, SIGNAL(seriesSelectionChanged(const QStringList&)), this, SLOT(OnSeriesSelectionChanged(const QStringList&))); connect(m_Controls->ctkDicomBrowser, SIGNAL(seriesDoubleClicked(const QModelIndex&)), this, SLOT(OnViewButtonClicked())); connect(m_LocalIndexer, SIGNAL(indexingComplete()),this, SLOT(OnFinishedImport())); connect(m_LocalIndexer, SIGNAL(indexingComplete()),this, SIGNAL(SignalFinishedImport())); connect(m_LocalIndexer, SIGNAL(indexingComplete()),this, SLOT(OnFinishedImport())); connect(m_LocalIndexer, SIGNAL(indexingFilePath(const QString&)), m_ProgressDialogLabel, SLOT(setText(const QString&))); connect(m_LocalIndexer, SIGNAL(progress(int)), m_ProgressDialog, SLOT(setValue(int))); connect(m_ProgressDialog, SIGNAL(canceled()), m_LocalIndexer, SLOT(cancel())); m_Controls->ctkDicomBrowser->setTableOrientation(Qt::Vertical); } } void QmitkDicomLocalStorageWidget::OnStartDicomImport(const QString& dicomData) { if(m_LocalDatabase->isOpen()) { m_LocalIndexer->addDirectory(*m_LocalDatabase,dicomData,m_LocalDatabase->databaseDirectory()); } } void QmitkDicomLocalStorageWidget::OnStartDicomImport(const QStringList& dicomData) { if(m_LocalDatabase->isOpen()) { m_ProgressDialog->show(); m_LocalIndexer->addListOfFiles(*m_LocalDatabase,dicomData,m_LocalDatabase->databaseDirectory()); } } void QmitkDicomLocalStorageWidget::OnFinishedImport() { m_ProgressDialog->setValue(m_ProgressDialog->maximum()); } void QmitkDicomLocalStorageWidget::OnDeleteButtonClicked() { if (!this->DeletePatients()) { if (!this->DeleteStudies()) { this->DeleteSeries(); } } m_Controls->ctkDicomBrowser->updateTableViews(); } bool QmitkDicomLocalStorageWidget::DeletePatients() { auto selectedPatientUIDs = m_Controls->ctkDicomBrowser->currentPatientsSelection(); if (!selectedPatientUIDs.empty()) { QStringList studyUIDs; for (const auto& patientUID : selectedPatientUIDs) studyUIDs.append(m_LocalDatabase->studiesForPatient(patientUID)); QStringList seriesUIDs; for (const auto& studyUID : studyUIDs) seriesUIDs.append(m_LocalDatabase->seriesForStudy(studyUID)); auto answer = QMessageBox::question( nullptr, "Delete Patients", QString("Do you really want to delete %1 %2, containing %3 series in %4 %5?") .arg(selectedPatientUIDs.count()) .arg(selectedPatientUIDs.count() != 1 ? "patients" : "patient") .arg(seriesUIDs.count()) .arg(studyUIDs.count()) .arg(studyUIDs.count() != 1 ? "studies" : "study"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (answer == QMessageBox::Yes) { for (const auto& patientUID : selectedPatientUIDs) m_LocalDatabase->removePatient(patientUID); } return true; } return false; } bool QmitkDicomLocalStorageWidget::DeleteStudies() { auto selectedStudyUIDs = m_Controls->ctkDicomBrowser->currentStudiesSelection(); if (!selectedStudyUIDs.empty()) { QStringList seriesUIDs; for (const auto& studyUID : selectedStudyUIDs) seriesUIDs.append(m_LocalDatabase->seriesForStudy(studyUID)); auto answer = QMessageBox::question( nullptr, "Delete Studies", QString("Do you really want to delete %1 %2, containing %3 series?") .arg(selectedStudyUIDs.count()) .arg(selectedStudyUIDs.count() != 1 ? "studies" : "study") .arg(seriesUIDs.count()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (answer == QMessageBox::Yes) { for (const auto& studyUID : selectedStudyUIDs) m_LocalDatabase->removeStudy(studyUID); } return true; } return false; } bool QmitkDicomLocalStorageWidget::DeleteSeries() { auto selectedSeriesUIDs = m_Controls->ctkDicomBrowser->currentSeriesSelection(); if (!selectedSeriesUIDs.empty()) { auto answer = QMessageBox::question( nullptr, "Delete Series", QString("Do you really want to delete %1 series?") .arg(selectedSeriesUIDs.count()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (answer == QMessageBox::Yes) { for (const auto& seriesUID : selectedSeriesUIDs) m_LocalDatabase->removeSeries(seriesUID); } return true; } return false; } void QmitkDicomLocalStorageWidget::OnViewButtonClicked() { QStringList uids = m_Controls->ctkDicomBrowser->currentSeriesSelection(); QString uid; foreach (uid, uids) { QStringList filesForSeries = m_LocalDatabase->filesForSeries(uid); QHash<QString, QVariant> eventProperty; eventProperty.insert("FilesForSeries", filesForSeries); emit SignalDicomToDataManager(eventProperty); } } void QmitkDicomLocalStorageWidget::SetDatabaseDirectory(QString newDatatbaseDirectory) { QDir databaseDirecory = QDir(newDatatbaseDirectory); if(!databaseDirecory.exists()) { databaseDirecory.mkpath(databaseDirecory.absolutePath()); } QString newDatatbaseFile = databaseDirecory.absolutePath() + QString("/ctkDICOM.sql"); this->SetDatabase(newDatatbaseFile); } void QmitkDicomLocalStorageWidget::SetDatabase(QString databaseFile) { m_LocalDatabase = new ctkDICOMDatabase(databaseFile); m_LocalDatabase->setParent(this); m_Controls->ctkDicomBrowser->setDICOMDatabase(m_LocalDatabase); } void QmitkDicomLocalStorageWidget::OnSeriesSelectionChanged(const QStringList &s) { m_Controls->viewInternalDataButton->setEnabled((s.size() != 0)); } void QmitkDicomLocalStorageWidget::SetupProgressDialog(QWidget* parent) { m_ProgressDialog = new QProgressDialog("DICOM Import", "Cancel", 0, 100, parent,Qt::WindowTitleHint | Qt::WindowSystemMenuHint); m_ProgressDialogLabel = new QLabel("Initialization...", m_ProgressDialog); m_ProgressDialog->setLabel(m_ProgressDialogLabel); m_ProgressDialog->setWindowModality(Qt::ApplicationModal); m_ProgressDialog->setMinimumDuration(0); } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkUSTelemedDevice.h" #include "mitkUSTelemedSDKHeader.h" mitk::USTelemedDevice::USTelemedDevice(std::string manufacturer, std::string model) : mitk::USDevice(manufacturer, model), m_ControlsProbes(mitk::USTelemedProbesControls::New(this)), m_ControlsBMode(mitk::USTelemedBModeControls::New(this)), m_ControlsDoppler(mitk::USTelemedDopplerControls::New(this)), m_ImageSource(mitk::USTelemedImageSource::New()), m_UsgMainInterface(0), m_Probe(0), m_UsgDataView(0), m_ProbesCollection(0) { SetNumberOfOutputs(1); SetNthOutput(0, this->MakeOutput(0)); } mitk::USTelemedDevice::~USTelemedDevice() { } std::string mitk::USTelemedDevice::GetDeviceClass() { return "org.mitk.modules.us.USTelemedDevice"; } mitk::USControlInterfaceBMode::Pointer mitk::USTelemedDevice::GetControlInterfaceBMode() { return m_ControlsBMode.GetPointer(); } mitk::USControlInterfaceProbes::Pointer mitk::USTelemedDevice::GetControlInterfaceProbes() { return m_ControlsProbes.GetPointer(); }; mitk::USControlInterfaceDoppler::Pointer mitk::USTelemedDevice::GetControlInterfaceDoppler() { return m_ControlsDoppler.GetPointer(); }; bool mitk::USTelemedDevice::OnInitialization() { CoInitialize(NULL); // initialize COM library return true; } bool mitk::USTelemedDevice::OnConnection() { // create main Telemed API COM library object HRESULT hr; hr = CoCreateInstance(Usgfw2Lib::CLSID_Usgfw2, NULL, CLSCTX_INPROC_SERVER, Usgfw2Lib::IID_IUsgfw2,(LPVOID*) &m_UsgMainInterface); if (FAILED(hr)) { SAFE_RELEASE(m_UsgMainInterface); MITK_ERROR("USDevice")("USTelemedDevice") << "Error at connecting to ultrasound device (" << hr << ")."; return false; } this->ConnectDeviceChangeSink(); return true; } bool mitk::USTelemedDevice::OnDisconnection() { // control objects cannot be active anymore m_ControlsBMode->SetIsActive(false); m_ControlsDoppler->SetIsActive(false); m_ControlsProbes->SetIsActive(false); ReleaseUsgControls(); return true; } bool mitk::USTelemedDevice::OnActivation() { // probe controls are available now m_ControlsProbes->SetIsActive(true); if ( m_ControlsProbes->GetProbesCount() < 1 ) { MITK_WARN("USDevice")("USTelemedDevice") << "No probe found."; return false; } // select first probe as a default m_ControlsProbes->SelectProbe(0); // set scan mode b as default for activation - // control interfaces can override this later HRESULT hr = m_UsgDataView->put_ScanMode(Usgfw2Lib::SCAN_MODE_B); if (FAILED(hr)) { MITK_ERROR("USDevice")("USTelemedDevice") << "Could not set scan mode b (" << hr << ")."; return false; } // start ultrasound scanning with selected scan mode hr = m_UsgDataView->put_ScanState(Usgfw2Lib::SCAN_STATE_RUN); if (FAILED(hr)) { MITK_ERROR("USDevice")("USTelemedDevice") << "Start scanning failed (" << hr << ")."; return false; } m_ControlsBMode->ReinitializeControls(); return true; } bool mitk::USTelemedDevice::OnDeactivation() { this->StopScanning(); return true; } void mitk::USTelemedDevice::OnFreeze(bool freeze) { if ( freeze ) { m_UsgDataView->put_ScanState(Usgfw2Lib::SCAN_STATE_FREEZE); } else { m_UsgDataView->put_ScanState(Usgfw2Lib::SCAN_STATE_RUN); } } mitk::USImageSource::Pointer mitk::USTelemedDevice::GetUSImageSource() { return m_ImageSource.GetPointer(); } void mitk::USTelemedDevice::ReleaseUsgControls() { if (m_UsgDataView) { this->StopScanning(); }; SAFE_RELEASE(m_UsgMainInterface); SAFE_RELEASE(m_Probe); SAFE_RELEASE(m_UsgDataView); SAFE_RELEASE(m_ProbesCollection); } void mitk::USTelemedDevice::StopScanning() { if ( ! m_UsgDataView ) { MITK_WARN("USDevice")("USTelemedDevice") << "Cannot stop scanning as Telemed Data View is null."; return; } HRESULT hr; hr = m_UsgDataView->put_ScanState(Usgfw2Lib::SCAN_STATE_STOP); if (FAILED(hr)) { MITK_ERROR("USDevice")("USTelemedDevice") << "Stop scanning failed (" << hr << ")."; mitkThrow() << "Stop scanning failed (" << hr << ")."; } } Usgfw2Lib::IUsgfw2* mitk::USTelemedDevice::GetUsgMainInterface() { return m_UsgMainInterface; } void mitk::USTelemedDevice::SetActiveDataView(Usgfw2Lib::IUsgDataView* usgDataView) { // scan converter plugin is conected to IUsgDataView -> a new plugin // must be created when changing IUsgDataView m_UsgDataView = usgDataView; if ( ! m_ImageSource->CreateAndConnectConverterPlugin(m_UsgDataView, Usgfw2Lib::SCAN_MODE_B)) { return; } // b mode control object must know about active data view m_ControlsBMode->SetUsgDataView(m_UsgDataView); } void mitk::USTelemedDevice::ConnectDeviceChangeSink( ) { IConnectionPointContainer* cpc = NULL; HRESULT hr = m_UsgMainInterface->QueryInterface(IID_IConnectionPointContainer, (void**)&cpc); if (hr != S_OK) cpc = NULL; if (cpc != NULL) hr = cpc->FindConnectionPoint(Usgfw2Lib::IID_IUsgDeviceChangeSink, &m_UsgDeviceChangeCpnt); if (hr != S_OK) { m_UsgDeviceChangeCpnt = NULL; m_UsgDeviceChangeCpntCookie = 0; } SAFE_RELEASE(cpc); if (m_UsgDeviceChangeCpnt != NULL) hr = m_UsgDeviceChangeCpnt->Advise((IUnknown*)((Usgfw2Lib::IUsgDeviceChangeSink*)this), &m_UsgDeviceChangeCpntCookie); } // --- Methods for Telemed API Interfaces HRESULT __stdcall mitk::USTelemedDevice::raw_OnBeamformerArrive(IUnknown *pUsgBeamformer, ULONG *reserved) { this->Connect(); return S_OK; } HRESULT __stdcall mitk::USTelemedDevice::raw_OnBeamformerRemove(IUnknown *pUsgBeamformer, ULONG *reserved) { if ( this->GetIsActive() ) { this->Deactivate(); } this->Disconnect(); return S_OK; } HRESULT __stdcall mitk::USTelemedDevice::raw_OnProbeArrive(IUnknown*, ULONG* probeIndex) { m_ControlsProbes->ProbeAdded(static_cast<unsigned int>(*probeIndex)); this->Activate(); return S_OK; }; HRESULT __stdcall mitk::USTelemedDevice::raw_OnProbeRemove(IUnknown*, ULONG* probeIndex) { m_ControlsProbes->ProbeRemoved(static_cast<unsigned int>(*probeIndex)); if ( this->GetIsActive() ) { this->Deactivate(); } return S_OK; }; STDMETHODIMP_(ULONG) mitk::USTelemedDevice::AddRef() { ++m_RefCount; return m_RefCount; } STDMETHODIMP_(ULONG) mitk::USTelemedDevice::Release() { --m_RefCount; return m_RefCount; } STDMETHODIMP mitk::USTelemedDevice::QueryInterface(REFIID riid, void** ppv) { if (riid == IID_IUnknown || riid == Usgfw2Lib::IID_IUsgDeviceChangeSink) { *ppv = (IUsgDeviceChangeSink*)this; return S_OK; } if (riid == IID_IDispatch) { *ppv = (IDispatch*)this; return S_OK; } return E_NOINTERFACE; } HRESULT mitk::USTelemedDevice::GetTypeInfoCount(UINT *pctinfo) { if (pctinfo == NULL) return E_INVALIDARG; *pctinfo = 0; return S_OK; } HRESULT mitk::USTelemedDevice::GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo** pptinfo) { if (pptinfo == NULL) return E_INVALIDARG; *pptinfo = NULL; if(itinfo != 0) return DISP_E_BADINDEX; return S_OK; } HRESULT mitk::USTelemedDevice::GetIDsOfNames(const IID &riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid) { // this is not used - must use the same fixed dispid's from Usgfw2 idl file return S_OK; } HRESULT mitk::USTelemedDevice::Invoke(DISPID dispIdMember, const IID &riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { if ( (dispIdMember >= 1) && (dispIdMember <= 6) ) { if (pDispParams->cArgs != 2) // we need 2 arguments return S_OK; IUnknown *unkn = NULL; ULONG *res = NULL; VARIANTARG* p1; VARIANTARG* p; p1 = pDispParams->rgvarg; p = p1; if (p->vt == (VT_BYREF|VT_UI4)) res = p->pulVal; p1++; p = p1; if (p->vt == VT_UNKNOWN) unkn = (IUnknown*)(p->punkVal); if (dispIdMember == 1) OnProbeArrive(unkn, res); else if (dispIdMember == 2) OnBeamformerArrive(unkn, res); else if (dispIdMember == 3) OnProbeRemove(unkn, res); else if (dispIdMember == 4) OnBeamformerRemove(unkn, res); else if (dispIdMember == 5) OnProbeStateChanged(unkn, res); else if (dispIdMember == 6) OnBeamformerStateChanged(unkn, res); } return S_OK; }<commit_msg>Create and connect scan converter plugin only if the usg data view was changed.<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkUSTelemedDevice.h" #include "mitkUSTelemedSDKHeader.h" mitk::USTelemedDevice::USTelemedDevice(std::string manufacturer, std::string model) : mitk::USDevice(manufacturer, model), m_ControlsProbes(mitk::USTelemedProbesControls::New(this)), m_ControlsBMode(mitk::USTelemedBModeControls::New(this)), m_ControlsDoppler(mitk::USTelemedDopplerControls::New(this)), m_ImageSource(mitk::USTelemedImageSource::New()), m_UsgMainInterface(0), m_Probe(0), m_UsgDataView(0), m_ProbesCollection(0) { SetNumberOfOutputs(1); SetNthOutput(0, this->MakeOutput(0)); } mitk::USTelemedDevice::~USTelemedDevice() { } std::string mitk::USTelemedDevice::GetDeviceClass() { return "org.mitk.modules.us.USTelemedDevice"; } mitk::USControlInterfaceBMode::Pointer mitk::USTelemedDevice::GetControlInterfaceBMode() { return m_ControlsBMode.GetPointer(); } mitk::USControlInterfaceProbes::Pointer mitk::USTelemedDevice::GetControlInterfaceProbes() { return m_ControlsProbes.GetPointer(); }; mitk::USControlInterfaceDoppler::Pointer mitk::USTelemedDevice::GetControlInterfaceDoppler() { return m_ControlsDoppler.GetPointer(); }; bool mitk::USTelemedDevice::OnInitialization() { CoInitialize(NULL); // initialize COM library return true; } bool mitk::USTelemedDevice::OnConnection() { // create main Telemed API COM library object HRESULT hr; hr = CoCreateInstance(Usgfw2Lib::CLSID_Usgfw2, NULL, CLSCTX_INPROC_SERVER, Usgfw2Lib::IID_IUsgfw2,(LPVOID*) &m_UsgMainInterface); if (FAILED(hr)) { SAFE_RELEASE(m_UsgMainInterface); MITK_ERROR("USDevice")("USTelemedDevice") << "Error at connecting to ultrasound device (" << hr << ")."; return false; } this->ConnectDeviceChangeSink(); return true; } bool mitk::USTelemedDevice::OnDisconnection() { // control objects cannot be active anymore m_ControlsBMode->SetIsActive(false); m_ControlsDoppler->SetIsActive(false); m_ControlsProbes->SetIsActive(false); ReleaseUsgControls(); return true; } bool mitk::USTelemedDevice::OnActivation() { // probe controls are available now m_ControlsProbes->SetIsActive(true); if ( m_ControlsProbes->GetProbesCount() < 1 ) { MITK_WARN("USDevice")("USTelemedDevice") << "No probe found."; return false; } // select first probe as a default m_ControlsProbes->SelectProbe(0); // set scan mode b as default for activation - // control interfaces can override this later HRESULT hr = m_UsgDataView->put_ScanMode(Usgfw2Lib::SCAN_MODE_B); if (FAILED(hr)) { MITK_ERROR("USDevice")("USTelemedDevice") << "Could not set scan mode b (" << hr << ")."; return false; } // start ultrasound scanning with selected scan mode hr = m_UsgDataView->put_ScanState(Usgfw2Lib::SCAN_STATE_RUN); if (FAILED(hr)) { MITK_ERROR("USDevice")("USTelemedDevice") << "Start scanning failed (" << hr << ")."; return false; } m_ControlsBMode->ReinitializeControls(); return true; } bool mitk::USTelemedDevice::OnDeactivation() { this->StopScanning(); return true; } void mitk::USTelemedDevice::OnFreeze(bool freeze) { if ( freeze ) { m_UsgDataView->put_ScanState(Usgfw2Lib::SCAN_STATE_FREEZE); } else { m_UsgDataView->put_ScanState(Usgfw2Lib::SCAN_STATE_RUN); } } mitk::USImageSource::Pointer mitk::USTelemedDevice::GetUSImageSource() { return m_ImageSource.GetPointer(); } void mitk::USTelemedDevice::ReleaseUsgControls() { if (m_UsgDataView) { this->StopScanning(); }; SAFE_RELEASE(m_UsgMainInterface); SAFE_RELEASE(m_Probe); SAFE_RELEASE(m_UsgDataView); SAFE_RELEASE(m_ProbesCollection); } void mitk::USTelemedDevice::StopScanning() { if ( ! m_UsgDataView ) { MITK_WARN("USDevice")("USTelemedDevice") << "Cannot stop scanning as Telemed Data View is null."; return; } HRESULT hr; hr = m_UsgDataView->put_ScanState(Usgfw2Lib::SCAN_STATE_STOP); if (FAILED(hr)) { MITK_ERROR("USDevice")("USTelemedDevice") << "Stop scanning failed (" << hr << ")."; mitkThrow() << "Stop scanning failed (" << hr << ")."; } } Usgfw2Lib::IUsgfw2* mitk::USTelemedDevice::GetUsgMainInterface() { return m_UsgMainInterface; } void mitk::USTelemedDevice::SetActiveDataView(Usgfw2Lib::IUsgDataView* usgDataView) { // do nothing if the usg data view hasn't changed if ( m_UsgDataView != usgDataView ) { // scan converter plugin is connected to IUsgDataView -> a new plugin // must be created when changing IUsgDataView m_UsgDataView = usgDataView; if ( ! m_ImageSource->CreateAndConnectConverterPlugin(m_UsgDataView, Usgfw2Lib::SCAN_MODE_B)) { return; } // b mode control object must know about active data view m_ControlsBMode->SetUsgDataView(m_UsgDataView); } } void mitk::USTelemedDevice::ConnectDeviceChangeSink( ) { IConnectionPointContainer* cpc = NULL; HRESULT hr = m_UsgMainInterface->QueryInterface(IID_IConnectionPointContainer, (void**)&cpc); if (hr != S_OK) cpc = NULL; if (cpc != NULL) hr = cpc->FindConnectionPoint(Usgfw2Lib::IID_IUsgDeviceChangeSink, &m_UsgDeviceChangeCpnt); if (hr != S_OK) { m_UsgDeviceChangeCpnt = NULL; m_UsgDeviceChangeCpntCookie = 0; } SAFE_RELEASE(cpc); if (m_UsgDeviceChangeCpnt != NULL) hr = m_UsgDeviceChangeCpnt->Advise((IUnknown*)((Usgfw2Lib::IUsgDeviceChangeSink*)this), &m_UsgDeviceChangeCpntCookie); } // --- Methods for Telemed API Interfaces HRESULT __stdcall mitk::USTelemedDevice::raw_OnBeamformerArrive(IUnknown *pUsgBeamformer, ULONG *reserved) { this->Connect(); return S_OK; } HRESULT __stdcall mitk::USTelemedDevice::raw_OnBeamformerRemove(IUnknown *pUsgBeamformer, ULONG *reserved) { if ( this->GetIsActive() ) { this->Deactivate(); } this->Disconnect(); return S_OK; } HRESULT __stdcall mitk::USTelemedDevice::raw_OnProbeArrive(IUnknown*, ULONG* probeIndex) { m_ControlsProbes->ProbeAdded(static_cast<unsigned int>(*probeIndex)); this->Activate(); return S_OK; }; HRESULT __stdcall mitk::USTelemedDevice::raw_OnProbeRemove(IUnknown*, ULONG* probeIndex) { m_ControlsProbes->ProbeRemoved(static_cast<unsigned int>(*probeIndex)); if ( this->GetIsActive() ) { this->Deactivate(); } return S_OK; }; STDMETHODIMP_(ULONG) mitk::USTelemedDevice::AddRef() { ++m_RefCount; return m_RefCount; } STDMETHODIMP_(ULONG) mitk::USTelemedDevice::Release() { --m_RefCount; return m_RefCount; } STDMETHODIMP mitk::USTelemedDevice::QueryInterface(REFIID riid, void** ppv) { if (riid == IID_IUnknown || riid == Usgfw2Lib::IID_IUsgDeviceChangeSink) { *ppv = (IUsgDeviceChangeSink*)this; return S_OK; } if (riid == IID_IDispatch) { *ppv = (IDispatch*)this; return S_OK; } return E_NOINTERFACE; } HRESULT mitk::USTelemedDevice::GetTypeInfoCount(UINT *pctinfo) { if (pctinfo == NULL) return E_INVALIDARG; *pctinfo = 0; return S_OK; } HRESULT mitk::USTelemedDevice::GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo** pptinfo) { if (pptinfo == NULL) return E_INVALIDARG; *pptinfo = NULL; if(itinfo != 0) return DISP_E_BADINDEX; return S_OK; } HRESULT mitk::USTelemedDevice::GetIDsOfNames(const IID &riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid) { // this is not used - must use the same fixed dispid's from Usgfw2 idl file return S_OK; } HRESULT mitk::USTelemedDevice::Invoke(DISPID dispIdMember, const IID &riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { if ( (dispIdMember >= 1) && (dispIdMember <= 6) ) { if (pDispParams->cArgs != 2) // we need 2 arguments return S_OK; IUnknown *unkn = NULL; ULONG *res = NULL; VARIANTARG* p1; VARIANTARG* p; p1 = pDispParams->rgvarg; p = p1; if (p->vt == (VT_BYREF|VT_UI4)) res = p->pulVal; p1++; p = p1; if (p->vt == VT_UNKNOWN) unkn = (IUnknown*)(p->punkVal); if (dispIdMember == 1) OnProbeArrive(unkn, res); else if (dispIdMember == 2) OnBeamformerArrive(unkn, res); else if (dispIdMember == 3) OnProbeRemove(unkn, res); else if (dispIdMember == 4) OnBeamformerRemove(unkn, res); else if (dispIdMember == 5) OnProbeStateChanged(unkn, res); else if (dispIdMember == 6) OnBeamformerStateChanged(unkn, res); } return S_OK; }<|endoftext|>
<commit_before>/* * ZoteroBetterBibTeX.cpp * * Copyright (C) 2009-20 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "ZoteroBetterBibTeX.hpp" #include <shared_core/json/Json.hpp> #include <shared_core/json/Json.hpp> #include <core/http/TcpIpBlockingClient.hpp> #include <core/http/SocketUtils.hpp> #include <session/prefs/UserPrefs.hpp> #include <session/prefs/UserState.hpp> #include <session/SessionModuleContext.hpp> #include "ZoteroCollections.hpp" #include "ZoteroCollectionsLocal.hpp" namespace rstudio { using namespace core; namespace session { namespace modules { namespace zotero { using namespace collections; namespace { template<typename T> bool betterBibtexJsonRpcRequest(const std::string& method, const json::Array& params, T* pResponse, std::string* pWarning) { // build request http::Request request; request.setMethod("POST"); request.setContentType("application/json"); request.setHeader("Accept", "application/json"); request.setUri("/better-bibtex/json-rpc"); json::Object rpcRequest; rpcRequest["jsonrpc"] = "2.0"; rpcRequest["method"] = method; rpcRequest["params"] = params; request.setBody(rpcRequest.writeFormatted()); http::Response response; Error error = http::sendRequest("localhost", "23119", boost::posix_time::milliseconds(1000), request, &response); if (!error) { if (response.statusCode() == http::status::Ok) { json::Value responseValue; Error error = responseValue.parse(response.body()); if (!error) { if (responseValue.isObject() && responseValue.getObject().hasMember("result")) { json::Value resultValue = responseValue.getObject()["result"]; if (json::isType<T>(resultValue)) { *pResponse = resultValue.getValue<T>(); return true; } } } *pWarning = "Unexpected data format provided by Better BibTeX"; LOG_ERROR_MESSAGE(*pWarning + " : " + response.body()); } else { *pWarning = "Unexpected status " + safe_convert::numberToString(response.statusCode()) + " from Better BibTeX"; LOG_ERROR_MESSAGE(*pWarning); } } else if (http::isConnectionUnavailableError(error) || (error = systemError(boost::system::errc::timed_out, ErrorLocation()))) { *pWarning = "Unable to connect to Better BibTeX. Please ensure that Zotero is running."; } else { *pWarning = "Unexpected error communicating with Better BibTex"; LOG_ERROR(error); } return false; } } // anonymous namespace bool betterBibtexInConfig(const std::string& config) { return config.find_first_of("extensions.zotero.translators.better-bibtex") != std::string::npos; } bool betterBibtexEnabled() { return session::prefs::userState().zoteroUseBetterBibtex(); } void betterBibtexProvideIds(const collections::ZoteroCollections& collections, collections::ZoteroCollectionsHandler handler) { // get zotero key for each item in all of the collections std::vector<std::string> zoteroKeys; for (auto collection : collections) { std::transform(collection.items.begin(), collection.items.end(), std::back_inserter(zoteroKeys), [](const json::Value& itemJson) { return itemJson.getObject()["key"].getString(); }); } // call better bibtex to create a map of zotero keys to bbt citation ids std::string warning; std::map<std::string,std::string> keyMap; json::Object keyMapJson; json::Array params; params.push_back(json::toJsonArray(zoteroKeys)); if (betterBibtexJsonRpcRequest("item.citationkey", params, &keyMapJson, &warning)) { for (auto member : keyMapJson) { if (member.getValue().isString()) keyMap[member.getName()] = member.getValue().getString(); } } // new set of collections with updated ids collections::ZoteroCollections updatedCollections; std::transform(collections.begin(), collections.end(), std::back_inserter(updatedCollections), [&keyMap](const collections::ZoteroCollection& collection) { json::Array updatedItems; std::transform(collection.items.begin(), collection.items.end(), std::back_inserter(updatedItems), [&keyMap](const json::Value& itemJson) { json::Object itemObject = itemJson.getObject(); if (itemObject.hasMember("key")) { std::string zoteroKey = itemObject["key"].getString(); std::map<std::string,std::string>::const_iterator it = keyMap.find(zoteroKey); if (it != keyMap.end()) { itemObject["id"] = it->second; } } return itemObject; }); collections::ZoteroCollection updatedCollection(collections::ZoteroCollectionSpec(collection.name, collection.key, collection.parentKey, collection.version)); updatedCollection.items = updatedItems; return updatedCollection; }); // return handler(Success(), updatedCollections, warning); } void setBetterBibtexNotFoundResult(const std::string& warning, json::JsonRpcResponse* pResponse) { json::Object resultJson; resultJson["status"] = "nohost"; resultJson["warning"] = warning; pResponse->setResult(resultJson); } Error betterBibtexExport(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // extract params json::Array itemKeysJson; std::string translatorId; int libraryId; Error error = json::readParams(request.params, &itemKeysJson, &translatorId, &libraryId); if (error) return error; // include library in item keys boost::format fmt("%1%:%2%"); for (std::size_t i=0; i<itemKeysJson.getSize(); i++) itemKeysJson[i] = boost::str(fmt % libraryId % itemKeysJson[i].getString()); // get citation keys std::string warning; json::Object keyMapJson; json::Array params; params.push_back(itemKeysJson); if (betterBibtexJsonRpcRequest("item.citationkey", params, &keyMapJson, &warning)) { // extract keys json::Array citekeysJson; std::transform(keyMapJson.begin(), keyMapJson.end(), std::back_inserter(citekeysJson), [](const json::Object::Member& member) { return member.getValue(); }); // perform export params.clear(); params.push_back(citekeysJson); params.push_back(translatorId); params.push_back(libraryId); json::Array exportJson; if (betterBibtexJsonRpcRequest("item.export", params, &exportJson, &warning)) { if (exportJson.getSize() >= 3 && exportJson[0].isInt() && exportJson[0].getInt() == 200 && exportJson[2].isString()) { json::Object jsonResult; jsonResult["status"] = "ok"; jsonResult["message"] = exportJson[2].getString(); pResponse->setResult(jsonResult); } else { std::string warning = "Unexpected response from Better BibTeX"; LOG_ERROR_MESSAGE(warning + " : " + exportJson.write()); setBetterBibtexNotFoundResult(warning, pResponse); } } else { setBetterBibtexNotFoundResult(warning, pResponse); } } else { setBetterBibtexNotFoundResult(warning, pResponse); } return Success(); } Error betterBibtexInit() { // force better bibtex pref off if the config isn't found if (collections::localZoteroAvailable()) { collections::DetectedLocalZoteroConfig config = collections::detectedLocalZoteroConfig(); if (prefs::userState().zoteroUseBetterBibtex() && !config.betterBibtex) prefs::userState().setZoteroUseBetterBibtex(false); } return Success(); } } // end namespace zotero } // end namespace modules } // end namespace session } // end namespace rstudio <commit_msg>Increase Better Bibtex Timeout<commit_after>/* * ZoteroBetterBibTeX.cpp * * Copyright (C) 2009-20 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "ZoteroBetterBibTeX.hpp" #include <shared_core/json/Json.hpp> #include <shared_core/json/Json.hpp> #include <core/http/TcpIpBlockingClient.hpp> #include <core/http/SocketUtils.hpp> #include <session/prefs/UserPrefs.hpp> #include <session/prefs/UserState.hpp> #include <session/SessionModuleContext.hpp> #include "ZoteroCollections.hpp" #include "ZoteroCollectionsLocal.hpp" namespace rstudio { using namespace core; namespace session { namespace modules { namespace zotero { using namespace collections; namespace { template<typename T> bool betterBibtexJsonRpcRequest(const std::string& method, const json::Array& params, T* pResponse, std::string* pWarning) { // build request http::Request request; request.setMethod("POST"); request.setContentType("application/json"); request.setHeader("Accept", "application/json"); request.setUri("/better-bibtex/json-rpc"); json::Object rpcRequest; rpcRequest["jsonrpc"] = "2.0"; rpcRequest["method"] = method; rpcRequest["params"] = params; request.setBody(rpcRequest.writeFormatted()); http::Response response; Error error = http::sendRequest("localhost", "23119", boost::posix_time::milliseconds(10000), request, &response); if (!error) { if (response.statusCode() == http::status::Ok) { json::Value responseValue; Error error = responseValue.parse(response.body()); if (!error) { if (responseValue.isObject() && responseValue.getObject().hasMember("result")) { json::Value resultValue = responseValue.getObject()["result"]; if (json::isType<T>(resultValue)) { *pResponse = resultValue.getValue<T>(); return true; } } } *pWarning = "Unexpected data format provided by Better BibTeX"; LOG_ERROR_MESSAGE(*pWarning + " : " + response.body()); } else { *pWarning = "Unexpected status " + safe_convert::numberToString(response.statusCode()) + " from Better BibTeX"; LOG_ERROR_MESSAGE(*pWarning); } } else if (http::isConnectionUnavailableError(error) || (error = systemError(boost::system::errc::timed_out, ErrorLocation()))) { *pWarning = "Unable to connect to Better BibTeX. Please ensure that Zotero is running."; } else { *pWarning = "Unexpected error communicating with Better BibTex"; LOG_ERROR(error); } return false; } } // anonymous namespace bool betterBibtexInConfig(const std::string& config) { return config.find_first_of("extensions.zotero.translators.better-bibtex") != std::string::npos; } bool betterBibtexEnabled() { return session::prefs::userState().zoteroUseBetterBibtex(); } void betterBibtexProvideIds(const collections::ZoteroCollections& collections, collections::ZoteroCollectionsHandler handler) { // get zotero key for each item in all of the collections std::vector<std::string> zoteroKeys; for (auto collection : collections) { std::transform(collection.items.begin(), collection.items.end(), std::back_inserter(zoteroKeys), [](const json::Value& itemJson) { return itemJson.getObject()["key"].getString(); }); } // call better bibtex to create a map of zotero keys to bbt citation ids std::string warning; std::map<std::string,std::string> keyMap; json::Object keyMapJson; json::Array params; params.push_back(json::toJsonArray(zoteroKeys)); if (betterBibtexJsonRpcRequest("item.citationkey", params, &keyMapJson, &warning)) { for (auto member : keyMapJson) { if (member.getValue().isString()) keyMap[member.getName()] = member.getValue().getString(); } } // new set of collections with updated ids collections::ZoteroCollections updatedCollections; std::transform(collections.begin(), collections.end(), std::back_inserter(updatedCollections), [&keyMap](const collections::ZoteroCollection& collection) { json::Array updatedItems; std::transform(collection.items.begin(), collection.items.end(), std::back_inserter(updatedItems), [&keyMap](const json::Value& itemJson) { json::Object itemObject = itemJson.getObject(); if (itemObject.hasMember("key")) { std::string zoteroKey = itemObject["key"].getString(); std::map<std::string,std::string>::const_iterator it = keyMap.find(zoteroKey); if (it != keyMap.end()) { itemObject["id"] = it->second; } } return itemObject; }); collections::ZoteroCollection updatedCollection(collections::ZoteroCollectionSpec(collection.name, collection.key, collection.parentKey, collection.version)); updatedCollection.items = updatedItems; return updatedCollection; }); // return handler(Success(), updatedCollections, warning); } void setBetterBibtexNotFoundResult(const std::string& warning, json::JsonRpcResponse* pResponse) { json::Object resultJson; resultJson["status"] = "nohost"; resultJson["warning"] = warning; pResponse->setResult(resultJson); } Error betterBibtexExport(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // extract params json::Array itemKeysJson; std::string translatorId; int libraryId; Error error = json::readParams(request.params, &itemKeysJson, &translatorId, &libraryId); if (error) return error; // include library in item keys boost::format fmt("%1%:%2%"); for (std::size_t i=0; i<itemKeysJson.getSize(); i++) itemKeysJson[i] = boost::str(fmt % libraryId % itemKeysJson[i].getString()); // get citation keys std::string warning; json::Object keyMapJson; json::Array params; params.push_back(itemKeysJson); if (betterBibtexJsonRpcRequest("item.citationkey", params, &keyMapJson, &warning)) { // extract keys json::Array citekeysJson; std::transform(keyMapJson.begin(), keyMapJson.end(), std::back_inserter(citekeysJson), [](const json::Object::Member& member) { return member.getValue(); }); // perform export params.clear(); params.push_back(citekeysJson); params.push_back(translatorId); params.push_back(libraryId); json::Array exportJson; if (betterBibtexJsonRpcRequest("item.export", params, &exportJson, &warning)) { if (exportJson.getSize() >= 3 && exportJson[0].isInt() && exportJson[0].getInt() == 200 && exportJson[2].isString()) { json::Object jsonResult; jsonResult["status"] = "ok"; jsonResult["message"] = exportJson[2].getString(); pResponse->setResult(jsonResult); } else { std::string warning = "Unexpected response from Better BibTeX"; LOG_ERROR_MESSAGE(warning + " : " + exportJson.write()); setBetterBibtexNotFoundResult(warning, pResponse); } } else { setBetterBibtexNotFoundResult(warning, pResponse); } } else { setBetterBibtexNotFoundResult(warning, pResponse); } return Success(); } Error betterBibtexInit() { // force better bibtex pref off if the config isn't found if (collections::localZoteroAvailable()) { collections::DetectedLocalZoteroConfig config = collections::detectedLocalZoteroConfig(); if (prefs::userState().zoteroUseBetterBibtex() && !config.betterBibtex) prefs::userState().setZoteroUseBetterBibtex(false); } return Success(); } } // end namespace zotero } // end namespace modules } // end namespace session } // end namespace rstudio <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich 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. ** ***********************************************************************************************************************/ #include "AutoTypeExpression.h" #include "../../declarations/VariableDeclaration.h" #include "../../types/ErrorType.h" #include "../../types/PointerType.h" #include "../../types/ReferenceType.h" #include "PointerTypeExpression.h" #include "ReferenceTypeExpression.h" #include "ModelBase/src/nodes/TypedList.hpp" template class Model::TypedList<OOModel::AutoTypeExpression>; namespace OOModel { COMPOSITENODE_DEFINE_EMPTY_CONSTRUCTORS(AutoTypeExpression) COMPOSITENODE_DEFINE_TYPE_REGISTRATION_METHODS(AutoTypeExpression) Type* AutoTypeExpression::type() { /** * TODO: like this we return the wrong type for auto && * note however that const and volatile are supported as TypeQualifierExpression * adds the qualifier when calling the type() method **/ auto p = parent(); Model::Node* current = this; VariableDeclaration* varDecl = nullptr; while (!(varDecl = DCast<VariableDeclaration>(p))) { current = p; p = p->parent(); Q_ASSERT(p); } if (!varDecl->initialValue()) return new ErrorType{"No initial value in auto type"}; auto initType = varDecl->initialValue()->type(); if (varDecl == p) return initType; if (DCast<ReferenceTypeExpression>(current)) return new ReferenceType{initType, initType->isValueType()}; if (DCast<PointerTypeExpression>(current)) return new PointerType{initType, initType->isValueType()}; return new ErrorType{"Could not find type of auto expression"}; } } <commit_msg>Fix crash when auto used as the element type in a for each loop<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich 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. ** ***********************************************************************************************************************/ #include "AutoTypeExpression.h" #include "../../declarations/VariableDeclaration.h" #include "../../statements/ForEachStatement.h" #include "../../types/ErrorType.h" #include "../../types/PointerType.h" #include "../../types/ReferenceType.h" #include "PointerTypeExpression.h" #include "ReferenceTypeExpression.h" #include "ModelBase/src/nodes/TypedList.hpp" template class Model::TypedList<OOModel::AutoTypeExpression>; namespace OOModel { COMPOSITENODE_DEFINE_EMPTY_CONSTRUCTORS(AutoTypeExpression) COMPOSITENODE_DEFINE_TYPE_REGISTRATION_METHODS(AutoTypeExpression) Type* AutoTypeExpression::type() { /** * TODO: like this we return the wrong type for auto && * note however that const and volatile are supported as TypeQualifierExpression * adds the qualifier when calling the type() method **/ auto p = parent(); Model::Node* current = this; VariableDeclaration* varDecl = nullptr; ForEachStatement* forEachStatement = nullptr; while (!(varDecl = DCast<VariableDeclaration>(p)) && !(forEachStatement = DCast<ForEachStatement>(p))) { current = p; p = p->parent(); Q_ASSERT(p); } Q_ASSERT(varDecl || forEachStatement); if (varDecl) { if (!varDecl->initialValue()) return new ErrorType{"No initial value in auto type"}; auto initType = varDecl->initialValue()->type(); if (varDecl == p) return initType; if (DCast<ReferenceTypeExpression>(current)) return new ReferenceType{initType, initType->isValueType()}; if (DCast<PointerTypeExpression>(current)) return new PointerType{initType, initType->isValueType()}; } if (forEachStatement) { // TODO: Add languge specific rules to infer the correct type // For starters we could also cheat and just take the first tempalte parameter, if any return new ErrorType{"Infering the type of a collection element in a for each loop is not currently supported."}; } return new ErrorType{"Could not find type of auto expression"}; } } <|endoftext|>
<commit_before>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2015 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Justin Madsen // ============================================================================= // // Base class for a Track vehicle model. // // ============================================================================= #include <algorithm> #include "ChTrackVehicle.h" #include "assets/ChAssetLevel.h" #include "assets/ChBoxShape.h" #include "assets/ChColorAsset.h" #include "assets/ChCylinderShape.h" #include "assets/ChSphereShape.h" #include "assets/ChTriangleMeshShape.h" #include "assets/ChTexture.h" #include "utils/ChUtilsInputOutput.h" #include "utils/ChUtilsData.h" // collision mesh #include "geometry/ChCTriangleMeshSoup.h" namespace chrono { ChTrackVehicle::ChTrackVehicle(const std::string& name, VisualizationType vis, CollisionType collide, double mass, const ChVector<>& Ixx, size_t num_engines, double step_size) : m_ownsSystem(true), m_vis(vis), m_collide(collide), // m_mass(mass), // m_inertia(Ixx), m_num_engines(num_engines), m_stepsize(step_size), m_save_log_to_file(false), // save the DebugLog() info to file? default false m_log_what_to_file(0), // set this in Setup_log_to_file(), if writing to file m_log_file_exists(false), // written the headers for log file yet? m_log_what_to_console(0) // pre-set what to write to console when calling { // create a new system, set gravity, default solver settings m_system = new ChSystem; m_system->Set_G_acc(ChVector<>(0, -9.81, 0)); m_system->SetStep(m_stepsize); m_system->SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR); m_system->SetIterLCPmaxItersSpeed(150); m_system->SetIterLCPmaxItersStab(150); m_system->SetTol(0); m_system->SetMaxPenetrationRecoverySpeed(1.5); m_system->SetMinBounceSpeed(1); // m_system->SetIterLCPomega(0.8); // m_system->SetIterLCPsharpnessLambda(0.9); // create the chassis to attach mass, inertia to. m_chassis = ChSharedPtr<ChBodyAuxRef>(new ChBodyAuxRef); m_chassis->SetMass(mass); m_chassis->SetInertiaXX(Ixx); m_chassis->SetNameString(name); // add the chassis body to the system m_system->Add(m_chassis); // init. any other variables with a default value m_meshName = "meshName"; m_meshFile = utils::GetModelDataFile("M113/Chassis_XforwardYup.obj"); m_chassisBoxSize = ChVector<>(4.0, 1.2, 1.5); // full length, height, width of chassis box // set any vector known sizes here m_ptrains.resize(num_engines); } // system already exists, create vehicle with specified input ChTrackVehicle::ChTrackVehicle(ChSystem* system, const std::string& name, VisualizationType vis, CollisionType collide, double mass, const ChVector<>& Ixx, size_t num_engines ): m_ownsSystem(false), m_system(system), m_vis(vis), m_collide(collide), // m_mass(mass), // m_inertia(Ixx), m_num_engines(num_engines), m_stepsize(system->GetStep()), m_save_log_to_file(false), // save the DebugLog() info to file? default false m_log_what_to_file(0), // set this in Setup_log_to_file(), if writing to file m_log_file_exists(false), // written the headers for log file yet? m_log_what_to_console(0) // pre-set what to write to console when calling { // don't worry about solver settings, other system will already handle that. // create the chassis to attach mass, inertia to. m_chassis = ChSharedPtr<ChBodyAuxRef>(new ChBodyAuxRef); m_chassis->SetMass(mass); m_chassis->SetInertiaXX(Ixx); m_chassis->SetNameString(name); // add the chassis body to the system m_system->Add(m_chassis); // init. any other variables with a default value m_meshName = "meshName"; m_meshFile = utils::GetModelDataFile("M113/Chassis_XforwardYup.obj"); m_chassisBoxSize = ChVector<>(4.0, 1.2, 1.5); // full length, height, width of chassis box } ChTrackVehicle::~ChTrackVehicle() { if (m_ownsSystem) delete m_system; } // ----------------------------------------------------------------------------- // Advance the state of the system, taking as many steps as needed to exactly // reach the specified value 'step'. void ChTrackVehicle::Advance(double step) { double t = 0; while (t < step) { double h = std::min<>(m_stepsize, step - t); m_system->DoStepDynamics(h); t += h; } } // ----------------------------------------------------------------------------- // Return the global driver position // ----------------------------------------------------------------------------- const ChVector<>& ChTrackVehicle::GetDriverPos() const { return m_chassis->GetCoord().TransformPointLocalToParent(GetLocalDriverCoordsys().pos); } void ChTrackVehicle::AddVisualization() { // add visual geometry asset to the chassis, if enabled switch (m_vis) { case VisualizationType::NONE: { // put a sphere at the chassis COM and at the REF point ChSharedPtr<ChSphereShape> COMsphere(new ChSphereShape); COMsphere->GetSphereGeometry().rad = 0.1; COMsphere->Pos = m_chassis->GetPos(); m_chassis->AddAsset(COMsphere); // make the COM sphere blue ChSharedPtr<ChColorAsset> blue(new ChColorAsset(0.1f, 0.2f, 0.8f)); m_chassis->AddAsset(blue); // to give the REF sphere a different color, add it to the level first. ChSharedPtr<ChAssetLevel> ref_level(new ChAssetLevel); ChSharedPtr<ChSphereShape> REFsphere(new ChSphereShape); REFsphere->GetSphereGeometry().rad = 0.1; REFsphere->Pos = ChVector<>(0,0,0); // REF should be at the body c-sys origin ref_level->AddAsset(REFsphere); // make the REF sphere red ChSharedPtr<ChColorAsset> red(new ChColorAsset(0.8f, 0.2f, 0.1f) ); ref_level->AddAsset(red); // add the level to the body m_chassis->AddAsset(ref_level); break; } case VisualizationType::PRIMITIVES: { ChSharedPtr<ChBoxShape> box(new ChBoxShape); // uses full lengths as input box->GetBoxGeometry().SetLengths(m_chassisBoxSize ); m_chassis->AddAsset(box); break; } case VisualizationType::MESH: { geometry::ChTriangleMeshConnected trimesh; trimesh.LoadWavefrontMesh(m_meshFile, true, true); ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape); trimesh_shape->SetMesh(trimesh); trimesh_shape->SetName("chassis triMesh"); m_chassis->AddAsset(trimesh_shape); break; } } // end switch } void ChTrackVehicle::AddCollisionGeometry(double mu, double mu_sliding, double mu_roll, double mu_spin) { // add collision geometrey to the chassis, if enabled if( m_collide == CollisionType::NONE) { m_chassis->SetCollide(false); return; } m_chassis->SetCollide(true); m_chassis->GetCollisionModel()->ClearModel(); m_chassis->GetCollisionModel()->SetSafeMargin(0.001); // inward safe margin m_chassis->GetCollisionModel()->SetEnvelope(0.002); // distance of the outward "collision envelope" // set the collision material m_chassis->GetMaterialSurface()->SetSfriction(mu); m_chassis->GetMaterialSurface()->SetKfriction(mu_sliding); m_chassis->GetMaterialSurface()->SetRollingFriction(mu_roll); m_chassis->GetMaterialSurface()->SetSpinningFriction(mu_spin); switch (m_collide) { case CollisionType::PRIMITIVES: { // use a simple box, half dimensions as input m_chassis->GetCollisionModel()->AddBox(0.5*m_chassisBoxSize.x, 0.5*m_chassisBoxSize.y, 0.5*m_chassisBoxSize.z); break; } case CollisionType::MESH: { // use a triangle mesh geometry::ChTriangleMeshSoup temp_trianglemesh; // TODO: fill the triangleMesh here with some track shoe geometry // is there an offset?? double shoelength = 0.2; ChVector<> mesh_displacement(shoelength*0.5,0,0); // since mesh origin is not in body center of mass m_chassis->GetCollisionModel()->AddTriangleMesh(temp_trianglemesh, false, false, mesh_displacement); break; } case CollisionType::CONVEXHULL: { // use convex hulls, loaded from file ChStreamInAsciiFile chull_file(GetChronoDataFile("track_shoe.chulls").c_str()); // transform the collision geometry as needed double mangle = 45.0; // guess ChQuaternion<>rot; rot.Q_from_AngAxis(mangle*(CH_C_PI/180.),VECT_X); ChMatrix33<> rot_offset(rot); ChVector<> disp_offset(0,0,0); // no displacement offset m_chassis->GetCollisionModel()->AddConvexHullsFromFile(chull_file, disp_offset, rot_offset); break; } default: // no collision geometry GetLog() << "not recognized CollisionType: " << (int)m_collide <<" for chassis \n"; m_chassis->SetCollide(false); return; } // end switch // set the collision family m_chassis->GetCollisionModel()->SetFamily( (int)CollisionFam::HULL ); // don't collide with rolling elements or tracks m_chassis->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)(CollisionFam::WHEELS) ); m_chassis->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)(CollisionFam::SHOES) ); m_chassis->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily((int)CollisionFam::GEAR); m_chassis->GetCollisionModel()->BuildModel(); } } // end namespace chrono <commit_msg>remove algorithm.h<commit_after>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2015 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Justin Madsen // ============================================================================= // // Base class for a Track vehicle model. // // ============================================================================= // #include <algorithm> #include "ChTrackVehicle.h" #include "assets/ChAssetLevel.h" #include "assets/ChBoxShape.h" #include "assets/ChColorAsset.h" #include "assets/ChCylinderShape.h" #include "assets/ChSphereShape.h" #include "assets/ChTriangleMeshShape.h" #include "assets/ChTexture.h" #include "utils/ChUtilsInputOutput.h" #include "utils/ChUtilsData.h" // collision mesh #include "geometry/ChCTriangleMeshSoup.h" namespace chrono { ChTrackVehicle::ChTrackVehicle(const std::string& name, VisualizationType vis, CollisionType collide, double mass, const ChVector<>& Ixx, size_t num_engines, double step_size) : m_ownsSystem(true), m_vis(vis), m_collide(collide), // m_mass(mass), // m_inertia(Ixx), m_num_engines(num_engines), m_stepsize(step_size), m_save_log_to_file(false), // save the DebugLog() info to file? default false m_log_what_to_file(0), // set this in Setup_log_to_file(), if writing to file m_log_file_exists(false), // written the headers for log file yet? m_log_what_to_console(0) // pre-set what to write to console when calling { // create a new system, set gravity, default solver settings m_system = new ChSystem; m_system->Set_G_acc(ChVector<>(0, -9.81, 0)); m_system->SetStep(m_stepsize); m_system->SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR); m_system->SetIterLCPmaxItersSpeed(150); m_system->SetIterLCPmaxItersStab(150); m_system->SetTol(0); m_system->SetMaxPenetrationRecoverySpeed(1.5); m_system->SetMinBounceSpeed(1); // m_system->SetIterLCPomega(0.8); // m_system->SetIterLCPsharpnessLambda(0.9); // create the chassis to attach mass, inertia to. m_chassis = ChSharedPtr<ChBodyAuxRef>(new ChBodyAuxRef); m_chassis->SetMass(mass); m_chassis->SetInertiaXX(Ixx); m_chassis->SetNameString(name); // add the chassis body to the system m_system->Add(m_chassis); // init. any other variables with a default value m_meshName = "meshName"; m_meshFile = utils::GetModelDataFile("M113/Chassis_XforwardYup.obj"); m_chassisBoxSize = ChVector<>(4.0, 1.2, 1.5); // full length, height, width of chassis box // set any vector known sizes here m_ptrains.resize(num_engines); } // system already exists, create vehicle with specified input ChTrackVehicle::ChTrackVehicle(ChSystem* system, const std::string& name, VisualizationType vis, CollisionType collide, double mass, const ChVector<>& Ixx, size_t num_engines ): m_ownsSystem(false), m_system(system), m_vis(vis), m_collide(collide), // m_mass(mass), // m_inertia(Ixx), m_num_engines(num_engines), m_stepsize(system->GetStep()), m_save_log_to_file(false), // save the DebugLog() info to file? default false m_log_what_to_file(0), // set this in Setup_log_to_file(), if writing to file m_log_file_exists(false), // written the headers for log file yet? m_log_what_to_console(0) // pre-set what to write to console when calling { // don't worry about solver settings, other system will already handle that. // create the chassis to attach mass, inertia to. m_chassis = ChSharedPtr<ChBodyAuxRef>(new ChBodyAuxRef); m_chassis->SetMass(mass); m_chassis->SetInertiaXX(Ixx); m_chassis->SetNameString(name); // add the chassis body to the system m_system->Add(m_chassis); // init. any other variables with a default value m_meshName = "meshName"; m_meshFile = utils::GetModelDataFile("M113/Chassis_XforwardYup.obj"); m_chassisBoxSize = ChVector<>(4.0, 1.2, 1.5); // full length, height, width of chassis box } ChTrackVehicle::~ChTrackVehicle() { if (m_ownsSystem) delete m_system; } // ----------------------------------------------------------------------------- // Advance the state of the system, taking as many steps as needed to exactly // reach the specified value 'step'. void ChTrackVehicle::Advance(double step) { double t = 0; while (t < step) { double h = std::min<>(m_stepsize, step - t); m_system->DoStepDynamics(h); t += h; } } // ----------------------------------------------------------------------------- // Return the global driver position // ----------------------------------------------------------------------------- const ChVector<>& ChTrackVehicle::GetDriverPos() const { return m_chassis->GetCoord().TransformPointLocalToParent(GetLocalDriverCoordsys().pos); } void ChTrackVehicle::AddVisualization() { // add visual geometry asset to the chassis, if enabled switch (m_vis) { case VisualizationType::NONE: { // put a sphere at the chassis COM and at the REF point ChSharedPtr<ChSphereShape> COMsphere(new ChSphereShape); COMsphere->GetSphereGeometry().rad = 0.1; COMsphere->Pos = m_chassis->GetPos(); m_chassis->AddAsset(COMsphere); // make the COM sphere blue ChSharedPtr<ChColorAsset> blue(new ChColorAsset(0.1f, 0.2f, 0.8f)); m_chassis->AddAsset(blue); // to give the REF sphere a different color, add it to the level first. ChSharedPtr<ChAssetLevel> ref_level(new ChAssetLevel); ChSharedPtr<ChSphereShape> REFsphere(new ChSphereShape); REFsphere->GetSphereGeometry().rad = 0.1; REFsphere->Pos = ChVector<>(0,0,0); // REF should be at the body c-sys origin ref_level->AddAsset(REFsphere); // make the REF sphere red ChSharedPtr<ChColorAsset> red(new ChColorAsset(0.8f, 0.2f, 0.1f) ); ref_level->AddAsset(red); // add the level to the body m_chassis->AddAsset(ref_level); break; } case VisualizationType::PRIMITIVES: { ChSharedPtr<ChBoxShape> box(new ChBoxShape); // uses full lengths as input box->GetBoxGeometry().SetLengths(m_chassisBoxSize ); m_chassis->AddAsset(box); break; } case VisualizationType::MESH: { geometry::ChTriangleMeshConnected trimesh; trimesh.LoadWavefrontMesh(m_meshFile, true, true); ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape); trimesh_shape->SetMesh(trimesh); trimesh_shape->SetName("chassis triMesh"); m_chassis->AddAsset(trimesh_shape); break; } } // end switch } void ChTrackVehicle::AddCollisionGeometry(double mu, double mu_sliding, double mu_roll, double mu_spin) { // add collision geometrey to the chassis, if enabled if( m_collide == CollisionType::NONE) { m_chassis->SetCollide(false); return; } m_chassis->SetCollide(true); m_chassis->GetCollisionModel()->ClearModel(); m_chassis->GetCollisionModel()->SetSafeMargin(0.001); // inward safe margin m_chassis->GetCollisionModel()->SetEnvelope(0.002); // distance of the outward "collision envelope" // set the collision material m_chassis->GetMaterialSurface()->SetSfriction(mu); m_chassis->GetMaterialSurface()->SetKfriction(mu_sliding); m_chassis->GetMaterialSurface()->SetRollingFriction(mu_roll); m_chassis->GetMaterialSurface()->SetSpinningFriction(mu_spin); switch (m_collide) { case CollisionType::PRIMITIVES: { // use a simple box, half dimensions as input m_chassis->GetCollisionModel()->AddBox(0.5*m_chassisBoxSize.x, 0.5*m_chassisBoxSize.y, 0.5*m_chassisBoxSize.z); break; } case CollisionType::MESH: { // use a triangle mesh geometry::ChTriangleMeshSoup temp_trianglemesh; // TODO: fill the triangleMesh here with some track shoe geometry // is there an offset?? double shoelength = 0.2; ChVector<> mesh_displacement(shoelength*0.5,0,0); // since mesh origin is not in body center of mass m_chassis->GetCollisionModel()->AddTriangleMesh(temp_trianglemesh, false, false, mesh_displacement); break; } case CollisionType::CONVEXHULL: { // use convex hulls, loaded from file ChStreamInAsciiFile chull_file(GetChronoDataFile("track_shoe.chulls").c_str()); // transform the collision geometry as needed double mangle = 45.0; // guess ChQuaternion<>rot; rot.Q_from_AngAxis(mangle*(CH_C_PI/180.),VECT_X); ChMatrix33<> rot_offset(rot); ChVector<> disp_offset(0,0,0); // no displacement offset m_chassis->GetCollisionModel()->AddConvexHullsFromFile(chull_file, disp_offset, rot_offset); break; } default: // no collision geometry GetLog() << "not recognized CollisionType: " << (int)m_collide <<" for chassis \n"; m_chassis->SetCollide(false); return; } // end switch // set the collision family m_chassis->GetCollisionModel()->SetFamily( (int)CollisionFam::HULL ); // don't collide with rolling elements or tracks m_chassis->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)(CollisionFam::WHEELS) ); m_chassis->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)(CollisionFam::SHOES) ); m_chassis->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily((int)CollisionFam::GEAR); m_chassis->GetCollisionModel()->BuildModel(); } } // end namespace chrono <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2013 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich 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. ** ***********************************************************************************************************************/ #include "expressions/VBinaryOperation.h" #include "VisualizationBase/src/items/Static.h" using namespace Visualization; using namespace OOModel; namespace OOVisualization { ITEM_COMMON_DEFINITIONS(VBinaryOperation, "item") VBinaryOperation::VBinaryOperation(Item* parent, NodeType* node, const StyleType* style) : Super(parent, node, style), pre_(nullptr), in_(nullptr), post_(nullptr), left_(nullptr), right_(nullptr) { } VBinaryOperation::~VBinaryOperation() { // These were automatically deleted by LayoutProvider's destructor pre_ = nullptr; in_ = nullptr; post_ = nullptr; left_ = nullptr; right_ = nullptr; } void VBinaryOperation::determineChildren() { const OperatorStyle* opStyle = &style()->op( node()->op() ); int index = 0; layout()->synchronizeFirst(pre_ , !opStyle->preSymbol().isEmpty(), &opStyle->preSymbol()); index += pre_?1:0; layout()->synchronizeMid(left_, node()->left(), index); index += left_?1:0; layout()->synchronizeMid(in_ , !opStyle->inSymbol().isEmpty(), &opStyle->inSymbol(), index); index += in_?1:0; layout()->synchronizeMid(right_, node()->right(), index); index += right_?1:0; layout()->synchronizeLast(post_ , !opStyle->postSymbol().isEmpty(), &opStyle->postSymbol()); // TODO: find a better way and place to determine the style of children. Is doing this causing too many updates? // TODO: consider the performance of this. Possibly introduce a style updated boolean for all items so that they know // what's the reason they are being updated. // The style needs to be updated every time since if our own style changes, so will that of the children. layout()->setStyle( &opStyle->layout()); if (pre_) pre_->setStyle( &opStyle->preSymbol()); if (in_) in_->setStyle( &opStyle->inSymbol()); if (post_) post_->setStyle( &opStyle->postSymbol()); // Set the spacing of this layout int depth = getExpressionDepth(node()); if (depth <= 1) layout()->setSpaceBetweenElements(false, 0); else { int space = 1; for (int i = 0; i<depth; ++i) space *= 2; layout()->setSpaceBetweenElements(true, space + opStyle->layout().spaceBetweenElements()); } } int VBinaryOperation::getExpressionDepth(OOModel::Expression* e, int* op) const { auto binary = dynamic_cast<OOModel::BinaryOperation*>(e); if (!binary) return 0; auto op_id = binary->op(); if (op) *op = op_id; int op_ida = -1; int op_idb = -1; int a = getExpressionDepth(binary->left(), &op_ida); int b = getExpressionDepth(binary->right(), &op_idb); if (op_ida == op_idb && op_ida == op_id) return a; if (op_idb < 0 && op_ida == op_id) return a; if (op_ida < 0 && op_idb == op_id) return b; return a>b ? a+1 : b+1; } } <commit_msg>Fix huge white space when rendering many nested binary operators<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2013 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich 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. ** ***********************************************************************************************************************/ #include "expressions/VBinaryOperation.h" #include "VisualizationBase/src/items/Static.h" using namespace Visualization; using namespace OOModel; namespace OOVisualization { ITEM_COMMON_DEFINITIONS(VBinaryOperation, "item") VBinaryOperation::VBinaryOperation(Item* parent, NodeType* node, const StyleType* style) : Super(parent, node, style), pre_(nullptr), in_(nullptr), post_(nullptr), left_(nullptr), right_(nullptr) { } VBinaryOperation::~VBinaryOperation() { // These were automatically deleted by LayoutProvider's destructor pre_ = nullptr; in_ = nullptr; post_ = nullptr; left_ = nullptr; right_ = nullptr; } void VBinaryOperation::determineChildren() { const OperatorStyle* opStyle = &style()->op( node()->op() ); int index = 0; layout()->synchronizeFirst(pre_ , !opStyle->preSymbol().isEmpty(), &opStyle->preSymbol()); index += pre_?1:0; layout()->synchronizeMid(left_, node()->left(), index); index += left_?1:0; layout()->synchronizeMid(in_ , !opStyle->inSymbol().isEmpty(), &opStyle->inSymbol(), index); index += in_?1:0; layout()->synchronizeMid(right_, node()->right(), index); index += right_?1:0; layout()->synchronizeLast(post_ , !opStyle->postSymbol().isEmpty(), &opStyle->postSymbol()); // TODO: find a better way and place to determine the style of children. Is doing this causing too many updates? // TODO: consider the performance of this. Possibly introduce a style updated boolean for all items so that they know // what's the reason they are being updated. // The style needs to be updated every time since if our own style changes, so will that of the children. layout()->setStyle( &opStyle->layout()); if (pre_) pre_->setStyle( &opStyle->preSymbol()); if (in_) in_->setStyle( &opStyle->inSymbol()); if (post_) post_->setStyle( &opStyle->postSymbol()); // Set the spacing of this layout int depth = getExpressionDepth(node()); if (depth <= 1) layout()->setSpaceBetweenElements(false, 0); else { int space = 1; for (int i = 0; i<depth; ++i) space *= 2; layout()->setSpaceBetweenElements(true, space + opStyle->layout().spaceBetweenElements()); } } int VBinaryOperation::getExpressionDepth(OOModel::Expression* e, int* op) const { auto binary = dynamic_cast<OOModel::BinaryOperation*>(e); if (!binary) return 0; auto op_id = binary->op(); if (op) *op = op_id; int op_ida = -1; int op_idb = -1; int a = getExpressionDepth(binary->left(), &op_ida); int b = getExpressionDepth(binary->right(), &op_idb); if (op_ida == op_idb && op_ida == op_id) return a>b?a:b; if (op_ida == op_id) return a; if (op_idb == op_id) return b; return a>b ? a+1 : b+1; } } <|endoftext|>
<commit_before><commit_msg>Fix ui test failure<commit_after><|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: // 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/test/ui/npapi_test_helper.h" #include "base/file_util.h" #include "base/test/test_file_util.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" #include "webkit/glue/plugins/plugin_list.h" #if defined(OS_WIN) static const char kNpapiTestPluginName[] = "npapi_test_plugin.dll"; #elif defined(OS_MACOSX) static const char kNpapiTestPluginName[] = "npapi_test_plugin.plugin"; static const char kLayoutPluginName[] = "TestNetscapePlugIn.plugin"; #elif defined(OS_LINUX) static const char kNpapiTestPluginName[] = "libnpapi_test_plugin.so"; #endif namespace npapi_test { const char kTestCompleteCookie[] = "status"; const char kTestCompleteSuccess[] = "OK"; } // namespace npapi_test. NPAPITesterBase::NPAPITesterBase(const std::string& test_plugin_name) : test_plugin_name_(test_plugin_name) { } void NPAPITesterBase::SetUp() { // We need to copy our test-plugin into the plugins directory so that // the browser can load it. FilePath plugins_directory = GetPluginsDirectory(); FilePath plugin_src = browser_directory_.AppendASCII(test_plugin_name_); ASSERT_TRUE(file_util::PathExists(plugin_src)); test_plugin_path_ = plugins_directory.AppendASCII(test_plugin_name_); file_util::CreateDirectory(plugins_directory); ASSERT_TRUE(file_util::CopyDirectory(plugin_src, test_plugin_path_, true)) << "Copy failed from " << plugin_src.value() << " to " << test_plugin_path_.value(); #if defined(OS_MACOSX) // The plugins directory isn't read by default on the Mac, so it needs to be // explicitly registered. launch_arguments_.AppendSwitchPath(switches::kExtraPluginDir, plugins_directory); #endif UITest::SetUp(); } void NPAPITesterBase::TearDown() { // Tear down the UI test first so that the browser stops using the plugin // files. UITest::TearDown(); EXPECT_TRUE(file_util::DieFileDie(test_plugin_path_, true)); } FilePath NPAPITesterBase::GetPluginsDirectory() { FilePath plugins_directory = browser_directory_.AppendASCII("plugins"); return plugins_directory; } NPAPITester::NPAPITester() : NPAPITesterBase(kNpapiTestPluginName) { } void NPAPITester::SetUp() { #if defined(OS_MACOSX) // TODO(stuartmorgan): Remove this whole subclass once the WebKit build is // changed to copy the plugin into a plugins directory next to the app as // is done on Linux and Windows. FilePath layout_src = browser_directory_.AppendASCII(kLayoutPluginName); ASSERT_TRUE(file_util::PathExists(layout_src)); FilePath plugins_directory = GetPluginsDirectory(); layout_plugin_path_ = plugins_directory.AppendASCII(kLayoutPluginName); file_util::CreateDirectory(plugins_directory); ASSERT_TRUE(file_util::CopyDirectory(layout_src, layout_plugin_path_, true)); #endif NPAPITesterBase::SetUp(); } void NPAPITester::TearDown() { // Tear down the base class first so that the browser stops using the plugin // files. NPAPITesterBase::TearDown(); #if defined(OS_MACOSX) EXPECT_TRUE(file_util::DieFileDie(layout_plugin_path_, true)); #endif // OS_MACOSX } // NPAPIVisiblePluginTester members. void NPAPIVisiblePluginTester::SetUp() { show_window_ = true; NPAPITester::SetUp(); } // NPAPIIncognitoTester members. void NPAPIIncognitoTester::SetUp() { launch_arguments_.AppendSwitch(switches::kIncognito); NPAPITester::SetUp(); } <commit_msg>Don't delete npapi plugins copied into <(PRODUCT_DIR)/plugins during UI tests.<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: // 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/test/ui/npapi_test_helper.h" #include "base/file_util.h" #include "base/test/test_file_util.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" #include "webkit/glue/plugins/plugin_list.h" #if defined(OS_WIN) static const char kNpapiTestPluginName[] = "npapi_test_plugin.dll"; #elif defined(OS_MACOSX) static const char kNpapiTestPluginName[] = "npapi_test_plugin.plugin"; static const char kLayoutPluginName[] = "TestNetscapePlugIn.plugin"; #elif defined(OS_LINUX) static const char kNpapiTestPluginName[] = "libnpapi_test_plugin.so"; #endif namespace npapi_test { const char kTestCompleteCookie[] = "status"; const char kTestCompleteSuccess[] = "OK"; } // namespace npapi_test. NPAPITesterBase::NPAPITesterBase(const std::string& test_plugin_name) : test_plugin_name_(test_plugin_name) { } void NPAPITesterBase::SetUp() { // We need to copy our test-plugin into the plugins directory so that // the browser can load it. // TODO(tc): We should copy the plugins as a build step, not during // the tests. Then we don't have to clean up after the copy in the test. FilePath plugins_directory = GetPluginsDirectory(); FilePath plugin_src = browser_directory_.AppendASCII(test_plugin_name_); ASSERT_TRUE(file_util::PathExists(plugin_src)); test_plugin_path_ = plugins_directory.AppendASCII(test_plugin_name_); file_util::CreateDirectory(plugins_directory); ASSERT_TRUE(file_util::CopyDirectory(plugin_src, test_plugin_path_, true)) << "Copy failed from " << plugin_src.value() << " to " << test_plugin_path_.value(); #if defined(OS_MACOSX) // The plugins directory isn't read by default on the Mac, so it needs to be // explicitly registered. launch_arguments_.AppendSwitchPath(switches::kExtraPluginDir, plugins_directory); #endif UITest::SetUp(); } void NPAPITesterBase::TearDown() { // Tear down the UI test first so that the browser stops using the plugin // files. UITest::TearDown(); } FilePath NPAPITesterBase::GetPluginsDirectory() { FilePath plugins_directory = browser_directory_.AppendASCII("plugins"); return plugins_directory; } NPAPITester::NPAPITester() : NPAPITesterBase(kNpapiTestPluginName) { } void NPAPITester::SetUp() { #if defined(OS_MACOSX) // TODO(stuartmorgan): Remove this whole subclass once the WebKit build is // changed to copy the plugin into a plugins directory next to the app as // is done on Linux and Windows. FilePath layout_src = browser_directory_.AppendASCII(kLayoutPluginName); ASSERT_TRUE(file_util::PathExists(layout_src)); FilePath plugins_directory = GetPluginsDirectory(); layout_plugin_path_ = plugins_directory.AppendASCII(kLayoutPluginName); file_util::CreateDirectory(plugins_directory); ASSERT_TRUE(file_util::CopyDirectory(layout_src, layout_plugin_path_, true)); #endif NPAPITesterBase::SetUp(); } void NPAPITester::TearDown() { // Tear down the base class first so that the browser stops using the plugin // files. NPAPITesterBase::TearDown(); } // NPAPIVisiblePluginTester members. void NPAPIVisiblePluginTester::SetUp() { show_window_ = true; NPAPITester::SetUp(); } // NPAPIIncognitoTester members. void NPAPIIncognitoTester::SetUp() { launch_arguments_.AppendSwitch(switches::kIncognito); NPAPITester::SetUp(); } <|endoftext|>
<commit_before>/* OpenDeck MIDI platform firmware Copyright (C) 2015-2017 Igor Petrovic 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Board.h" #include "Variables.h" bool encodersProcessed; uint16_t encoderData[MAX_NUMBER_OF_ENCODERS]; void Board::initEncoders() { for (int i=0; i<MAX_NUMBER_OF_ENCODERS; i++) { encoderData[i] |= ((uint16_t)0 << 8); encoderData[i] |= ((uint16_t)ENCODER_DEFAULT_PULSE_COUNT_STATE << 4); //set number of pulses to 8 } } uint8_t Board::getEncoderPair(uint8_t buttonID) { return buttonID/2; } int8_t Board::getEncoderState(uint8_t encoderID) { //first, find out array index of digital input buffer where data is stored for requested encoder uint8_t buttonID = encoderID*2; uint8_t arrayIndex = buttonID/8; uint8_t pairState = BIT_READ(digitalInBuffer[arrayIndex], 7-buttonID); pairState <<= 1; pairState |= BIT_READ(digitalInBuffer[arrayIndex], 6-buttonID); return readEncoder(encoderID, pairState); } int8_t Board::readEncoder(uint8_t encoderID, uint8_t pairState) { //add new data uint8_t newPairData = 0; newPairData |= (((encoderData[encoderID] << 2) & 0x000F) | (uint16_t)pairState); //remove old data encoderData[encoderID] &= ENCODER_CLEAR_TEMP_STATE_MASK; //shift in new data encoderData[encoderID] |= (uint16_t)newPairData; int8_t encRead = encoderLookUpTable[newPairData]; if (!encRead) return 0; bool newEncoderDirection = encRead > 0; //get current number of pulses from encoderData int8_t currentPulses = (encoderData[encoderID] >> 4) & 0x000F; currentPulses += encRead; //clear current pulses encoderData[encoderID] &= ENCODER_CLEAR_PULSES_MASK; //shift in new pulse count encoderData[encoderID] |= (uint16_t)(currentPulses << 4); //get last encoder direction bool lastEncoderDirection = BIT_READ(encoderData[encoderID], ENCODER_DIRECTION_BIT); //write new encoder direction BIT_WRITE(encoderData[encoderID], ENCODER_DIRECTION_BIT, newEncoderDirection); if (lastEncoderDirection != newEncoderDirection) return 0; if (currentPulses % PULSES_PER_STEP) return 0; //clear current pulses encoderData[encoderID] &= ENCODER_CLEAR_PULSES_MASK; //set default pulse count encoderData[encoderID] |= ((uint16_t)ENCODER_DEFAULT_PULSE_COUNT_STATE << 4); if (newEncoderDirection) return 1; else return -1; } <commit_msg>formatting<commit_after>/* OpenDeck MIDI platform firmware Copyright (C) 2015-2017 Igor Petrovic 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Board.h" #include "Variables.h" bool encodersProcessed; uint16_t encoderData[MAX_NUMBER_OF_ENCODERS]; void Board::initEncoders() { for (int i=0; i<MAX_NUMBER_OF_ENCODERS; i++) { encoderData[i] |= ((uint16_t)0 << 8); encoderData[i] |= ((uint16_t)ENCODER_DEFAULT_PULSE_COUNT_STATE << 4); //set number of pulses to 8 } } uint8_t Board::getEncoderPair(uint8_t buttonID) { return buttonID/2; } int8_t Board::getEncoderState(uint8_t encoderID) { //first, find out array index of digital input buffer where data is stored for requested encoder uint8_t buttonID = encoderID*2; uint8_t arrayIndex = buttonID/8; uint8_t pairState = BIT_READ(digitalInBuffer[arrayIndex], 7-buttonID); pairState <<= 1; pairState |= BIT_READ(digitalInBuffer[arrayIndex], 6-buttonID); return readEncoder(encoderID, pairState); } int8_t Board::readEncoder(uint8_t encoderID, uint8_t pairState) { //add new data uint8_t newPairData = 0; newPairData |= (((encoderData[encoderID] << 2) & 0x000F) | (uint16_t)pairState); //remove old data encoderData[encoderID] &= ENCODER_CLEAR_TEMP_STATE_MASK; //shift in new data encoderData[encoderID] |= (uint16_t)newPairData; int8_t encRead = encoderLookUpTable[newPairData]; if (!encRead) return 0; bool newEncoderDirection = encRead > 0; //get current number of pulses from encoderData int8_t currentPulses = (encoderData[encoderID] >> 4) & 0x000F; currentPulses += encRead; //clear current pulses encoderData[encoderID] &= ENCODER_CLEAR_PULSES_MASK; //shift in new pulse count encoderData[encoderID] |= (uint16_t)(currentPulses << 4); //get last encoder direction bool lastEncoderDirection = BIT_READ(encoderData[encoderID], ENCODER_DIRECTION_BIT); //write new encoder direction BIT_WRITE(encoderData[encoderID], ENCODER_DIRECTION_BIT, newEncoderDirection); if (lastEncoderDirection != newEncoderDirection) return 0; if (currentPulses % PULSES_PER_STEP) return 0; //clear current pulses encoderData[encoderID] &= ENCODER_CLEAR_PULSES_MASK; //set default pulse count encoderData[encoderID] |= ((uint16_t)ENCODER_DEFAULT_PULSE_COUNT_STATE << 4); if (newEncoderDirection) return 1; else return -1; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/devtools/render_view_devtools_agent_host.h" #include "base/basictypes.h" #include "base/lazy_instance.h" #include "content/browser/child_process_security_policy_impl.h" #include "content/browser/devtools/devtools_manager_impl.h" #include "content/browser/devtools/devtools_protocol.h" #include "content/browser/devtools/devtools_protocol_constants.h" #include "content/browser/devtools/devtools_tracing_handler.h" #include "content/browser/devtools/renderer_overrides_handler.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/site_instance_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/devtools_messages.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" namespace content { typedef std::vector<RenderViewDevToolsAgentHost*> Instances; namespace { base::LazyInstance<Instances>::Leaky g_instances = LAZY_INSTANCE_INITIALIZER; static RenderViewDevToolsAgentHost* FindAgentHost(RenderViewHost* rvh) { if (g_instances == NULL) return NULL; for (Instances::iterator it = g_instances.Get().begin(); it != g_instances.Get().end(); ++it) { if (rvh == (*it)->render_view_host()) return *it; } return NULL; } } // namespace class RenderViewDevToolsAgentHost::DevToolsAgentHostRvhObserver : public RenderViewHostObserver { public: DevToolsAgentHostRvhObserver(RenderViewHost* rvh, RenderViewDevToolsAgentHost* agent_host) : RenderViewHostObserver(rvh), agent_host_(agent_host) { } virtual ~DevToolsAgentHostRvhObserver() {} // RenderViewHostObserver overrides. virtual void RenderViewHostDestroyed(RenderViewHost* rvh) OVERRIDE { agent_host_->RenderViewHostDestroyed(rvh); } virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE { return agent_host_->OnRvhMessageReceived(message); } private: RenderViewDevToolsAgentHost* agent_host_; DISALLOW_COPY_AND_ASSIGN(DevToolsAgentHostRvhObserver); }; // static scoped_refptr<DevToolsAgentHost> DevToolsAgentHost::GetOrCreateFor(RenderViewHost* rvh) { RenderViewDevToolsAgentHost* result = FindAgentHost(rvh); if (!result) result = new RenderViewDevToolsAgentHost(rvh); return result; } // static bool DevToolsAgentHost::HasFor(RenderViewHost* rvh) { return FindAgentHost(rvh) != NULL; } // static bool DevToolsAgentHost::IsDebuggerAttached(WebContents* web_contents) { if (g_instances == NULL) return false; DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); if (!devtools_manager) return false; RenderViewHostDelegate* delegate = static_cast<WebContentsImpl*>(web_contents); for (Instances::iterator it = g_instances.Get().begin(); it != g_instances.Get().end(); ++it) { RenderViewHost* rvh = (*it)->render_view_host_; if (rvh && rvh->GetDelegate() != delegate) continue; if ((*it)->IsAttached()) return true; } return false; } //static std::vector<RenderViewHost*> DevToolsAgentHost::GetValidRenderViewHosts() { std::vector<RenderViewHost*> result; RenderWidgetHost::List widgets = RenderWidgetHost::GetRenderWidgetHosts(); for (size_t i = 0; i < widgets.size(); ++i) { // Ignore processes that don't have a connection, such as crashed contents. if (!widgets[i]->GetProcess()->HasConnection()) continue; if (!widgets[i]->IsRenderView()) continue; RenderViewHost* rvh = RenderViewHost::From(widgets[i]); WebContents* web_contents = WebContents::FromRenderViewHost(rvh); // Don't report a RenderViewHost if it is not the current RenderViewHost // for some WebContents. if (!web_contents || rvh != web_contents->GetRenderViewHost()) continue; result.push_back(rvh); } return result; } // static void RenderViewDevToolsAgentHost::OnCancelPendingNavigation( RenderViewHost* pending, RenderViewHost* current) { RenderViewDevToolsAgentHost* agent_host = FindAgentHost(pending); if (!agent_host) return; agent_host->DisconnectRenderViewHost(); agent_host->ConnectRenderViewHost(current); } RenderViewDevToolsAgentHost::RenderViewDevToolsAgentHost( RenderViewHost* rvh) : overrides_handler_(new RendererOverridesHandler(this)), tracing_handler_(new DevToolsTracingHandler()) { SetRenderViewHost(rvh); DevToolsProtocol::Notifier notifier(base::Bind( &RenderViewDevToolsAgentHost::OnDispatchOnInspectorFrontend, base::Unretained(this))); overrides_handler_->SetNotifier(notifier); tracing_handler_->SetNotifier(notifier); g_instances.Get().push_back(this); RenderViewHostDelegate* delegate = render_view_host_->GetDelegate(); if (delegate && delegate->GetAsWebContents()) Observe(delegate->GetAsWebContents()); AddRef(); // Balanced in RenderViewHostDestroyed. } RenderViewHost* RenderViewDevToolsAgentHost::GetRenderViewHost() { return render_view_host_; } void RenderViewDevToolsAgentHost::DispatchOnInspectorBackend( const std::string& message) { std::string error_message; scoped_refptr<DevToolsProtocol::Command> command = DevToolsProtocol::ParseCommand(message, &error_message); if (command) { scoped_refptr<DevToolsProtocol::Response> overridden_response = overrides_handler_->HandleCommand(command); if (!overridden_response) overridden_response = tracing_handler_->HandleCommand(command); if (overridden_response) { if (!overridden_response->is_async_promise()) OnDispatchOnInspectorFrontend(overridden_response->Serialize()); return; } } IPCDevToolsAgentHost::DispatchOnInspectorBackend(message); } void RenderViewDevToolsAgentHost::SendMessageToAgent(IPC::Message* msg) { if (!render_view_host_) return; msg->set_routing_id(render_view_host_->GetRoutingID()); render_view_host_->Send(msg); } void RenderViewDevToolsAgentHost::OnClientAttached() { if (!render_view_host_) return; ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadRawCookies( render_view_host_->GetProcess()->GetID()); // TODO(kaznacheev): Move this call back to DevToolsManagerImpl when // ExtensionProcessManager no longer relies on this notification. DevToolsManagerImpl::GetInstance()->NotifyObservers(this, true); } void RenderViewDevToolsAgentHost::OnClientDetached() { if (!render_view_host_) return; bool process_has_agents = false; RenderProcessHost* render_process_host = render_view_host_->GetProcess(); for (Instances::iterator it = g_instances.Get().begin(); it != g_instances.Get().end(); ++it) { if (*it == this || !(*it)->IsAttached()) continue; RenderViewHost* rvh = (*it)->render_view_host(); if (rvh && rvh->GetProcess() == render_process_host) process_has_agents = true; } // We are the last to disconnect from the renderer -> revoke permissions. if (!process_has_agents) { ChildProcessSecurityPolicyImpl::GetInstance()->RevokeReadRawCookies( render_process_host->GetID()); } // TODO(kaznacheev): Move this call back to DevToolsManagerImpl when // ExtensionProcessManager no longer relies on this notification. DevToolsManagerImpl::GetInstance()->NotifyObservers(this, false); } RenderViewDevToolsAgentHost::~RenderViewDevToolsAgentHost() { Instances::iterator it = std::find(g_instances.Get().begin(), g_instances.Get().end(), this); if (it != g_instances.Get().end()) g_instances.Get().erase(it); } void RenderViewDevToolsAgentHost::AboutToNavigateRenderView( RenderViewHost* dest_rvh) { if (!render_view_host_) return; if (render_view_host_ == dest_rvh && static_cast<RenderViewHostImpl*>( render_view_host_)->render_view_termination_status() == base::TERMINATION_STATUS_STILL_RUNNING) return; DisconnectRenderViewHost(); ConnectRenderViewHost(dest_rvh); } void RenderViewDevToolsAgentHost::RenderProcessGone( base::TerminationStatus status) { switch(status) { case base::TERMINATION_STATUS_ABNORMAL_TERMINATION: case base::TERMINATION_STATUS_PROCESS_WAS_KILLED: case base::TERMINATION_STATUS_PROCESS_CRASHED: RenderViewCrashed(); break; default: break; } } void RenderViewDevToolsAgentHost::DidAttachInterstitialPage() { if (!render_view_host_) return; // The rvh set in AboutToNavigateRenderView turned out to be interstitial. // Connect back to the real one. WebContents* web_contents = WebContents::FromRenderViewHost(render_view_host_); if (!web_contents) return; DisconnectRenderViewHost(); ConnectRenderViewHost(web_contents->GetRenderViewHost()); } void RenderViewDevToolsAgentHost::SetRenderViewHost(RenderViewHost* rvh) { render_view_host_ = rvh; rvh_observer_.reset(new DevToolsAgentHostRvhObserver(rvh, this)); } void RenderViewDevToolsAgentHost::ConnectRenderViewHost(RenderViewHost* rvh) { SetRenderViewHost(rvh); Reattach(state_); } void RenderViewDevToolsAgentHost::DisconnectRenderViewHost() { OnClientDetached(); rvh_observer_.reset(); render_view_host_ = NULL; } void RenderViewDevToolsAgentHost::RenderViewHostDestroyed( RenderViewHost* rvh) { DCHECK(render_view_host_); scoped_refptr<RenderViewDevToolsAgentHost> protect(this); NotifyCloseListener(); render_view_host_ = NULL; Release(); } void RenderViewDevToolsAgentHost::RenderViewCrashed() { scoped_refptr<DevToolsProtocol::Notification> notification = DevToolsProtocol::CreateNotification( devtools::Inspector::targetCrashed::kName, NULL); DevToolsManagerImpl::GetInstance()-> DispatchOnInspectorFrontend(this, notification->Serialize()); } bool RenderViewDevToolsAgentHost::OnRvhMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderViewDevToolsAgentHost, message) IPC_MESSAGE_HANDLER(DevToolsClientMsg_DispatchOnInspectorFrontend, OnDispatchOnInspectorFrontend) IPC_MESSAGE_HANDLER(DevToolsHostMsg_SaveAgentRuntimeState, OnSaveAgentRuntimeState) IPC_MESSAGE_HANDLER(DevToolsHostMsg_ClearBrowserCache, OnClearBrowserCache) IPC_MESSAGE_HANDLER(DevToolsHostMsg_ClearBrowserCookies, OnClearBrowserCookies) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void RenderViewDevToolsAgentHost::OnSaveAgentRuntimeState( const std::string& state) { if (!render_view_host_) return; state_ = state; } void RenderViewDevToolsAgentHost::OnDispatchOnInspectorFrontend( const std::string& message) { if (!render_view_host_) return; DevToolsManagerImpl::GetInstance()->DispatchOnInspectorFrontend( this, message); } void RenderViewDevToolsAgentHost::OnClearBrowserCache() { if (render_view_host_) GetContentClient()->browser()->ClearCache(render_view_host_); } void RenderViewDevToolsAgentHost::OnClearBrowserCookies() { if (render_view_host_) GetContentClient()->browser()->ClearCookies(render_view_host_); } } // namespace content <commit_msg>DevTools should not try to reattach in Render process is no actual client is connected<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 "content/browser/devtools/render_view_devtools_agent_host.h" #include "base/basictypes.h" #include "base/lazy_instance.h" #include "content/browser/child_process_security_policy_impl.h" #include "content/browser/devtools/devtools_manager_impl.h" #include "content/browser/devtools/devtools_protocol.h" #include "content/browser/devtools/devtools_protocol_constants.h" #include "content/browser/devtools/devtools_tracing_handler.h" #include "content/browser/devtools/renderer_overrides_handler.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/site_instance_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/devtools_messages.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" namespace content { typedef std::vector<RenderViewDevToolsAgentHost*> Instances; namespace { base::LazyInstance<Instances>::Leaky g_instances = LAZY_INSTANCE_INITIALIZER; static RenderViewDevToolsAgentHost* FindAgentHost(RenderViewHost* rvh) { if (g_instances == NULL) return NULL; for (Instances::iterator it = g_instances.Get().begin(); it != g_instances.Get().end(); ++it) { if (rvh == (*it)->render_view_host()) return *it; } return NULL; } } // namespace class RenderViewDevToolsAgentHost::DevToolsAgentHostRvhObserver : public RenderViewHostObserver { public: DevToolsAgentHostRvhObserver(RenderViewHost* rvh, RenderViewDevToolsAgentHost* agent_host) : RenderViewHostObserver(rvh), agent_host_(agent_host) { } virtual ~DevToolsAgentHostRvhObserver() {} // RenderViewHostObserver overrides. virtual void RenderViewHostDestroyed(RenderViewHost* rvh) OVERRIDE { agent_host_->RenderViewHostDestroyed(rvh); } virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE { return agent_host_->OnRvhMessageReceived(message); } private: RenderViewDevToolsAgentHost* agent_host_; DISALLOW_COPY_AND_ASSIGN(DevToolsAgentHostRvhObserver); }; // static scoped_refptr<DevToolsAgentHost> DevToolsAgentHost::GetOrCreateFor(RenderViewHost* rvh) { RenderViewDevToolsAgentHost* result = FindAgentHost(rvh); if (!result) result = new RenderViewDevToolsAgentHost(rvh); return result; } // static bool DevToolsAgentHost::HasFor(RenderViewHost* rvh) { return FindAgentHost(rvh) != NULL; } // static bool DevToolsAgentHost::IsDebuggerAttached(WebContents* web_contents) { if (g_instances == NULL) return false; DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); if (!devtools_manager) return false; RenderViewHostDelegate* delegate = static_cast<WebContentsImpl*>(web_contents); for (Instances::iterator it = g_instances.Get().begin(); it != g_instances.Get().end(); ++it) { RenderViewHost* rvh = (*it)->render_view_host_; if (rvh && rvh->GetDelegate() != delegate) continue; if ((*it)->IsAttached()) return true; } return false; } //static std::vector<RenderViewHost*> DevToolsAgentHost::GetValidRenderViewHosts() { std::vector<RenderViewHost*> result; RenderWidgetHost::List widgets = RenderWidgetHost::GetRenderWidgetHosts(); for (size_t i = 0; i < widgets.size(); ++i) { // Ignore processes that don't have a connection, such as crashed contents. if (!widgets[i]->GetProcess()->HasConnection()) continue; if (!widgets[i]->IsRenderView()) continue; RenderViewHost* rvh = RenderViewHost::From(widgets[i]); WebContents* web_contents = WebContents::FromRenderViewHost(rvh); // Don't report a RenderViewHost if it is not the current RenderViewHost // for some WebContents. if (!web_contents || rvh != web_contents->GetRenderViewHost()) continue; result.push_back(rvh); } return result; } // static void RenderViewDevToolsAgentHost::OnCancelPendingNavigation( RenderViewHost* pending, RenderViewHost* current) { RenderViewDevToolsAgentHost* agent_host = FindAgentHost(pending); if (!agent_host) return; agent_host->DisconnectRenderViewHost(); agent_host->ConnectRenderViewHost(current); } RenderViewDevToolsAgentHost::RenderViewDevToolsAgentHost( RenderViewHost* rvh) : overrides_handler_(new RendererOverridesHandler(this)), tracing_handler_(new DevToolsTracingHandler()) { SetRenderViewHost(rvh); DevToolsProtocol::Notifier notifier(base::Bind( &RenderViewDevToolsAgentHost::OnDispatchOnInspectorFrontend, base::Unretained(this))); overrides_handler_->SetNotifier(notifier); tracing_handler_->SetNotifier(notifier); g_instances.Get().push_back(this); RenderViewHostDelegate* delegate = render_view_host_->GetDelegate(); if (delegate && delegate->GetAsWebContents()) Observe(delegate->GetAsWebContents()); AddRef(); // Balanced in RenderViewHostDestroyed. } RenderViewHost* RenderViewDevToolsAgentHost::GetRenderViewHost() { return render_view_host_; } void RenderViewDevToolsAgentHost::DispatchOnInspectorBackend( const std::string& message) { std::string error_message; scoped_refptr<DevToolsProtocol::Command> command = DevToolsProtocol::ParseCommand(message, &error_message); if (command) { scoped_refptr<DevToolsProtocol::Response> overridden_response = overrides_handler_->HandleCommand(command); if (!overridden_response) overridden_response = tracing_handler_->HandleCommand(command); if (overridden_response) { if (!overridden_response->is_async_promise()) OnDispatchOnInspectorFrontend(overridden_response->Serialize()); return; } } IPCDevToolsAgentHost::DispatchOnInspectorBackend(message); } void RenderViewDevToolsAgentHost::SendMessageToAgent(IPC::Message* msg) { if (!render_view_host_) return; msg->set_routing_id(render_view_host_->GetRoutingID()); render_view_host_->Send(msg); } void RenderViewDevToolsAgentHost::OnClientAttached() { if (!render_view_host_) return; ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadRawCookies( render_view_host_->GetProcess()->GetID()); // TODO(kaznacheev): Move this call back to DevToolsManagerImpl when // ExtensionProcessManager no longer relies on this notification. DevToolsManagerImpl::GetInstance()->NotifyObservers(this, true); } void RenderViewDevToolsAgentHost::OnClientDetached() { if (!render_view_host_) return; bool process_has_agents = false; RenderProcessHost* render_process_host = render_view_host_->GetProcess(); for (Instances::iterator it = g_instances.Get().begin(); it != g_instances.Get().end(); ++it) { if (*it == this || !(*it)->IsAttached()) continue; RenderViewHost* rvh = (*it)->render_view_host(); if (rvh && rvh->GetProcess() == render_process_host) process_has_agents = true; } // We are the last to disconnect from the renderer -> revoke permissions. if (!process_has_agents) { ChildProcessSecurityPolicyImpl::GetInstance()->RevokeReadRawCookies( render_process_host->GetID()); } // TODO(kaznacheev): Move this call back to DevToolsManagerImpl when // ExtensionProcessManager no longer relies on this notification. DevToolsManagerImpl::GetInstance()->NotifyObservers(this, false); } RenderViewDevToolsAgentHost::~RenderViewDevToolsAgentHost() { Instances::iterator it = std::find(g_instances.Get().begin(), g_instances.Get().end(), this); if (it != g_instances.Get().end()) g_instances.Get().erase(it); } void RenderViewDevToolsAgentHost::AboutToNavigateRenderView( RenderViewHost* dest_rvh) { if (!render_view_host_ || !IsAttached()) return; if (render_view_host_ == dest_rvh && static_cast<RenderViewHostImpl*>( render_view_host_)->render_view_termination_status() == base::TERMINATION_STATUS_STILL_RUNNING) return; DisconnectRenderViewHost(); ConnectRenderViewHost(dest_rvh); } void RenderViewDevToolsAgentHost::RenderProcessGone( base::TerminationStatus status) { switch(status) { case base::TERMINATION_STATUS_ABNORMAL_TERMINATION: case base::TERMINATION_STATUS_PROCESS_WAS_KILLED: case base::TERMINATION_STATUS_PROCESS_CRASHED: RenderViewCrashed(); break; default: break; } } void RenderViewDevToolsAgentHost::DidAttachInterstitialPage() { if (!render_view_host_) return; // The rvh set in AboutToNavigateRenderView turned out to be interstitial. // Connect back to the real one. WebContents* web_contents = WebContents::FromRenderViewHost(render_view_host_); if (!web_contents) return; DisconnectRenderViewHost(); ConnectRenderViewHost(web_contents->GetRenderViewHost()); } void RenderViewDevToolsAgentHost::SetRenderViewHost(RenderViewHost* rvh) { render_view_host_ = rvh; rvh_observer_.reset(new DevToolsAgentHostRvhObserver(rvh, this)); } void RenderViewDevToolsAgentHost::ConnectRenderViewHost(RenderViewHost* rvh) { SetRenderViewHost(rvh); Reattach(state_); } void RenderViewDevToolsAgentHost::DisconnectRenderViewHost() { OnClientDetached(); rvh_observer_.reset(); render_view_host_ = NULL; } void RenderViewDevToolsAgentHost::RenderViewHostDestroyed( RenderViewHost* rvh) { DCHECK(render_view_host_); scoped_refptr<RenderViewDevToolsAgentHost> protect(this); NotifyCloseListener(); render_view_host_ = NULL; Release(); } void RenderViewDevToolsAgentHost::RenderViewCrashed() { scoped_refptr<DevToolsProtocol::Notification> notification = DevToolsProtocol::CreateNotification( devtools::Inspector::targetCrashed::kName, NULL); DevToolsManagerImpl::GetInstance()-> DispatchOnInspectorFrontend(this, notification->Serialize()); } bool RenderViewDevToolsAgentHost::OnRvhMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderViewDevToolsAgentHost, message) IPC_MESSAGE_HANDLER(DevToolsClientMsg_DispatchOnInspectorFrontend, OnDispatchOnInspectorFrontend) IPC_MESSAGE_HANDLER(DevToolsHostMsg_SaveAgentRuntimeState, OnSaveAgentRuntimeState) IPC_MESSAGE_HANDLER(DevToolsHostMsg_ClearBrowserCache, OnClearBrowserCache) IPC_MESSAGE_HANDLER(DevToolsHostMsg_ClearBrowserCookies, OnClearBrowserCookies) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void RenderViewDevToolsAgentHost::OnSaveAgentRuntimeState( const std::string& state) { if (!render_view_host_) return; state_ = state; } void RenderViewDevToolsAgentHost::OnDispatchOnInspectorFrontend( const std::string& message) { if (!render_view_host_) return; DevToolsManagerImpl::GetInstance()->DispatchOnInspectorFrontend( this, message); } void RenderViewDevToolsAgentHost::OnClearBrowserCache() { if (render_view_host_) GetContentClient()->browser()->ClearCache(render_view_host_); } void RenderViewDevToolsAgentHost::OnClearBrowserCookies() { if (render_view_host_) GetContentClient()->browser()->ClearCookies(render_view_host_); } } // namespace content <|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/bind.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/memory/ref_counted.h" #include "base/scoped_temp_dir.h" #include "base/test/thread_test_helper.h" #include "base/utf_string_conversions.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/in_process_webkit/indexed_db_context.h" #include "content/browser/in_process_webkit/webkit_context.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/public/common/content_switches.h" #include "webkit/database/database_util.h" #include "webkit/quota/mock_special_storage_policy.h" #include "webkit/quota/quota_manager.h" #include "webkit/quota/special_storage_policy.h" using content::BrowserThread; using quota::QuotaManager; using webkit_database::DatabaseUtil; // This browser test is aimed towards exercising the IndexedDB bindings and // the actual implementation that lives in the browser side (in_process_webkit). class IndexedDBBrowserTest : public InProcessBrowserTest { public: IndexedDBBrowserTest() { EnableDOMAutomation(); } GURL testUrl(const FilePath& file_path) { const FilePath kTestDir(FILE_PATH_LITERAL("indexeddb")); return ui_test_utils::GetTestUrl(kTestDir, file_path); } void SimpleTest(const GURL& test_url, bool incognito = false) { // The test page will perform tests on IndexedDB, then navigate to either // a #pass or #fail ref. Browser* the_browser = incognito ? CreateIncognitoBrowser() : browser(); LOG(INFO) << "Navigating to URL and blocking."; ui_test_utils::NavigateToURLBlockUntilNavigationsComplete( the_browser, test_url, 2); LOG(INFO) << "Navigation done."; std::string result = the_browser->GetSelectedTabContents()->GetURL().ref(); if (result != "pass") { std::string js_result; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( the_browser->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(getLog())", &js_result)); FAIL() << "Failed: " << js_result; } } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html")))); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTestIncognito) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html"))), true /* incognito */); } // Flaky: http://crbug.com/70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_IndexTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("index_test.html")))); } // Flaky: http://crbug.com/70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_KeyPathTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_path_test.html")))); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_get_test.html")))); } #if defined(OS_WIN) // http://crbug.com/104306 #define KeyTypesTest FLAKY_KeyTypesTest #endif IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, KeyTypesTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_types_test.html")))); } // Flaky: http://crbug.com/70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_ObjectStoreTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("object_store_test.html")))); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("database_test.html")))); } // Flaky: http://crbug.com/70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_TransactionTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html")))); } // Flaky: http://crbug.com/70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_DoesntHangTest) { SimpleTest(testUrl(FilePath( FILE_PATH_LITERAL("transaction_run_forever.html")))); ui_test_utils::CrashTab(browser()->GetSelectedTabContents()); SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html")))); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug84933Test) { const GURL url = testUrl(FilePath(FILE_PATH_LITERAL("bug_84933.html"))); // Just navigate to the URL. Test will crash if it fails. ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 1); } // In proc browser test is needed here because ClearLocalState indirectly calls // WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearLocalState) { ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath protected_path; FilePath unprotected_path; // Create the scope which will ensure we run the destructor of the webkit // context which should trigger the clean up. { TestingProfile profile; // Test our assumptions about what is protected and what is not. const GURL kProtectedOrigin("chrome-extension://foo/"); const GURL kUnprotectedOrigin("http://foo/"); quota::SpecialStoragePolicy* policy = profile.GetSpecialStoragePolicy(); ASSERT_TRUE(policy->IsStorageProtected(kProtectedOrigin)); ASSERT_FALSE(policy->IsStorageProtected(kUnprotectedOrigin)); // Create some indexedDB paths. // With the levelDB backend, these are directories. WebKitContext *webkit_context = profile.GetWebKitContext(); IndexedDBContext* idb_context = webkit_context->indexed_db_context(); idb_context->set_data_path_for_testing(temp_dir.path()); protected_path = idb_context->GetIndexedDBFilePath( DatabaseUtil::GetOriginIdentifier(kProtectedOrigin)); unprotected_path = idb_context->GetIndexedDBFilePath( DatabaseUtil::GetOriginIdentifier(kUnprotectedOrigin)); ASSERT_TRUE(file_util::CreateDirectory(protected_path)); ASSERT_TRUE(file_util::CreateDirectory(unprotected_path)); // Setup to clear all unprotected origins on exit. webkit_context->set_clear_local_state_on_exit(true); } // Make sure we wait until the destructor has run. scoped_refptr<base::ThreadTestHelper> helper( new base::ThreadTestHelper( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::WEBKIT))); ASSERT_TRUE(helper->Run()); ASSERT_TRUE(file_util::DirectoryExists(protected_path)); ASSERT_FALSE(file_util::DirectoryExists(unprotected_path)); } // In proc browser test is needed here because ClearLocalState indirectly calls // WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearSessionOnlyDatabases) { ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath normal_path; FilePath session_only_path; // Create the scope which will ensure we run the destructor of the webkit // context which should trigger the clean up. { TestingProfile profile; const GURL kNormalOrigin("http://normal/"); const GURL kSessionOnlyOrigin("http://session-only/"); scoped_refptr<quota::MockSpecialStoragePolicy> special_storage_policy = new quota::MockSpecialStoragePolicy; special_storage_policy->AddSessionOnly(kSessionOnlyOrigin); // Create some indexedDB paths. // With the levelDB backend, these are directories. WebKitContext *webkit_context = profile.GetWebKitContext(); IndexedDBContext* idb_context = webkit_context->indexed_db_context(); // Override the storage policy with our own. idb_context->special_storage_policy_ = special_storage_policy; idb_context->set_data_path_for_testing(temp_dir.path()); normal_path = idb_context->GetIndexedDBFilePath( DatabaseUtil::GetOriginIdentifier(kNormalOrigin)); session_only_path = idb_context->GetIndexedDBFilePath( DatabaseUtil::GetOriginIdentifier(kSessionOnlyOrigin)); ASSERT_TRUE(file_util::CreateDirectory(normal_path)); ASSERT_TRUE(file_util::CreateDirectory(session_only_path)); } // Make sure we wait until the destructor has run. scoped_refptr<base::ThreadTestHelper> helper( new base::ThreadTestHelper( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::WEBKIT))); ASSERT_TRUE(helper->Run()); EXPECT_TRUE(file_util::DirectoryExists(normal_path)); EXPECT_FALSE(file_util::DirectoryExists(session_only_path)); } class IndexedDBBrowserTestWithLowQuota : public IndexedDBBrowserTest { public: virtual void SetUpOnMainThread() { const int kInitialQuotaKilobytes = 5000; const int kTemporaryStorageQuotaMaxSize = kInitialQuotaKilobytes * 1024 * QuotaManager::kPerHostTemporaryPortion; SetTempQuota( kTemporaryStorageQuotaMaxSize, browser()->profile()->GetQuotaManager()); } static void SetTempQuota(int64 bytes, scoped_refptr<QuotaManager> qm) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&IndexedDBBrowserTestWithLowQuota::SetTempQuota, bytes, qm)); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); qm->SetTemporaryGlobalOverrideQuota(bytes, quota::QuotaCallback()); // Don't return until the quota has been set. scoped_refptr<base::ThreadTestHelper> helper( new base::ThreadTestHelper( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB))); ASSERT_TRUE(helper->Run()); } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithLowQuota, QuotaTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("quota_test.html")))); } class IndexedDBBrowserTestWithGCExposed : public IndexedDBBrowserTest { public: virtual void SetUpCommandLine(CommandLine* command_line) { command_line->AppendSwitchASCII(switches::kJavaScriptFlags, "--expose-gc"); } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithGCExposed, DatabaseCallbacksTest) { SimpleTest( testUrl(FilePath(FILE_PATH_LITERAL("database_callbacks_first.html")))); } <commit_msg>Add FAIL to IndexedDBBrowserTestWithLowQuota.QuotaTest<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 "base/bind.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/memory/ref_counted.h" #include "base/scoped_temp_dir.h" #include "base/test/thread_test_helper.h" #include "base/utf_string_conversions.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/in_process_webkit/indexed_db_context.h" #include "content/browser/in_process_webkit/webkit_context.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/public/common/content_switches.h" #include "webkit/database/database_util.h" #include "webkit/quota/mock_special_storage_policy.h" #include "webkit/quota/quota_manager.h" #include "webkit/quota/special_storage_policy.h" using content::BrowserThread; using quota::QuotaManager; using webkit_database::DatabaseUtil; // This browser test is aimed towards exercising the IndexedDB bindings and // the actual implementation that lives in the browser side (in_process_webkit). class IndexedDBBrowserTest : public InProcessBrowserTest { public: IndexedDBBrowserTest() { EnableDOMAutomation(); } GURL testUrl(const FilePath& file_path) { const FilePath kTestDir(FILE_PATH_LITERAL("indexeddb")); return ui_test_utils::GetTestUrl(kTestDir, file_path); } void SimpleTest(const GURL& test_url, bool incognito = false) { // The test page will perform tests on IndexedDB, then navigate to either // a #pass or #fail ref. Browser* the_browser = incognito ? CreateIncognitoBrowser() : browser(); LOG(INFO) << "Navigating to URL and blocking."; ui_test_utils::NavigateToURLBlockUntilNavigationsComplete( the_browser, test_url, 2); LOG(INFO) << "Navigation done."; std::string result = the_browser->GetSelectedTabContents()->GetURL().ref(); if (result != "pass") { std::string js_result; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( the_browser->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(getLog())", &js_result)); FAIL() << "Failed: " << js_result; } } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html")))); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTestIncognito) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html"))), true /* incognito */); } // Flaky: http://crbug.com/70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_IndexTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("index_test.html")))); } // Flaky: http://crbug.com/70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_KeyPathTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_path_test.html")))); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_get_test.html")))); } #if defined(OS_WIN) // http://crbug.com/104306 #define KeyTypesTest FLAKY_KeyTypesTest #endif IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, KeyTypesTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_types_test.html")))); } // Flaky: http://crbug.com/70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_ObjectStoreTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("object_store_test.html")))); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("database_test.html")))); } // Flaky: http://crbug.com/70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_TransactionTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html")))); } // Flaky: http://crbug.com/70773 IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_DoesntHangTest) { SimpleTest(testUrl(FilePath( FILE_PATH_LITERAL("transaction_run_forever.html")))); ui_test_utils::CrashTab(browser()->GetSelectedTabContents()); SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html")))); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug84933Test) { const GURL url = testUrl(FilePath(FILE_PATH_LITERAL("bug_84933.html"))); // Just navigate to the URL. Test will crash if it fails. ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 1); } // In proc browser test is needed here because ClearLocalState indirectly calls // WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearLocalState) { ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath protected_path; FilePath unprotected_path; // Create the scope which will ensure we run the destructor of the webkit // context which should trigger the clean up. { TestingProfile profile; // Test our assumptions about what is protected and what is not. const GURL kProtectedOrigin("chrome-extension://foo/"); const GURL kUnprotectedOrigin("http://foo/"); quota::SpecialStoragePolicy* policy = profile.GetSpecialStoragePolicy(); ASSERT_TRUE(policy->IsStorageProtected(kProtectedOrigin)); ASSERT_FALSE(policy->IsStorageProtected(kUnprotectedOrigin)); // Create some indexedDB paths. // With the levelDB backend, these are directories. WebKitContext *webkit_context = profile.GetWebKitContext(); IndexedDBContext* idb_context = webkit_context->indexed_db_context(); idb_context->set_data_path_for_testing(temp_dir.path()); protected_path = idb_context->GetIndexedDBFilePath( DatabaseUtil::GetOriginIdentifier(kProtectedOrigin)); unprotected_path = idb_context->GetIndexedDBFilePath( DatabaseUtil::GetOriginIdentifier(kUnprotectedOrigin)); ASSERT_TRUE(file_util::CreateDirectory(protected_path)); ASSERT_TRUE(file_util::CreateDirectory(unprotected_path)); // Setup to clear all unprotected origins on exit. webkit_context->set_clear_local_state_on_exit(true); } // Make sure we wait until the destructor has run. scoped_refptr<base::ThreadTestHelper> helper( new base::ThreadTestHelper( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::WEBKIT))); ASSERT_TRUE(helper->Run()); ASSERT_TRUE(file_util::DirectoryExists(protected_path)); ASSERT_FALSE(file_util::DirectoryExists(unprotected_path)); } // In proc browser test is needed here because ClearLocalState indirectly calls // WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearSessionOnlyDatabases) { ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath normal_path; FilePath session_only_path; // Create the scope which will ensure we run the destructor of the webkit // context which should trigger the clean up. { TestingProfile profile; const GURL kNormalOrigin("http://normal/"); const GURL kSessionOnlyOrigin("http://session-only/"); scoped_refptr<quota::MockSpecialStoragePolicy> special_storage_policy = new quota::MockSpecialStoragePolicy; special_storage_policy->AddSessionOnly(kSessionOnlyOrigin); // Create some indexedDB paths. // With the levelDB backend, these are directories. WebKitContext *webkit_context = profile.GetWebKitContext(); IndexedDBContext* idb_context = webkit_context->indexed_db_context(); // Override the storage policy with our own. idb_context->special_storage_policy_ = special_storage_policy; idb_context->set_data_path_for_testing(temp_dir.path()); normal_path = idb_context->GetIndexedDBFilePath( DatabaseUtil::GetOriginIdentifier(kNormalOrigin)); session_only_path = idb_context->GetIndexedDBFilePath( DatabaseUtil::GetOriginIdentifier(kSessionOnlyOrigin)); ASSERT_TRUE(file_util::CreateDirectory(normal_path)); ASSERT_TRUE(file_util::CreateDirectory(session_only_path)); } // Make sure we wait until the destructor has run. scoped_refptr<base::ThreadTestHelper> helper( new base::ThreadTestHelper( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::WEBKIT))); ASSERT_TRUE(helper->Run()); EXPECT_TRUE(file_util::DirectoryExists(normal_path)); EXPECT_FALSE(file_util::DirectoryExists(session_only_path)); } class IndexedDBBrowserTestWithLowQuota : public IndexedDBBrowserTest { public: virtual void SetUpOnMainThread() { const int kInitialQuotaKilobytes = 5000; const int kTemporaryStorageQuotaMaxSize = kInitialQuotaKilobytes * 1024 * QuotaManager::kPerHostTemporaryPortion; SetTempQuota( kTemporaryStorageQuotaMaxSize, browser()->profile()->GetQuotaManager()); } static void SetTempQuota(int64 bytes, scoped_refptr<QuotaManager> qm) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&IndexedDBBrowserTestWithLowQuota::SetTempQuota, bytes, qm)); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); qm->SetTemporaryGlobalOverrideQuota(bytes, quota::QuotaCallback()); // Don't return until the quota has been set. scoped_refptr<base::ThreadTestHelper> helper( new base::ThreadTestHelper( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB))); ASSERT_TRUE(helper->Run()); } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithLowQuota, FAILS_QuotaTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("quota_test.html")))); } class IndexedDBBrowserTestWithGCExposed : public IndexedDBBrowserTest { public: virtual void SetUpCommandLine(CommandLine* command_line) { command_line->AppendSwitchASCII(switches::kJavaScriptFlags, "--expose-gc"); } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithGCExposed, DatabaseCallbacksTest) { SimpleTest( testUrl(FilePath(FILE_PATH_LITERAL("database_callbacks_first.html")))); } <|endoftext|>
<commit_before>/* * This file is part of the UnTech Editor Suite. * Copyright (c) 2016 - 2018, Marcus Rowe <undisbeliever@gmail.com>. * Distributed under The MIT License: https://opensource.org/licenses/MIT */ #include "palettecentralwidget.h" #include "paletteresourceitem.h" #include "gui-qt/resources/palette/palettecentralwidget.ui.h" using namespace UnTech::GuiQt::Resources; const QColor PaletteGraphicsItem::LINE_COLOR = QColor(200, 200, 255, 128); const QColor PaletteGraphicsItem::FRAME_LINE_COLOR = QColor(200, 100, 200, 192); PaletteCentralWidget::PaletteCentralWidget(QWidget* parent) : AbstractResourceWidget(parent) , _ui(new Ui::PaletteCentralWidget) , _graphicsScene(new QGraphicsScene(this)) , _palette(nullptr) , _graphicsItem(nullptr) { _ui->setupUi(this); _animationTimer.setRegionCombo(_ui->region); _animationTimer.setPlayButton(_ui->playButton); _ui->graphicsView->setScene(_graphicsScene); setEnabled(false); updateFrameLabel(); connect(&_animationTimer, &AnimationTimer::animationStarted, this, &PaletteCentralWidget::onAnimationStarted); connect(&_animationTimer, &AnimationTimer::animationFrameAdvance, this, &PaletteCentralWidget::onAnimationFrameAdvance); connect(&_animationTimer, &AnimationTimer::animationStopped, this, &PaletteCentralWidget::onAnimationStopped); } PaletteCentralWidget::~PaletteCentralWidget() = default; ResourceTypeIndex PaletteCentralWidget::resourceTypeIndex() const { return ResourceTypeIndex::PALETTE; } void PaletteCentralWidget::setResourceItem(AbstractResourceItem* abstractItem) { _animationTimer.stopTimer(); PaletteResourceItem* item = qobject_cast<PaletteResourceItem*>(abstractItem); if (_palette == item) { return; } if (_palette) { _palette->disconnect(this); } _palette = item; _graphicsScene->clear(); _graphicsItem = nullptr; if (_palette) { _graphicsItem = new PaletteGraphicsItem(item); _graphicsScene->addItem(_graphicsItem); onPaletteDataChanged(); updateFrameLabel(); } else { clearGui(); } setEnabled(item != nullptr); } void PaletteCentralWidget::updateFrameLabel() { if (_palette == nullptr) { clearGui(); return; } unsigned nFrames = _palette->paletteData()->nFrames(); int fIndex = _graphicsItem->frameIndex(); if (fIndex >= 0 && nFrames > 0) { _ui->animationFrameLabel->setText( tr("Frame %1").arg(fIndex % nFrames)); } else { _ui->animationFrameLabel->clear(); } } void PaletteCentralWidget::centerGraphicsItem() { Q_ASSERT(_graphicsItem); _graphicsScene->setSceneRect(_graphicsItem->boundingRect()); _ui->graphicsView->viewport()->update(); } void PaletteCentralWidget::clearGui() { _animationTimer.setEnabled(false); _ui->animationFrameLabel->clear(); } void PaletteCentralWidget::onPaletteDataChanged() { Q_ASSERT(_palette); const auto& pData = _palette->paletteData(); Q_ASSERT(pData); _animationTimer.setAnimationDelay(pData->animationDelay); _animationTimer.setEnabled(pData->nFrames() > 0); centerGraphicsItem(); } void PaletteCentralWidget::onAnimationStarted() { if (_graphicsItem) { _graphicsItem->setFrameIndex(0); centerGraphicsItem(); updateFrameLabel(); } } void PaletteCentralWidget::onAnimationFrameAdvance() { _graphicsItem->nextAnimationFrame(); updateFrameLabel(); } void PaletteCentralWidget::onAnimationStopped() { if (_graphicsItem) { _graphicsItem->setFrameIndex(-1); centerGraphicsItem(); updateFrameLabel(); } } PaletteGraphicsItem::PaletteGraphicsItem(PaletteResourceItem* item) : QGraphicsItem() , _palette(item) , _frameIndex(-1) { Q_ASSERT(_palette != nullptr); updatePixmap(); } void PaletteGraphicsItem::updatePixmap() { prepareGeometryChange(); const std::string& fn = _palette->paletteData()->paletteImageFilename; if (!fn.empty()) { _pixmap.load(QString::fromStdString(fn)); } else { _pixmap = QPixmap(); } } void PaletteGraphicsItem::setFrameIndex(int index) { if (_frameIndex != index) { update(); } if ((_frameIndex < 0 && index >= 0) || (_frameIndex >= 0 && index < 0)) { prepareGeometryChange(); } _frameIndex = index; } QRectF PaletteGraphicsItem::boundingRect() const { const auto& pal = _palette->paletteData(); unsigned w = _pixmap.width(); unsigned h = _pixmap.height(); if (_frameIndex >= 0 && pal && pal->nFrames() > 0) { h = pal->rowsPerFrame; } return QRectF(-FRAME_OVERHANG, -FRAME_LINE_WIDTH, w * PALETTE_SCALE + FRAME_OVERHANG * 2, h * PALETTE_SCALE + FRAME_LINE_WIDTH * 2); } void PaletteGraphicsItem::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) { const auto& pal = _palette->paletteData(); if (_pixmap.isNull() || pal == nullptr) { return; } // draw image unsigned w = _pixmap.width(); unsigned h = _pixmap.height(); unsigned sx = 0; unsigned sy = 0; if (_frameIndex >= 0 && pal->nFrames() > 0) { h = pal->rowsPerFrame; sy = (_frameIndex % pal->nFrames() + pal->skipFirstFrame) * pal->rowsPerFrame; } unsigned sw = w; unsigned sh = h; w *= PALETTE_SCALE; h *= PALETTE_SCALE; painter->drawPixmap(0, 0, w, h, _pixmap, sx, sy, sw, sh); // draw grid painter->save(); painter->setBrush(QBrush()); painter->setPen(QPen(LINE_COLOR, LINE_WIDTH)); painter->drawRect(-LINE_WIDTH, -LINE_WIDTH, w + LINE_WIDTH, h + LINE_WIDTH); for (unsigned x = PALETTE_SCALE; x < w; x += PALETTE_SCALE) { painter->drawLine(x, 0, x, h); } for (unsigned y = PALETTE_SCALE; y < h; y += PALETTE_SCALE) { painter->drawLine(0, y, w, y); } // draw frame rows painter->setPen(QPen(FRAME_LINE_COLOR, FRAME_LINE_WIDTH)); unsigned fh = PALETTE_SCALE * pal->rowsPerFrame; for (unsigned y = 0; y <= h; y += fh) { painter->drawLine(-FRAME_OVERHANG, y, w + FRAME_OVERHANG, y); } painter->restore(); } <commit_msg>Fix possible infinite loop in PaletteCentralWidget<commit_after>/* * This file is part of the UnTech Editor Suite. * Copyright (c) 2016 - 2018, Marcus Rowe <undisbeliever@gmail.com>. * Distributed under The MIT License: https://opensource.org/licenses/MIT */ #include "palettecentralwidget.h" #include "paletteresourceitem.h" #include "gui-qt/resources/palette/palettecentralwidget.ui.h" using namespace UnTech::GuiQt::Resources; const QColor PaletteGraphicsItem::LINE_COLOR = QColor(200, 200, 255, 128); const QColor PaletteGraphicsItem::FRAME_LINE_COLOR = QColor(200, 100, 200, 192); PaletteCentralWidget::PaletteCentralWidget(QWidget* parent) : AbstractResourceWidget(parent) , _ui(new Ui::PaletteCentralWidget) , _graphicsScene(new QGraphicsScene(this)) , _palette(nullptr) , _graphicsItem(nullptr) { _ui->setupUi(this); _animationTimer.setRegionCombo(_ui->region); _animationTimer.setPlayButton(_ui->playButton); _ui->graphicsView->setScene(_graphicsScene); setEnabled(false); updateFrameLabel(); connect(&_animationTimer, &AnimationTimer::animationStarted, this, &PaletteCentralWidget::onAnimationStarted); connect(&_animationTimer, &AnimationTimer::animationFrameAdvance, this, &PaletteCentralWidget::onAnimationFrameAdvance); connect(&_animationTimer, &AnimationTimer::animationStopped, this, &PaletteCentralWidget::onAnimationStopped); } PaletteCentralWidget::~PaletteCentralWidget() = default; ResourceTypeIndex PaletteCentralWidget::resourceTypeIndex() const { return ResourceTypeIndex::PALETTE; } void PaletteCentralWidget::setResourceItem(AbstractResourceItem* abstractItem) { _animationTimer.stopTimer(); PaletteResourceItem* item = qobject_cast<PaletteResourceItem*>(abstractItem); if (_palette == item) { return; } if (_palette) { _palette->disconnect(this); } _palette = item; _graphicsScene->clear(); _graphicsItem = nullptr; if (_palette) { _graphicsItem = new PaletteGraphicsItem(item); _graphicsScene->addItem(_graphicsItem); onPaletteDataChanged(); updateFrameLabel(); } else { clearGui(); } setEnabled(item != nullptr); } void PaletteCentralWidget::updateFrameLabel() { if (_palette == nullptr) { clearGui(); return; } unsigned nFrames = _palette->paletteData()->nFrames(); int fIndex = _graphicsItem->frameIndex(); if (fIndex >= 0 && nFrames > 0) { _ui->animationFrameLabel->setText( tr("Frame %1").arg(fIndex % nFrames)); } else { _ui->animationFrameLabel->clear(); } } void PaletteCentralWidget::centerGraphicsItem() { Q_ASSERT(_graphicsItem); _graphicsScene->setSceneRect(_graphicsItem->boundingRect()); _ui->graphicsView->viewport()->update(); } void PaletteCentralWidget::clearGui() { _animationTimer.setEnabled(false); _ui->animationFrameLabel->clear(); } void PaletteCentralWidget::onPaletteDataChanged() { Q_ASSERT(_palette); const auto& pData = _palette->paletteData(); Q_ASSERT(pData); _animationTimer.setAnimationDelay(pData->animationDelay); _animationTimer.setEnabled(pData->nFrames() > 0); centerGraphicsItem(); } void PaletteCentralWidget::onAnimationStarted() { if (_graphicsItem) { _graphicsItem->setFrameIndex(0); centerGraphicsItem(); updateFrameLabel(); } } void PaletteCentralWidget::onAnimationFrameAdvance() { _graphicsItem->nextAnimationFrame(); updateFrameLabel(); } void PaletteCentralWidget::onAnimationStopped() { if (_graphicsItem) { _graphicsItem->setFrameIndex(-1); centerGraphicsItem(); updateFrameLabel(); } } PaletteGraphicsItem::PaletteGraphicsItem(PaletteResourceItem* item) : QGraphicsItem() , _palette(item) , _frameIndex(-1) { Q_ASSERT(_palette != nullptr); updatePixmap(); } void PaletteGraphicsItem::updatePixmap() { prepareGeometryChange(); const std::string& fn = _palette->paletteData()->paletteImageFilename; if (!fn.empty()) { _pixmap.load(QString::fromStdString(fn)); } else { _pixmap = QPixmap(); } } void PaletteGraphicsItem::setFrameIndex(int index) { if (_frameIndex != index) { update(); } if ((_frameIndex < 0 && index >= 0) || (_frameIndex >= 0 && index < 0)) { prepareGeometryChange(); } _frameIndex = index; } QRectF PaletteGraphicsItem::boundingRect() const { const auto& pal = _palette->paletteData(); unsigned w = _pixmap.width(); unsigned h = _pixmap.height(); if (_frameIndex >= 0 && pal && pal->nFrames() > 0) { h = pal->rowsPerFrame; } return QRectF(-FRAME_OVERHANG, -FRAME_LINE_WIDTH, w * PALETTE_SCALE + FRAME_OVERHANG * 2, h * PALETTE_SCALE + FRAME_LINE_WIDTH * 2); } void PaletteGraphicsItem::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) { const auto& pal = _palette->paletteData(); if (_pixmap.isNull() || pal == nullptr) { return; } if (pal->rowsPerFrame <= 0) { pal->rowsPerFrame = 1; } // draw image unsigned w = _pixmap.width(); unsigned h = _pixmap.height(); unsigned sx = 0; unsigned sy = 0; if (_frameIndex >= 0 && pal->nFrames() > 0) { h = pal->rowsPerFrame; sy = (_frameIndex % pal->nFrames() + pal->skipFirstFrame) * pal->rowsPerFrame; } unsigned sw = w; unsigned sh = h; w *= PALETTE_SCALE; h *= PALETTE_SCALE; painter->drawPixmap(0, 0, w, h, _pixmap, sx, sy, sw, sh); // draw grid painter->save(); painter->setBrush(QBrush()); painter->setPen(QPen(LINE_COLOR, LINE_WIDTH)); painter->drawRect(-LINE_WIDTH, -LINE_WIDTH, w + LINE_WIDTH, h + LINE_WIDTH); Q_ASSERT(PALETTE_SCALE > 0); for (unsigned x = PALETTE_SCALE; x < w; x += PALETTE_SCALE) { painter->drawLine(x, 0, x, h); } for (unsigned y = PALETTE_SCALE; y < h; y += PALETTE_SCALE) { painter->drawLine(0, y, w, y); } // draw frame rows painter->setPen(QPen(FRAME_LINE_COLOR, FRAME_LINE_WIDTH)); unsigned fh = PALETTE_SCALE * pal->rowsPerFrame; Q_ASSERT(fh > 0); for (unsigned y = 0; y <= h; y += fh) { painter->drawLine(-FRAME_OVERHANG, y, w + FRAME_OVERHANG, y); } painter->restore(); } <|endoftext|>
<commit_before>// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2021-present David Ok <david.ok8@gmail.com> // // 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/. // ========================================================================== // //! @example #include <DO/Sara/Core/DebugUtilities.hpp> #include <DO/Sara/Core/Timer.hpp> #include <DO/Sara/Geometry.hpp> #include <DO/Sara/Visualization.hpp> #include <random> using namespace std; using namespace DO::Sara; namespace sara = DO::Sara; GRAPHICS_MAIN() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<> coord_dist(100., 300.); std::uniform_real_distribution<> radius_dist(1.0, 150.); std::uniform_real_distribution<> orientation_dist(0., 2 * M_PI); auto bad_computations = 0; auto total = 10000; for (auto i = 0; i < total; ++i) { const auto e1 = sara::Ellipse{radius_dist(gen), radius_dist(gen), orientation_dist(gen), Point2d(coord_dist(gen), coord_dist(gen))}; const auto e2 = sara::Ellipse{radius_dist(gen), radius_dist(gen), orientation_dist(gen), Point2d(coord_dist(gen), coord_dist(gen))}; const auto intersection_points = compute_intersection_points(e1, e2); const auto inter_area_analytic = sara::analytic_intersection_area(e1, e2); const auto inter_area_approx = sara::area(sara::approximate_intersection(e1, e2, 360)); const auto diff = std::abs(inter_area_analytic - inter_area_approx); const auto diff_relative = inter_area_approx < 1e-2 ? 0 : diff / inter_area_approx; const auto good = diff_relative < 1e-2; SARA_CHECK(i); SARA_CHECK(diff_relative); SARA_CHECK(inter_area_analytic); SARA_CHECK(inter_area_approx); SARA_DEBUG << (good ? "OK" : "KOOOOOOOOOOOOOO") << std::endl; #define INSPECT_VISUALLY #ifdef INSPECT_VISUALLY if (!active_window()) { create_window(400, 400); set_antialiasing(); } clear_window(); draw_ellipse(e1, Red8, 3); draw_ellipse(e2, Blue8, 3); for (const auto& p : intersection_points) fill_circle(p.cast<float>(), 3.f, Green8); if (!good) get_key(); #endif bad_computations += int(!good); } SARA_CHECK(bad_computations); SARA_CHECK(bad_computations / double(total)); return 0; }<commit_msg>WIP: save work.<commit_after>// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2021-present David Ok <david.ok8@gmail.com> // // 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/. // ========================================================================== // //! @example #include <DO/Sara/Core/DebugUtilities.hpp> #include <DO/Sara/Core/Timer.hpp> #include <DO/Sara/Geometry.hpp> #include <DO/Sara/Visualization.hpp> #include <random> using namespace std; using namespace DO::Sara; namespace sara = DO::Sara; GRAPHICS_MAIN() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<> coord_dist(100., 300.); std::uniform_real_distribution<> radius_dist(1.0, 150.); std::uniform_real_distribution<> orientation_dist(-2 * M_PI, 2 * M_PI); auto bad_computations = 0; auto total = 10000; for (auto i = 0; i < total; ++i) { const auto e1 = sara::Ellipse{radius_dist(gen), radius_dist(gen), orientation_dist(gen), Point2d(coord_dist(gen), coord_dist(gen))}; const auto e2 = sara::Ellipse{radius_dist(gen), radius_dist(gen), orientation_dist(gen), Point2d(coord_dist(gen), coord_dist(gen))}; const auto intersection_points = compute_intersection_points(e1, e2); const auto inter_area_analytic = sara::analytic_intersection_area(e1, e2); const auto inter_area_approx = sara::area(sara::approximate_intersection(e1, e2, 360)); const auto diff = std::abs(inter_area_analytic - inter_area_approx); const auto diff_relative = inter_area_approx < 1e-2 ? 0 : diff / inter_area_approx; const auto good = diff_relative < 1e-2; SARA_CHECK(i); SARA_CHECK(diff_relative); SARA_CHECK(inter_area_analytic); SARA_CHECK(inter_area_approx); SARA_DEBUG << (good ? "OK" : "KOOOOOOOOOOOOOO") << std::endl; #define INSPECT_VISUALLY #ifdef INSPECT_VISUALLY if (!active_window()) { create_window(400, 400); set_antialiasing(); } clear_window(); draw_ellipse(e1, Red8, 3); draw_ellipse(e2, Blue8, 3); for (const auto& p : intersection_points) fill_circle(p.cast<float>(), 3.f, Green8); if (!good) get_key(); #endif bad_computations += int(!good); } SARA_CHECK(bad_computations); SARA_CHECK(bad_computations / double(total)); return 0; }<|endoftext|>
<commit_before>#if !defined (__CINT__) || defined (__MAKECINT__) #include "AliAnalysisManager.h" #include "AliAnalysisTaskPtEMCalTriggerV1.h" #include "AliESDtrackCuts.h" #include "AliJetContainer.h" #include <TList.h> #include <TString.h> #include <cstring> #endif void AddClusterComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, bool usePatches); void AddTrackComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *trackcuts, bool isMC, bool usePatches, bool isSwapEta); void AddMCParticleComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group); void AddEventCounterComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, bool usePatches); void AddMCJetComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, double minJetPt); void AddRecJetComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *trackcuts, double minJetPt, bool isMC, bool usePatches, bool isSwapEta); void CreateJetPtBinning(EMCalTriggerPtAnalysis::AliAnalysisTaskPtEMCalTriggerV1 *task); EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *CreateDefaultTrackCuts(bool isAOD); EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *CreateHybridTrackCuts(bool isAOD); EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *TrackCutsFactory(const char *trackCutsName, bool isAOD); AliAnalysisTask* AddTaskPtEMCalTriggerV1( bool isMC, bool usePythiaHard, const char *period ="LHC13d", const char *ntrackContainer = "", const char *nclusterContainer = "", const char *njetcontainerData = "", const char *njetcontainerMC = "", const char *ntriggerContainer = "", double jetradius = 0.5, const char *ntrackcuts = "standard", const char *components = "particles:clusters:tracks:mcjets:recjets:triggers", bool usePatches = kFALSE, bool useOfflinePatches = kFALSE ) { //AliLog::SetClassDebugLevel("EMCalTriggerPtAnalysis::AliAnalysisTaskPtEMCalTrigger", 2); AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskPtEMCalTrigger", "No analysis manager to connect to."); return NULL; } if (!mgr->GetInputEventHandler()) { ::Error("AddTaskPtEMCalTrigger", "This task requires an input event handler"); return NULL; } bool isAOD = (mgr->GetInputEventHandler()->IsA() == AliAODInputHandler::Class()); // Decode components bool doClusters(false), doMCParticles(false), doTracks(false), doMCJets(false), doRecJets(false), doTriggers(false); TObjArray *compsplit = TString(components).Tokenize(":"); TIter tokenIter(compsplit); TObjString *compstring(NULL); while((compstring = (TObjString *)tokenIter())){ if(!compstring->String().CompareTo("clusters")) doClusters = true; if(!compstring->String().CompareTo("particles")) doMCParticles = true; if(!compstring->String().CompareTo("tracks")) doTracks = true; if(!compstring->String().CompareTo("mcjets")) doMCJets = true; if(!compstring->String().CompareTo("recjets")) doRecJets = true; if(!compstring->String().CompareTo("triggers")) doTriggers = true; } std::cout << "Track task configuration:" << std::endl; std::cout << "==================================" << std::endl; std::cout << "Monte-Carlo particles: " << (doMCParticles ? "ON" : "OFF") << std::endl; std::cout << "Monte-Carlo jets: " << (doMCJets ? "ON" : "OFF") << std::endl; std::cout << "Trigger Patch QA: " << (doTriggers ? "ON" : "OFF") << std::endl; std::cout << "Tracks: " << (doTracks ? "ON" : "OFF") << std::endl; std::cout << "EMCAL clusters: " << (doClusters ? "ON" : "OFF") << std::endl; std::cout << "Reconstructed jets: " << (doRecJets ? "ON" : "OFF") << std::endl; bool isSwapEta = TString(period).CompareTo("LHC13f") ? kFALSE : kTRUE; EMCalTriggerPtAnalysis::AliAnalysisTaskPtEMCalTriggerV1 *pttriggertask = new EMCalTriggerPtAnalysis::AliAnalysisTaskPtEMCalTriggerV1(Form("ptemcaltriggertask%s", ntrackcuts)); //pttriggertask->SelectCollisionCandidates(AliVEvent::kINT7 | AliVEvent::kEMC7); // Select both INT7 or EMC7 triggered events pttriggertask->SelectCollisionCandidates(AliVEvent::kAny); EMCalTriggerPtAnalysis::AliEMCalTriggerAnaTriggerDecisionConfig *trgconf = new EMCalTriggerPtAnalysis::AliEMCalTriggerAnaTriggerDecisionConfig; if(isMC) trgconf->SetSwapThresholds(); trgconf->SetUseOfflinePatches(useOfflinePatches); pttriggertask->SetTriggerDecisionConfig(trgconf); CreateJetPtBinning(pttriggertask); //pttriggertask->SetTriggerDebug(kTRUE); mgr->AddTask(pttriggertask); if(usePythiaHard){ pttriggertask->SetIsPythia(kTRUE); } if(strlen(ntriggerContainer)){ pttriggertask->SetCaloTriggerPatchInfoName(ntriggerContainer); } // Add components if(doTriggers){ EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *noselect = new EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup("noselect"); noselect->AddAnalysisComponent(new EMCalTriggerPtAnalysis::AliEMCalTriggerPatchAnalysisComponent("patchanalysis")); pttriggertask->AddAnalysisGroup(noselect); } double jetpt[4] = {40., 60., 80., 100.}; EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *defaultselect = new EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup("defaultselect"); defaultselect->SetEventSelection(new EMCalTriggerPtAnalysis::AliEMCalTriggerEventSelection()); EMCalTriggerPtAnalysis::AliEMCalTriggerKineCuts *kineCuts = new EMCalTriggerPtAnalysis::AliEMCalTriggerKineCuts(); kineCuts->SetPtRange(2., 100.); defaultselect->SetKineCuts(kineCuts); AddEventCounterComponent(defaultselect, isMC); if(isMC){ if(doMCParticles) AddMCParticleComponent(defaultselect); if(doMCJets) AddMCJetComponent(defaultselect, 20.); /* for(int ijpt = 0; ijpt < 4; ijpt++) AddMCJetComponent(defaultselect, jetpt[ijpt]); */ } if(doClusters) AddClusterComponent(defaultselect, usePatches); if(doTracks) AddTrackComponent(defaultselect, TrackCutsFactory(ntrackcuts, isAOD), isMC, usePatches, isSwapEta); if(doRecJets) AddRecJetComponent(defaultselect, TrackCutsFactory(ntrackcuts, isAOD), 20., isMC, usePatches, isSwapEta); /* * for(int ijpt = 0; ijpt < 4; ijpt++) AddRecJetComponent(defaultselect, TrackCutsFactory(ntrackcuts), jetpt[ijpt], isMC, isSwapEta); */ pttriggertask->AddAnalysisGroup(defaultselect); // Add containers Bool_t isAOD = mgr->GetInputEventHandler()->IsA() == AliAODInputHandler::Class(); AliParticleContainer *trackContainer = pttriggertask->AddParticleContainer(ntrackContainer); //trackContainer->SetClassName("AliVTrack"); AliClusterContainer *clusterContainer = pttriggertask->AddClusterContainer(nclusterContainer); AliParticleContainer *mcpartcont = isMC ? pttriggertask->AddParticleContainer("MCParticlesSelected") : NULL; // Handle Jet Containers if(strlen(njetcontainerData)){ AliJetContainer *jetcontainerData = pttriggertask->AddJetContainer(njetcontainerData, "EMCAL", jetradius); pttriggertask->SetDataJetContainerName("PtTriggerTaskJetsData"); jetcontainerData->ConnectParticleContainer(trackContainer); jetcontainerData->SetName("PtTriggerTaskJetsData"); jetcontainerData->SetJetPtCut(20.); printf("jet container added for Data\n"); } if(isMC && strlen(njetcontainerMC)){ AliJetContainer *jetcontainerMC = pttriggertask->AddJetContainer(njetcontainerMC, "EMCAL", jetradius); pttriggertask->SetMCJetContainerName("PtTriggerTaskJetsMC"); jetcontainerMC->ConnectParticleContainer(mcpartcont); jetcontainerMC->SetName("PtTriggerTaskJetsMC"); jetcontainerMC->SetJetPtCut(20.); printf("Jet container added for MC"); } TString containerName = mgr->GetCommonFileName(); containerName += ":PtEMCalTriggerTask" + TString(ntrackcuts); printf("container name: %s\n", containerName.Data()); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *coutput = mgr->CreateContainer(Form("TriggerTracksResults%s", ntrackcuts), TList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); //Connect input/output mgr->ConnectInput(pttriggertask, 0, cinput); mgr->ConnectOutput(pttriggertask, 1, coutput); return pttriggertask; } void AddClusterComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, bool usePatches){ EMCalTriggerPtAnalysis::AliEMCalTriggerClusterAnalysisComponent *clusteranalysis = new EMCalTriggerPtAnalysis::AliEMCalTriggerClusterAnalysisComponent("clusterAnalysis"); clusteranalysis->SetEnergyRange(2., 100.); clusteranalysis->SetUsePatches(usePatches); group->AddAnalysisComponent(clusteranalysis); } void AddTrackComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection * trackcuts, bool isMC, bool usePatches, bool isSwapEta){ EMCalTriggerPtAnalysis::AliEMCalTriggerRecTrackAnalysisComponent *trackanalysis = new EMCalTriggerPtAnalysis::AliEMCalTriggerRecTrackAnalysisComponent("trackAnalysisStandard"); group->AddAnalysisComponent(trackanalysis); // Create charged hadrons pPb standard track cuts trackanalysis->SetTrackSelection(trackcuts); if(isMC) trackanalysis->SetRequestMCtrueTracks(); if(usePatches) trackanalysis->SetUsePatches(); if(isSwapEta) trackanalysis->SetSwapEta(); } void AddEventCounterComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, Bool_t usePatches){ EMCalTriggerPtAnalysis::AliEMCalTriggerEventCounterAnalysisComponent * evcount = new EMCalTriggerPtAnalysis::AliEMCalTriggerEventCounterAnalysisComponent("eventCounter"); evcount->SetUsePatches(usePatches); group->AddAnalysisComponent(evcount); } void AddMCParticleComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group){ group->AddAnalysisComponent(new EMCalTriggerPtAnalysis::AliEMCalTriggerMCParticleAnalysisComponent("partana")); } void AddMCJetComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, double minJetPt){ EMCalTriggerPtAnalysis::AliEMCalTriggerMCJetAnalysisComponent *jetana = new EMCalTriggerPtAnalysis::AliEMCalTriggerMCJetAnalysisComponent(Form("MCJetAna%f", minJetPt)); jetana->SetMinimumJetPt(minJetPt); jetana->SetUsePatches(); group->AddAnalysisComponent(jetana); } void AddRecJetComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *trackcuts, double minJetPt, bool isMC, bool usePatches, bool isSwapEta){ EMCalTriggerPtAnalysis::AliEMCalTriggerRecJetAnalysisComponent *jetana = new EMCalTriggerPtAnalysis::AliEMCalTriggerRecJetAnalysisComponent(Form("RecJetAna%f", minJetPt)); jetana->SetMinimumJetPt(minJetPt); jetana->SetUsePatches(usePatches); jetana->SetSingleTrackCuts(trackcuts); //jetana->SetComponentDebugLevel(2); group->AddAnalysisComponent(jetana); } void CreateJetPtBinning(EMCalTriggerPtAnalysis::AliAnalysisTaskPtEMCalTriggerV1 *task){ // Linear binning in steps of 10 GeV/c up to 200 GeV/c TArrayD binlimits(21); for(int i = 0; i < 21; i++) binlimits[i] = 10.*i; task->SetBinning("jetpt", binlimits); } EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *CreateDefaultTrackCuts(bool isAOD){ EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection * trackSelection(NULL); if(isAOD){ EMCalTriggerPtAnalysis::AliEMCalPtTaskTrackSelectionAOD *aodsel = new EMCalTriggerPtAnalysis::AliEMCalPtTaskTrackSelectionAOD(); aodsel->AddFilterBit(AliAODTrack::kTrkGlobal); trackSelection = aodsel; } else { AliESDtrackCuts *standardTrackCuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(true, 1); standardTrackCuts->SetName("Standard Track cuts"); standardTrackCuts->SetMinNCrossedRowsTPC(120); standardTrackCuts->SetMaxDCAToVertexXYPtDep("0.0182+0.0350/pt^1.01"); trackSelection = new EMCalTriggerPtAnalysis::AliEMCalPtTaskTrackSelectionESD(standardTrackCuts); } return trackSelection; } EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *CreateHybridTrackCuts(bool isAOD){ EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection * trackSelection(NULL); if(isAOD){ // Purely use filter bits EMCalTriggerPtAnalysis::AliEMCalPtTaskTrackSelectionAOD *aodsel = new EMCalTriggerPtAnalysis::AliEMCalPtTaskTrackSelectionAOD(NULL); aodsel->AddFilterBit(256); aodsel->AddFilterBit(512); trackSelection = aodsel; } else { AliESDtrackCuts* hybridTrackCuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kFALSE); hybridTrackCuts->SetName("Global Hybrid tracks, loose DCA"); hybridTrackCuts->SetMaxDCAToVertexXY(2.4); hybridTrackCuts->SetMaxDCAToVertexZ(3.2); hybridTrackCuts->SetDCAToVertex2D(kTRUE); hybridTrackCuts->SetMaxChi2TPCConstrainedGlobal(36); hybridTrackCuts->SetMaxFractionSharedTPCClusters(0.4); trackSelection = new EMCalTriggerPtAnalysis::AliEMCalPtTaskTrackSelectionESD(hybridTrackCuts); } return trackSelection; } EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *TrackCutsFactory(const char* trackCutsName, bool isAOD) { if(!strcmp(trackCutsName, "standard")) return CreateDefaultTrackCuts(isAOD); else if(!strcmp(trackCutsName, "hybrid")) return CreateHybridTrackCuts(isAOD); return NULL; } <commit_msg>Fix selection of trigger patches in event counting<commit_after>#if !defined (__CINT__) || defined (__MAKECINT__) #include "AliAnalysisManager.h" #include "AliAnalysisTaskPtEMCalTriggerV1.h" #include "AliESDtrackCuts.h" #include "AliJetContainer.h" #include <TList.h> #include <TString.h> #include <cstring> #endif void AddClusterComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, bool usePatches); void AddTrackComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *trackcuts, bool isMC, bool usePatches, bool isSwapEta); void AddMCParticleComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group); void AddEventCounterComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, bool usePatches); void AddMCJetComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, double minJetPt); void AddRecJetComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *trackcuts, double minJetPt, bool isMC, bool usePatches, bool isSwapEta); void CreateJetPtBinning(EMCalTriggerPtAnalysis::AliAnalysisTaskPtEMCalTriggerV1 *task); EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *CreateDefaultTrackCuts(bool isAOD); EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *CreateHybridTrackCuts(bool isAOD); EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *TrackCutsFactory(const char *trackCutsName, bool isAOD); AliAnalysisTask* AddTaskPtEMCalTriggerV1( bool isMC, bool usePythiaHard, const char *period ="LHC13d", const char *ntrackContainer = "", const char *nclusterContainer = "", const char *njetcontainerData = "", const char *njetcontainerMC = "", const char *ntriggerContainer = "", double jetradius = 0.5, const char *ntrackcuts = "standard", const char *components = "particles:clusters:tracks:mcjets:recjets:triggers", bool usePatches = kFALSE, bool useOfflinePatches = kFALSE ) { //AliLog::SetClassDebugLevel("EMCalTriggerPtAnalysis::AliAnalysisTaskPtEMCalTrigger", 2); AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskPtEMCalTrigger", "No analysis manager to connect to."); return NULL; } if (!mgr->GetInputEventHandler()) { ::Error("AddTaskPtEMCalTrigger", "This task requires an input event handler"); return NULL; } bool isAOD = (mgr->GetInputEventHandler()->IsA() == AliAODInputHandler::Class()); // Decode components bool doClusters(false), doMCParticles(false), doTracks(false), doMCJets(false), doRecJets(false), doTriggers(false); TObjArray *compsplit = TString(components).Tokenize(":"); TIter tokenIter(compsplit); TObjString *compstring(NULL); while((compstring = (TObjString *)tokenIter())){ if(!compstring->String().CompareTo("clusters")) doClusters = true; if(!compstring->String().CompareTo("particles")) doMCParticles = true; if(!compstring->String().CompareTo("tracks")) doTracks = true; if(!compstring->String().CompareTo("mcjets")) doMCJets = true; if(!compstring->String().CompareTo("recjets")) doRecJets = true; if(!compstring->String().CompareTo("triggers")) doTriggers = true; } std::cout << "Track task configuration:" << std::endl; std::cout << "==================================" << std::endl; std::cout << "Monte-Carlo particles: " << (doMCParticles ? "ON" : "OFF") << std::endl; std::cout << "Monte-Carlo jets: " << (doMCJets ? "ON" : "OFF") << std::endl; std::cout << "Trigger Patch QA: " << (doTriggers ? "ON" : "OFF") << std::endl; std::cout << "Tracks: " << (doTracks ? "ON" : "OFF") << std::endl; std::cout << "EMCAL clusters: " << (doClusters ? "ON" : "OFF") << std::endl; std::cout << "Reconstructed jets: " << (doRecJets ? "ON" : "OFF") << std::endl; bool isSwapEta = TString(period).CompareTo("LHC13f") ? kFALSE : kTRUE; EMCalTriggerPtAnalysis::AliAnalysisTaskPtEMCalTriggerV1 *pttriggertask = new EMCalTriggerPtAnalysis::AliAnalysisTaskPtEMCalTriggerV1(Form("ptemcaltriggertask%s", ntrackcuts)); //pttriggertask->SelectCollisionCandidates(AliVEvent::kINT7 | AliVEvent::kEMC7); // Select both INT7 or EMC7 triggered events pttriggertask->SelectCollisionCandidates(AliVEvent::kAny); EMCalTriggerPtAnalysis::AliEMCalTriggerAnaTriggerDecisionConfig *trgconf = new EMCalTriggerPtAnalysis::AliEMCalTriggerAnaTriggerDecisionConfig; if(isMC) trgconf->SetSwapThresholds(); trgconf->SetUseOfflinePatches(useOfflinePatches); pttriggertask->SetTriggerDecisionConfig(trgconf); CreateJetPtBinning(pttriggertask); //pttriggertask->SetTriggerDebug(kTRUE); mgr->AddTask(pttriggertask); if(usePythiaHard){ pttriggertask->SetIsPythia(kTRUE); } if(strlen(ntriggerContainer)){ pttriggertask->SetCaloTriggerPatchInfoName(ntriggerContainer); } // Add components if(doTriggers){ EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *noselect = new EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup("noselect"); noselect->AddAnalysisComponent(new EMCalTriggerPtAnalysis::AliEMCalTriggerPatchAnalysisComponent("patchanalysis")); pttriggertask->AddAnalysisGroup(noselect); } double jetpt[4] = {40., 60., 80., 100.}; EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *defaultselect = new EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup("defaultselect"); defaultselect->SetEventSelection(new EMCalTriggerPtAnalysis::AliEMCalTriggerEventSelection()); EMCalTriggerPtAnalysis::AliEMCalTriggerKineCuts *kineCuts = new EMCalTriggerPtAnalysis::AliEMCalTriggerKineCuts(); kineCuts->SetPtRange(2., 100.); defaultselect->SetKineCuts(kineCuts); AddEventCounterComponent(defaultselect, usePatches); if(isMC){ if(doMCParticles) AddMCParticleComponent(defaultselect); if(doMCJets) AddMCJetComponent(defaultselect, 20.); /* for(int ijpt = 0; ijpt < 4; ijpt++) AddMCJetComponent(defaultselect, jetpt[ijpt]); */ } if(doClusters) AddClusterComponent(defaultselect, usePatches); if(doTracks) AddTrackComponent(defaultselect, TrackCutsFactory(ntrackcuts, isAOD), isMC, usePatches, isSwapEta); if(doRecJets) AddRecJetComponent(defaultselect, TrackCutsFactory(ntrackcuts, isAOD), 20., isMC, usePatches, isSwapEta); /* * for(int ijpt = 0; ijpt < 4; ijpt++) AddRecJetComponent(defaultselect, TrackCutsFactory(ntrackcuts), jetpt[ijpt], isMC, isSwapEta); */ pttriggertask->AddAnalysisGroup(defaultselect); // Add containers Bool_t isAOD = mgr->GetInputEventHandler()->IsA() == AliAODInputHandler::Class(); AliParticleContainer *trackContainer = pttriggertask->AddParticleContainer(ntrackContainer); //trackContainer->SetClassName("AliVTrack"); AliClusterContainer *clusterContainer = pttriggertask->AddClusterContainer(nclusterContainer); AliParticleContainer *mcpartcont = isMC ? pttriggertask->AddParticleContainer("MCParticlesSelected") : NULL; // Handle Jet Containers if(strlen(njetcontainerData)){ AliJetContainer *jetcontainerData = pttriggertask->AddJetContainer(njetcontainerData, "EMCAL", jetradius); pttriggertask->SetDataJetContainerName("PtTriggerTaskJetsData"); jetcontainerData->ConnectParticleContainer(trackContainer); jetcontainerData->SetName("PtTriggerTaskJetsData"); jetcontainerData->SetJetPtCut(20.); printf("jet container added for Data\n"); } if(isMC && strlen(njetcontainerMC)){ AliJetContainer *jetcontainerMC = pttriggertask->AddJetContainer(njetcontainerMC, "EMCAL", jetradius); pttriggertask->SetMCJetContainerName("PtTriggerTaskJetsMC"); jetcontainerMC->ConnectParticleContainer(mcpartcont); jetcontainerMC->SetName("PtTriggerTaskJetsMC"); jetcontainerMC->SetJetPtCut(20.); printf("Jet container added for MC"); } TString containerName = mgr->GetCommonFileName(); containerName += ":PtEMCalTriggerTask" + TString(ntrackcuts); printf("container name: %s\n", containerName.Data()); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *coutput = mgr->CreateContainer(Form("TriggerTracksResults%s", ntrackcuts), TList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); //Connect input/output mgr->ConnectInput(pttriggertask, 0, cinput); mgr->ConnectOutput(pttriggertask, 1, coutput); return pttriggertask; } void AddClusterComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, bool usePatches){ EMCalTriggerPtAnalysis::AliEMCalTriggerClusterAnalysisComponent *clusteranalysis = new EMCalTriggerPtAnalysis::AliEMCalTriggerClusterAnalysisComponent("clusterAnalysis"); clusteranalysis->SetEnergyRange(2., 100.); clusteranalysis->SetUsePatches(usePatches); group->AddAnalysisComponent(clusteranalysis); } void AddTrackComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection * trackcuts, bool isMC, bool usePatches, bool isSwapEta){ EMCalTriggerPtAnalysis::AliEMCalTriggerRecTrackAnalysisComponent *trackanalysis = new EMCalTriggerPtAnalysis::AliEMCalTriggerRecTrackAnalysisComponent("trackAnalysisStandard"); group->AddAnalysisComponent(trackanalysis); // Create charged hadrons pPb standard track cuts trackanalysis->SetTrackSelection(trackcuts); if(isMC) trackanalysis->SetRequestMCtrueTracks(); if(usePatches) trackanalysis->SetUsePatches(); if(isSwapEta) trackanalysis->SetSwapEta(); } void AddEventCounterComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, Bool_t usePatches){ EMCalTriggerPtAnalysis::AliEMCalTriggerEventCounterAnalysisComponent * evcount = new EMCalTriggerPtAnalysis::AliEMCalTriggerEventCounterAnalysisComponent("eventCounter"); evcount->SetUsePatches(usePatches); group->AddAnalysisComponent(evcount); } void AddMCParticleComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group){ group->AddAnalysisComponent(new EMCalTriggerPtAnalysis::AliEMCalTriggerMCParticleAnalysisComponent("partana")); } void AddMCJetComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, double minJetPt){ EMCalTriggerPtAnalysis::AliEMCalTriggerMCJetAnalysisComponent *jetana = new EMCalTriggerPtAnalysis::AliEMCalTriggerMCJetAnalysisComponent(Form("MCJetAna%f", minJetPt)); jetana->SetMinimumJetPt(minJetPt); jetana->SetUsePatches(); group->AddAnalysisComponent(jetana); } void AddRecJetComponent(EMCalTriggerPtAnalysis::AliEMCalTriggerTaskGroup *group, EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *trackcuts, double minJetPt, bool isMC, bool usePatches, bool isSwapEta){ EMCalTriggerPtAnalysis::AliEMCalTriggerRecJetAnalysisComponent *jetana = new EMCalTriggerPtAnalysis::AliEMCalTriggerRecJetAnalysisComponent(Form("RecJetAna%f", minJetPt)); jetana->SetMinimumJetPt(minJetPt); jetana->SetUsePatches(usePatches); jetana->SetSingleTrackCuts(trackcuts); //jetana->SetComponentDebugLevel(2); group->AddAnalysisComponent(jetana); } void CreateJetPtBinning(EMCalTriggerPtAnalysis::AliAnalysisTaskPtEMCalTriggerV1 *task){ // Linear binning in steps of 10 GeV/c up to 200 GeV/c TArrayD binlimits(21); for(int i = 0; i < 21; i++) binlimits[i] = 10.*i; task->SetBinning("jetpt", binlimits); } EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *CreateDefaultTrackCuts(bool isAOD){ EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection * trackSelection(NULL); if(isAOD){ EMCalTriggerPtAnalysis::AliEMCalPtTaskTrackSelectionAOD *aodsel = new EMCalTriggerPtAnalysis::AliEMCalPtTaskTrackSelectionAOD(); aodsel->AddFilterBit(AliAODTrack::kTrkGlobal); trackSelection = aodsel; } else { AliESDtrackCuts *standardTrackCuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(true, 1); standardTrackCuts->SetName("Standard Track cuts"); standardTrackCuts->SetMinNCrossedRowsTPC(120); standardTrackCuts->SetMaxDCAToVertexXYPtDep("0.0182+0.0350/pt^1.01"); trackSelection = new EMCalTriggerPtAnalysis::AliEMCalPtTaskTrackSelectionESD(standardTrackCuts); } return trackSelection; } EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *CreateHybridTrackCuts(bool isAOD){ EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection * trackSelection(NULL); if(isAOD){ // Purely use filter bits EMCalTriggerPtAnalysis::AliEMCalPtTaskTrackSelectionAOD *aodsel = new EMCalTriggerPtAnalysis::AliEMCalPtTaskTrackSelectionAOD(NULL); aodsel->AddFilterBit(256); aodsel->AddFilterBit(512); trackSelection = aodsel; } else { AliESDtrackCuts* hybridTrackCuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kFALSE); hybridTrackCuts->SetName("Global Hybrid tracks, loose DCA"); hybridTrackCuts->SetMaxDCAToVertexXY(2.4); hybridTrackCuts->SetMaxDCAToVertexZ(3.2); hybridTrackCuts->SetDCAToVertex2D(kTRUE); hybridTrackCuts->SetMaxChi2TPCConstrainedGlobal(36); hybridTrackCuts->SetMaxFractionSharedTPCClusters(0.4); trackSelection = new EMCalTriggerPtAnalysis::AliEMCalPtTaskTrackSelectionESD(hybridTrackCuts); } return trackSelection; } EMCalTriggerPtAnalysis::AliEMCalPtTaskVTrackSelection *TrackCutsFactory(const char* trackCutsName, bool isAOD) { if(!strcmp(trackCutsName, "standard")) return CreateDefaultTrackCuts(isAOD); else if(!strcmp(trackCutsName, "hybrid")) return CreateHybridTrackCuts(isAOD); return NULL; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestAxisActor3D.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkSphereSource.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkAxisActor.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkCamera.h" #include "vtkStringArray.h" #include "vtkSmartPointer.h" #include "vtkTestUtilities.h" //---------------------------------------------------------------------------- int TestAxisActor3D( int argc, char * argv [] ) { // Create the axis actor vtkSmartPointer<vtkAxisActor> axis = vtkSmartPointer<vtkAxisActor>::New(); axis->SetPoint1(0,0,0); axis->SetPoint2(1,1,0); axis->SetBounds(0,1,0,0,0,0); axis->SetTickLocationToBoth(); axis->SetAxisTypeToX(); axis->SetTitle("1.0"); axis->SetTitleScale(0.5); axis->SetTitleVisibility(1); axis->SetMajorTickSize(0.01); axis->SetRange(0,1); vtkSmartPointer<vtkStringArray> labels = vtkSmartPointer<vtkStringArray>::New(); labels->SetNumberOfTuples(1); labels->SetValue(0,"X"); axis->SetLabels(labels); axis->SetLabelScale(.2); axis->MinorTicksVisibleOff(); axis->SetDeltaMajor(0,.1); axis->SetCalculateTitleOffset(0); axis->SetCalculateLabelOffset(0); axis->Print(std::cout); vtkSmartPointer<vtkSphereSource> source = vtkSmartPointer<vtkSphereSource>::New(); source->SetCenter(1,1,1); vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputConnection(source->GetOutputPort()); vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New(); actor->SetMapper(mapper); // Create the RenderWindow, Renderer and both Actors vtkSmartPointer<vtkRenderer> ren1 = vtkRenderer::New(); vtkSmartPointer<vtkRenderWindow> renWin = vtkRenderWindow::New(); renWin->AddRenderer(ren1); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); axis->SetCamera(ren1->GetActiveCamera()); ren1->AddActor(actor); ren1->AddActor(axis); ren1->SetBackground(.3, .4, .5); renWin->SetSize(500,200); ren1->ResetCamera(); ren1->ResetCameraClippingRange(); // render the image iren->Initialize(); renWin->Render(); iren->Start(); return EXIT_SUCCESS; } <commit_msg>fix unused parameter warning<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestAxisActor3D.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkSphereSource.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkAxisActor.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkCamera.h" #include "vtkStringArray.h" #include "vtkSmartPointer.h" #include "vtkTestUtilities.h" //---------------------------------------------------------------------------- int TestAxisActor3D( int vtkNotUsed(argc), char * vtkNotUsed(argv) [] ) { // Create the axis actor vtkSmartPointer<vtkAxisActor> axis = vtkSmartPointer<vtkAxisActor>::New(); axis->SetPoint1(0,0,0); axis->SetPoint2(1,1,0); axis->SetBounds(0,1,0,0,0,0); axis->SetTickLocationToBoth(); axis->SetAxisTypeToX(); axis->SetTitle("1.0"); axis->SetTitleScale(0.5); axis->SetTitleVisibility(1); axis->SetMajorTickSize(0.01); axis->SetRange(0,1); vtkSmartPointer<vtkStringArray> labels = vtkSmartPointer<vtkStringArray>::New(); labels->SetNumberOfTuples(1); labels->SetValue(0,"X"); axis->SetLabels(labels); axis->SetLabelScale(.2); axis->MinorTicksVisibleOff(); axis->SetDeltaMajor(0,.1); axis->SetCalculateTitleOffset(0); axis->SetCalculateLabelOffset(0); axis->Print(std::cout); vtkSmartPointer<vtkSphereSource> source = vtkSmartPointer<vtkSphereSource>::New(); source->SetCenter(1,1,1); vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputConnection(source->GetOutputPort()); vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New(); actor->SetMapper(mapper); // Create the RenderWindow, Renderer and both Actors vtkSmartPointer<vtkRenderer> ren1 = vtkRenderer::New(); vtkSmartPointer<vtkRenderWindow> renWin = vtkRenderWindow::New(); renWin->AddRenderer(ren1); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); axis->SetCamera(ren1->GetActiveCamera()); ren1->AddActor(actor); ren1->AddActor(axis); ren1->SetBackground(.3, .4, .5); renWin->SetSize(500,200); ren1->ResetCamera(); ren1->ResetCameraClippingRange(); // render the image iren->Initialize(); renWin->Render(); iren->Start(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkImageFileWriterStreamingTest1.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif #include <fstream> #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkPipelineMonitorImageFilter.h" int itkImageFileWriterStreamingTest1(int argc, char* argv[]) { if( argc < 3 ) { std::cerr << "Usage: " << argv[0] << " input output [existingFile [ no-streaming 1|0] ]" << std::endl; return EXIT_FAILURE; } // We remove the output file if (argc == 3) { itksys::SystemTools::RemoveFile(argv[2]); } else { // copy this file to over write itksys::SystemTools::CopyAFile(argv[3], argv[2]); } // By default we decide to use 4 pieces, but this value can // be changed from the command line. unsigned int numberOfDataPieces = 4; if( argc > 3 ) { numberOfDataPieces = atoi( argv[3] ); } bool forceNoStreamingInput = false; if (argc > 4) { if (atoi(argv[4]) == 1) forceNoStreamingInput = true; } typedef unsigned char PixelType; typedef itk::Image<PixelType,3> ImageType; typedef itk::ImageFileReader<ImageType> ReaderType; typedef itk::ImageFileWriter< ImageType > WriterType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); reader->SetUseStreaming( true ); typedef itk::PipelineMonitorImageFilter<ImageType> MonitorFilter; MonitorFilter::Pointer monitor = MonitorFilter::New(); monitor->SetInput(reader->GetOutput()); // if (forceNoStreamingInput) // monitor->UpdateLargestPossibleRegion(); // Setup the writer WriterType::Pointer writer = WriterType::New(); writer->SetFileName(argv[2]); writer->SetInput(monitor->GetOutput()); writer->SetNumberOfStreamDivisions(numberOfDataPieces); try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } //check that the pipeline executed as expected if (!forceNoStreamingInput && monitor->GetNumberOfUpdates() <= 1) { std::cerr << "pipeline did not execute as expected" << std::endl; std::cerr << monitor; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>BUG: corrected issues with command line arguments causing tests to fail<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkImageFileWriterStreamingTest1.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif #include <fstream> #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkPipelineMonitorImageFilter.h" int itkImageFileWriterStreamingTest1(int argc, char* argv[]) { if( argc < 3 ) { std::cerr << "Usage: " << argv[0] << " input output [existingFile [ no-streaming 1|0] ]" << std::endl; return EXIT_FAILURE; } // We remove the output file if (argc == 3) { itksys::SystemTools::RemoveFile(argv[2]); } else { // copy this file to over write itksys::SystemTools::CopyAFile(argv[3], argv[2]); } unsigned int numberOfDataPieces = 4; bool forceNoStreamingInput = false; if (argc > 4) { if (atoi(argv[4]) == 1) forceNoStreamingInput = true; } typedef unsigned char PixelType; typedef itk::Image<PixelType,3> ImageType; typedef itk::ImageFileReader<ImageType> ReaderType; typedef itk::ImageFileWriter< ImageType > WriterType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); reader->SetUseStreaming( true ); typedef itk::PipelineMonitorImageFilter<ImageType> MonitorFilter; MonitorFilter::Pointer monitor = MonitorFilter::New(); monitor->SetInput(reader->GetOutput()); if (forceNoStreamingInput) monitor->UpdateLargestPossibleRegion(); // Setup the writer WriterType::Pointer writer = WriterType::New(); writer->SetFileName(argv[2]); writer->SetInput(monitor->GetOutput()); writer->SetNumberOfStreamDivisions(numberOfDataPieces); try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } //check that the pipeline executed as expected if (!forceNoStreamingInput && monitor->GetNumberOfUpdates() <= 1) { std::cerr << "pipeline did not execute as expected" << std::endl; std::cerr << monitor; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkExhaustiveOptimizerTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkExhaustiveOptimizer.h" #include <vnl/vnl_math.h> /** * The objectif function is the quadratic form: * * 1/2 x^T A x - b^T x * * Where A is a matrix and b is a vector * The system in this example is: * * | 3 2 ||x| | 2| |0| * | 2 6 ||y| + |-8| = |0| * * * the solution is the vector | 2 -2 | * */ class RSGCostFunction : public itk::SingleValuedCostFunction { public: typedef RSGCostFunction Self; typedef itk::SingleValuedCostFunction Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; itkNewMacro( Self ); enum { SpaceDimension=2 }; typedef Superclass::ParametersType ParametersType; typedef Superclass::DerivativeType DerivativeType; typedef Superclass::MeasureType MeasureType ; RSGCostFunction() { } MeasureType GetValue( const ParametersType & parameters ) const { double x = parameters[0]; double y = parameters[1]; std::cout << "GetValue( " ; std::cout << x << " "; std::cout << y << ") = "; MeasureType measure = 0.5*(3*x*x+4*x*y+6*y*y) - 2*x + 8*y; std::cout << measure << std::endl; return measure; } void GetDerivative( const ParametersType & parameters, DerivativeType & derivative ) const { double x = parameters[0]; double y = parameters[1]; std::cout << "GetDerivative( " ; std::cout << x << " "; std::cout << y << ") = "; derivative = DerivativeType( SpaceDimension ); derivative[0] = 3 * x + 2 * y -2; derivative[1] = 2 * x + 6 * y +8; } unsigned int GetNumberOfParameters(void) const { return SpaceDimension; } private: }; int itkExhaustiveOptimizerTest(int, char* [] ) { std::cout << "ExhaustiveOptimizer Test "; std::cout << std::endl << std::endl; typedef itk::ExhaustiveOptimizer OptimizerType; typedef OptimizerType::ScalesType ScalesType; // Declaration of a itkOptimizer OptimizerType::Pointer itkOptimizer = OptimizerType::New(); // Declaration of the CostFunction RSGCostFunction::Pointer costFunction = RSGCostFunction::New(); itkOptimizer->SetCostFunction( costFunction.GetPointer() ); typedef RSGCostFunction::ParametersType ParametersType; const unsigned int spaceDimension = costFunction->GetNumberOfParameters(); // We start not so far from | 2 -2 | ParametersType initialPosition( spaceDimension ); initialPosition[0] = 100; initialPosition[1] = -100; ScalesType parametersScale( spaceDimension ); parametersScale[0] = 1.0; parametersScale[1] = 1.0; itkOptimizer->SetScales( parametersScale ); try { itkOptimizer->StartOptimization(); } catch( itk::ExceptionObject & e ) { std::cout << "Exception thrown ! " << std::endl; std::cout << "An error ocurred during Optimization" << std::endl; std::cout << "Location = " << e.GetLocation() << std::endl; std::cout << "Description = " << e.GetDescription() << std::endl; return EXIT_FAILURE; } ParametersType finalPosition = itkOptimizer->GetCurrentPosition(); std::cout << "Solution = ("; std::cout << finalPosition[0] << "," ; std::cout << finalPosition[1] << ")" << std::endl; // // check results to see if it is within range // bool pass = true; double trueParameters[2] = { 2, -2 }; for( unsigned int j = 0; j < 2; j++ ) { if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 ) { pass = false; } } if( !pass ) { std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; } <commit_msg>BUG: it was missing to setup initial position and then to recover min and maximum values and positions.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkExhaustiveOptimizerTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkExhaustiveOptimizer.h" #include <vnl/vnl_math.h> /** * The objectif function is the quadratic form: * * 1/2 x^T A x - b^T x * * Where A is a matrix and b is a vector * The system in this example is: * * | 3 2 ||x| | 2| |0| * | 2 6 ||y| + |-8| = |0| * * * the solution is the vector | 2 -2 | * */ class RSGCostFunction : public itk::SingleValuedCostFunction { public: typedef RSGCostFunction Self; typedef itk::SingleValuedCostFunction Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; itkNewMacro( Self ); enum { SpaceDimension=2 }; typedef Superclass::ParametersType ParametersType; typedef Superclass::DerivativeType DerivativeType; typedef Superclass::MeasureType MeasureType ; RSGCostFunction() { } MeasureType GetValue( const ParametersType & parameters ) const { double x = parameters[0]; double y = parameters[1]; std::cout << "GetValue( " ; std::cout << x << " "; std::cout << y << ") = "; MeasureType measure = 0.5*(3*x*x+4*x*y+6*y*y) - 2*x + 8*y; std::cout << measure << std::endl; return measure; } void GetDerivative( const ParametersType & parameters, DerivativeType & derivative ) const { double x = parameters[0]; double y = parameters[1]; std::cout << "GetDerivative( " ; std::cout << x << " "; std::cout << y << ") = "; derivative = DerivativeType( SpaceDimension ); derivative[0] = 3 * x + 2 * y -2; derivative[1] = 2 * x + 6 * y +8; } unsigned int GetNumberOfParameters(void) const { return SpaceDimension; } private: }; int itkExhaustiveOptimizerTest(int, char* [] ) { std::cout << "ExhaustiveOptimizer Test "; std::cout << std::endl << std::endl; typedef itk::ExhaustiveOptimizer OptimizerType; typedef OptimizerType::ScalesType ScalesType; // Declaration of a itkOptimizer OptimizerType::Pointer itkOptimizer = OptimizerType::New(); // Declaration of the CostFunction RSGCostFunction::Pointer costFunction = RSGCostFunction::New(); itkOptimizer->SetCostFunction( costFunction.GetPointer() ); typedef RSGCostFunction::ParametersType ParametersType; const unsigned int spaceDimension = costFunction->GetNumberOfParameters(); // We start not so far from | 2 -2 | ParametersType initialPosition( spaceDimension ); initialPosition[0] = 0.0; initialPosition[1] = -4.0; itkOptimizer->SetInitialPosition( initialPosition ); ScalesType parametersScale( spaceDimension ); parametersScale[0] = 1.0; parametersScale[1] = 1.0; itkOptimizer->SetScales( parametersScale ); itkOptimizer->SetStepLength( 1.0 ); typedef OptimizerType::StepsType StepsType; StepsType steps( 2 ); steps[0] = 10; steps[1] = 10; itkOptimizer->SetNumberOfSteps( steps ); try { itkOptimizer->StartOptimization(); } catch( itk::ExceptionObject & e ) { std::cout << "Exception thrown ! " << std::endl; std::cout << "An error ocurred during Optimization" << std::endl; std::cout << "Location = " << e.GetLocation() << std::endl; std::cout << "Description = " << e.GetDescription() << std::endl; return EXIT_FAILURE; } std::cout << "MinimumMetricValue = " << itkOptimizer->GetMinimumMetricValue() << std::endl; std::cout << "Minimum Position = " << itkOptimizer->GetMinimumMetricValuePosition() << std::endl; std::cout << "MaximumMetricValue = " << itkOptimizer->GetMaximumMetricValue() << std::endl; std::cout << "Maximum Position = " << itkOptimizer->GetMaximumMetricValuePosition() << std::endl; ParametersType finalPosition = itkOptimizer->GetMinimumMetricValuePosition(); std::cout << "Solution = ("; std::cout << finalPosition[0] << "," ; std::cout << finalPosition[1] << ")" << std::endl; // // check results to see if it is within range // bool pass = true; double trueParameters[2] = { 2, -2 }; for( unsigned int j = 0; j < 2; j++ ) { if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 ) { pass = false; } } if( !pass ) { std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } std::cout << "Testing PrintSelf " << std::endl; itkOptimizer->Print( std::cout ); std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "searchresulttreemodel.h" #include "searchresulttreeitems.h" #include "searchresulttreeitemroles.h" #include <QApplication> #include <QFont> #include <QFontMetrics> #include <QDebug> using namespace Core; using namespace Core::Internal; SearchResultTreeModel::SearchResultTreeModel(QObject *parent) : QAbstractItemModel(parent) , m_currentParent(0) , m_showReplaceUI(false) , m_editorFontIsUsed(false) { m_rootItem = new SearchResultTreeItem; m_textEditorFont = QFont(QLatin1String("Courier")); } SearchResultTreeModel::~SearchResultTreeModel() { delete m_rootItem; } void SearchResultTreeModel::setShowReplaceUI(bool show) { beginResetModel(); m_showReplaceUI = show; endResetModel(); } void SearchResultTreeModel::setTextEditorFont(const QFont &font, const SearchResultColor &color) { layoutAboutToBeChanged(); m_textEditorFont = font; m_color = color; layoutChanged(); } Qt::ItemFlags SearchResultTreeModel::flags(const QModelIndex &idx) const { Qt::ItemFlags flags = QAbstractItemModel::flags(idx); if (idx.isValid()) { if (m_showReplaceUI) flags |= Qt::ItemIsUserCheckable; } return flags; } QModelIndex SearchResultTreeModel::index(int row, int column, const QModelIndex &parent) const { if (!hasIndex(row, column, parent)) return QModelIndex(); const SearchResultTreeItem *parentItem; if (!parent.isValid()) parentItem = m_rootItem; else parentItem = treeItemAtIndex(parent); const SearchResultTreeItem *childItem = parentItem->childAt(row); if (childItem) return createIndex(row, column, (void *)childItem); else return QModelIndex(); } QModelIndex SearchResultTreeModel::index(SearchResultTreeItem *item) const { return createIndex(item->rowOfItem(), 0, (void *)item); } QModelIndex SearchResultTreeModel::parent(const QModelIndex &idx) const { if (!idx.isValid()) return QModelIndex(); const SearchResultTreeItem *childItem = treeItemAtIndex(idx); const SearchResultTreeItem *parentItem = childItem->parent(); if (parentItem == m_rootItem) return QModelIndex(); return createIndex(parentItem->rowOfItem(), 0, (void *)parentItem); } int SearchResultTreeModel::rowCount(const QModelIndex &parent) const { if (parent.column() > 0) return 0; const SearchResultTreeItem *parentItem; if (!parent.isValid()) parentItem = m_rootItem; else parentItem = treeItemAtIndex(parent); return parentItem->childrenCount(); } int SearchResultTreeModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent) return 1; } SearchResultTreeItem *SearchResultTreeModel::treeItemAtIndex(const QModelIndex &idx) const { return static_cast<SearchResultTreeItem*>(idx.internalPointer()); } QVariant SearchResultTreeModel::data(const QModelIndex &idx, int role) const { if (!idx.isValid()) return QVariant(); QVariant result; if (role == Qt::SizeHintRole) { int height = QApplication::fontMetrics().height(); if (m_editorFontIsUsed) { const int editorFontHeight = QFontMetrics(m_textEditorFont).height(); height = qMax(height, editorFontHeight); } result = QSize(0, height); } else { result = data(treeItemAtIndex(idx), role); } return result; } bool SearchResultTreeModel::setData(const QModelIndex &idx, const QVariant &value, int role) { if (role == Qt::CheckStateRole) { Qt::CheckState checkState = static_cast<Qt::CheckState>(value.toInt()); return setCheckState(idx, checkState); } return QAbstractItemModel::setData(idx, value, role); } bool SearchResultTreeModel::setCheckState(const QModelIndex &idx, Qt::CheckState checkState, bool firstCall) { SearchResultTreeItem *item = treeItemAtIndex(idx); if (item->checkState() == checkState) return false; item->setCheckState(checkState); if (firstCall) { emit dataChanged(idx, idx); // check parents SearchResultTreeItem *currentItem = item; QModelIndex currentIndex = idx; while (SearchResultTreeItem *parent = currentItem->parent()) { bool hasChecked = false; bool hasUnchecked = false; for (int i = 0; i < parent->childrenCount(); ++i) { SearchResultTreeItem *child = parent->childAt(i); if (child->checkState() == Qt::Checked) hasChecked = true; else if (child->checkState() == Qt::Unchecked) hasUnchecked = true; else if (child->checkState() == Qt::PartiallyChecked) hasChecked = hasUnchecked = true; } if (hasChecked && hasUnchecked) parent->setCheckState(Qt::PartiallyChecked); else if (hasChecked) parent->setCheckState(Qt::Checked); else parent->setCheckState(Qt::Unchecked); emit dataChanged(idx.parent(), idx.parent()); currentItem = parent; currentIndex = idx.parent(); } } // check children if (int children = item->childrenCount()) { for (int i = 0; i < children; ++i) { setCheckState(idx.child(i, 0), checkState, false); } emit dataChanged(idx.child(0, 0), idx.child(children-1, 0)); } return true; } void setDataInternal(const QModelIndex &index, const QVariant &value, int role); QVariant SearchResultTreeModel::data(const SearchResultTreeItem *row, int role) const { QVariant result; switch (role) { case Qt::CheckStateRole: result = row->checkState(); break; case Qt::ToolTipRole: result = row->item.text.trimmed(); break; case Qt::FontRole: if (row->item.useTextEditorFont) result = m_textEditorFont; else result = QVariant(); break; case Qt::TextColorRole: result = m_color.textForeground; break; case Qt::BackgroundRole: result = m_color.textBackground; break; case ItemDataRoles::ResultLineRole: case Qt::DisplayRole: result = row->item.text; break; case ItemDataRoles::ResultItemRole: result = qVariantFromValue(row->item); break; case ItemDataRoles::ResultLineNumberRole: result = row->item.lineNumber; break; case ItemDataRoles::ResultIconRole: result = row->item.icon; break; case ItemDataRoles::ResultHighlightBackgroundColor: result = m_color.highlightBackground; break; case ItemDataRoles::ResultHighlightForegroundColor: result = m_color.highlightForeground; break; case ItemDataRoles::SearchTermStartRole: result = row->item.textMarkPos; break; case ItemDataRoles::SearchTermLengthRole: result = row->item.textMarkLength; break; case ItemDataRoles::IsGeneratedRole: result = row->isGenerated(); break; default: result = QVariant(); break; } return result; } QVariant SearchResultTreeModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(section) Q_UNUSED(orientation) Q_UNUSED(role) return QVariant(); } /** * Makes sure that the nodes for a specific path exist and sets * m_currentParent to the last final */ QSet<SearchResultTreeItem *> SearchResultTreeModel::addPath(const QStringList &path) { QSet<SearchResultTreeItem *> pathNodes; SearchResultTreeItem *currentItem = m_rootItem; QModelIndex currentItemIndex = QModelIndex(); SearchResultTreeItem *partItem = 0; QStringList currentPath; foreach (const QString &part, path) { const int insertionIndex = currentItem->insertionIndex(part, &partItem); if (!partItem) { SearchResultItem item; item.path = currentPath; item.text = part; partItem = new SearchResultTreeItem(item, currentItem); if (m_showReplaceUI) partItem->setCheckState(Qt::Checked); partItem->setGenerated(true); beginInsertRows(currentItemIndex, insertionIndex, insertionIndex); currentItem->insertChild(insertionIndex, partItem); endInsertRows(); } pathNodes << partItem; currentItemIndex = index(insertionIndex, 0, currentItemIndex); currentItem = partItem; currentPath << part; } m_currentParent = currentItem; m_currentPath = currentPath; m_currentIndex = currentItemIndex; return pathNodes; } void SearchResultTreeModel::addResultsToCurrentParent(const QList<SearchResultItem> &items, SearchResult::AddMode mode) { if (!m_currentParent) return; if (mode == SearchResult::AddOrdered) { // this is the mode for e.g. text search beginInsertRows(m_currentIndex, m_currentParent->childrenCount(), m_currentParent->childrenCount() + items.count()); foreach (const SearchResultItem &item, items) { m_currentParent->appendChild(item); } endInsertRows(); } else if (mode == SearchResult::AddSorted) { foreach (const SearchResultItem &item, items) { SearchResultTreeItem *existingItem; const int insertionIndex = m_currentParent->insertionIndex(item, &existingItem); if (existingItem) { existingItem->setGenerated(false); existingItem->item = item; QModelIndex itemIndex = m_currentIndex.child(insertionIndex, 0); dataChanged(itemIndex, itemIndex); } else { beginInsertRows(m_currentIndex, insertionIndex, insertionIndex); m_currentParent->insertChild(insertionIndex, item); endInsertRows(); } } } dataChanged(m_currentIndex, m_currentIndex); // Make sure that the number after the file name gets updated } static bool lessThanByPath(const SearchResultItem &a, const SearchResultItem &b) { if (a.path.size() < b.path.size()) return true; if (a.path.size() > b.path.size()) return false; for (int i = 0; i < a.path.size(); ++i) { if (a.path.at(i) < b.path.at(i)) return true; if (a.path.at(i) > b.path.at(i)) return false; } return false; } /** * Adds the search result to the list of results, creating nodes for the path when * necessary. */ QList<QModelIndex> SearchResultTreeModel::addResults(const QList<SearchResultItem> &items, SearchResult::AddMode mode) { QSet<SearchResultTreeItem *> pathNodes; QList<SearchResultItem> sortedItems = items; qStableSort(sortedItems.begin(), sortedItems.end(), lessThanByPath); QList<SearchResultItem> itemSet; foreach (const SearchResultItem &item, sortedItems) { m_editorFontIsUsed |= item.useTextEditorFont; if (!m_currentParent || (m_currentPath != item.path)) { // first add all the items from before if (!itemSet.isEmpty()) { addResultsToCurrentParent(itemSet, mode); itemSet.clear(); } // switch parent pathNodes += addPath(item.path); } itemSet << item; } if (!itemSet.isEmpty()) { addResultsToCurrentParent(itemSet, mode); itemSet.clear(); } QList<QModelIndex> pathIndices; foreach (SearchResultTreeItem *item, pathNodes) pathIndices << index(item); return pathIndices; } void SearchResultTreeModel::clear() { beginResetModel(); m_currentParent = NULL; m_rootItem->clearChildren(); m_editorFontIsUsed = false; endResetModel(); } QModelIndex SearchResultTreeModel::nextIndex(const QModelIndex &idx, bool *wrapped) const { if (wrapped) *wrapped = false; // pathological if (!idx.isValid()) return index(0, 0); if (rowCount(idx) > 0) { // node with children return idx.child(0, 0); } // leaf node QModelIndex nextIndex; QModelIndex current = idx; while (!nextIndex.isValid()) { int row = current.row(); current = current.parent(); if (row + 1 < rowCount(current)) { // Same parent has another child nextIndex = index(row + 1, 0, current); } else { // go up one parent if (!current.isValid()) { // we start from the beginning if (wrapped) *wrapped = true; nextIndex = index(0, 0); } } } return nextIndex; } QModelIndex SearchResultTreeModel::next(const QModelIndex &idx, bool includeGenerated, bool *wrapped) const { QModelIndex value = idx; do { value = nextIndex(value, wrapped); } while (value != idx && !includeGenerated && treeItemAtIndex(value)->isGenerated()); return value; } QModelIndex SearchResultTreeModel::prevIndex(const QModelIndex &idx, bool *wrapped) const { if (wrapped) *wrapped = false; QModelIndex current = idx; bool checkForChildren = true; if (current.isValid()) { int row = current.row(); if (row > 0) { current = index(row - 1, 0, current.parent()); } else { current = current.parent(); checkForChildren = !current.isValid(); if (checkForChildren && wrapped) { // we start from the end *wrapped = true; } } } if (checkForChildren) { // traverse down the hierarchy while (int rc = rowCount(current)) { current = index(rc - 1, 0, current); } } return current; } QModelIndex SearchResultTreeModel::prev(const QModelIndex &idx, bool includeGenerated, bool *wrapped) const { QModelIndex value = idx; do { value = prevIndex(value, wrapped); } while (value != idx && !includeGenerated && treeItemAtIndex(value)->isGenerated()); return value; } <commit_msg>Search results: Fix that auto-expand failed on first set of results<commit_after>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "searchresulttreemodel.h" #include "searchresulttreeitems.h" #include "searchresulttreeitemroles.h" #include <QApplication> #include <QFont> #include <QFontMetrics> #include <QDebug> using namespace Core; using namespace Core::Internal; SearchResultTreeModel::SearchResultTreeModel(QObject *parent) : QAbstractItemModel(parent) , m_currentParent(0) , m_showReplaceUI(false) , m_editorFontIsUsed(false) { m_rootItem = new SearchResultTreeItem; m_textEditorFont = QFont(QLatin1String("Courier")); } SearchResultTreeModel::~SearchResultTreeModel() { delete m_rootItem; } void SearchResultTreeModel::setShowReplaceUI(bool show) { m_showReplaceUI = show; // We cannot send dataChanged for the whole hierarchy in one go, // because all items in a dataChanged must have the same parent. // Send dataChanged for each parent of children individually... QList<QModelIndex> changeQueue; changeQueue.append(QModelIndex()); while (!changeQueue.isEmpty()) { const QModelIndex current = changeQueue.takeFirst(); int childCount = rowCount(current); if (childCount > 0) { emit dataChanged(index(0, 0, current), index(childCount - 1, 0, current)); for (int r = 0; r < childCount; ++r) changeQueue.append(index(r, 0, current)); } } } void SearchResultTreeModel::setTextEditorFont(const QFont &font, const SearchResultColor &color) { layoutAboutToBeChanged(); m_textEditorFont = font; m_color = color; layoutChanged(); } Qt::ItemFlags SearchResultTreeModel::flags(const QModelIndex &idx) const { Qt::ItemFlags flags = QAbstractItemModel::flags(idx); if (idx.isValid()) { if (m_showReplaceUI) flags |= Qt::ItemIsUserCheckable; } return flags; } QModelIndex SearchResultTreeModel::index(int row, int column, const QModelIndex &parent) const { if (!hasIndex(row, column, parent)) return QModelIndex(); const SearchResultTreeItem *parentItem; if (!parent.isValid()) parentItem = m_rootItem; else parentItem = treeItemAtIndex(parent); const SearchResultTreeItem *childItem = parentItem->childAt(row); if (childItem) return createIndex(row, column, (void *)childItem); else return QModelIndex(); } QModelIndex SearchResultTreeModel::index(SearchResultTreeItem *item) const { return createIndex(item->rowOfItem(), 0, (void *)item); } QModelIndex SearchResultTreeModel::parent(const QModelIndex &idx) const { if (!idx.isValid()) return QModelIndex(); const SearchResultTreeItem *childItem = treeItemAtIndex(idx); const SearchResultTreeItem *parentItem = childItem->parent(); if (parentItem == m_rootItem) return QModelIndex(); return createIndex(parentItem->rowOfItem(), 0, (void *)parentItem); } int SearchResultTreeModel::rowCount(const QModelIndex &parent) const { if (parent.column() > 0) return 0; const SearchResultTreeItem *parentItem; if (!parent.isValid()) parentItem = m_rootItem; else parentItem = treeItemAtIndex(parent); return parentItem->childrenCount(); } int SearchResultTreeModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent) return 1; } SearchResultTreeItem *SearchResultTreeModel::treeItemAtIndex(const QModelIndex &idx) const { return static_cast<SearchResultTreeItem*>(idx.internalPointer()); } QVariant SearchResultTreeModel::data(const QModelIndex &idx, int role) const { if (!idx.isValid()) return QVariant(); QVariant result; if (role == Qt::SizeHintRole) { int height = QApplication::fontMetrics().height(); if (m_editorFontIsUsed) { const int editorFontHeight = QFontMetrics(m_textEditorFont).height(); height = qMax(height, editorFontHeight); } result = QSize(0, height); } else { result = data(treeItemAtIndex(idx), role); } return result; } bool SearchResultTreeModel::setData(const QModelIndex &idx, const QVariant &value, int role) { if (role == Qt::CheckStateRole) { Qt::CheckState checkState = static_cast<Qt::CheckState>(value.toInt()); return setCheckState(idx, checkState); } return QAbstractItemModel::setData(idx, value, role); } bool SearchResultTreeModel::setCheckState(const QModelIndex &idx, Qt::CheckState checkState, bool firstCall) { SearchResultTreeItem *item = treeItemAtIndex(idx); if (item->checkState() == checkState) return false; item->setCheckState(checkState); if (firstCall) { emit dataChanged(idx, idx); // check parents SearchResultTreeItem *currentItem = item; QModelIndex currentIndex = idx; while (SearchResultTreeItem *parent = currentItem->parent()) { bool hasChecked = false; bool hasUnchecked = false; for (int i = 0; i < parent->childrenCount(); ++i) { SearchResultTreeItem *child = parent->childAt(i); if (child->checkState() == Qt::Checked) hasChecked = true; else if (child->checkState() == Qt::Unchecked) hasUnchecked = true; else if (child->checkState() == Qt::PartiallyChecked) hasChecked = hasUnchecked = true; } if (hasChecked && hasUnchecked) parent->setCheckState(Qt::PartiallyChecked); else if (hasChecked) parent->setCheckState(Qt::Checked); else parent->setCheckState(Qt::Unchecked); emit dataChanged(idx.parent(), idx.parent()); currentItem = parent; currentIndex = idx.parent(); } } // check children if (int children = item->childrenCount()) { for (int i = 0; i < children; ++i) { setCheckState(idx.child(i, 0), checkState, false); } emit dataChanged(idx.child(0, 0), idx.child(children-1, 0)); } return true; } void setDataInternal(const QModelIndex &index, const QVariant &value, int role); QVariant SearchResultTreeModel::data(const SearchResultTreeItem *row, int role) const { QVariant result; switch (role) { case Qt::CheckStateRole: result = row->checkState(); break; case Qt::ToolTipRole: result = row->item.text.trimmed(); break; case Qt::FontRole: if (row->item.useTextEditorFont) result = m_textEditorFont; else result = QVariant(); break; case Qt::TextColorRole: result = m_color.textForeground; break; case Qt::BackgroundRole: result = m_color.textBackground; break; case ItemDataRoles::ResultLineRole: case Qt::DisplayRole: result = row->item.text; break; case ItemDataRoles::ResultItemRole: result = qVariantFromValue(row->item); break; case ItemDataRoles::ResultLineNumberRole: result = row->item.lineNumber; break; case ItemDataRoles::ResultIconRole: result = row->item.icon; break; case ItemDataRoles::ResultHighlightBackgroundColor: result = m_color.highlightBackground; break; case ItemDataRoles::ResultHighlightForegroundColor: result = m_color.highlightForeground; break; case ItemDataRoles::SearchTermStartRole: result = row->item.textMarkPos; break; case ItemDataRoles::SearchTermLengthRole: result = row->item.textMarkLength; break; case ItemDataRoles::IsGeneratedRole: result = row->isGenerated(); break; default: result = QVariant(); break; } return result; } QVariant SearchResultTreeModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(section) Q_UNUSED(orientation) Q_UNUSED(role) return QVariant(); } /** * Makes sure that the nodes for a specific path exist and sets * m_currentParent to the last final */ QSet<SearchResultTreeItem *> SearchResultTreeModel::addPath(const QStringList &path) { QSet<SearchResultTreeItem *> pathNodes; SearchResultTreeItem *currentItem = m_rootItem; QModelIndex currentItemIndex = QModelIndex(); SearchResultTreeItem *partItem = 0; QStringList currentPath; foreach (const QString &part, path) { const int insertionIndex = currentItem->insertionIndex(part, &partItem); if (!partItem) { SearchResultItem item; item.path = currentPath; item.text = part; partItem = new SearchResultTreeItem(item, currentItem); if (m_showReplaceUI) partItem->setCheckState(Qt::Checked); partItem->setGenerated(true); beginInsertRows(currentItemIndex, insertionIndex, insertionIndex); currentItem->insertChild(insertionIndex, partItem); endInsertRows(); } pathNodes << partItem; currentItemIndex = index(insertionIndex, 0, currentItemIndex); currentItem = partItem; currentPath << part; } m_currentParent = currentItem; m_currentPath = currentPath; m_currentIndex = currentItemIndex; return pathNodes; } void SearchResultTreeModel::addResultsToCurrentParent(const QList<SearchResultItem> &items, SearchResult::AddMode mode) { if (!m_currentParent) return; if (mode == SearchResult::AddOrdered) { // this is the mode for e.g. text search beginInsertRows(m_currentIndex, m_currentParent->childrenCount(), m_currentParent->childrenCount() + items.count()); foreach (const SearchResultItem &item, items) { m_currentParent->appendChild(item); } endInsertRows(); } else if (mode == SearchResult::AddSorted) { foreach (const SearchResultItem &item, items) { SearchResultTreeItem *existingItem; const int insertionIndex = m_currentParent->insertionIndex(item, &existingItem); if (existingItem) { existingItem->setGenerated(false); existingItem->item = item; QModelIndex itemIndex = m_currentIndex.child(insertionIndex, 0); dataChanged(itemIndex, itemIndex); } else { beginInsertRows(m_currentIndex, insertionIndex, insertionIndex); m_currentParent->insertChild(insertionIndex, item); endInsertRows(); } } } dataChanged(m_currentIndex, m_currentIndex); // Make sure that the number after the file name gets updated } static bool lessThanByPath(const SearchResultItem &a, const SearchResultItem &b) { if (a.path.size() < b.path.size()) return true; if (a.path.size() > b.path.size()) return false; for (int i = 0; i < a.path.size(); ++i) { if (a.path.at(i) < b.path.at(i)) return true; if (a.path.at(i) > b.path.at(i)) return false; } return false; } /** * Adds the search result to the list of results, creating nodes for the path when * necessary. */ QList<QModelIndex> SearchResultTreeModel::addResults(const QList<SearchResultItem> &items, SearchResult::AddMode mode) { QSet<SearchResultTreeItem *> pathNodes; QList<SearchResultItem> sortedItems = items; qStableSort(sortedItems.begin(), sortedItems.end(), lessThanByPath); QList<SearchResultItem> itemSet; foreach (const SearchResultItem &item, sortedItems) { m_editorFontIsUsed |= item.useTextEditorFont; if (!m_currentParent || (m_currentPath != item.path)) { // first add all the items from before if (!itemSet.isEmpty()) { addResultsToCurrentParent(itemSet, mode); itemSet.clear(); } // switch parent pathNodes += addPath(item.path); } itemSet << item; } if (!itemSet.isEmpty()) { addResultsToCurrentParent(itemSet, mode); itemSet.clear(); } QList<QModelIndex> pathIndices; foreach (SearchResultTreeItem *item, pathNodes) pathIndices << index(item); return pathIndices; } void SearchResultTreeModel::clear() { beginResetModel(); m_currentParent = NULL; m_rootItem->clearChildren(); m_editorFontIsUsed = false; endResetModel(); } QModelIndex SearchResultTreeModel::nextIndex(const QModelIndex &idx, bool *wrapped) const { if (wrapped) *wrapped = false; // pathological if (!idx.isValid()) return index(0, 0); if (rowCount(idx) > 0) { // node with children return idx.child(0, 0); } // leaf node QModelIndex nextIndex; QModelIndex current = idx; while (!nextIndex.isValid()) { int row = current.row(); current = current.parent(); if (row + 1 < rowCount(current)) { // Same parent has another child nextIndex = index(row + 1, 0, current); } else { // go up one parent if (!current.isValid()) { // we start from the beginning if (wrapped) *wrapped = true; nextIndex = index(0, 0); } } } return nextIndex; } QModelIndex SearchResultTreeModel::next(const QModelIndex &idx, bool includeGenerated, bool *wrapped) const { QModelIndex value = idx; do { value = nextIndex(value, wrapped); } while (value != idx && !includeGenerated && treeItemAtIndex(value)->isGenerated()); return value; } QModelIndex SearchResultTreeModel::prevIndex(const QModelIndex &idx, bool *wrapped) const { if (wrapped) *wrapped = false; QModelIndex current = idx; bool checkForChildren = true; if (current.isValid()) { int row = current.row(); if (row > 0) { current = index(row - 1, 0, current.parent()); } else { current = current.parent(); checkForChildren = !current.isValid(); if (checkForChildren && wrapped) { // we start from the end *wrapped = true; } } } if (checkForChildren) { // traverse down the hierarchy while (int rc = rowCount(current)) { current = index(rc - 1, 0, current); } } return current; } QModelIndex SearchResultTreeModel::prev(const QModelIndex &idx, bool includeGenerated, bool *wrapped) const { QModelIndex value = idx; do { value = prevIndex(value, wrapped); } while (value != idx && !includeGenerated && treeItemAtIndex(value)->isGenerated()); return value; } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "targetspage.h" #include "qt4projectmanager/qt4target.h" #include "qt4projectmanager/qtversionmanager.h" #include <QtCore/QSet> #include <QtCore/QString> #include <QtGui/QTreeWidget> #include <QtGui/QLabel> #include <QtGui/QLayout> using namespace Qt4ProjectManager::Internal; TargetsPage::TargetsPage(QWidget *parent) : QWizardPage(parent) { setTitle(tr("Choose Qt versions")); QVBoxLayout *vbox = new QVBoxLayout(this); setTitle(tr("Select required Qt versions")); QLabel *label = new QLabel(tr("Select the Qt versions to use in your project."), this); label->setWordWrap(true); vbox->addWidget(label); m_treeWidget = new QTreeWidget(this); m_treeWidget->setHeaderHidden(true); vbox->addWidget(m_treeWidget); QtVersionManager *vm = QtVersionManager::instance(); QSet<QString> targets = vm->supportedTargetIds(); Qt4TargetFactory factory; bool hasDesktop = targets.contains(QLatin1String(DESKTOP_TARGET_ID)); bool isExpanded = false; bool isQtVersionChecked = false; foreach (const QString &t, targets) { QTreeWidgetItem *targetItem = new QTreeWidgetItem(m_treeWidget); targetItem->setText(0, factory.displayNameForId(t)); targetItem->setFlags(Qt::ItemIsEnabled); targetItem->setData(0, Qt::UserRole, t); if (!isExpanded) { if ((hasDesktop && t == QLatin1String(DESKTOP_TARGET_ID)) || !hasDesktop) { isExpanded = true; targetItem->setExpanded(true); } } foreach (QtVersion *v, vm->versionsForTargetId(t)) { QTreeWidgetItem *versionItem = new QTreeWidgetItem(targetItem); versionItem->setText(0, v->displayName()); versionItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); versionItem->setData(0, Qt::UserRole, v->uniqueId()); if (isExpanded && !isQtVersionChecked) { isQtVersionChecked = true; versionItem->setCheckState(0, Qt::Checked); } else { versionItem->setCheckState(0, Qt::Unchecked); } } } connect(m_treeWidget, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(itemWasClicked())); m_isComplete = isQtVersionChecked; emit completeChanged(); } QSet<QString> TargetsPage::selectedTargets() const { QSet<QString> result; for (int i = 0; i < m_treeWidget->topLevelItemCount(); ++i) { QString target = m_treeWidget->topLevelItem(i)->data(0, Qt::UserRole).toString(); QList<int> versions = selectedVersionIdsForTarget(target); if (!versions.isEmpty()) result.insert(target); } return result; } QList<int> TargetsPage::selectedVersionIdsForTarget(const QString &t) const { QList<int> result; for (int i = 0; i < m_treeWidget->topLevelItemCount(); ++i) { QTreeWidgetItem * current = m_treeWidget->topLevelItem(i); QString target = current->data(0, Qt::UserRole).toString(); if (t != target) continue; for (int j = 0; j < current->childCount(); ++j) { QTreeWidgetItem * child = current->child(j); if (child->checkState(0) != Qt::Checked) continue; result.append(child->data(0, Qt::UserRole).toInt()); } } return result; } void TargetsPage::itemWasClicked() { emit completeChanged(); } bool TargetsPage::isComplete() const { return !selectedTargets().isEmpty(); } <commit_msg>Sort targets by name<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "targetspage.h" #include "qt4projectmanager/qt4target.h" #include "qt4projectmanager/qtversionmanager.h" #include <QtCore/QSet> #include <QtCore/QString> #include <QtGui/QTreeWidget> #include <QtGui/QLabel> #include <QtGui/QLayout> using namespace Qt4ProjectManager::Internal; TargetsPage::TargetsPage(QWidget *parent) : QWizardPage(parent) { setTitle(tr("Choose Qt versions")); QVBoxLayout *vbox = new QVBoxLayout(this); setTitle(tr("Select required Qt versions")); QLabel *label = new QLabel(tr("Select the Qt versions to use in your project."), this); label->setWordWrap(true); vbox->addWidget(label); m_treeWidget = new QTreeWidget(this); m_treeWidget->setHeaderHidden(true); vbox->addWidget(m_treeWidget); QtVersionManager *vm = QtVersionManager::instance(); QStringList targets = vm->supportedTargetIds().toList(); qSort(targets.begin(), targets.end()); Qt4TargetFactory factory; bool hasDesktop = targets.contains(QLatin1String(DESKTOP_TARGET_ID)); bool isExpanded = false; bool isQtVersionChecked = false; foreach (const QString &t, targets) { QTreeWidgetItem *targetItem = new QTreeWidgetItem(m_treeWidget); targetItem->setText(0, factory.displayNameForId(t)); targetItem->setFlags(Qt::ItemIsEnabled); targetItem->setData(0, Qt::UserRole, t); if (!isExpanded) { if ((hasDesktop && t == QLatin1String(DESKTOP_TARGET_ID)) || !hasDesktop) { isExpanded = true; targetItem->setExpanded(true); } } foreach (QtVersion *v, vm->versionsForTargetId(t)) { QTreeWidgetItem *versionItem = new QTreeWidgetItem(targetItem); versionItem->setText(0, v->displayName()); versionItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); versionItem->setData(0, Qt::UserRole, v->uniqueId()); if (isExpanded && !isQtVersionChecked) { isQtVersionChecked = true; versionItem->setCheckState(0, Qt::Checked); } else { versionItem->setCheckState(0, Qt::Unchecked); } } } connect(m_treeWidget, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(itemWasClicked())); m_isComplete = isQtVersionChecked; emit completeChanged(); } QSet<QString> TargetsPage::selectedTargets() const { QSet<QString> result; for (int i = 0; i < m_treeWidget->topLevelItemCount(); ++i) { QString target = m_treeWidget->topLevelItem(i)->data(0, Qt::UserRole).toString(); QList<int> versions = selectedVersionIdsForTarget(target); if (!versions.isEmpty()) result.insert(target); } return result; } QList<int> TargetsPage::selectedVersionIdsForTarget(const QString &t) const { QList<int> result; for (int i = 0; i < m_treeWidget->topLevelItemCount(); ++i) { QTreeWidgetItem * current = m_treeWidget->topLevelItem(i); QString target = current->data(0, Qt::UserRole).toString(); if (t != target) continue; for (int j = 0; j < current->childCount(); ++j) { QTreeWidgetItem * child = current->child(j); if (child->checkState(0) != Qt::Checked) continue; result.append(child->data(0, Qt::UserRole).toInt()); } } return result; } void TargetsPage::itemWasClicked() { emit completeChanged(); } bool TargetsPage::isComplete() const { return !selectedTargets().isEmpty(); } <|endoftext|>
<commit_before>#include "halley/tools/assets/import_assets_database.h" #include "halley/bytes/byte_serializer.h" #include "halley/resources/resource_data.h" #include "halley/tools/file/filesystem.h" constexpr static int currentAssetVersion = 50; using namespace Halley; void ImportAssetsDatabaseEntry::serialize(Serializer& s) const { s << assetId; s << srcDir; s << inputFiles; s << additionalInputFiles; s << outputFiles; int t = int(assetType); s << t; } void ImportAssetsDatabaseEntry::deserialize(Deserializer& s) { s >> assetId; s >> srcDir; s >> inputFiles; s >> additionalInputFiles; s >> outputFiles; int t; s >> t; assetType = ImportAssetType(t); } void ImportAssetsDatabase::AssetEntry::serialize(Serializer& s) const { s << asset; } void ImportAssetsDatabase::AssetEntry::deserialize(Deserializer& s) { s >> asset; } void ImportAssetsDatabase::InputFileEntry::serialize(Serializer& s) const { const int nTimestamps = int(timestamp.size()); s << nTimestamps; for (int i = 0; i < nTimestamps; ++i) { s << timestamp[i]; } s << metadata; } void ImportAssetsDatabase::InputFileEntry::deserialize(Deserializer& s) { int nTimestamps; s >> nTimestamps; for (int i = 0; i < nTimestamps; ++i) { if (i < int(timestamp.size())) { s >> timestamp[i]; } } for (int i = nTimestamps; i < int(timestamp.size()); ++i) { timestamp[i] = 0; } s >> metadata; } ImportAssetsDatabase::ImportAssetsDatabase(Path directory, Path dbFile, Path assetsDbFile, std::vector<String> platforms) : platforms(std::move(platforms)) , directory(directory) , dbFile(dbFile) , assetsDbFile(assetsDbFile) { load(); } void ImportAssetsDatabase::load() { std::lock_guard<std::mutex> lock(mutex); auto data = FileSystem::readFile(dbFile); if (data.size() > 0) { auto s = Deserializer(data); deserialize(s); } } void ImportAssetsDatabase::save() const { std::lock_guard<std::mutex> lock(mutex); FileSystem::writeFile(dbFile, Serializer::toBytes(*this)); for (auto& platform: platforms) { // TODO: fix this auto assetDb = makeAssetDatabase(platform); FileSystem::writeFile(assetsDbFile, Serializer::toBytes(*assetDb)); } } bool ImportAssetsDatabase::needToLoadInputMetadata(const Path& path, std::array<int64_t, 3> timestamps) const { std::lock_guard<std::mutex> lock(mutex); // Is it an unknown file? auto pathStr = path.toString(); auto iter = inputFiles.find(pathStr); if (iter == inputFiles.end()) { return true; } // Any of the timestamps changed? for (int i = 0; i < timestamps.size(); ++i) { if (iter->second.timestamp[i] != timestamps[i]) { return true; } } return false; } void ImportAssetsDatabase::setInputFileMetadata(const Path& path, std::array<int64_t, 3> timestamps, const Metadata& data) { std::lock_guard<std::mutex> lock(mutex); auto pathStr = path.toString(); auto& input = inputFiles[pathStr]; input.timestamp = timestamps; input.metadata = data; } Maybe<Metadata> ImportAssetsDatabase::getMetadata(const Path& path) const { std::lock_guard<std::mutex> lock(mutex); auto pathStr = path.toString(); auto iter = inputFiles.find(pathStr); if (iter == inputFiles.end()) { return {}; } else { return iter->second.metadata; } } bool ImportAssetsDatabase::needsImporting(const ImportAssetsDatabaseEntry& asset) const { std::lock_guard<std::mutex> lock(mutex); // Check if it failed loading last time auto iter = assetsFailed.find(asset.assetId); bool failed = iter != assetsFailed.end(); if (!failed) { // No failures, check if this was imported before iter = assetsImported.find(asset.assetId); if (iter == assetsImported.end()) { // Asset didn't even exist before return true; } } // At this point, iter points to the failed one if it failed, or the the old successful one if it didn't. auto& oldAsset = iter->second.asset; // Input directory changed? if (asset.srcDir != oldAsset.srcDir) { return true; } // Total count of input files changed? if (asset.inputFiles.size() != oldAsset.inputFiles.size()) { return true; } // Any of the input files changed? // Note: We don't have to check old files on new input, because the size matches and all entries matched. for (auto& i: asset.inputFiles) { auto result = std::find_if(oldAsset.inputFiles.begin(), oldAsset.inputFiles.end(), [&](const TimestampedPath& entry) { return entry.first == i.first; }); if (result == oldAsset.inputFiles.end()) { // File wasn't there before return true; } else if (result->second != i.second) { // Timestamp changed return true; } } // Any of the additional input files changed? for (auto& i: oldAsset.additionalInputFiles) { if (!FileSystem::exists(i.first)) { // File removed return true; } else if (FileSystem::getLastWriteTime(i.first) != i.second) { // Timestamp changed return true; } } // Have any of the output files gone missing? if (!failed) { for (auto& o: oldAsset.outputFiles) { for (auto& version: o.platformVersions) { if (!FileSystem::exists(directory / version.second.filepath)) { return true; } } } } return false; } void ImportAssetsDatabase::markAsImported(const ImportAssetsDatabaseEntry& asset) { AssetEntry entry; entry.asset = asset; entry.present = true; std::lock_guard<std::mutex> lock(mutex); assetsImported[asset.assetId] = entry; auto failIter = assetsFailed.find(asset.assetId); if (failIter != assetsFailed.end()) { assetsFailed.erase(failIter); } } void ImportAssetsDatabase::markDeleted(const ImportAssetsDatabaseEntry& asset) { std::lock_guard<std::mutex> lock(mutex); assetsImported.erase(asset.assetId); } void ImportAssetsDatabase::markFailed(const ImportAssetsDatabaseEntry& asset) { AssetEntry entry; entry.asset = asset; entry.present = true; std::lock_guard<std::mutex> lock(mutex); assetsFailed[asset.assetId] = entry; } void ImportAssetsDatabase::markAssetsAsStillPresent(const std::map<String, ImportAssetsDatabaseEntry>& assets) { std::lock_guard<std::mutex> lock(mutex); for (auto& e: assetsImported) { e.second.present = assets.find(e.first) != assets.end(); } } std::vector<ImportAssetsDatabaseEntry> ImportAssetsDatabase::getAllMissing() const { std::lock_guard<std::mutex> lock(mutex); std::vector<ImportAssetsDatabaseEntry> result; for (auto& e : assetsImported) { if (!e.second.present) { result.push_back(e.second.asset); } } return result; } std::vector<AssetResource> ImportAssetsDatabase::getOutFiles(String assetId) const { auto iter = assetsImported.find(assetId); if (iter != assetsImported.end()) { return iter->second.asset.outputFiles; } else { return {}; } } void ImportAssetsDatabase::serialize(Serializer& s) const { int version = currentAssetVersion; s << version; s << platforms; s << assetsImported; s << inputFiles; } void ImportAssetsDatabase::deserialize(Deserializer& s) { int version; s >> version; if (version == currentAssetVersion) { std::vector<String> platformsRead; s >> platformsRead; if (platformsRead == platforms) { s >> assetsImported; s >> inputFiles; } } } std::unique_ptr<AssetDatabase> ImportAssetsDatabase::makeAssetDatabase(const String& platform) const { auto result = std::make_unique<AssetDatabase>(); for (auto& a: assetsImported) { auto& asset = a.second.asset; for (auto& o: asset.outputFiles) { auto iter = o.platformVersions.find(platform); const AssetResource::PlatformVersion* version = nullptr; if (iter != o.platformVersions.end()) { version = &iter->second; } else { iter = o.platformVersions.find("pc"); if (iter != o.platformVersions.end()) { version = &iter->second; } } if (version) { result->addAsset(o.name, o.type, AssetDatabase::Entry(version->filepath, version->metadata)); } } } return result; } <commit_msg>Bump asset version.<commit_after>#include "halley/tools/assets/import_assets_database.h" #include "halley/bytes/byte_serializer.h" #include "halley/resources/resource_data.h" #include "halley/tools/file/filesystem.h" constexpr static int currentAssetVersion = 51; using namespace Halley; void ImportAssetsDatabaseEntry::serialize(Serializer& s) const { s << assetId; s << srcDir; s << inputFiles; s << additionalInputFiles; s << outputFiles; int t = int(assetType); s << t; } void ImportAssetsDatabaseEntry::deserialize(Deserializer& s) { s >> assetId; s >> srcDir; s >> inputFiles; s >> additionalInputFiles; s >> outputFiles; int t; s >> t; assetType = ImportAssetType(t); } void ImportAssetsDatabase::AssetEntry::serialize(Serializer& s) const { s << asset; } void ImportAssetsDatabase::AssetEntry::deserialize(Deserializer& s) { s >> asset; } void ImportAssetsDatabase::InputFileEntry::serialize(Serializer& s) const { const int nTimestamps = int(timestamp.size()); s << nTimestamps; for (int i = 0; i < nTimestamps; ++i) { s << timestamp[i]; } s << metadata; } void ImportAssetsDatabase::InputFileEntry::deserialize(Deserializer& s) { int nTimestamps; s >> nTimestamps; for (int i = 0; i < nTimestamps; ++i) { if (i < int(timestamp.size())) { s >> timestamp[i]; } } for (int i = nTimestamps; i < int(timestamp.size()); ++i) { timestamp[i] = 0; } s >> metadata; } ImportAssetsDatabase::ImportAssetsDatabase(Path directory, Path dbFile, Path assetsDbFile, std::vector<String> platforms) : platforms(std::move(platforms)) , directory(directory) , dbFile(dbFile) , assetsDbFile(assetsDbFile) { load(); } void ImportAssetsDatabase::load() { std::lock_guard<std::mutex> lock(mutex); auto data = FileSystem::readFile(dbFile); if (data.size() > 0) { auto s = Deserializer(data); deserialize(s); } } void ImportAssetsDatabase::save() const { std::lock_guard<std::mutex> lock(mutex); FileSystem::writeFile(dbFile, Serializer::toBytes(*this)); for (auto& platform: platforms) { // TODO: fix this auto assetDb = makeAssetDatabase(platform); FileSystem::writeFile(assetsDbFile, Serializer::toBytes(*assetDb)); } } bool ImportAssetsDatabase::needToLoadInputMetadata(const Path& path, std::array<int64_t, 3> timestamps) const { std::lock_guard<std::mutex> lock(mutex); // Is it an unknown file? auto pathStr = path.toString(); auto iter = inputFiles.find(pathStr); if (iter == inputFiles.end()) { return true; } // Any of the timestamps changed? for (int i = 0; i < timestamps.size(); ++i) { if (iter->second.timestamp[i] != timestamps[i]) { return true; } } return false; } void ImportAssetsDatabase::setInputFileMetadata(const Path& path, std::array<int64_t, 3> timestamps, const Metadata& data) { std::lock_guard<std::mutex> lock(mutex); auto pathStr = path.toString(); auto& input = inputFiles[pathStr]; input.timestamp = timestamps; input.metadata = data; } Maybe<Metadata> ImportAssetsDatabase::getMetadata(const Path& path) const { std::lock_guard<std::mutex> lock(mutex); auto pathStr = path.toString(); auto iter = inputFiles.find(pathStr); if (iter == inputFiles.end()) { return {}; } else { return iter->second.metadata; } } bool ImportAssetsDatabase::needsImporting(const ImportAssetsDatabaseEntry& asset) const { std::lock_guard<std::mutex> lock(mutex); // Check if it failed loading last time auto iter = assetsFailed.find(asset.assetId); bool failed = iter != assetsFailed.end(); if (!failed) { // No failures, check if this was imported before iter = assetsImported.find(asset.assetId); if (iter == assetsImported.end()) { // Asset didn't even exist before return true; } } // At this point, iter points to the failed one if it failed, or the the old successful one if it didn't. auto& oldAsset = iter->second.asset; // Input directory changed? if (asset.srcDir != oldAsset.srcDir) { return true; } // Total count of input files changed? if (asset.inputFiles.size() != oldAsset.inputFiles.size()) { return true; } // Any of the input files changed? // Note: We don't have to check old files on new input, because the size matches and all entries matched. for (auto& i: asset.inputFiles) { auto result = std::find_if(oldAsset.inputFiles.begin(), oldAsset.inputFiles.end(), [&](const TimestampedPath& entry) { return entry.first == i.first; }); if (result == oldAsset.inputFiles.end()) { // File wasn't there before return true; } else if (result->second != i.second) { // Timestamp changed return true; } } // Any of the additional input files changed? for (auto& i: oldAsset.additionalInputFiles) { if (!FileSystem::exists(i.first)) { // File removed return true; } else if (FileSystem::getLastWriteTime(i.first) != i.second) { // Timestamp changed return true; } } // Have any of the output files gone missing? if (!failed) { for (auto& o: oldAsset.outputFiles) { for (auto& version: o.platformVersions) { if (!FileSystem::exists(directory / version.second.filepath)) { return true; } } } } return false; } void ImportAssetsDatabase::markAsImported(const ImportAssetsDatabaseEntry& asset) { AssetEntry entry; entry.asset = asset; entry.present = true; std::lock_guard<std::mutex> lock(mutex); assetsImported[asset.assetId] = entry; auto failIter = assetsFailed.find(asset.assetId); if (failIter != assetsFailed.end()) { assetsFailed.erase(failIter); } } void ImportAssetsDatabase::markDeleted(const ImportAssetsDatabaseEntry& asset) { std::lock_guard<std::mutex> lock(mutex); assetsImported.erase(asset.assetId); } void ImportAssetsDatabase::markFailed(const ImportAssetsDatabaseEntry& asset) { AssetEntry entry; entry.asset = asset; entry.present = true; std::lock_guard<std::mutex> lock(mutex); assetsFailed[asset.assetId] = entry; } void ImportAssetsDatabase::markAssetsAsStillPresent(const std::map<String, ImportAssetsDatabaseEntry>& assets) { std::lock_guard<std::mutex> lock(mutex); for (auto& e: assetsImported) { e.second.present = assets.find(e.first) != assets.end(); } } std::vector<ImportAssetsDatabaseEntry> ImportAssetsDatabase::getAllMissing() const { std::lock_guard<std::mutex> lock(mutex); std::vector<ImportAssetsDatabaseEntry> result; for (auto& e : assetsImported) { if (!e.second.present) { result.push_back(e.second.asset); } } return result; } std::vector<AssetResource> ImportAssetsDatabase::getOutFiles(String assetId) const { auto iter = assetsImported.find(assetId); if (iter != assetsImported.end()) { return iter->second.asset.outputFiles; } else { return {}; } } void ImportAssetsDatabase::serialize(Serializer& s) const { int version = currentAssetVersion; s << version; s << platforms; s << assetsImported; s << inputFiles; } void ImportAssetsDatabase::deserialize(Deserializer& s) { int version; s >> version; if (version == currentAssetVersion) { std::vector<String> platformsRead; s >> platformsRead; if (platformsRead == platforms) { s >> assetsImported; s >> inputFiles; } } } std::unique_ptr<AssetDatabase> ImportAssetsDatabase::makeAssetDatabase(const String& platform) const { auto result = std::make_unique<AssetDatabase>(); for (auto& a: assetsImported) { auto& asset = a.second.asset; for (auto& o: asset.outputFiles) { auto iter = o.platformVersions.find(platform); const AssetResource::PlatformVersion* version = nullptr; if (iter != o.platformVersions.end()) { version = &iter->second; } else { iter = o.platformVersions.find("pc"); if (iter != o.platformVersions.end()) { version = &iter->second; } } if (version) { result->addAsset(o.name, o.type, AssetDatabase::Entry(version->filepath, version->metadata)); } } } return result; } <|endoftext|>
<commit_before>/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/trace_processor/dynamic/thread_state_generator.h" #include <memory> #include <set> #include "src/trace_processor/containers/row_map.h" #include "src/trace_processor/types/trace_processor_context.h" namespace perfetto { namespace trace_processor { ThreadStateGenerator::ThreadStateGenerator(TraceProcessorContext* context) : running_string_id_(context->storage->InternString("Running")), runnable_string_id_(context->storage->InternString("R")), context_(context) {} ThreadStateGenerator::~ThreadStateGenerator() = default; util::Status ThreadStateGenerator::ValidateConstraints( const QueryConstraints&) { return util::OkStatus(); } std::unique_ptr<Table> ThreadStateGenerator::ComputeTable( const std::vector<Constraint>&, const std::vector<Order>&) { if (!unsorted_thread_state_table_) { int64_t trace_end_ts = context_->storage->GetTraceTimestampBoundsNs().second; unsorted_thread_state_table_ = ComputeThreadStateTable(trace_end_ts); // We explicitly sort by ts here as ComputeThreadStateTable does not insert // rows in sorted order but we expect our clients to always want to sort // on ts. Writing ComputeThreadStateTable to insert in sorted order is // more trouble than its worth. sorted_thread_state_table_ = unsorted_thread_state_table_->Sort( {unsorted_thread_state_table_->ts().ascending()}); } PERFETTO_CHECK(sorted_thread_state_table_); return std::unique_ptr<Table>(new Table(sorted_thread_state_table_->Copy())); } std::unique_ptr<tables::ThreadStateTable> ThreadStateGenerator::ComputeThreadStateTable(int64_t trace_end_ts) { std::unique_ptr<tables::ThreadStateTable> table(new tables::ThreadStateTable( context_->storage->mutable_string_pool(), nullptr)); const auto& raw_sched = context_->storage->sched_slice_table(); const auto& instants = context_->storage->instant_table(); // In both tables, exclude utid == 0 which represents the idle thread. Table sched = raw_sched.Filter({raw_sched.utid().ne(0)}, RowMap::OptimizeFor::kLookupSpeed); Table waking = instants.Filter( {instants.name().eq("sched_waking"), instants.ref().ne(0)}, RowMap::OptimizeFor::kLookupSpeed); // We prefer to use waking if at all possible and fall back to wakeup if not // available. if (waking.row_count() == 0) { waking = instants.Filter( {instants.name().eq("sched_wakeup"), instants.ref().ne(0)}, RowMap::OptimizeFor::kLookupSpeed); } Table sched_blocked_reason = instants.Filter( {instants.name().eq("sched_blocked_reason"), instants.ref().ne(0)}, RowMap::OptimizeFor::kLookupSpeed); const auto& sched_ts_col = sched.GetTypedColumnByName<int64_t>("ts"); const auto& waking_ts_col = waking.GetTypedColumnByName<int64_t>("ts"); const auto& blocked_ts_col = sched_blocked_reason.GetTypedColumnByName<int64_t>("ts"); uint32_t sched_idx = 0; uint32_t waking_idx = 0; uint32_t blocked_idx = 0; std::unordered_map<UniqueTid, ThreadSchedInfo> state_map; while (sched_idx < sched.row_count() || waking_idx < waking.row_count() || blocked_idx < sched_blocked_reason.row_count()) { int64_t sched_ts = sched_idx < sched.row_count() ? sched_ts_col[sched_idx] : std::numeric_limits<int64_t>::max(); int64_t waking_ts = waking_idx < waking.row_count() ? waking_ts_col[waking_idx] : std::numeric_limits<int64_t>::max(); int64_t blocked_ts = blocked_idx < sched_blocked_reason.row_count() ? blocked_ts_col[blocked_idx] : std::numeric_limits<int64_t>::max(); // We go through all tables, picking the earliest timestamp from any // to process that event. int64_t min_ts = std::min({sched_ts, waking_ts, blocked_ts}); if (min_ts == sched_ts) { AddSchedEvent(sched, sched_idx++, state_map, trace_end_ts, table.get()); } else if (min_ts == waking_ts) { AddWakingEvent(waking, waking_idx++, state_map); } else /* (min_ts == blocked_ts) */ { AddBlockedReasonEvent(sched_blocked_reason, blocked_idx++, state_map); } } // At the end, go through and flush any remaining pending events. for (const auto& utid_to_pending_info : state_map) { UniqueTid utid = utid_to_pending_info.first; const ThreadSchedInfo& pending_info = utid_to_pending_info.second; FlushPendingEventsForThread(utid, pending_info, table.get(), base::nullopt); } return table; } void ThreadStateGenerator::AddSchedEvent( const Table& sched, uint32_t sched_idx, std::unordered_map<UniqueTid, ThreadSchedInfo>& state_map, int64_t trace_end_ts, tables::ThreadStateTable* table) { int64_t ts = sched.GetTypedColumnByName<int64_t>("ts")[sched_idx]; UniqueTid utid = sched.GetTypedColumnByName<uint32_t>("utid")[sched_idx]; ThreadSchedInfo* info = &state_map[utid]; // Due to races in the kernel, it is possible for the same thread to be // scheduled on different CPUs at the same time. This will manifest itself // here by having |info->desched_ts| in the future of this scheduling slice // (i.e. there was a scheduling slice in the past which ended after the start // of the current scheduling slice). // // We work around this problem by truncating the previous slice to the start // of this slice and not adding the descheduled slice (i.e. we don't call // |FlushPendingEventsForThread| which adds this slice). // // See b/186509316 for details and an example on when this happens. if (info->desched_ts && info->desched_ts.value() > ts) { uint32_t prev_sched_row = info->scheduled_row.value(); int64_t prev_sched_start = table->ts()[prev_sched_row]; // Just a double check that descheduling slice would have started at the // same time the scheduling slice would have ended. PERFETTO_DCHECK(prev_sched_start + table->dur()[prev_sched_row] == info->desched_ts.value()); // Truncate the duration of the old slice to end at the start of this // scheduling slice. table->mutable_dur()->Set(prev_sched_row, ts - prev_sched_start); } else { FlushPendingEventsForThread(utid, *info, table, ts); } // Reset so we don't have any leftover data on the next round. *info = {}; // Undo the expansion of the final sched slice for each CPU to the end of the // trace by setting the duration back to -1. This counteracts the code in // SchedEventTracker::FlushPendingEvents // TODO(lalitm): remove this hack when we stop expanding the last slice to the // end of the trace. int64_t dur = sched.GetTypedColumnByName<int64_t>("dur")[sched_idx]; if (ts + dur == trace_end_ts) { dur = -1; } // Now add the sched slice itself as "Running" with the other fields // unchanged. tables::ThreadStateTable::Row sched_row; sched_row.ts = ts; sched_row.dur = dur; sched_row.cpu = sched.GetTypedColumnByName<uint32_t>("cpu")[sched_idx]; sched_row.state = running_string_id_; sched_row.utid = utid; auto id_and_row = table->Insert(sched_row); // If the sched row had a negative duration, don't add any descheduled slice // because it would be meaningless. if (sched_row.dur == -1) { return; } // This will be flushed to the table on the next sched slice (or the very end // of the big loop). info->desched_ts = ts + dur; info->desched_end_state = sched.GetTypedColumnByName<StringId>("end_state")[sched_idx]; info->scheduled_row = id_and_row.row; } void ThreadStateGenerator::AddWakingEvent( const Table& waking, uint32_t waking_idx, std::unordered_map<UniqueTid, ThreadSchedInfo>& state_map) { int64_t ts = waking.GetTypedColumnByName<int64_t>("ts")[waking_idx]; UniqueTid utid = static_cast<UniqueTid>( waking.GetTypedColumnByName<int64_t>("ref")[waking_idx]); ThreadSchedInfo* info = &state_map[utid]; // Occasionally, it is possible to get a waking event for a thread // which is already in a runnable state. When this happens, we just // ignore the waking event. // See b/186509316 for details and an example on when this happens. if (info->desched_end_state && *info->desched_end_state == runnable_string_id_) { return; } // As counter-intuitive as it seems, occasionally we can get a waking // event for a thread which is currently running. // // There are two cases when this can happen: // 1. The kernel legitimately send a waking event for a "running" thread // because the thread was woken up before the kernel switched away // from it. In this case, the waking timestamp will be in the past // because we added the descheduled slice when we processed the sched // event. // 2. We're close to the end of the trace or had data-loss and we missed // the switch out event for a thread but we see a waking after. // Case 1 described above. In this situation, we should drop the waking // entirely. if (info->desched_ts && *info->desched_ts > ts) { return; } // For case 2 and otherwise, we should just note the fact that the thread // became runnable at this time. Note that we cannot check if runnable is // already not set because we could have data-loss which leads to us getting // back to back waking for a single thread. info->runnable_ts = ts; } Table::Schema ThreadStateGenerator::CreateSchema() { auto schema = tables::ThreadStateTable::Schema(); // Because we expect our users to generally want ordered by ts, we set the // ordering for the schema to match our forced sort pass in ComputeTable. auto ts_it = std::find_if( schema.columns.begin(), schema.columns.end(), [](const Table::Schema::Column& col) { return col.name == "ts"; }); ts_it->is_sorted = true; auto id_it = std::find_if( schema.columns.begin(), schema.columns.end(), [](const Table::Schema::Column& col) { return col.name == "id"; }); id_it->is_sorted = false; return schema; } void ThreadStateGenerator::FlushPendingEventsForThread( UniqueTid utid, const ThreadSchedInfo& info, tables::ThreadStateTable* table, base::Optional<int64_t> end_ts) { // First, let's flush the descheduled period (if any) to the table. if (info.desched_ts) { PERFETTO_DCHECK(info.desched_end_state); int64_t dur; if (end_ts) { int64_t desched_end_ts = info.runnable_ts ? *info.runnable_ts : *end_ts; dur = desched_end_ts - *info.desched_ts; } else { dur = -1; } tables::ThreadStateTable::Row row; row.ts = *info.desched_ts; row.dur = dur; row.state = *info.desched_end_state; row.utid = utid; row.io_wait = info.io_wait; row.blocked_function = info.blocked_function; table->Insert(row); } // Next, flush the runnable period (if any) to the table. if (info.runnable_ts) { tables::ThreadStateTable::Row row; row.ts = *info.runnable_ts; row.dur = end_ts ? *end_ts - row.ts : -1; row.state = runnable_string_id_; row.utid = utid; table->Insert(row); } } void ThreadStateGenerator::AddBlockedReasonEvent( const Table& blocked_reason, uint32_t blocked_idx, std::unordered_map<UniqueTid, ThreadSchedInfo>& state_map) { const auto& utid_col = blocked_reason.GetTypedColumnByName<int64_t>("ref"); const auto& arg_set_id_col = blocked_reason.GetTypedColumnByName<uint32_t>("arg_set_id"); UniqueTid utid = static_cast<UniqueTid>(utid_col[blocked_idx]); uint32_t arg_set_id = arg_set_id_col[blocked_idx]; ThreadSchedInfo& info = state_map[utid]; base::Optional<Variadic> opt_value; util::Status status = context_->storage->ExtractArg(arg_set_id, "io_wait", &opt_value); // We can't do anything better than ignoring any errors here. // TODO(lalitm): see if there's a better way to handle this. if (status.ok() && opt_value) { PERFETTO_CHECK(opt_value->type == Variadic::Type::kBool); info.io_wait = opt_value->bool_value; } status = context_->storage->ExtractArg(arg_set_id, "function", &opt_value); if (status.ok() && opt_value) { PERFETTO_CHECK(opt_value->type == Variadic::Type::kString); info.blocked_function = opt_value->string_value; } } std::string ThreadStateGenerator::TableName() { return "thread_state"; } uint32_t ThreadStateGenerator::EstimateRowCount() { return context_->storage->sched_slice_table().row_count(); } } // namespace trace_processor } // namespace perfetto <commit_msg>tp: fix compile am: 82b99102e5 am: 5203a5a811<commit_after>/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/trace_processor/dynamic/thread_state_generator.h" #include <memory> #include <set> #include "src/trace_processor/types/trace_processor_context.h" namespace perfetto { namespace trace_processor { ThreadStateGenerator::ThreadStateGenerator(TraceProcessorContext* context) : running_string_id_(context->storage->InternString("Running")), runnable_string_id_(context->storage->InternString("R")), context_(context) {} ThreadStateGenerator::~ThreadStateGenerator() = default; util::Status ThreadStateGenerator::ValidateConstraints( const QueryConstraints&) { return util::OkStatus(); } std::unique_ptr<Table> ThreadStateGenerator::ComputeTable( const std::vector<Constraint>&, const std::vector<Order>&) { if (!unsorted_thread_state_table_) { int64_t trace_end_ts = context_->storage->GetTraceTimestampBoundsNs().second; unsorted_thread_state_table_ = ComputeThreadStateTable(trace_end_ts); // We explicitly sort by ts here as ComputeThreadStateTable does not insert // rows in sorted order but we expect our clients to always want to sort // on ts. Writing ComputeThreadStateTable to insert in sorted order is // more trouble than its worth. sorted_thread_state_table_ = unsorted_thread_state_table_->Sort( {unsorted_thread_state_table_->ts().ascending()}); } PERFETTO_CHECK(sorted_thread_state_table_); return std::unique_ptr<Table>(new Table(sorted_thread_state_table_->Copy())); } std::unique_ptr<tables::ThreadStateTable> ThreadStateGenerator::ComputeThreadStateTable(int64_t trace_end_ts) { std::unique_ptr<tables::ThreadStateTable> table(new tables::ThreadStateTable( context_->storage->mutable_string_pool(), nullptr)); const auto& raw_sched = context_->storage->sched_slice_table(); const auto& instants = context_->storage->instant_table(); // In both tables, exclude utid == 0 which represents the idle thread. Table sched = raw_sched.Filter({raw_sched.utid().ne(0)}, RowMap::OptimizeFor::kLookupSpeed); Table waking = instants.Filter( {instants.name().eq("sched_waking"), instants.ref().ne(0)}, RowMap::OptimizeFor::kLookupSpeed); // We prefer to use waking if at all possible and fall back to wakeup if not // available. if (waking.row_count() == 0) { waking = instants.Filter( {instants.name().eq("sched_wakeup"), instants.ref().ne(0)}, RowMap::OptimizeFor::kLookupSpeed); } Table sched_blocked_reason = instants.Filter( {instants.name().eq("sched_blocked_reason"), instants.ref().ne(0)}, RowMap::OptimizeFor::kLookupSpeed); const auto& sched_ts_col = sched.GetTypedColumnByName<int64_t>("ts"); const auto& waking_ts_col = waking.GetTypedColumnByName<int64_t>("ts"); const auto& blocked_ts_col = sched_blocked_reason.GetTypedColumnByName<int64_t>("ts"); uint32_t sched_idx = 0; uint32_t waking_idx = 0; uint32_t blocked_idx = 0; std::unordered_map<UniqueTid, ThreadSchedInfo> state_map; while (sched_idx < sched.row_count() || waking_idx < waking.row_count() || blocked_idx < sched_blocked_reason.row_count()) { int64_t sched_ts = sched_idx < sched.row_count() ? sched_ts_col[sched_idx] : std::numeric_limits<int64_t>::max(); int64_t waking_ts = waking_idx < waking.row_count() ? waking_ts_col[waking_idx] : std::numeric_limits<int64_t>::max(); int64_t blocked_ts = blocked_idx < sched_blocked_reason.row_count() ? blocked_ts_col[blocked_idx] : std::numeric_limits<int64_t>::max(); // We go through all tables, picking the earliest timestamp from any // to process that event. int64_t min_ts = std::min({sched_ts, waking_ts, blocked_ts}); if (min_ts == sched_ts) { AddSchedEvent(sched, sched_idx++, state_map, trace_end_ts, table.get()); } else if (min_ts == waking_ts) { AddWakingEvent(waking, waking_idx++, state_map); } else /* (min_ts == blocked_ts) */ { AddBlockedReasonEvent(sched_blocked_reason, blocked_idx++, state_map); } } // At the end, go through and flush any remaining pending events. for (const auto& utid_to_pending_info : state_map) { UniqueTid utid = utid_to_pending_info.first; const ThreadSchedInfo& pending_info = utid_to_pending_info.second; FlushPendingEventsForThread(utid, pending_info, table.get(), base::nullopt); } return table; } void ThreadStateGenerator::AddSchedEvent( const Table& sched, uint32_t sched_idx, std::unordered_map<UniqueTid, ThreadSchedInfo>& state_map, int64_t trace_end_ts, tables::ThreadStateTable* table) { int64_t ts = sched.GetTypedColumnByName<int64_t>("ts")[sched_idx]; UniqueTid utid = sched.GetTypedColumnByName<uint32_t>("utid")[sched_idx]; ThreadSchedInfo* info = &state_map[utid]; // Due to races in the kernel, it is possible for the same thread to be // scheduled on different CPUs at the same time. This will manifest itself // here by having |info->desched_ts| in the future of this scheduling slice // (i.e. there was a scheduling slice in the past which ended after the start // of the current scheduling slice). // // We work around this problem by truncating the previous slice to the start // of this slice and not adding the descheduled slice (i.e. we don't call // |FlushPendingEventsForThread| which adds this slice). // // See b/186509316 for details and an example on when this happens. if (info->desched_ts && info->desched_ts.value() > ts) { uint32_t prev_sched_row = info->scheduled_row.value(); int64_t prev_sched_start = table->ts()[prev_sched_row]; // Just a double check that descheduling slice would have started at the // same time the scheduling slice would have ended. PERFETTO_DCHECK(prev_sched_start + table->dur()[prev_sched_row] == info->desched_ts.value()); // Truncate the duration of the old slice to end at the start of this // scheduling slice. table->mutable_dur()->Set(prev_sched_row, ts - prev_sched_start); } else { FlushPendingEventsForThread(utid, *info, table, ts); } // Reset so we don't have any leftover data on the next round. *info = {}; // Undo the expansion of the final sched slice for each CPU to the end of the // trace by setting the duration back to -1. This counteracts the code in // SchedEventTracker::FlushPendingEvents // TODO(lalitm): remove this hack when we stop expanding the last slice to the // end of the trace. int64_t dur = sched.GetTypedColumnByName<int64_t>("dur")[sched_idx]; if (ts + dur == trace_end_ts) { dur = -1; } // Now add the sched slice itself as "Running" with the other fields // unchanged. tables::ThreadStateTable::Row sched_row; sched_row.ts = ts; sched_row.dur = dur; sched_row.cpu = sched.GetTypedColumnByName<uint32_t>("cpu")[sched_idx]; sched_row.state = running_string_id_; sched_row.utid = utid; auto id_and_row = table->Insert(sched_row); // If the sched row had a negative duration, don't add any descheduled slice // because it would be meaningless. if (sched_row.dur == -1) { return; } // This will be flushed to the table on the next sched slice (or the very end // of the big loop). info->desched_ts = ts + dur; info->desched_end_state = sched.GetTypedColumnByName<StringId>("end_state")[sched_idx]; info->scheduled_row = id_and_row.row; } void ThreadStateGenerator::AddWakingEvent( const Table& waking, uint32_t waking_idx, std::unordered_map<UniqueTid, ThreadSchedInfo>& state_map) { int64_t ts = waking.GetTypedColumnByName<int64_t>("ts")[waking_idx]; UniqueTid utid = static_cast<UniqueTid>( waking.GetTypedColumnByName<int64_t>("ref")[waking_idx]); ThreadSchedInfo* info = &state_map[utid]; // Occasionally, it is possible to get a waking event for a thread // which is already in a runnable state. When this happens, we just // ignore the waking event. // See b/186509316 for details and an example on when this happens. if (info->desched_end_state && *info->desched_end_state == runnable_string_id_) { return; } // As counter-intuitive as it seems, occasionally we can get a waking // event for a thread which is currently running. // // There are two cases when this can happen: // 1. The kernel legitimately send a waking event for a "running" thread // because the thread was woken up before the kernel switched away // from it. In this case, the waking timestamp will be in the past // because we added the descheduled slice when we processed the sched // event. // 2. We're close to the end of the trace or had data-loss and we missed // the switch out event for a thread but we see a waking after. // Case 1 described above. In this situation, we should drop the waking // entirely. if (info->desched_ts && *info->desched_ts > ts) { return; } // For case 2 and otherwise, we should just note the fact that the thread // became runnable at this time. Note that we cannot check if runnable is // already not set because we could have data-loss which leads to us getting // back to back waking for a single thread. info->runnable_ts = ts; } Table::Schema ThreadStateGenerator::CreateSchema() { auto schema = tables::ThreadStateTable::Schema(); // Because we expect our users to generally want ordered by ts, we set the // ordering for the schema to match our forced sort pass in ComputeTable. auto ts_it = std::find_if( schema.columns.begin(), schema.columns.end(), [](const Table::Schema::Column& col) { return col.name == "ts"; }); ts_it->is_sorted = true; auto id_it = std::find_if( schema.columns.begin(), schema.columns.end(), [](const Table::Schema::Column& col) { return col.name == "id"; }); id_it->is_sorted = false; return schema; } void ThreadStateGenerator::FlushPendingEventsForThread( UniqueTid utid, const ThreadSchedInfo& info, tables::ThreadStateTable* table, base::Optional<int64_t> end_ts) { // First, let's flush the descheduled period (if any) to the table. if (info.desched_ts) { PERFETTO_DCHECK(info.desched_end_state); int64_t dur; if (end_ts) { int64_t desched_end_ts = info.runnable_ts ? *info.runnable_ts : *end_ts; dur = desched_end_ts - *info.desched_ts; } else { dur = -1; } tables::ThreadStateTable::Row row; row.ts = *info.desched_ts; row.dur = dur; row.state = *info.desched_end_state; row.utid = utid; row.io_wait = info.io_wait; row.blocked_function = info.blocked_function; table->Insert(row); } // Next, flush the runnable period (if any) to the table. if (info.runnable_ts) { tables::ThreadStateTable::Row row; row.ts = *info.runnable_ts; row.dur = end_ts ? *end_ts - row.ts : -1; row.state = runnable_string_id_; row.utid = utid; table->Insert(row); } } void ThreadStateGenerator::AddBlockedReasonEvent( const Table& blocked_reason, uint32_t blocked_idx, std::unordered_map<UniqueTid, ThreadSchedInfo>& state_map) { const auto& utid_col = blocked_reason.GetTypedColumnByName<int64_t>("ref"); const auto& arg_set_id_col = blocked_reason.GetTypedColumnByName<uint32_t>("arg_set_id"); UniqueTid utid = static_cast<UniqueTid>(utid_col[blocked_idx]); uint32_t arg_set_id = arg_set_id_col[blocked_idx]; ThreadSchedInfo& info = state_map[utid]; base::Optional<Variadic> opt_value; util::Status status = context_->storage->ExtractArg(arg_set_id, "io_wait", &opt_value); // We can't do anything better than ignoring any errors here. // TODO(lalitm): see if there's a better way to handle this. if (status.ok() && opt_value) { PERFETTO_CHECK(opt_value->type == Variadic::Type::kBool); info.io_wait = opt_value->bool_value; } status = context_->storage->ExtractArg(arg_set_id, "function", &opt_value); if (status.ok() && opt_value) { PERFETTO_CHECK(opt_value->type == Variadic::Type::kString); info.blocked_function = opt_value->string_value; } } std::string ThreadStateGenerator::TableName() { return "thread_state"; } uint32_t ThreadStateGenerator::EstimateRowCount() { return context_->storage->sched_slice_table().row_count(); } } // namespace trace_processor } // namespace perfetto <|endoftext|>
<commit_before>// Copyright Toru Niina 2017. // Distributed under the MIT License. #ifndef TOML11_TYPES_HPP #define TOML11_TYPES_HPP #include "datetime.hpp" #include "string.hpp" #include "traits.hpp" #include "comments.hpp" namespace toml { template<typename Comment, // discard/preserve_comment template<typename ...> Table, // map-like class template<typename ...> Array> // vector-like class class basic_value; using character = char; using key = std::string; using boolean = bool; using integer = std::int64_t; using floating = double; // "float" is a keyward, cannot use it here. // the following stuffs are structs defined here, so aliases are not needed. // - string // - offset_datetime // - offset_datetime // - local_datetime // - local_date // - local_time // default toml::value and default array/table using value = basic_value<discard_comment, std::unordered_map, std::vector>; enum class value_t : std::uint8_t { empty = 0, boolean = 1, integer = 2, floating = 3, string = 4, offset_datetime = 5, local_datetime = 6, local_date = 7, local_time = 8, array = 9, table = 10, }; template<typename charT, typename traits> inline std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& os, value_t t) { switch(t) { case value_t::boolean : os << "boolean"; return os; case value_t::integer : os << "integer"; return os; case value_t::floating : os << "floating"; return os; case value_t::string : os << "string"; return os; case value_t::offset_datetime : os << "offset_datetime"; return os; case value_t::local_datetime : os << "local_datetime"; return os; case value_t::local_date : os << "local_date"; return os; case value_t::local_time : os << "local_time"; return os; case value_t::array : os << "array"; return os; case value_t::table : os << "table"; return os; case value_t::empty : os << "empty"; return os; default : os << "unknown"; return os; } } template<typename charT = char, typename traits = std::char_traits<charT>, typename alloc = std::allocator<charT>> inline std::basic_string<charT, traits, alloc> stringize(value_t t) { std::basic_ostringstream<charT, traits, alloc> oss; oss << t; return oss.str(); } namespace detail { // helper to define a type that represents a value_t value. template<value_t V> using value_t_constant = std::integral_constant<value_t, V>; // meta-function that convertes from value_t to the exact toml type that corresponds to. // It takes toml::basic_value type because array and table types depend on it. template<value_t t, typename Value> struct enum_to_type {using type = void ;}; template<typename Value> struct enum_to_type<value_t::empty , Value>{using type = void ;}; template<typename Value> struct enum_to_type<value_t::boolean , Value>{using type = boolean ;}; template<typename Value> struct enum_to_type<value_t::integer , Value>{using type = integer ;}; template<typename Value> struct enum_to_type<value_t::floating , Value>{using type = floating ;}; template<typename Value> struct enum_to_type<value_t::string , Value>{using type = string ;}; template<typename Value> struct enum_to_type<value_t::offset_datetime, Value>{using type = offset_datetime ;}; template<typename Value> struct enum_to_type<value_t::local_datetime , Value>{using type = local_datetime ;}; template<typename Value> struct enum_to_type<value_t::local_date , Value>{using type = local_date ;}; template<typename Value> struct enum_to_type<value_t::local_time , Value>{using type = local_time ;}; template<typename Value> struct enum_to_type<value_t::array , Value>{using type = typename Value::array_type;}; template<typename Value> struct enum_to_type<value_t::table , Value>{using type = typename Value::table_type;}; // meta-function that converts from an exact toml type to the enum that corresponds to. template<typename T, typename Value> struct type_to_enum : typename std::conditional< std::is_same<T, typename Value::array_type>::value, // if T == array_type, value_t_constant<value_t::array>, // then value_t::array typename std::conditional< // else... std::is_same<T, typename Value::table_type>::value, // if T == table_type value_t_constant<value_t::table>, // then value_t::table value_t_constant<value_t::empty> // else value_t::empty >::type >::type {} template<typename Value> struct type_to_enum<boolean , Value>: value_t_constant<value_t::boolean > {}; template<typename Value> struct type_to_enum<integer , Value>: value_t_constant<value_t::integer > {}; template<typename Value> struct type_to_enum<floating , Value>: value_t_constant<value_t::floating > {}; template<typename Value> struct type_to_enum<string , Value>: value_t_constant<value_t::string > {}; template<typename Value> struct type_to_enum<offset_datetime, Value>: value_t_constant<value_t::offset_datetime> {}; template<typename Value> struct type_to_enum<local_datetime , Value>: value_t_constant<value_t::local_datetime > {}; template<typename Value> struct type_to_enum<local_date , Value>: value_t_constant<value_t::local_date > {}; template<typename Value> struct type_to_enum<local_time , Value>: value_t_constant<value_t::local_time > {}; // meta-function that checks the type T is the same as one of the toml::* types. template<typename T, typename Value> struct is_exact_toml_type : disjunction< std::is_same<T, boolean >, std::is_same<T, integer >, std::is_same<T, floating >, std::is_same<T, string >, std::is_same<T, offset_datetime>, std::is_same<T, local_datetime >, std::is_same<T, local_date >, std::is_same<T, local_time >, std::is_same<T, typename Value::array_type>, std::is_same<T, typename Value::table_type> >{}; template<typename T, typename V> struct is_exact_toml_type<T&, V> : is_exact_toml_type<T, V>{}; template<typename T, typename V> struct is_exact_toml_type<T const&, V> : is_exact_toml_type<T, V>{}; template<typename T, typename V> struct is_exact_toml_type<T volatile&, V> : is_exact_toml_type<T, V>{}; template<typename T, typename V> struct is_exact_toml_type<T const volatile&, V>: is_exact_toml_type<T, V>{}; // meta-function that check type T is convertible to toml::* types template<typename T, typename Value> struct is_convertible_to_toml_value : disjunction< std::is_same<T, boolean>, // T is bool or std::is_integral<T>, // T is an integer or std::is_floating_point<T>, // T is a floating point or std::is_same<T, std::string>, // T is std::string or std::is_same<T, toml::string>, // T is toml::string or is_string_literal<T>, // T is "string literal" or std::is_same<T, toml::local_date>, // T is local_date or std::is_same<T, toml::local_time>, // T is local_time or std::is_same<T, toml::local_datetime>, // T is local_datetime or std::is_same<T, toml::offset_datetime>, // T is offset_datetime or std::is_same<T, std::chrono::system_clock::time_point> // T is time_point or is_chrono_duration<T>, // T is a duration or std::is_same<T, typename Value::array_type>, // T is an array type or std::is_same<T, typename Value::table_type>, // T is an array type or >{} // meta-function that returns value_t that represent the convertible type template<typename T, typename Value> struct convertible_toml_type_of : typename std::conditional< /* if */ is_exact_toml_type<T, Value>::value, /* then */ value_t_constant<type_to_enum<T, Value>::value>, /* else */ typename std::conditional< // ---------------------------------------------------------------------- /* if */ std::is_integral<T>::value, /* then */ value_t_constant<value_t::integer>, /* else */ typename std::conditional< // ---------------------------------------------------------------------- /* if */ std::is_floating_point<T>::value, /* then */ value_t_constant<value_t::floating>, /* else */ typename std::conditional< // ---------------------------------------------------------------------- /* if */ std::is_same<std::string>::value, /* then */ value_t_constant<value_t::string>, /* else */ typename std::conditional< // ---------------------------------------------------------------------- /* if */ is_string_literal<T>, /* then */ value_t_constant<value_t::string>, /* else */ typename std::conditional< // ---------------------------------------------------------------------- /* if */ is_chrono_duration<T>, /* then */ value_t_constant<value_t::local_time>, /* else */ typename std::conditional< // ---------------------------------------------------------------------- /* if */ std::is_same<T, std::chrono::system_clock::time_point>, /* then */ value_t_constant<value_t::offset_datetime>, /* else */ value_t_constant<value_t::empty>, // ---------------------------------------------------------------------- >::type>::type>::type>::type>::type>::type>::type >{} } // detail } // toml #endif// TOML11_TYPES_H <commit_msg>fix: typos<commit_after>// Copyright Toru Niina 2017. // Distributed under the MIT License. #ifndef TOML11_TYPES_HPP #define TOML11_TYPES_HPP #include "datetime.hpp" #include "string.hpp" #include "traits.hpp" #include "comments.hpp" #include <vector> #include <unordered_map> namespace toml { template<typename Comment, // discard/preserve_comment template<typename ...> class Table, // map-like class template<typename ...> class Array> // vector-like class class basic_value; using character = char; using key = std::string; using boolean = bool; using integer = std::int64_t; using floating = double; // "float" is a keyward, cannot use it here. // the following stuffs are structs defined here, so aliases are not needed. // - string // - offset_datetime // - offset_datetime // - local_datetime // - local_date // - local_time // default toml::value and default array/table using value = basic_value<discard_comments, std::unordered_map, std::vector>; enum class value_t : std::uint8_t { empty = 0, boolean = 1, integer = 2, floating = 3, string = 4, offset_datetime = 5, local_datetime = 6, local_date = 7, local_time = 8, array = 9, table = 10, }; template<typename charT, typename traits> inline std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& os, value_t t) { switch(t) { case value_t::boolean : os << "boolean"; return os; case value_t::integer : os << "integer"; return os; case value_t::floating : os << "floating"; return os; case value_t::string : os << "string"; return os; case value_t::offset_datetime : os << "offset_datetime"; return os; case value_t::local_datetime : os << "local_datetime"; return os; case value_t::local_date : os << "local_date"; return os; case value_t::local_time : os << "local_time"; return os; case value_t::array : os << "array"; return os; case value_t::table : os << "table"; return os; case value_t::empty : os << "empty"; return os; default : os << "unknown"; return os; } } template<typename charT = char, typename traits = std::char_traits<charT>, typename alloc = std::allocator<charT>> inline std::basic_string<charT, traits, alloc> stringize(value_t t) { std::basic_ostringstream<charT, traits, alloc> oss; oss << t; return oss.str(); } namespace detail { // helper to define a type that represents a value_t value. template<value_t V> using value_t_constant = std::integral_constant<value_t, V>; // meta-function that convertes from value_t to the exact toml type that corresponds to. // It takes toml::basic_value type because array and table types depend on it. template<value_t t, typename Value> struct enum_to_type {using type = void ;}; template<typename Value> struct enum_to_type<value_t::empty , Value>{using type = void ;}; template<typename Value> struct enum_to_type<value_t::boolean , Value>{using type = boolean ;}; template<typename Value> struct enum_to_type<value_t::integer , Value>{using type = integer ;}; template<typename Value> struct enum_to_type<value_t::floating , Value>{using type = floating ;}; template<typename Value> struct enum_to_type<value_t::string , Value>{using type = string ;}; template<typename Value> struct enum_to_type<value_t::offset_datetime, Value>{using type = offset_datetime ;}; template<typename Value> struct enum_to_type<value_t::local_datetime , Value>{using type = local_datetime ;}; template<typename Value> struct enum_to_type<value_t::local_date , Value>{using type = local_date ;}; template<typename Value> struct enum_to_type<value_t::local_time , Value>{using type = local_time ;}; template<typename Value> struct enum_to_type<value_t::array , Value>{using type = typename Value::array_type;}; template<typename Value> struct enum_to_type<value_t::table , Value>{using type = typename Value::table_type;}; // meta-function that converts from an exact toml type to the enum that corresponds to. template<typename T, typename Value> struct type_to_enum : std::conditional< std::is_same<T, typename Value::array_type>::value, // if T == array_type, value_t_constant<value_t::array>, // then value_t::array typename std::conditional< // else... std::is_same<T, typename Value::table_type>::value, // if T == table_type value_t_constant<value_t::table>, // then value_t::table value_t_constant<value_t::empty> // else value_t::empty >::type >::type {}; template<typename Value> struct type_to_enum<boolean , Value>: value_t_constant<value_t::boolean > {}; template<typename Value> struct type_to_enum<integer , Value>: value_t_constant<value_t::integer > {}; template<typename Value> struct type_to_enum<floating , Value>: value_t_constant<value_t::floating > {}; template<typename Value> struct type_to_enum<string , Value>: value_t_constant<value_t::string > {}; template<typename Value> struct type_to_enum<offset_datetime, Value>: value_t_constant<value_t::offset_datetime> {}; template<typename Value> struct type_to_enum<local_datetime , Value>: value_t_constant<value_t::local_datetime > {}; template<typename Value> struct type_to_enum<local_date , Value>: value_t_constant<value_t::local_date > {}; template<typename Value> struct type_to_enum<local_time , Value>: value_t_constant<value_t::local_time > {}; // meta-function that checks the type T is the same as one of the toml::* types. template<typename T, typename Value> struct is_exact_toml_type : disjunction< std::is_same<T, boolean >, std::is_same<T, integer >, std::is_same<T, floating >, std::is_same<T, string >, std::is_same<T, offset_datetime>, std::is_same<T, local_datetime >, std::is_same<T, local_date >, std::is_same<T, local_time >, std::is_same<T, typename Value::array_type>, std::is_same<T, typename Value::table_type> >{}; template<typename T, typename V> struct is_exact_toml_type<T&, V> : is_exact_toml_type<T, V>{}; template<typename T, typename V> struct is_exact_toml_type<T const&, V> : is_exact_toml_type<T, V>{}; template<typename T, typename V> struct is_exact_toml_type<T volatile&, V> : is_exact_toml_type<T, V>{}; template<typename T, typename V> struct is_exact_toml_type<T const volatile&, V>: is_exact_toml_type<T, V>{}; // meta-function that check type T is convertible to toml::* types template<typename T, typename Value> struct is_convertible_to_toml_value : disjunction< std::is_same<T, boolean>, // T is bool or std::is_integral<T>, // T is an integer or std::is_floating_point<T>, // T is a floating point or std::is_same<T, std::string>, // T is std::string or std::is_same<T, toml::string>, // T is toml::string or is_string_literal<T>, // T is "string literal" or std::is_same<T, toml::local_date>, // T is local_date or std::is_same<T, toml::local_time>, // T is local_time or std::is_same<T, toml::local_datetime>, // T is local_datetime or std::is_same<T, toml::offset_datetime>, // T is offset_datetime or std::is_same<T, std::chrono::system_clock::time_point>, // T is time_point or is_chrono_duration<T>, // T is a duration or std::is_same<T, typename Value::array_type>, // T is an array type or std::is_same<T, typename Value::table_type> // T is an array type or >{}; // meta-function that returns value_t that represent the convertible type template<typename T, typename Value> struct convertible_toml_type_of : std::conditional< /* if */ is_exact_toml_type<T, Value>::value, /* then */ value_t_constant<type_to_enum<T, Value>::value>, /* else */ typename std::conditional< // ---------------------------------------------------------------------- /* if */ std::is_integral<T>::value, /* then */ value_t_constant<value_t::integer>, /* else */ typename std::conditional< // ---------------------------------------------------------------------- /* if */ std::is_floating_point<T>::value, /* then */ value_t_constant<value_t::floating>, /* else */ typename std::conditional< // ---------------------------------------------------------------------- /* if */ std::is_same<T, std::string>::value, /* then */ value_t_constant<value_t::string>, /* else */ typename std::conditional< // ---------------------------------------------------------------------- /* if */ is_string_literal<T>::value, /* then */ value_t_constant<value_t::string>, /* else */ typename std::conditional< // ---------------------------------------------------------------------- /* if */ is_chrono_duration<T>::value, /* then */ value_t_constant<value_t::local_time>, /* else */ typename std::conditional< // ---------------------------------------------------------------------- /* if */ std::is_same<T, std::chrono::system_clock::time_point>::value, /* then */ value_t_constant<value_t::offset_datetime>, /* else */ value_t_constant<value_t::empty> // ---------------------------------------------------------------------- >::type>::type>::type>::type>::type>::type>::type {}; } // detail } // toml #endif// TOML11_TYPES_H <|endoftext|>
<commit_before>// Copyright 2017-2020 The Verible Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 "verilog/formatting/formatter.h" #include <algorithm> #include <cstddef> #include <iostream> #include <iterator> #include <vector> #include "common/formatting/format_token.h" #include "common/formatting/line_wrap_searcher.h" #include "common/formatting/token_partition_tree.h" #include "common/formatting/unwrapped_line.h" #include "common/strings/range.h" #include "common/text/line_column_map.h" #include "common/text/text_structure.h" #include "common/text/token_info.h" #include "common/util/expandable_tree_view.h" #include "common/util/iterator_range.h" #include "common/util/logging.h" #include "common/util/spacer.h" #include "common/util/status.h" #include "common/util/vector_tree.h" #include "verilog/formatting/comment_controls.h" #include "verilog/formatting/format_style.h" #include "verilog/formatting/token_annotator.h" #include "verilog/formatting/tree_unwrapper.h" #include "verilog/parser/verilog_token_enum.h" namespace verilog { namespace formatter { using verible::ExpandableTreeView; using verible::PartitionPolicyEnum; using verible::TokenPartitionTree; using verible::TreeViewNodeInfo; using verible::UnwrappedLine; using verible::VectorTree; typedef VectorTree<TreeViewNodeInfo<UnwrappedLine>> partition_node_type; // Decided at each node in UnwrappedLine partition tree whether or not // it should be expanded or unexpanded. static void DeterminePartitionExpansion(partition_node_type* node, const FormatStyle& style) { auto& node_view = node->Value(); const auto& children = node->Children(); // If this is a leaf partition, there is nothing to expand. if (children.empty()) { VLOG(3) << "No children to expand."; node_view.Unexpand(); return; } // If any children are expanded, then this node must be expanded, // regardless of the UnwrappedLine's chosen policy. // Thus, this function must be executed with a post-order traversal. const auto iter = std::find_if(children.begin(), children.end(), [](const partition_node_type& child) { return child.Value().IsExpanded(); }); if (iter != children.end()) { VLOG(3) << "Child forces parent to expand."; node_view.Expand(); return; } // Expand or not, depending on partition policy and other conditions. const auto& uwline = node_view.Value(); const auto partition_policy = uwline.PartitionPolicy(); VLOG(3) << "partition policy: " << partition_policy; switch (partition_policy) { case PartitionPolicyEnum::kAlwaysExpand: { node_view.Expand(); break; } case PartitionPolicyEnum::kFitOnLineElseExpand: { if (verible::FitsOnLine(uwline, style)) { VLOG(3) << "Fits, un-expanding."; node_view.Unexpand(); } else { VLOG(3) << "Does not fit, expanding."; node_view.Expand(); } } } } // Produce a worklist of independently formattable UnwrappedLines. static std::vector<UnwrappedLine> MakeUnwrappedLinesWorklist( const TokenPartitionTree& format_tokens_partitions, const FormatStyle& style) { // Initialize a tree view that treats partitions as fully-expanded. ExpandableTreeView<UnwrappedLine> format_tokens_partition_view( format_tokens_partitions); // For unwrapped lines that fit, don't bother expanding their partitions. // Post-order traversal: if a child doesn't 'fit' and needs to be expanded, // so must all of its parents (and transitively, ancestors). format_tokens_partition_view.ApplyPostOrder( [&style](partition_node_type& node) { DeterminePartitionExpansion(&node, style); }); // Remove trailing blank lines. std::vector<UnwrappedLine> unwrapped_lines( format_tokens_partition_view.begin(), format_tokens_partition_view.end()); while (!unwrapped_lines.empty() && unwrapped_lines.back().IsEmpty()) { unwrapped_lines.pop_back(); } return unwrapped_lines; } static void PrintLargestPartitions( std::ostream& stream, const TokenPartitionTree& token_partitions, size_t max_partitions, const verible::LineColumnMap& line_column_map, absl::string_view base_text) { stream << "Showing the " << max_partitions << " largest (leaf) token partitions:" << std::endl; const auto ranked_partitions = FindLargestPartitions(token_partitions, max_partitions); const verible::Spacer hline(80, '='); for (const auto& partition : ranked_partitions) { stream << hline << "\n[" << partition->Size() << " tokens"; if (!partition->IsEmpty()) { stream << ", starting at line:col " << line_column_map( partition->TokensRange().front().token->left(base_text)); } stream << "]: " << *partition << std::endl; } stream << hline << std::endl; } std::ostream& Formatter::ExecutionControl::Stream() const { return (stream != nullptr) ? *stream : std::cout; } static verible::iterator_range<std::vector<verible::PreFormatToken>::iterator> FindFormatTokensInByteOffsetRange( std::vector<verible::PreFormatToken>::iterator begin, std::vector<verible::PreFormatToken>::iterator end, std::pair<int, int> byte_offset_range, absl::string_view base_text) { const auto tokens_begin = std::lower_bound(begin, end, byte_offset_range.first, [=](const verible::PreFormatToken& t, size_t position) { return t.token->left(base_text) < position; }); const auto tokens_end = std::upper_bound(tokens_begin, end, byte_offset_range.second, [=](size_t position, const verible::PreFormatToken& t) { return position < t.token->right(base_text); }); return verible::make_range(tokens_begin, tokens_end); } static void PreserveSpacesOnDisabledTokenRanges( std::vector<verible::PreFormatToken>* ftokens, const ByteOffsetSet& disabled_ranges, absl::string_view base_text) { VLOG(2) << __FUNCTION__; // saved_iter: shrink bounds of binary search with every iteration, // due to monotonic, non-overlapping intervals. auto saved_iter = ftokens->begin(); for (const auto& range : disabled_ranges) { // 'range' is in byte offsets. // [begin_disable, end_disable) mark the range of format tokens to be // marked as preserving original spacing (i.e. not formatted). VLOG(2) << "disabling: [" << range.first << ',' << range.second << ')'; const auto disable_range = FindFormatTokensInByteOffsetRange( saved_iter, ftokens->end(), range, base_text); const auto begin_disable = disable_range.begin(); const auto end_disable = disable_range.end(); VLOG(2) << "tokens: [" << std::distance(ftokens->begin(), begin_disable) << ',' << std::distance(ftokens->begin(), end_disable) << ')'; // Mark tokens in the disabled range as preserving original spaces. for (auto& ft : disable_range) { VLOG(2) << "disable-format preserve spaces before: " << *ft.token; ft.before.break_decision = verible::SpacingOptions::Preserve; } // kludge: When the disabled range immediately follows a //-style // comment, skip past the trailing '\n' (not included in the comment // token), which will be printed by the Emit() method, and preserve the // whitespaces *beyond* that point up to the start of the following // token's text. This way, rendering the start of the format-disabled // excerpt won't get redundant '\n's. if (begin_disable != ftokens->begin() && begin_disable != end_disable) { const auto prev_ftoken = std::prev(begin_disable); if (prev_ftoken->token->token_enum == TK_EOL_COMMENT) { // consume the trailing '\n' from the preceding //-comment ++begin_disable->before.preserved_space_start; } } // start next iteration search from previous iteration's end saved_iter = end_disable; } } verible::util::Status Formatter::Format(const ExecutionControl& control) { const absl::string_view full_text(text_structure_.Contents()); const auto& token_stream(text_structure_.TokenStream()); // Initialize auxiliary data needed for TreeUnwrapper. UnwrapperData unwrapper_data(token_stream); // Partition input token stream into hierarchical set of UnwrappedLines. TreeUnwrapper tree_unwrapper(text_structure_, style_, unwrapper_data.preformatted_tokens); const TokenPartitionTree* format_tokens_partitions = nullptr; // TODO(fangism): The following block could be parallelized because // full-partitioning does not depend on format annotations. { // Annotate inter-token information between all adjacent PreFormatTokens. // This must be done before any decisions about ExpandableTreeView // can be made because they depend on minimum-spacing, and must-break. AnnotateFormattingInformation(style_, text_structure_, unwrapper_data.preformatted_tokens.begin(), unwrapper_data.preformatted_tokens.end()); if (style_.preserve_horizontal_spaces != PreserveSpaces::All) { // Determine ranges of disabling the formatter. disabled_ranges_ = DisableFormattingRanges(full_text, token_stream); PreserveSpacesOnDisabledTokenRanges(&unwrapper_data.preformatted_tokens, disabled_ranges_, full_text); } // else don't bother, when already preserving all spaces // Partition PreFormatTokens into candidate unwrapped lines. format_tokens_partitions = tree_unwrapper.Unwrap(); } { // For debugging only: identify largest leaf partitions, and stop. if (control.show_token_partition_tree) { control.Stream() << "Full token partition tree:\n" << verible::TokenPartitionTreePrinter( *format_tokens_partitions) << std::endl; } if (control.show_largest_token_partitions != 0) { PrintLargestPartitions(control.Stream(), *format_tokens_partitions, control.show_largest_token_partitions, text_structure_.GetLineColumnMap(), full_text); } if (control.AnyStop()) { return verible::util::OkStatus(); } } // Produce sequence of independently operable UnwrappedLines. const auto unwrapped_lines = MakeUnwrappedLinesWorklist(*format_tokens_partitions, style_); // For each UnwrappedLine: minimize total penalty of wrap/break decisions. // TODO(fangism): This could be parallelized if results are written // to their own 'slots'. std::vector<const UnwrappedLine*> partially_formatted_lines; formatted_lines_.reserve(unwrapped_lines.size()); for (const auto& uwline : unwrapped_lines) { // TODO(fangism): Use different formatting strategies depending on // uwline.PartitionPolicy(). const auto optimal_solutions = verible::SearchLineWraps(uwline, style_, control.max_search_states); if (control.show_equally_optimal_wrappings && optimal_solutions.size() > 1) { verible::DisplayEquallyOptimalWrappings(control.Stream(), uwline, optimal_solutions); } // Arbitrarily choose the first solution, if there are multiple. formatted_lines_.push_back(optimal_solutions.front()); if (!formatted_lines_.back().CompletedFormatting()) { // Copy over any lines that did not finish wrap searching. partially_formatted_lines.push_back(&uwline); } } // Report any unwrapped lines that failed to complete wrap searching. if (!partially_formatted_lines.empty()) { std::ostringstream err_stream; err_stream << "*** Some token partitions failed to complete within the " "search limit:" << std::endl; for (const auto* line : partially_formatted_lines) { err_stream << *line << std::endl; } err_stream << "*** end of partially formatted partition list" << std::endl; // Treat search state limit like a limited resource. return verible::util::ResourceExhaustedError(err_stream.str()); } return verible::util::OkStatus(); } // Returns text between last token and EOF. absl::string_view Formatter::TrailingWhiteSpaces() const { const absl::string_view full_text(text_structure_.Contents()); if (formatted_lines_.empty()) { // Text contains only whitespace tokens. return full_text; } else { // Preserve vertical spaces between last token and EOF. const auto& last_line = formatted_lines_.back().Tokens(); const auto* end_of_buffer = full_text.end(); if (last_line.empty()) { return absl::string_view(end_of_buffer, 0); } else { const auto* last_printed_offset = last_line.back().token->text.end(); return verible::make_string_view_range(last_printed_offset, end_of_buffer); } } } void Formatter::Emit(std::ostream& stream) const { const absl::string_view full_text(text_structure_.Contents()); if (style_.preserve_horizontal_spaces == PreserveSpaces::All) { // Need to track pre-existing spaces between token partitions. for (const auto& line : formatted_lines_) { line.FormatLinePreserveLeadingSpace(stream); } // Handle trailing spaces after last token. stream << TrailingWhiteSpaces(); } else { // (horizontal) PreserveSpaces::None or UnhandledCasesOnly switch (style_.preserve_vertical_spaces) { case PreserveSpaces::None: { for (const auto& line : formatted_lines_) { stream << line; // Normally, print a '\n' after this FormattedExcerpt. // The exception is when the space that follows the last token // on this line is covered by one of the formatting-disabled // intervals. In that case, print the original spacing instead. const auto back_offset = line.Tokens().back().token->right(full_text); if (!disabled_ranges_.Contains(back_offset)) stream << '\n'; } // possibly preserve spaces after the last token if (disabled_ranges_.Contains(full_text.length() - 1)) { stream << TrailingWhiteSpaces(); } break; } case PreserveSpaces::All: case PreserveSpaces::UnhandledCasesOnly: bool is_first_line = true; for (const auto& line : formatted_lines_) { line.FormatLinePreserveLeadingNewlines(stream, is_first_line); is_first_line = false; } // Handle trailing spaces after last token. const size_t newline_count = verible::FormattedExcerpt::PreservedNewlinesCount( TrailingWhiteSpaces(), is_first_line); stream << verible::Spacer(newline_count, '\n'); break; } // TODO(fangism): This currently doesn't adequately handle anything betweeen // PreserveSpace::None and ::All, needs a clean policy for // PreserveSpace::UnhandledCasesOnly. } } } // namespace formatter } // namespace verilog <commit_msg>Consistently use signed int for byte-offset comparisons.<commit_after>// Copyright 2017-2020 The Verible Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 "verilog/formatting/formatter.h" #include <algorithm> #include <cstddef> #include <iostream> #include <iterator> #include <vector> #include "common/formatting/format_token.h" #include "common/formatting/line_wrap_searcher.h" #include "common/formatting/token_partition_tree.h" #include "common/formatting/unwrapped_line.h" #include "common/strings/range.h" #include "common/text/line_column_map.h" #include "common/text/text_structure.h" #include "common/text/token_info.h" #include "common/util/expandable_tree_view.h" #include "common/util/iterator_range.h" #include "common/util/logging.h" #include "common/util/spacer.h" #include "common/util/status.h" #include "common/util/vector_tree.h" #include "verilog/formatting/comment_controls.h" #include "verilog/formatting/format_style.h" #include "verilog/formatting/token_annotator.h" #include "verilog/formatting/tree_unwrapper.h" #include "verilog/parser/verilog_token_enum.h" namespace verilog { namespace formatter { using verible::ExpandableTreeView; using verible::PartitionPolicyEnum; using verible::TokenPartitionTree; using verible::TreeViewNodeInfo; using verible::UnwrappedLine; using verible::VectorTree; typedef VectorTree<TreeViewNodeInfo<UnwrappedLine>> partition_node_type; // Decided at each node in UnwrappedLine partition tree whether or not // it should be expanded or unexpanded. static void DeterminePartitionExpansion(partition_node_type* node, const FormatStyle& style) { auto& node_view = node->Value(); const auto& children = node->Children(); // If this is a leaf partition, there is nothing to expand. if (children.empty()) { VLOG(3) << "No children to expand."; node_view.Unexpand(); return; } // If any children are expanded, then this node must be expanded, // regardless of the UnwrappedLine's chosen policy. // Thus, this function must be executed with a post-order traversal. const auto iter = std::find_if(children.begin(), children.end(), [](const partition_node_type& child) { return child.Value().IsExpanded(); }); if (iter != children.end()) { VLOG(3) << "Child forces parent to expand."; node_view.Expand(); return; } // Expand or not, depending on partition policy and other conditions. const auto& uwline = node_view.Value(); const auto partition_policy = uwline.PartitionPolicy(); VLOG(3) << "partition policy: " << partition_policy; switch (partition_policy) { case PartitionPolicyEnum::kAlwaysExpand: { node_view.Expand(); break; } case PartitionPolicyEnum::kFitOnLineElseExpand: { if (verible::FitsOnLine(uwline, style)) { VLOG(3) << "Fits, un-expanding."; node_view.Unexpand(); } else { VLOG(3) << "Does not fit, expanding."; node_view.Expand(); } } } } // Produce a worklist of independently formattable UnwrappedLines. static std::vector<UnwrappedLine> MakeUnwrappedLinesWorklist( const TokenPartitionTree& format_tokens_partitions, const FormatStyle& style) { // Initialize a tree view that treats partitions as fully-expanded. ExpandableTreeView<UnwrappedLine> format_tokens_partition_view( format_tokens_partitions); // For unwrapped lines that fit, don't bother expanding their partitions. // Post-order traversal: if a child doesn't 'fit' and needs to be expanded, // so must all of its parents (and transitively, ancestors). format_tokens_partition_view.ApplyPostOrder( [&style](partition_node_type& node) { DeterminePartitionExpansion(&node, style); }); // Remove trailing blank lines. std::vector<UnwrappedLine> unwrapped_lines( format_tokens_partition_view.begin(), format_tokens_partition_view.end()); while (!unwrapped_lines.empty() && unwrapped_lines.back().IsEmpty()) { unwrapped_lines.pop_back(); } return unwrapped_lines; } static void PrintLargestPartitions( std::ostream& stream, const TokenPartitionTree& token_partitions, size_t max_partitions, const verible::LineColumnMap& line_column_map, absl::string_view base_text) { stream << "Showing the " << max_partitions << " largest (leaf) token partitions:" << std::endl; const auto ranked_partitions = FindLargestPartitions(token_partitions, max_partitions); const verible::Spacer hline(80, '='); for (const auto& partition : ranked_partitions) { stream << hline << "\n[" << partition->Size() << " tokens"; if (!partition->IsEmpty()) { stream << ", starting at line:col " << line_column_map( partition->TokensRange().front().token->left(base_text)); } stream << "]: " << *partition << std::endl; } stream << hline << std::endl; } std::ostream& Formatter::ExecutionControl::Stream() const { return (stream != nullptr) ? *stream : std::cout; } static verible::iterator_range<std::vector<verible::PreFormatToken>::iterator> FindFormatTokensInByteOffsetRange( std::vector<verible::PreFormatToken>::iterator begin, std::vector<verible::PreFormatToken>::iterator end, std::pair<int, int> byte_offset_range, absl::string_view base_text) { const auto tokens_begin = std::lower_bound(begin, end, byte_offset_range.first, [=](const verible::PreFormatToken& t, int position) { return t.token->left(base_text) < position; }); const auto tokens_end = std::upper_bound(tokens_begin, end, byte_offset_range.second, [=](int position, const verible::PreFormatToken& t) { return position < t.token->right(base_text); }); return verible::make_range(tokens_begin, tokens_end); } static void PreserveSpacesOnDisabledTokenRanges( std::vector<verible::PreFormatToken>* ftokens, const ByteOffsetSet& disabled_ranges, absl::string_view base_text) { VLOG(2) << __FUNCTION__; // saved_iter: shrink bounds of binary search with every iteration, // due to monotonic, non-overlapping intervals. auto saved_iter = ftokens->begin(); for (const auto& range : disabled_ranges) { // 'range' is in byte offsets. // [begin_disable, end_disable) mark the range of format tokens to be // marked as preserving original spacing (i.e. not formatted). VLOG(2) << "disabling: [" << range.first << ',' << range.second << ')'; const auto disable_range = FindFormatTokensInByteOffsetRange( saved_iter, ftokens->end(), range, base_text); const auto begin_disable = disable_range.begin(); const auto end_disable = disable_range.end(); VLOG(2) << "tokens: [" << std::distance(ftokens->begin(), begin_disable) << ',' << std::distance(ftokens->begin(), end_disable) << ')'; // Mark tokens in the disabled range as preserving original spaces. for (auto& ft : disable_range) { VLOG(2) << "disable-format preserve spaces before: " << *ft.token; ft.before.break_decision = verible::SpacingOptions::Preserve; } // kludge: When the disabled range immediately follows a //-style // comment, skip past the trailing '\n' (not included in the comment // token), which will be printed by the Emit() method, and preserve the // whitespaces *beyond* that point up to the start of the following // token's text. This way, rendering the start of the format-disabled // excerpt won't get redundant '\n's. if (begin_disable != ftokens->begin() && begin_disable != end_disable) { const auto prev_ftoken = std::prev(begin_disable); if (prev_ftoken->token->token_enum == TK_EOL_COMMENT) { // consume the trailing '\n' from the preceding //-comment ++begin_disable->before.preserved_space_start; } } // start next iteration search from previous iteration's end saved_iter = end_disable; } } verible::util::Status Formatter::Format(const ExecutionControl& control) { const absl::string_view full_text(text_structure_.Contents()); const auto& token_stream(text_structure_.TokenStream()); // Initialize auxiliary data needed for TreeUnwrapper. UnwrapperData unwrapper_data(token_stream); // Partition input token stream into hierarchical set of UnwrappedLines. TreeUnwrapper tree_unwrapper(text_structure_, style_, unwrapper_data.preformatted_tokens); const TokenPartitionTree* format_tokens_partitions = nullptr; // TODO(fangism): The following block could be parallelized because // full-partitioning does not depend on format annotations. { // Annotate inter-token information between all adjacent PreFormatTokens. // This must be done before any decisions about ExpandableTreeView // can be made because they depend on minimum-spacing, and must-break. AnnotateFormattingInformation(style_, text_structure_, unwrapper_data.preformatted_tokens.begin(), unwrapper_data.preformatted_tokens.end()); if (style_.preserve_horizontal_spaces != PreserveSpaces::All) { // Determine ranges of disabling the formatter. disabled_ranges_ = DisableFormattingRanges(full_text, token_stream); PreserveSpacesOnDisabledTokenRanges(&unwrapper_data.preformatted_tokens, disabled_ranges_, full_text); } // else don't bother, when already preserving all spaces // Partition PreFormatTokens into candidate unwrapped lines. format_tokens_partitions = tree_unwrapper.Unwrap(); } { // For debugging only: identify largest leaf partitions, and stop. if (control.show_token_partition_tree) { control.Stream() << "Full token partition tree:\n" << verible::TokenPartitionTreePrinter( *format_tokens_partitions) << std::endl; } if (control.show_largest_token_partitions != 0) { PrintLargestPartitions(control.Stream(), *format_tokens_partitions, control.show_largest_token_partitions, text_structure_.GetLineColumnMap(), full_text); } if (control.AnyStop()) { return verible::util::OkStatus(); } } // Produce sequence of independently operable UnwrappedLines. const auto unwrapped_lines = MakeUnwrappedLinesWorklist(*format_tokens_partitions, style_); // For each UnwrappedLine: minimize total penalty of wrap/break decisions. // TODO(fangism): This could be parallelized if results are written // to their own 'slots'. std::vector<const UnwrappedLine*> partially_formatted_lines; formatted_lines_.reserve(unwrapped_lines.size()); for (const auto& uwline : unwrapped_lines) { // TODO(fangism): Use different formatting strategies depending on // uwline.PartitionPolicy(). const auto optimal_solutions = verible::SearchLineWraps(uwline, style_, control.max_search_states); if (control.show_equally_optimal_wrappings && optimal_solutions.size() > 1) { verible::DisplayEquallyOptimalWrappings(control.Stream(), uwline, optimal_solutions); } // Arbitrarily choose the first solution, if there are multiple. formatted_lines_.push_back(optimal_solutions.front()); if (!formatted_lines_.back().CompletedFormatting()) { // Copy over any lines that did not finish wrap searching. partially_formatted_lines.push_back(&uwline); } } // Report any unwrapped lines that failed to complete wrap searching. if (!partially_formatted_lines.empty()) { std::ostringstream err_stream; err_stream << "*** Some token partitions failed to complete within the " "search limit:" << std::endl; for (const auto* line : partially_formatted_lines) { err_stream << *line << std::endl; } err_stream << "*** end of partially formatted partition list" << std::endl; // Treat search state limit like a limited resource. return verible::util::ResourceExhaustedError(err_stream.str()); } return verible::util::OkStatus(); } // Returns text between last token and EOF. absl::string_view Formatter::TrailingWhiteSpaces() const { const absl::string_view full_text(text_structure_.Contents()); if (formatted_lines_.empty()) { // Text contains only whitespace tokens. return full_text; } else { // Preserve vertical spaces between last token and EOF. const auto& last_line = formatted_lines_.back().Tokens(); const auto* end_of_buffer = full_text.end(); if (last_line.empty()) { return absl::string_view(end_of_buffer, 0); } else { const auto* last_printed_offset = last_line.back().token->text.end(); return verible::make_string_view_range(last_printed_offset, end_of_buffer); } } } void Formatter::Emit(std::ostream& stream) const { const absl::string_view full_text(text_structure_.Contents()); if (style_.preserve_horizontal_spaces == PreserveSpaces::All) { // Need to track pre-existing spaces between token partitions. for (const auto& line : formatted_lines_) { line.FormatLinePreserveLeadingSpace(stream); } // Handle trailing spaces after last token. stream << TrailingWhiteSpaces(); } else { // (horizontal) PreserveSpaces::None or UnhandledCasesOnly switch (style_.preserve_vertical_spaces) { case PreserveSpaces::None: { for (const auto& line : formatted_lines_) { stream << line; // Normally, print a '\n' after this FormattedExcerpt. // The exception is when the space that follows the last token // on this line is covered by one of the formatting-disabled // intervals. In that case, print the original spacing instead. const auto back_offset = line.Tokens().back().token->right(full_text); if (!disabled_ranges_.Contains(back_offset)) stream << '\n'; } // possibly preserve spaces after the last token if (disabled_ranges_.Contains(full_text.length() - 1)) { stream << TrailingWhiteSpaces(); } break; } case PreserveSpaces::All: case PreserveSpaces::UnhandledCasesOnly: bool is_first_line = true; for (const auto& line : formatted_lines_) { line.FormatLinePreserveLeadingNewlines(stream, is_first_line); is_first_line = false; } // Handle trailing spaces after last token. const size_t newline_count = verible::FormattedExcerpt::PreservedNewlinesCount( TrailingWhiteSpaces(), is_first_line); stream << verible::Spacer(newline_count, '\n'); break; } // TODO(fangism): This currently doesn't adequately handle anything betweeen // PreserveSpace::None and ::All, needs a clean policy for // PreserveSpace::UnhandledCasesOnly. } } } // namespace formatter } // namespace verilog <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // RenderEnumsTest.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "UnitTest++/src/UnitTest++.h" #include "Core/String/String.h" #include "Render/Core/Enums.h" #include "Render/gl/gl_impl.h" using namespace Oryol::Core; using namespace Oryol::Render; //------------------------------------------------------------------------------ TEST(PixelFormatTest) { CHECK(PixelFormat::NumPixelFormats == 15); } //------------------------------------------------------------------------------ TEST(PixelFormatChannelBitsTest) { CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8A8, PixelFormat::Red) == 8); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8A8, PixelFormat::Green) == 8); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8A8, PixelFormat::Blue) == 8); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8A8, PixelFormat::Alpha) == 8); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8A8, PixelFormat::Depth) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8A8, PixelFormat::Stencil) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8, PixelFormat::Red) == 8); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8, PixelFormat::Green) == 8); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8, PixelFormat::Blue) == 8); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8, PixelFormat::Alpha) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8, PixelFormat::Depth) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8, PixelFormat::Stencil) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R5G6B5, PixelFormat::Red) == 5); CHECK(PixelFormat::NumBits(PixelFormat::R5G6B5, PixelFormat::Green) == 6); CHECK(PixelFormat::NumBits(PixelFormat::R5G6B5, PixelFormat::Blue) == 5); CHECK(PixelFormat::NumBits(PixelFormat::R5G6B5, PixelFormat::Alpha) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R5G6B5, PixelFormat::Depth) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R5G6B5, PixelFormat::Stencil) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R5G5B5A1, PixelFormat::Red) == 5); CHECK(PixelFormat::NumBits(PixelFormat::R5G5B5A1, PixelFormat::Green) == 5); CHECK(PixelFormat::NumBits(PixelFormat::R5G5B5A1, PixelFormat::Blue) == 5); CHECK(PixelFormat::NumBits(PixelFormat::R5G5B5A1, PixelFormat::Alpha) == 1); CHECK(PixelFormat::NumBits(PixelFormat::R5G5B5A1, PixelFormat::Depth) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R5G5B5A1, PixelFormat::Stencil) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R4G4B4A4, PixelFormat::Red) == 4); CHECK(PixelFormat::NumBits(PixelFormat::R4G4B4A4, PixelFormat::Green) == 4); CHECK(PixelFormat::NumBits(PixelFormat::R4G4B4A4, PixelFormat::Blue) == 4); CHECK(PixelFormat::NumBits(PixelFormat::R4G4B4A4, PixelFormat::Alpha) == 4); CHECK(PixelFormat::NumBits(PixelFormat::R4G4B4A4, PixelFormat::Depth) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R4G4B4A4, PixelFormat::Stencil) == 0); CHECK(PixelFormat::NumBits(PixelFormat::L8, PixelFormat::Red) == 8); CHECK(PixelFormat::NumBits(PixelFormat::L8, PixelFormat::Green) == 0); CHECK(PixelFormat::NumBits(PixelFormat::L8, PixelFormat::Blue) == 0); CHECK(PixelFormat::NumBits(PixelFormat::L8, PixelFormat::Alpha) == 0); CHECK(PixelFormat::NumBits(PixelFormat::L8, PixelFormat::Depth) == 0); CHECK(PixelFormat::NumBits(PixelFormat::L8, PixelFormat::Stencil) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D16, PixelFormat::Red) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D16, PixelFormat::Green) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D16, PixelFormat::Blue) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D16, PixelFormat::Alpha) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D16, PixelFormat::Depth) == 16); CHECK(PixelFormat::NumBits(PixelFormat::D16, PixelFormat::Stencil) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D32, PixelFormat::Red) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D32, PixelFormat::Green) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D32, PixelFormat::Blue) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D32, PixelFormat::Alpha) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D32, PixelFormat::Depth) == 32); CHECK(PixelFormat::NumBits(PixelFormat::D32, PixelFormat::Stencil) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D24S8, PixelFormat::Red) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D24S8, PixelFormat::Green) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D24S8, PixelFormat::Blue) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D24S8, PixelFormat::Alpha) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D24S8, PixelFormat::Depth) == 24); CHECK(PixelFormat::NumBits(PixelFormat::D24S8, PixelFormat::Stencil) == 8); CHECK(PixelFormat::NumBits(PixelFormat::R32F, PixelFormat::Red) == 32); CHECK(PixelFormat::NumBits(PixelFormat::R32F, PixelFormat::Green) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R32F, PixelFormat::Blue) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R32F, PixelFormat::Alpha) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R32F, PixelFormat::Depth) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R32F, PixelFormat::Stencil) == 0); // all other pixel formats must return 0 for all channels for (int pf = 0; pf < PixelFormat::NumPixelFormats; pf++) { if ((pf != PixelFormat::R8G8B8A8) && (pf != PixelFormat::R8G8B8) && (pf != PixelFormat::R5G6B5) && (pf != PixelFormat::R5G5B5A1) && (pf != PixelFormat::R4G4B4A4) && (pf != PixelFormat::L8) && (pf != PixelFormat::D16) && (pf != PixelFormat::D32) && (pf != PixelFormat::D24S8) && (pf != PixelFormat::R32F)) { for (int chn = 0; chn < PixelFormat::NumChannels; chn++) { CHECK(PixelFormat::NumBits((PixelFormat::Code)pf, (PixelFormat::Channel)chn) == 0); } } } } //------------------------------------------------------------------------------ TEST(TextureTypeTest) { CHECK(TextureType::NumTextureTypes == 3); CHECK(TextureType::Texture2D == GL_TEXTURE_2D); #if !ORYOL_OPENGLES2 CHECK(TextureType::Texture3D == GL_TEXTURE_3D); #endif CHECK(TextureType::TextureCube == GL_TEXTURE_CUBE_MAP); } //------------------------------------------------------------------------------ TEST(PrimitiveTypeTest) { CHECK(PrimitiveType::NumPrimitiveTypes == 7); CHECK(PrimitiveType::Points == GL_POINTS); CHECK(PrimitiveType::Lines == GL_LINES); CHECK(PrimitiveType::LineLoop == GL_LINE_LOOP); CHECK(PrimitiveType::LineStrip == GL_LINE_STRIP); CHECK(PrimitiveType::Triangles == GL_TRIANGLES); CHECK(PrimitiveType::TriangleStrip == GL_TRIANGLE_STRIP); CHECK(PrimitiveType::TriangleFan == GL_TRIANGLE_FAN); } //------------------------------------------------------------------------------ TEST(UsageTest) { CHECK(Usage::NumUsages == 3); CHECK(Usage::Immutable == GL_STATIC_DRAW); CHECK(Usage::DynamicWrite == GL_DYNAMIC_DRAW); CHECK(Usage::DynamicStream == GL_STREAM_DRAW); } //------------------------------------------------------------------------------ TEST(TextureWrapMode) { CHECK(TextureWrapMode::NumTextureWrapModes == 3); CHECK(TextureWrapMode::ClampToEdge == GL_CLAMP_TO_EDGE); CHECK(TextureWrapMode::Repeat == GL_REPEAT); CHECK(TextureWrapMode::MirroredRepeat == GL_MIRRORED_REPEAT); } //------------------------------------------------------------------------------ TEST(IndexTypeTest) { CHECK(IndexType::NumIndexTypes == 3); CHECK(IndexType::Index16 == GL_UNSIGNED_SHORT); CHECK(IndexType::Index32 == GL_UNSIGNED_INT); CHECK(IndexType::ByteSize(IndexType::Index16) == 2); CHECK(IndexType::ByteSize(IndexType::Index32) == 4); } //------------------------------------------------------------------------------ TEST(TextureFilterModeTest) { CHECK(TextureFilterMode::NumTextureFilterModes == 6); CHECK(TextureFilterMode::Nearest == GL_NEAREST); CHECK(TextureFilterMode::Linear == GL_LINEAR); CHECK(TextureFilterMode::NearestMipmapNearest == GL_NEAREST_MIPMAP_NEAREST); CHECK(TextureFilterMode::NearestMipmapLinear == GL_NEAREST_MIPMAP_LINEAR); CHECK(TextureFilterMode::LinearMipmapNearest == GL_LINEAR_MIPMAP_NEAREST); CHECK(TextureFilterMode::LinearMipmapLinear == GL_LINEAR_MIPMAP_LINEAR); } //------------------------------------------------------------------------------ TEST(VertexFormatTest) { CHECK(VertexFormat::NumVertexFormats == 12); CHECK(VertexFormat::ByteSize(VertexFormat::Float) == 4); CHECK(VertexFormat::ByteSize(VertexFormat::Float2) == 8); CHECK(VertexFormat::ByteSize(VertexFormat::Float3) == 12); CHECK(VertexFormat::ByteSize(VertexFormat::Float4) == 16); CHECK(VertexFormat::ByteSize(VertexFormat::Byte4) == 4); CHECK(VertexFormat::ByteSize(VertexFormat::Byte4N) == 4); CHECK(VertexFormat::ByteSize(VertexFormat::UByte4) == 4); CHECK(VertexFormat::ByteSize(VertexFormat::UByte4N) == 4); CHECK(VertexFormat::ByteSize(VertexFormat::Short2) == 4); CHECK(VertexFormat::ByteSize(VertexFormat::Short2N) == 4); CHECK(VertexFormat::ByteSize(VertexFormat::Short4) == 8); CHECK(VertexFormat::ByteSize(VertexFormat::Short4N) == 8); } //------------------------------------------------------------------------------ TEST(VertexAttrTest) { CHECK(VertexAttr::NumVertexAttrs == 16); CHECK(String(VertexAttr::ToString(VertexAttr::Position)) == "position"); CHECK(String(VertexAttr::ToString(VertexAttr::Normal)) == "normal"); CHECK(String(VertexAttr::ToString(VertexAttr::TexCoord0)) == "texcoord0"); CHECK(String(VertexAttr::ToString(VertexAttr::TexCoord1)) == "texcoord1"); CHECK(String(VertexAttr::ToString(VertexAttr::TexCoord2)) == "texcoord2"); CHECK(String(VertexAttr::ToString(VertexAttr::TexCoord3)) == "texcoord3"); CHECK(String(VertexAttr::ToString(VertexAttr::Tangent)) == "tangent"); CHECK(String(VertexAttr::ToString(VertexAttr::Binormal)) == "binormal"); CHECK(String(VertexAttr::ToString(VertexAttr::Weights)) == "weights"); CHECK(String(VertexAttr::ToString(VertexAttr::Indices)) == "indices"); CHECK(String(VertexAttr::ToString(VertexAttr::Color0)) == "color0"); CHECK(String(VertexAttr::ToString(VertexAttr::Color1)) == "color1"); CHECK(String(VertexAttr::ToString(VertexAttr::Custom0)) == "custom0"); CHECK(String(VertexAttr::ToString(VertexAttr::Custom1)) == "custom1"); CHECK(String(VertexAttr::ToString(VertexAttr::Custom2)) == "custom2"); CHECK(String(VertexAttr::ToString(VertexAttr::Custom3)) == "custom3"); } //------------------------------------------------------------------------------ TEST(RenderResourceTypeTest) { CHECK(ResourceType::NumResourceTypes == 6); } //------------------------------------------------------------------------------ TEST(ShaderTypeTest) { CHECK(ShaderType::NumShaderTypes == 2); CHECK(ShaderType::VertexShader == GL_VERTEX_SHADER); CHECK(ShaderType::FragmentShader == GL_FRAGMENT_SHADER); } //------------------------------------------------------------------------------ TEST(StateTest) { CHECK(State::Undefined == -1); CHECK(State::Zero == GL_ZERO); CHECK(State::One == GL_ONE); CHECK(State::CW == GL_CW); CHECK(State::CCW == GL_CCW); CHECK(State::Front == GL_FRONT); CHECK(State::Back == GL_BACK); CHECK(State::FrontAndBack == GL_FRONT_AND_BACK); CHECK(State::Never == GL_NEVER); CHECK(State::Always == GL_ALWAYS); CHECK(State::Less == GL_LESS); CHECK(State::LessEqual == GL_LEQUAL); CHECK(State::GreaterEqual == GL_GEQUAL); CHECK(State::Greater == GL_GREATER); CHECK(State::Equal == GL_EQUAL); CHECK(State::NotEqual == GL_NOTEQUAL); CHECK(State::Keep == GL_KEEP); CHECK(State::Replace == GL_REPLACE); CHECK(State::Incr == GL_INCR); CHECK(State::Decr == GL_DECR); CHECK(State::Invert == GL_INVERT); CHECK(State::IncrWrap == GL_INCR_WRAP); CHECK(State::DecrWrap == GL_DECR_WRAP); CHECK(State::SrcColor == GL_SRC_COLOR); CHECK(State::InvSrcColor == GL_ONE_MINUS_SRC_COLOR); CHECK(State::DstColor == GL_DST_COLOR); CHECK(State::InvDstColor == GL_ONE_MINUS_DST_COLOR); CHECK(State::SrcAlpha == GL_SRC_ALPHA); CHECK(State::InvSrcAlpha == GL_ONE_MINUS_SRC_ALPHA); CHECK(State::DstAlpha == GL_DST_ALPHA); CHECK(State::InvDstAlpha == GL_ONE_MINUS_DST_ALPHA); CHECK(State::ConstColor == GL_CONSTANT_COLOR); CHECK(State::InvConstColor == GL_ONE_MINUS_CONSTANT_COLOR); CHECK(State::ConstAlpha == GL_CONSTANT_ALPHA); CHECK(State::InvConstAlpha == GL_ONE_MINUS_CONSTANT_ALPHA); CHECK(State::SrcAlphaSaturate == GL_SRC_ALPHA_SATURATE); CHECK(State::InvalidStateValue == 0xFFFFFFFF); } <commit_msg>Missing test for PixelFormat::ByteSize<commit_after>//------------------------------------------------------------------------------ // RenderEnumsTest.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "UnitTest++/src/UnitTest++.h" #include "Core/String/String.h" #include "Render/Core/Enums.h" #include "Render/gl/gl_impl.h" using namespace Oryol::Core; using namespace Oryol::Render; //------------------------------------------------------------------------------ TEST(PixelFormatTest) { CHECK(PixelFormat::NumPixelFormats == 15); } //------------------------------------------------------------------------------ TEST(PixelFormatChannelBitsTest) { CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8A8, PixelFormat::Red) == 8); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8A8, PixelFormat::Green) == 8); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8A8, PixelFormat::Blue) == 8); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8A8, PixelFormat::Alpha) == 8); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8A8, PixelFormat::Depth) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8A8, PixelFormat::Stencil) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8, PixelFormat::Red) == 8); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8, PixelFormat::Green) == 8); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8, PixelFormat::Blue) == 8); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8, PixelFormat::Alpha) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8, PixelFormat::Depth) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R8G8B8, PixelFormat::Stencil) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R5G6B5, PixelFormat::Red) == 5); CHECK(PixelFormat::NumBits(PixelFormat::R5G6B5, PixelFormat::Green) == 6); CHECK(PixelFormat::NumBits(PixelFormat::R5G6B5, PixelFormat::Blue) == 5); CHECK(PixelFormat::NumBits(PixelFormat::R5G6B5, PixelFormat::Alpha) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R5G6B5, PixelFormat::Depth) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R5G6B5, PixelFormat::Stencil) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R5G5B5A1, PixelFormat::Red) == 5); CHECK(PixelFormat::NumBits(PixelFormat::R5G5B5A1, PixelFormat::Green) == 5); CHECK(PixelFormat::NumBits(PixelFormat::R5G5B5A1, PixelFormat::Blue) == 5); CHECK(PixelFormat::NumBits(PixelFormat::R5G5B5A1, PixelFormat::Alpha) == 1); CHECK(PixelFormat::NumBits(PixelFormat::R5G5B5A1, PixelFormat::Depth) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R5G5B5A1, PixelFormat::Stencil) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R4G4B4A4, PixelFormat::Red) == 4); CHECK(PixelFormat::NumBits(PixelFormat::R4G4B4A4, PixelFormat::Green) == 4); CHECK(PixelFormat::NumBits(PixelFormat::R4G4B4A4, PixelFormat::Blue) == 4); CHECK(PixelFormat::NumBits(PixelFormat::R4G4B4A4, PixelFormat::Alpha) == 4); CHECK(PixelFormat::NumBits(PixelFormat::R4G4B4A4, PixelFormat::Depth) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R4G4B4A4, PixelFormat::Stencil) == 0); CHECK(PixelFormat::NumBits(PixelFormat::L8, PixelFormat::Red) == 8); CHECK(PixelFormat::NumBits(PixelFormat::L8, PixelFormat::Green) == 0); CHECK(PixelFormat::NumBits(PixelFormat::L8, PixelFormat::Blue) == 0); CHECK(PixelFormat::NumBits(PixelFormat::L8, PixelFormat::Alpha) == 0); CHECK(PixelFormat::NumBits(PixelFormat::L8, PixelFormat::Depth) == 0); CHECK(PixelFormat::NumBits(PixelFormat::L8, PixelFormat::Stencil) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D16, PixelFormat::Red) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D16, PixelFormat::Green) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D16, PixelFormat::Blue) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D16, PixelFormat::Alpha) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D16, PixelFormat::Depth) == 16); CHECK(PixelFormat::NumBits(PixelFormat::D16, PixelFormat::Stencil) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D32, PixelFormat::Red) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D32, PixelFormat::Green) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D32, PixelFormat::Blue) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D32, PixelFormat::Alpha) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D32, PixelFormat::Depth) == 32); CHECK(PixelFormat::NumBits(PixelFormat::D32, PixelFormat::Stencil) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D24S8, PixelFormat::Red) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D24S8, PixelFormat::Green) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D24S8, PixelFormat::Blue) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D24S8, PixelFormat::Alpha) == 0); CHECK(PixelFormat::NumBits(PixelFormat::D24S8, PixelFormat::Depth) == 24); CHECK(PixelFormat::NumBits(PixelFormat::D24S8, PixelFormat::Stencil) == 8); CHECK(PixelFormat::NumBits(PixelFormat::R32F, PixelFormat::Red) == 32); CHECK(PixelFormat::NumBits(PixelFormat::R32F, PixelFormat::Green) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R32F, PixelFormat::Blue) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R32F, PixelFormat::Alpha) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R32F, PixelFormat::Depth) == 0); CHECK(PixelFormat::NumBits(PixelFormat::R32F, PixelFormat::Stencil) == 0); // all other pixel formats must return 0 for all channels for (int pf = 0; pf < PixelFormat::NumPixelFormats; pf++) { if ((pf != PixelFormat::R8G8B8A8) && (pf != PixelFormat::R8G8B8) && (pf != PixelFormat::R5G6B5) && (pf != PixelFormat::R5G5B5A1) && (pf != PixelFormat::R4G4B4A4) && (pf != PixelFormat::L8) && (pf != PixelFormat::D16) && (pf != PixelFormat::D32) && (pf != PixelFormat::D24S8) && (pf != PixelFormat::R32F)) { for (int chn = 0; chn < PixelFormat::NumChannels; chn++) { CHECK(PixelFormat::NumBits((PixelFormat::Code)pf, (PixelFormat::Channel)chn) == 0); } } } } //------------------------------------------------------------------------------ TEST(PixelFormatByteSizeTest) { CHECK(PixelFormat::ByteSize(PixelFormat::R8G8B8A8) == 4); CHECK(PixelFormat::ByteSize(PixelFormat::R8G8B8) == 3); CHECK(PixelFormat::ByteSize(PixelFormat::R5G6B5) == 2); CHECK(PixelFormat::ByteSize(PixelFormat::R5G5B5A1) == 2); CHECK(PixelFormat::ByteSize(PixelFormat::R4G4B4A4) == 2); CHECK(PixelFormat::ByteSize(PixelFormat::L8) == 1); CHECK(PixelFormat::ByteSize(PixelFormat::D16) == 2); CHECK(PixelFormat::ByteSize(PixelFormat::D32) == 4); CHECK(PixelFormat::ByteSize(PixelFormat::D24S8) == 4); CHECK(PixelFormat::ByteSize(PixelFormat::R32F) == 4); } //------------------------------------------------------------------------------ TEST(TextureTypeTest) { CHECK(TextureType::NumTextureTypes == 3); CHECK(TextureType::Texture2D == GL_TEXTURE_2D); #if !ORYOL_OPENGLES2 CHECK(TextureType::Texture3D == GL_TEXTURE_3D); #endif CHECK(TextureType::TextureCube == GL_TEXTURE_CUBE_MAP); } //------------------------------------------------------------------------------ TEST(PrimitiveTypeTest) { CHECK(PrimitiveType::NumPrimitiveTypes == 7); CHECK(PrimitiveType::Points == GL_POINTS); CHECK(PrimitiveType::Lines == GL_LINES); CHECK(PrimitiveType::LineLoop == GL_LINE_LOOP); CHECK(PrimitiveType::LineStrip == GL_LINE_STRIP); CHECK(PrimitiveType::Triangles == GL_TRIANGLES); CHECK(PrimitiveType::TriangleStrip == GL_TRIANGLE_STRIP); CHECK(PrimitiveType::TriangleFan == GL_TRIANGLE_FAN); } //------------------------------------------------------------------------------ TEST(UsageTest) { CHECK(Usage::NumUsages == 3); CHECK(Usage::Immutable == GL_STATIC_DRAW); CHECK(Usage::DynamicWrite == GL_DYNAMIC_DRAW); CHECK(Usage::DynamicStream == GL_STREAM_DRAW); } //------------------------------------------------------------------------------ TEST(TextureWrapMode) { CHECK(TextureWrapMode::NumTextureWrapModes == 3); CHECK(TextureWrapMode::ClampToEdge == GL_CLAMP_TO_EDGE); CHECK(TextureWrapMode::Repeat == GL_REPEAT); CHECK(TextureWrapMode::MirroredRepeat == GL_MIRRORED_REPEAT); } //------------------------------------------------------------------------------ TEST(IndexTypeTest) { CHECK(IndexType::NumIndexTypes == 3); CHECK(IndexType::Index16 == GL_UNSIGNED_SHORT); CHECK(IndexType::Index32 == GL_UNSIGNED_INT); CHECK(IndexType::ByteSize(IndexType::Index16) == 2); CHECK(IndexType::ByteSize(IndexType::Index32) == 4); } //------------------------------------------------------------------------------ TEST(TextureFilterModeTest) { CHECK(TextureFilterMode::NumTextureFilterModes == 6); CHECK(TextureFilterMode::Nearest == GL_NEAREST); CHECK(TextureFilterMode::Linear == GL_LINEAR); CHECK(TextureFilterMode::NearestMipmapNearest == GL_NEAREST_MIPMAP_NEAREST); CHECK(TextureFilterMode::NearestMipmapLinear == GL_NEAREST_MIPMAP_LINEAR); CHECK(TextureFilterMode::LinearMipmapNearest == GL_LINEAR_MIPMAP_NEAREST); CHECK(TextureFilterMode::LinearMipmapLinear == GL_LINEAR_MIPMAP_LINEAR); } //------------------------------------------------------------------------------ TEST(VertexFormatTest) { CHECK(VertexFormat::NumVertexFormats == 12); CHECK(VertexFormat::ByteSize(VertexFormat::Float) == 4); CHECK(VertexFormat::ByteSize(VertexFormat::Float2) == 8); CHECK(VertexFormat::ByteSize(VertexFormat::Float3) == 12); CHECK(VertexFormat::ByteSize(VertexFormat::Float4) == 16); CHECK(VertexFormat::ByteSize(VertexFormat::Byte4) == 4); CHECK(VertexFormat::ByteSize(VertexFormat::Byte4N) == 4); CHECK(VertexFormat::ByteSize(VertexFormat::UByte4) == 4); CHECK(VertexFormat::ByteSize(VertexFormat::UByte4N) == 4); CHECK(VertexFormat::ByteSize(VertexFormat::Short2) == 4); CHECK(VertexFormat::ByteSize(VertexFormat::Short2N) == 4); CHECK(VertexFormat::ByteSize(VertexFormat::Short4) == 8); CHECK(VertexFormat::ByteSize(VertexFormat::Short4N) == 8); } //------------------------------------------------------------------------------ TEST(VertexAttrTest) { CHECK(VertexAttr::NumVertexAttrs == 16); CHECK(String(VertexAttr::ToString(VertexAttr::Position)) == "position"); CHECK(String(VertexAttr::ToString(VertexAttr::Normal)) == "normal"); CHECK(String(VertexAttr::ToString(VertexAttr::TexCoord0)) == "texcoord0"); CHECK(String(VertexAttr::ToString(VertexAttr::TexCoord1)) == "texcoord1"); CHECK(String(VertexAttr::ToString(VertexAttr::TexCoord2)) == "texcoord2"); CHECK(String(VertexAttr::ToString(VertexAttr::TexCoord3)) == "texcoord3"); CHECK(String(VertexAttr::ToString(VertexAttr::Tangent)) == "tangent"); CHECK(String(VertexAttr::ToString(VertexAttr::Binormal)) == "binormal"); CHECK(String(VertexAttr::ToString(VertexAttr::Weights)) == "weights"); CHECK(String(VertexAttr::ToString(VertexAttr::Indices)) == "indices"); CHECK(String(VertexAttr::ToString(VertexAttr::Color0)) == "color0"); CHECK(String(VertexAttr::ToString(VertexAttr::Color1)) == "color1"); CHECK(String(VertexAttr::ToString(VertexAttr::Custom0)) == "custom0"); CHECK(String(VertexAttr::ToString(VertexAttr::Custom1)) == "custom1"); CHECK(String(VertexAttr::ToString(VertexAttr::Custom2)) == "custom2"); CHECK(String(VertexAttr::ToString(VertexAttr::Custom3)) == "custom3"); } //------------------------------------------------------------------------------ TEST(RenderResourceTypeTest) { CHECK(ResourceType::NumResourceTypes == 6); } //------------------------------------------------------------------------------ TEST(ShaderTypeTest) { CHECK(ShaderType::NumShaderTypes == 2); CHECK(ShaderType::VertexShader == GL_VERTEX_SHADER); CHECK(ShaderType::FragmentShader == GL_FRAGMENT_SHADER); } //------------------------------------------------------------------------------ TEST(StateTest) { CHECK(State::Undefined == -1); CHECK(State::Zero == GL_ZERO); CHECK(State::One == GL_ONE); CHECK(State::CW == GL_CW); CHECK(State::CCW == GL_CCW); CHECK(State::Front == GL_FRONT); CHECK(State::Back == GL_BACK); CHECK(State::FrontAndBack == GL_FRONT_AND_BACK); CHECK(State::Never == GL_NEVER); CHECK(State::Always == GL_ALWAYS); CHECK(State::Less == GL_LESS); CHECK(State::LessEqual == GL_LEQUAL); CHECK(State::GreaterEqual == GL_GEQUAL); CHECK(State::Greater == GL_GREATER); CHECK(State::Equal == GL_EQUAL); CHECK(State::NotEqual == GL_NOTEQUAL); CHECK(State::Keep == GL_KEEP); CHECK(State::Replace == GL_REPLACE); CHECK(State::Incr == GL_INCR); CHECK(State::Decr == GL_DECR); CHECK(State::Invert == GL_INVERT); CHECK(State::IncrWrap == GL_INCR_WRAP); CHECK(State::DecrWrap == GL_DECR_WRAP); CHECK(State::SrcColor == GL_SRC_COLOR); CHECK(State::InvSrcColor == GL_ONE_MINUS_SRC_COLOR); CHECK(State::DstColor == GL_DST_COLOR); CHECK(State::InvDstColor == GL_ONE_MINUS_DST_COLOR); CHECK(State::SrcAlpha == GL_SRC_ALPHA); CHECK(State::InvSrcAlpha == GL_ONE_MINUS_SRC_ALPHA); CHECK(State::DstAlpha == GL_DST_ALPHA); CHECK(State::InvDstAlpha == GL_ONE_MINUS_DST_ALPHA); CHECK(State::ConstColor == GL_CONSTANT_COLOR); CHECK(State::InvConstColor == GL_ONE_MINUS_CONSTANT_COLOR); CHECK(State::ConstAlpha == GL_CONSTANT_ALPHA); CHECK(State::InvConstAlpha == GL_ONE_MINUS_CONSTANT_ALPHA); CHECK(State::SrcAlphaSaturate == GL_SRC_ALPHA_SATURATE); CHECK(State::InvalidStateValue == 0xFFFFFFFF); } <|endoftext|>
<commit_before>/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2014 * Utilities for the solidity compiler. */ #include <libsolidity/codegen/CompilerContext.h> #include <utility> #include <numeric> #include <boost/algorithm/string/replace.hpp> #include <libsolidity/ast/AST.h> #include <libsolidity/codegen/Compiler.h> #include <libsolidity/interface/Version.h> #include <libsolidity/inlineasm/AsmData.h> #include <libsolidity/inlineasm/AsmStack.h> using namespace std; namespace dev { namespace solidity { void CompilerContext::addMagicGlobal(MagicVariableDeclaration const& _declaration) { m_magicGlobals.insert(&_declaration); } void CompilerContext::addStateVariable( VariableDeclaration const& _declaration, u256 const& _storageOffset, unsigned _byteOffset ) { m_stateVariables[&_declaration] = make_pair(_storageOffset, _byteOffset); } void CompilerContext::startFunction(Declaration const& _function) { m_functionCompilationQueue.startFunction(_function); *this << functionEntryLabel(_function); } void CompilerContext::addVariable(VariableDeclaration const& _declaration, unsigned _offsetToCurrent) { solAssert(m_asm->deposit() >= 0 && unsigned(m_asm->deposit()) >= _offsetToCurrent, ""); m_localVariables[&_declaration] = unsigned(m_asm->deposit()) - _offsetToCurrent; } void CompilerContext::removeVariable(VariableDeclaration const& _declaration) { solAssert(!!m_localVariables.count(&_declaration), ""); m_localVariables.erase(&_declaration); } eth::Assembly const& CompilerContext::compiledContract(const ContractDefinition& _contract) const { auto ret = m_compiledContracts.find(&_contract); solAssert(ret != m_compiledContracts.end(), "Compiled contract not found."); return *ret->second; } bool CompilerContext::isLocalVariable(Declaration const* _declaration) const { return !!m_localVariables.count(_declaration); } eth::AssemblyItem CompilerContext::functionEntryLabel(Declaration const& _declaration) { return m_functionCompilationQueue.entryLabel(_declaration, *this); } eth::AssemblyItem CompilerContext::functionEntryLabelIfExists(Declaration const& _declaration) const { return m_functionCompilationQueue.entryLabelIfExists(_declaration); } FunctionDefinition const& CompilerContext::resolveVirtualFunction(FunctionDefinition const& _function) { // Libraries do not allow inheritance and their functions can be inlined, so we should not // search the inheritance hierarchy (which will be the wrong one in case the function // is inlined). if (auto scope = dynamic_cast<ContractDefinition const*>(_function.scope())) if (scope->isLibrary()) return _function; solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); return resolveVirtualFunction(_function, m_inheritanceHierarchy.begin()); } FunctionDefinition const& CompilerContext::superFunction(FunctionDefinition const& _function, ContractDefinition const& _base) { solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); return resolveVirtualFunction(_function, superContract(_base)); } FunctionDefinition const* CompilerContext::nextConstructor(ContractDefinition const& _contract) const { vector<ContractDefinition const*>::const_iterator it = superContract(_contract); for (; it != m_inheritanceHierarchy.end(); ++it) if ((*it)->constructor()) return (*it)->constructor(); return nullptr; } Declaration const* CompilerContext::nextFunctionToCompile() const { return m_functionCompilationQueue.nextFunctionToCompile(); } ModifierDefinition const& CompilerContext::functionModifier(string const& _name) const { solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); for (ContractDefinition const* contract: m_inheritanceHierarchy) for (ModifierDefinition const* modifier: contract->functionModifiers()) if (modifier->name() == _name) return *modifier; BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Function modifier " + _name + " not found.")); } unsigned CompilerContext::baseStackOffsetOfVariable(Declaration const& _declaration) const { auto res = m_localVariables.find(&_declaration); solAssert(res != m_localVariables.end(), "Variable not found on stack."); return res->second; } unsigned CompilerContext::baseToCurrentStackOffset(unsigned _baseOffset) const { return m_asm->deposit() - _baseOffset - 1; } unsigned CompilerContext::currentToBaseStackOffset(unsigned _offset) const { return m_asm->deposit() - _offset - 1; } pair<u256, unsigned> CompilerContext::storageLocationOfVariable(const Declaration& _declaration) const { auto it = m_stateVariables.find(&_declaration); solAssert(it != m_stateVariables.end(), "Variable not found in storage."); return it->second; } CompilerContext& CompilerContext::appendJump(eth::AssemblyItem::JumpType _jumpType) { eth::AssemblyItem item(Instruction::JUMP); item.setJumpType(_jumpType); return *this << item; } void CompilerContext::resetVisitedNodes(ASTNode const* _node) { stack<ASTNode const*> newStack; newStack.push(_node); std::swap(m_visitedNodes, newStack); updateSourceLocation(); } void CompilerContext::appendInlineAssembly( string const& _assembly, vector<string> const& _localVariables, map<string, string> const& _replacements ) { string replacedAssembly; string const* assembly = &_assembly; if (!_replacements.empty()) { replacedAssembly = _assembly; for (auto const& replacement: _replacements) replacedAssembly = boost::algorithm::replace_all_copy(replacedAssembly, replacement.first, replacement.second); assembly = &replacedAssembly; } unsigned startStackHeight = stackHeight(); auto identifierAccess = [&]( assembly::Identifier const& _identifier, eth::Assembly& _assembly, assembly::CodeGenerator::IdentifierContext _context ) { auto it = std::find(_localVariables.begin(), _localVariables.end(), _identifier.name); if (it == _localVariables.end()) return false; unsigned stackDepth = _localVariables.end() - it; int stackDiff = _assembly.deposit() - startStackHeight + stackDepth; if (stackDiff < 1 || stackDiff > 16) BOOST_THROW_EXCEPTION( CompilerError() << errinfo_comment("Stack too deep, try removing local variables.") ); if (_context == assembly::CodeGenerator::IdentifierContext::RValue) _assembly.append(dupInstruction(stackDiff)); else { _assembly.append(swapInstruction(stackDiff)); _assembly.append(Instruction::POP); } return true; }; solAssert(assembly::InlineAssemblyStack().parseAndAssemble(*assembly, *m_asm, identifierAccess), "Failed to assemble inline assembly block."); setStackOffset(startStackHeight); } FunctionDefinition const& CompilerContext::resolveVirtualFunction( FunctionDefinition const& _function, vector<ContractDefinition const*>::const_iterator _searchStart ) { string name = _function.name(); FunctionType functionType(_function); auto it = _searchStart; for (; it != m_inheritanceHierarchy.end(); ++it) for (FunctionDefinition const* function: (*it)->definedFunctions()) if ( function->name() == name && !function->isConstructor() && FunctionType(*function).hasEqualArgumentTypes(functionType) ) return *function; solAssert(false, "Super function " + name + " not found."); return _function; // not reached } vector<ContractDefinition const*>::const_iterator CompilerContext::superContract(ContractDefinition const& _contract) const { solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); auto it = find(m_inheritanceHierarchy.begin(), m_inheritanceHierarchy.end(), &_contract); solAssert(it != m_inheritanceHierarchy.end(), "Base not found in inheritance hierarchy."); return ++it; } void CompilerContext::updateSourceLocation() { m_asm->setSourceLocation(m_visitedNodes.empty() ? SourceLocation() : m_visitedNodes.top()->location()); } eth::AssemblyItem CompilerContext::FunctionCompilationQueue::entryLabel( Declaration const& _declaration, CompilerContext& _context ) { auto res = m_entryLabels.find(&_declaration); if (res == m_entryLabels.end()) { eth::AssemblyItem tag(_context.newTag()); m_entryLabels.insert(make_pair(&_declaration, tag)); m_functionsToCompile.push(&_declaration); return tag.tag(); } else return res->second.tag(); } eth::AssemblyItem CompilerContext::FunctionCompilationQueue::entryLabelIfExists(Declaration const& _declaration) const { auto res = m_entryLabels.find(&_declaration); return res == m_entryLabels.end() ? eth::AssemblyItem(eth::UndefinedItem) : res->second.tag(); } Declaration const* CompilerContext::FunctionCompilationQueue::nextFunctionToCompile() const { while (!m_functionsToCompile.empty()) { if (m_alreadyCompiledFunctions.count(m_functionsToCompile.front())) m_functionsToCompile.pop(); else return m_functionsToCompile.front(); } return nullptr; } void CompilerContext::FunctionCompilationQueue::startFunction(Declaration const& _function) { if (!m_functionsToCompile.empty() && m_functionsToCompile.front() == &_function) m_functionsToCompile.pop(); m_alreadyCompiledFunctions.insert(&_function); } } } <commit_msg>Fix inline assembly.<commit_after>/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2014 * Utilities for the solidity compiler. */ #include <libsolidity/codegen/CompilerContext.h> #include <utility> #include <numeric> #include <boost/algorithm/string/replace.hpp> #include <libsolidity/ast/AST.h> #include <libsolidity/codegen/Compiler.h> #include <libsolidity/interface/Version.h> #include <libsolidity/inlineasm/AsmData.h> #include <libsolidity/inlineasm/AsmStack.h> using namespace std; namespace dev { namespace solidity { void CompilerContext::addMagicGlobal(MagicVariableDeclaration const& _declaration) { m_magicGlobals.insert(&_declaration); } void CompilerContext::addStateVariable( VariableDeclaration const& _declaration, u256 const& _storageOffset, unsigned _byteOffset ) { m_stateVariables[&_declaration] = make_pair(_storageOffset, _byteOffset); } void CompilerContext::startFunction(Declaration const& _function) { m_functionCompilationQueue.startFunction(_function); *this << functionEntryLabel(_function); } void CompilerContext::addVariable(VariableDeclaration const& _declaration, unsigned _offsetToCurrent) { solAssert(m_asm->deposit() >= 0 && unsigned(m_asm->deposit()) >= _offsetToCurrent, ""); m_localVariables[&_declaration] = unsigned(m_asm->deposit()) - _offsetToCurrent; } void CompilerContext::removeVariable(VariableDeclaration const& _declaration) { solAssert(!!m_localVariables.count(&_declaration), ""); m_localVariables.erase(&_declaration); } eth::Assembly const& CompilerContext::compiledContract(const ContractDefinition& _contract) const { auto ret = m_compiledContracts.find(&_contract); solAssert(ret != m_compiledContracts.end(), "Compiled contract not found."); return *ret->second; } bool CompilerContext::isLocalVariable(Declaration const* _declaration) const { return !!m_localVariables.count(_declaration); } eth::AssemblyItem CompilerContext::functionEntryLabel(Declaration const& _declaration) { return m_functionCompilationQueue.entryLabel(_declaration, *this); } eth::AssemblyItem CompilerContext::functionEntryLabelIfExists(Declaration const& _declaration) const { return m_functionCompilationQueue.entryLabelIfExists(_declaration); } FunctionDefinition const& CompilerContext::resolveVirtualFunction(FunctionDefinition const& _function) { // Libraries do not allow inheritance and their functions can be inlined, so we should not // search the inheritance hierarchy (which will be the wrong one in case the function // is inlined). if (auto scope = dynamic_cast<ContractDefinition const*>(_function.scope())) if (scope->isLibrary()) return _function; solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); return resolveVirtualFunction(_function, m_inheritanceHierarchy.begin()); } FunctionDefinition const& CompilerContext::superFunction(FunctionDefinition const& _function, ContractDefinition const& _base) { solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); return resolveVirtualFunction(_function, superContract(_base)); } FunctionDefinition const* CompilerContext::nextConstructor(ContractDefinition const& _contract) const { vector<ContractDefinition const*>::const_iterator it = superContract(_contract); for (; it != m_inheritanceHierarchy.end(); ++it) if ((*it)->constructor()) return (*it)->constructor(); return nullptr; } Declaration const* CompilerContext::nextFunctionToCompile() const { return m_functionCompilationQueue.nextFunctionToCompile(); } ModifierDefinition const& CompilerContext::functionModifier(string const& _name) const { solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); for (ContractDefinition const* contract: m_inheritanceHierarchy) for (ModifierDefinition const* modifier: contract->functionModifiers()) if (modifier->name() == _name) return *modifier; BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Function modifier " + _name + " not found.")); } unsigned CompilerContext::baseStackOffsetOfVariable(Declaration const& _declaration) const { auto res = m_localVariables.find(&_declaration); solAssert(res != m_localVariables.end(), "Variable not found on stack."); return res->second; } unsigned CompilerContext::baseToCurrentStackOffset(unsigned _baseOffset) const { return m_asm->deposit() - _baseOffset - 1; } unsigned CompilerContext::currentToBaseStackOffset(unsigned _offset) const { return m_asm->deposit() - _offset - 1; } pair<u256, unsigned> CompilerContext::storageLocationOfVariable(const Declaration& _declaration) const { auto it = m_stateVariables.find(&_declaration); solAssert(it != m_stateVariables.end(), "Variable not found in storage."); return it->second; } CompilerContext& CompilerContext::appendJump(eth::AssemblyItem::JumpType _jumpType) { eth::AssemblyItem item(Instruction::JUMP); item.setJumpType(_jumpType); return *this << item; } void CompilerContext::resetVisitedNodes(ASTNode const* _node) { stack<ASTNode const*> newStack; newStack.push(_node); std::swap(m_visitedNodes, newStack); updateSourceLocation(); } void CompilerContext::appendInlineAssembly( string const& _assembly, vector<string> const& _localVariables, map<string, string> const& _replacements ) { string replacedAssembly; string const* assembly = &_assembly; if (!_replacements.empty()) { replacedAssembly = _assembly; for (auto const& replacement: _replacements) replacedAssembly = boost::algorithm::replace_all_copy(replacedAssembly, replacement.first, replacement.second); assembly = &replacedAssembly; } unsigned startStackHeight = stackHeight(); auto identifierAccess = [&]( assembly::Identifier const& _identifier, eth::Assembly& _assembly, assembly::CodeGenerator::IdentifierContext _context ) { auto it = std::find(_localVariables.begin(), _localVariables.end(), _identifier.name); if (it == _localVariables.end()) return false; unsigned stackDepth = _localVariables.end() - it; int stackDiff = _assembly.deposit() - startStackHeight + stackDepth; if (_context == assembly::CodeGenerator::IdentifierContext::LValue) stackDiff -= 1; if (stackDiff < 1 || stackDiff > 16) BOOST_THROW_EXCEPTION( CompilerError() << errinfo_comment("Stack too deep, try removing local variables.") ); if (_context == assembly::CodeGenerator::IdentifierContext::RValue) _assembly.append(dupInstruction(stackDiff)); else { _assembly.append(swapInstruction(stackDiff)); _assembly.append(Instruction::POP); } return true; }; solAssert(assembly::InlineAssemblyStack().parseAndAssemble(*assembly, *m_asm, identifierAccess), "Failed to assemble inline assembly block."); } FunctionDefinition const& CompilerContext::resolveVirtualFunction( FunctionDefinition const& _function, vector<ContractDefinition const*>::const_iterator _searchStart ) { string name = _function.name(); FunctionType functionType(_function); auto it = _searchStart; for (; it != m_inheritanceHierarchy.end(); ++it) for (FunctionDefinition const* function: (*it)->definedFunctions()) if ( function->name() == name && !function->isConstructor() && FunctionType(*function).hasEqualArgumentTypes(functionType) ) return *function; solAssert(false, "Super function " + name + " not found."); return _function; // not reached } vector<ContractDefinition const*>::const_iterator CompilerContext::superContract(ContractDefinition const& _contract) const { solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); auto it = find(m_inheritanceHierarchy.begin(), m_inheritanceHierarchy.end(), &_contract); solAssert(it != m_inheritanceHierarchy.end(), "Base not found in inheritance hierarchy."); return ++it; } void CompilerContext::updateSourceLocation() { m_asm->setSourceLocation(m_visitedNodes.empty() ? SourceLocation() : m_visitedNodes.top()->location()); } eth::AssemblyItem CompilerContext::FunctionCompilationQueue::entryLabel( Declaration const& _declaration, CompilerContext& _context ) { auto res = m_entryLabels.find(&_declaration); if (res == m_entryLabels.end()) { eth::AssemblyItem tag(_context.newTag()); m_entryLabels.insert(make_pair(&_declaration, tag)); m_functionsToCompile.push(&_declaration); return tag.tag(); } else return res->second.tag(); } eth::AssemblyItem CompilerContext::FunctionCompilationQueue::entryLabelIfExists(Declaration const& _declaration) const { auto res = m_entryLabels.find(&_declaration); return res == m_entryLabels.end() ? eth::AssemblyItem(eth::UndefinedItem) : res->second.tag(); } Declaration const* CompilerContext::FunctionCompilationQueue::nextFunctionToCompile() const { while (!m_functionsToCompile.empty()) { if (m_alreadyCompiledFunctions.count(m_functionsToCompile.front())) m_functionsToCompile.pop(); else return m_functionsToCompile.front(); } return nullptr; } void CompilerContext::FunctionCompilationQueue::startFunction(Declaration const& _function) { if (!m_functionsToCompile.empty() && m_functionsToCompile.front() == &_function) m_functionsToCompile.pop(); m_alreadyCompiledFunctions.insert(&_function); } } } <|endoftext|>
<commit_before>/* Copyright (c) 2003-2012, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DEBUG_HPP_INCLUDED #define TORRENT_DEBUG_HPP_INCLUDED #if defined TORRENT_ASIO_DEBUGGING #include "libtorrent/assert.hpp" #include "libtorrent/thread.hpp" #include <map> #include <cstring> std::string demangle(char const* name); namespace libtorrent { struct async_t { async_t() : refs(0) {} std::string stack; int refs; }; extern std::map<std::string, async_t> _async_ops; extern int _async_ops_nthreads; extern mutex _async_ops_mutex; inline void add_outstanding_async(char const* name) { mutex::scoped_lock l(_async_ops_mutex); async_t& a = _async_ops[name]; if (a.stack.empty()) { char stack_text[10000]; print_backtrace(stack_text, sizeof(stack_text), 9); a.stack = stack_text; } ++a.refs; } inline void complete_async(char const* name) { mutex::scoped_lock l(_async_ops_mutex); async_t& a = _async_ops[name]; TORRENT_ASSERT(a.refs > 0); --a.refs; } inline void async_inc_threads() { mutex::scoped_lock l(_async_ops_mutex); ++_async_ops_nthreads; } inline void async_dec_threads() { mutex::scoped_lock l(_async_ops_mutex); --_async_ops_nthreads; } inline int log_async() { mutex::scoped_lock l(_async_ops_mutex); int ret = 0; for (std::map<std::string, async_t>::iterator i = _async_ops.begin() , end(_async_ops.end()); i != end; ++i) { if (i->second.refs <= _async_ops_nthreads - 1) continue; ret += i->second.refs; printf("%s: (%d)\n%s\n", i->first.c_str(), i->second.refs, i->second.stack.c_str()); } return ret; } } #endif #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING #include <cstring> #include "libtorrent/config.hpp" #include "libtorrent/file.hpp" #include "libtorrent/thread.hpp" #if TORRENT_USE_IOSTREAM #include <string> #include <fstream> #include <iostream> #endif namespace libtorrent { // DEBUG API struct logger { #if TORRENT_USE_IOSTREAM // all log streams share a single file descriptor // and re-opens the file for each log line // these members are defined in session_impl.cpp static std::ofstream log_file; static std::string open_filename; static mutex file_mutex; #endif ~logger() { mutex::scoped_lock l(file_mutex); log_file.close(); open_filename.clear(); } logger(std::string const& logpath, std::string const& filename , int instance, bool append) { char log_name[512]; snprintf(log_name, sizeof(log_name), "libtorrent_logs%d", instance); std::string dir(complete(combine_path(combine_path(logpath, log_name), filename)) + ".log"); error_code ec; if (!exists(parent_path(dir))) create_directories(parent_path(dir), ec); m_filename = dir; mutex::scoped_lock l(file_mutex); open(!append); log_file << "\n\n\n*** starting log ***\n"; } void move_log_file(std::string const& logpath, std::string const& new_name, int instance) { mutex::scoped_lock l(file_mutex); if (open_filename == m_filename) { log_file.close(); open_filename.clear(); } char log_name[512]; snprintf(log_name, sizeof(log_name), "libtorrent_logs%d", instance); std::string dir(combine_path(combine_path(complete(logpath), log_name), new_name) + ".log"); error_code ec; create_directories(parent_path(dir), ec); if (ec) fprintf(stderr, "Failed to create logfile directory %s: %s\n" , parent_path(dir).c_str(), ec.message().c_str()); ec.clear(); rename(m_filename, dir, ec); if (ec) fprintf(stderr, "Failed to move logfile %s: %s\n" , parent_path(dir).c_str(), ec.message().c_str()); m_filename = dir; } #if TORRENT_USE_IOSTREAM void open(bool truncate) { if (open_filename == m_filename) return; log_file.close(); log_file.clear(); log_file.open(m_filename.c_str(), truncate ? std::ios_base::trunc : std::ios_base::app); open_filename = m_filename; if (!log_file.good()) fprintf(stderr, "Failed to open logfile %s: %s\n", m_filename.c_str(), strerror(errno)); } #endif template <class T> logger& operator<<(T const& v) { #if TORRENT_USE_IOSTREAM mutex::scoped_lock l(file_mutex); open(false); log_file << v; #endif return *this; } std::string m_filename; }; } #endif // TORRENT_VERBOSE_LOGGING || TORRENT_LOGGING || TORRENT_ERROR_LOGGING #endif // TORRENT_DEBUG_HPP_INCLUDED <commit_msg>completely disable log file creation<commit_after>/* Copyright (c) 2003-2012, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DEBUG_HPP_INCLUDED #define TORRENT_DEBUG_HPP_INCLUDED #if defined TORRENT_ASIO_DEBUGGING #include "libtorrent/assert.hpp" #include "libtorrent/thread.hpp" #include <map> #include <cstring> std::string demangle(char const* name); namespace libtorrent { struct async_t { async_t() : refs(0) {} std::string stack; int refs; }; extern std::map<std::string, async_t> _async_ops; extern int _async_ops_nthreads; extern mutex _async_ops_mutex; inline void add_outstanding_async(char const* name) { mutex::scoped_lock l(_async_ops_mutex); async_t& a = _async_ops[name]; if (a.stack.empty()) { char stack_text[10000]; print_backtrace(stack_text, sizeof(stack_text), 9); a.stack = stack_text; } ++a.refs; } inline void complete_async(char const* name) { mutex::scoped_lock l(_async_ops_mutex); async_t& a = _async_ops[name]; TORRENT_ASSERT(a.refs > 0); --a.refs; } inline void async_inc_threads() { mutex::scoped_lock l(_async_ops_mutex); ++_async_ops_nthreads; } inline void async_dec_threads() { mutex::scoped_lock l(_async_ops_mutex); --_async_ops_nthreads; } inline int log_async() { mutex::scoped_lock l(_async_ops_mutex); int ret = 0; for (std::map<std::string, async_t>::iterator i = _async_ops.begin() , end(_async_ops.end()); i != end; ++i) { if (i->second.refs <= _async_ops_nthreads - 1) continue; ret += i->second.refs; printf("%s: (%d)\n%s\n", i->first.c_str(), i->second.refs, i->second.stack.c_str()); } return ret; } } #endif #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING #include <cstring> #include "libtorrent/config.hpp" #include "libtorrent/file.hpp" #include "libtorrent/thread.hpp" #if TORRENT_USE_IOSTREAM #include <string> #include <fstream> #include <iostream> #endif namespace libtorrent { // DEBUG API struct logger { #if TORRENT_USE_IOSTREAM // all log streams share a single file descriptor // and re-opens the file for each log line // these members are defined in session_impl.cpp static std::ofstream log_file; static std::string open_filename; static mutex file_mutex; #endif ~logger() { mutex::scoped_lock l(file_mutex); log_file.close(); open_filename.clear(); } logger(std::string const& logpath, std::string const& filename , int instance, bool append) { /* [MF] log is now in bitcoin char log_name[512]; snprintf(log_name, sizeof(log_name), "libtorrent_logs%d", instance); std::string dir(complete(combine_path(combine_path(logpath, log_name), filename)) + ".log"); error_code ec; if (!exists(parent_path(dir))) create_directories(parent_path(dir), ec); m_filename = dir; */ mutex::scoped_lock l(file_mutex); // [MF] //open(!append); //log_file << "\n\n\n*** starting log ***\n"; } void move_log_file(std::string const& logpath, std::string const& new_name, int instance) { mutex::scoped_lock l(file_mutex); /* if (open_filename == m_filename) { log_file.close(); open_filename.clear(); } char log_name[512]; snprintf(log_name, sizeof(log_name), "libtorrent_logs%d", instance); std::string dir(combine_path(combine_path(complete(logpath), log_name), new_name) + ".log"); error_code ec; create_directories(parent_path(dir), ec); if (ec) fprintf(stderr, "Failed to create logfile directory %s: %s\n" , parent_path(dir).c_str(), ec.message().c_str()); ec.clear(); rename(m_filename, dir, ec); if (ec) fprintf(stderr, "Failed to move logfile %s: %s\n" , parent_path(dir).c_str(), ec.message().c_str()); m_filename = dir; */ } #if TORRENT_USE_IOSTREAM void open(bool truncate) { if (open_filename == m_filename) return; log_file.close(); log_file.clear(); log_file.open(m_filename.c_str(), truncate ? std::ios_base::trunc : std::ios_base::app); open_filename = m_filename; if (!log_file.good()) fprintf(stderr, "Failed to open logfile %s: %s\n", m_filename.c_str(), strerror(errno)); } #endif template <class T> logger& operator<<(T const& v) { #if TORRENT_USE_IOSTREAM mutex::scoped_lock l(file_mutex); open(false); log_file << v; #endif return *this; } std::string m_filename; }; } #endif // TORRENT_VERBOSE_LOGGING || TORRENT_LOGGING || TORRENT_ERROR_LOGGING #endif // TORRENT_DEBUG_HPP_INCLUDED <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/audio/sounds/wav_audio_handler.h" #include <algorithm> #include <cstring> #include "base/logging.h" #include "base/sys_byteorder.h" #include "media/base/audio_bus.h" namespace { const char kChunkId[] = "RIFF"; const char kFormat[] = "WAVE"; const char kSubchunk1Id[] = "fmt "; const char kSubchunk2Id[] = "data"; // The size of the header of a wav file. The header consists of 'RIFF', 4 bytes // of total data length, and 'WAVE'. const size_t kWavFileHeaderSize = 12; // The size of a chunk header in wav file format. A chunk header consists of a // tag ('fmt ' or 'data') and 4 bytes of chunk length. const size_t kChunkHeaderSize = 8; // The minimum size of 'fmt' chunk. const size_t kFmtChunkMinimumSize = 16; // The offsets of 'fmt' fields. const size_t kAudioFormatOffset = 0; const size_t kChannelOffset = 2; const size_t kSampleRateOffset = 4; const size_t kByteRateOffset = 8; const size_t kBitsPerSampleOffset = 14; // Some constants for audio format. const int kAudioFormatPCM = 1; // Reads an integer from |data| with |offset|. template<typename T> T ReadInt(const base::StringPiece& data, size_t offset) { CHECK_LE(offset + sizeof(T), data.size()); T result; memcpy(&result, data.data() + offset, sizeof(T)); #if !defined(ARCH_CPU_LITTLE_ENDIAN) result = base::ByteSwap(result); #endif return result; } } // namespace namespace media { WavAudioHandler::WavAudioHandler(const base::StringPiece& wav_data) : num_channels_(0), sample_rate_(0), byte_rate_(0), bits_per_sample_(0) { CHECK_LE(kWavFileHeaderSize, wav_data.size()) << "wav data is too small"; CHECK(wav_data.starts_with(kChunkId) && memcmp(wav_data.data() + 8, kFormat, 4) == 0) << "incorrect wav header"; uint32 total_length = std::min(ReadInt<uint32>(wav_data, 4), static_cast<uint32>(wav_data.size())); uint32 offset = kWavFileHeaderSize; while (offset < total_length) { const int length = ParseSubChunk(wav_data.substr(offset)); CHECK_LE(0, length) << "can't parse wav sub-chunk"; offset += length; } } WavAudioHandler::~WavAudioHandler() { } bool WavAudioHandler::AtEnd(size_t cursor) const { return data_.size() <= cursor; } bool WavAudioHandler::CopyTo(AudioBus* bus, size_t cursor, size_t* bytes_written) const { if (!bus) return false; if (bus->channels() != num_channels_) { LOG(ERROR) << "Number of channel mismatch."; return false; } if (AtEnd(cursor)) { bus->Zero(); return true; } const int remaining_frames = (data_.size() - cursor) / bytes_per_frame_; const int frames = std::min(bus->frames(), remaining_frames); bus->FromInterleaved(data_.data() + cursor, frames, bytes_per_sample_); *bytes_written = frames * bytes_per_frame_; bus->ZeroFramesPartial(frames, bus->frames() - frames); return true; } int WavAudioHandler::ParseSubChunk(const base::StringPiece& data) { if (data.size() < kChunkHeaderSize) return data.size(); uint32 chunk_length = ReadInt<uint32>(data, 4); if (data.starts_with(kSubchunk1Id)) { if (!ParseFmtChunk(data.substr(kChunkHeaderSize, chunk_length))) return -1; } else if (data.starts_with(kSubchunk2Id)) { if (!ParseDataChunk(data.substr(kChunkHeaderSize, chunk_length))) return -1; } else { LOG(ERROR) << "Unknown data chunk: " << data.substr(0, 4) << "."; } return chunk_length + kChunkHeaderSize; } bool WavAudioHandler::ParseFmtChunk(const base::StringPiece& data) { if (data.size() < kFmtChunkMinimumSize) { LOG(ERROR) << "Data size " << data.size() << " is too short."; return false; } DCHECK_EQ(ReadInt<uint16>(data, kAudioFormatOffset), kAudioFormatPCM); num_channels_ = ReadInt<uint16>(data, kChannelOffset); sample_rate_ = ReadInt<uint32>(data, kSampleRateOffset); byte_rate_ = ReadInt<uint32>(data, kByteRateOffset); bits_per_sample_ = ReadInt<uint16>(data, kBitsPerSampleOffset); bytes_per_sample_ = bits_per_sample_ >> 3; bytes_per_frame_ = num_channels_ * bytes_per_sample_; return true; } bool WavAudioHandler::ParseDataChunk(const base::StringPiece& data) { data_ = data; return true; } } // namespace media <commit_msg>LOG(ERROR) -> VLOG(1)<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/audio/sounds/wav_audio_handler.h" #include <algorithm> #include <cstring> #include "base/logging.h" #include "base/sys_byteorder.h" #include "media/base/audio_bus.h" namespace { const char kChunkId[] = "RIFF"; const char kFormat[] = "WAVE"; const char kSubchunk1Id[] = "fmt "; const char kSubchunk2Id[] = "data"; // The size of the header of a wav file. The header consists of 'RIFF', 4 bytes // of total data length, and 'WAVE'. const size_t kWavFileHeaderSize = 12; // The size of a chunk header in wav file format. A chunk header consists of a // tag ('fmt ' or 'data') and 4 bytes of chunk length. const size_t kChunkHeaderSize = 8; // The minimum size of 'fmt' chunk. const size_t kFmtChunkMinimumSize = 16; // The offsets of 'fmt' fields. const size_t kAudioFormatOffset = 0; const size_t kChannelOffset = 2; const size_t kSampleRateOffset = 4; const size_t kByteRateOffset = 8; const size_t kBitsPerSampleOffset = 14; // Some constants for audio format. const int kAudioFormatPCM = 1; // Reads an integer from |data| with |offset|. template<typename T> T ReadInt(const base::StringPiece& data, size_t offset) { CHECK_LE(offset + sizeof(T), data.size()); T result; memcpy(&result, data.data() + offset, sizeof(T)); #if !defined(ARCH_CPU_LITTLE_ENDIAN) result = base::ByteSwap(result); #endif return result; } } // namespace namespace media { WavAudioHandler::WavAudioHandler(const base::StringPiece& wav_data) : num_channels_(0), sample_rate_(0), byte_rate_(0), bits_per_sample_(0) { CHECK_LE(kWavFileHeaderSize, wav_data.size()) << "wav data is too small"; CHECK(wav_data.starts_with(kChunkId) && memcmp(wav_data.data() + 8, kFormat, 4) == 0) << "incorrect wav header"; uint32 total_length = std::min(ReadInt<uint32>(wav_data, 4), static_cast<uint32>(wav_data.size())); uint32 offset = kWavFileHeaderSize; while (offset < total_length) { const int length = ParseSubChunk(wav_data.substr(offset)); CHECK_LE(0, length) << "can't parse wav sub-chunk"; offset += length; } } WavAudioHandler::~WavAudioHandler() { } bool WavAudioHandler::AtEnd(size_t cursor) const { return data_.size() <= cursor; } bool WavAudioHandler::CopyTo(AudioBus* bus, size_t cursor, size_t* bytes_written) const { if (!bus) return false; if (bus->channels() != num_channels_) { DLOG(ERROR) << "Number of channel mismatch."; return false; } if (AtEnd(cursor)) { bus->Zero(); return true; } const int remaining_frames = (data_.size() - cursor) / bytes_per_frame_; const int frames = std::min(bus->frames(), remaining_frames); bus->FromInterleaved(data_.data() + cursor, frames, bytes_per_sample_); *bytes_written = frames * bytes_per_frame_; bus->ZeroFramesPartial(frames, bus->frames() - frames); return true; } int WavAudioHandler::ParseSubChunk(const base::StringPiece& data) { if (data.size() < kChunkHeaderSize) return data.size(); uint32 chunk_length = ReadInt<uint32>(data, 4); if (data.starts_with(kSubchunk1Id)) { if (!ParseFmtChunk(data.substr(kChunkHeaderSize, chunk_length))) return -1; } else if (data.starts_with(kSubchunk2Id)) { if (!ParseDataChunk(data.substr(kChunkHeaderSize, chunk_length))) return -1; } else { DVLOG(1) << "Unknown data chunk: " << data.substr(0, 4) << "."; } return chunk_length + kChunkHeaderSize; } bool WavAudioHandler::ParseFmtChunk(const base::StringPiece& data) { if (data.size() < kFmtChunkMinimumSize) { DLOG(ERROR) << "Data size " << data.size() << " is too short."; return false; } DCHECK_EQ(ReadInt<uint16>(data, kAudioFormatOffset), kAudioFormatPCM); num_channels_ = ReadInt<uint16>(data, kChannelOffset); sample_rate_ = ReadInt<uint32>(data, kSampleRateOffset); byte_rate_ = ReadInt<uint32>(data, kByteRateOffset); bits_per_sample_ = ReadInt<uint16>(data, kBitsPerSampleOffset); bytes_per_sample_ = bits_per_sample_ >> 3; bytes_per_frame_ = num_channels_ * bytes_per_sample_; return true; } bool WavAudioHandler::ParseDataChunk(const base::StringPiece& data) { data_ = data; return true; } } // namespace media <|endoftext|>
<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0 #ifndef __BSE_PUGIXML_HH__ #define __BSE_PUGIXML_HH__ #define PUGIXML_NO_XPATH #define PUGIXML_NO_EXCEPTIONS // Tune these constants to adjust memory-related behavior // #define PUGIXML_MEMORY_PAGE_SIZE 32768 // #define PUGIXML_MEMORY_OUTPUT_STACK 10240 // #define PUGIXML_MEMORY_XPATH_PAGE_SIZE 4096 #include "../external/pugixml/src/pugixml.hpp" #endif // __BSE_PUGIXML_HH__ <commit_msg>BSE: pugixml: compile pugixml without exceptions<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0 #ifndef __BSE_PUGIXML_HH__ #define __BSE_PUGIXML_HH__ #define PUGIXML_NO_XPATH #define PUGIXML_NO_EXCEPTIONS // Tune these constants to adjust memory-related behavior // #define PUGIXML_MEMORY_PAGE_SIZE 32768 // #define PUGIXML_MEMORY_OUTPUT_STACK 10240 // #define PUGIXML_MEMORY_XPATH_PAGE_SIZE 4096 #define PUGIXML_NO_EXCEPTIONS // use error return codes #include "../external/pugixml/src/pugixml.hpp" #endif // __BSE_PUGIXML_HH__ <|endoftext|>
<commit_before>// @(#)root/winnt:$Name: $:$Id: TWin32Timer.cxx,v 1.1.1.1 2000/05/16 17:00:46 rdm Exp $ // Author: Valery Fine(fine@mail.cern.ch) 29/09/98 #include <process.h> #include "Windows4Root.h" #include "TTimer.h" #include "TROOT.h" #include "TWin32Timer.h" #include "TWin32HookViaThread.h" #include "TGWin32Command.h" #include "TInterpreter.h" struct WIN32TIMETHREAD { HANDLE ThrSem; TWin32Timer *ti; } ; enum ETimerCallbackCmd {kCreateTimer, kKillTimer}; const Char_t *TIMERCLASS = "Timer"; //*-* //*-* Macros to call the Callback methods via Timer thread: //*-* #define CallMethodThread(_function,_p1,_p2,_p3) \ else \ { \ TWin32SendWaitClass code(this,(UInt_t)k##_function,(UInt_t)(_p1),(UInt_t)(_p2),(UInt_t)(_p3)); \ ExecTimerThread(&code); \ code.Wait(); \ } #define ReturnMethodThread(_type,_function,_p1,_p2) \ else \ { \ _type _local; \ TWin32SendWaitClass code(this,(UInt_t)k##_function,(UInt_t)(_p1),(UInt_t)(_p2),(UInt_t)(&_local)); \ ExecTimerThread(&code); \ code.Wait(); \ return _local; \ } //*-* #define CallWindowMethod1(_function,_p1) \ if ( IsTimeThread()) \ {TWin32Timer::_function(_p1);} \ CallMethodThread(_function,_p1,0,0) //*-* #define CallWindowMethod(_function) \ if ( IsTimeThread()) \ {TWin32Timer::_function();} \ CallMethodThread(_function,0,0,0) //*-* #define ReturnWindowMethod1(_type,_function,_p1) \ if ( IsTimeThread()) \ {return TWin32Timer::_function(_p1);} \ ReturnMethodThread(_type,_function,_p1,0) //*-* #define ReturnWindowMethod(_type,_function) \ if ( IsTimeThread()) \ {return TWin32Timer::_function();} \ ReturnMethodThread(_type,_function,0,0) //______________________________________________________________________________ static VOID CALLBACK DispatchTimers(HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime) { //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- //*-* //*-* HWND hwnd, // handle of window for timer messages //*-* UINT uMsg, // WM_TIMER message //*-* UINT idEvent, // timer identifier (pointer to TTimer object) //*-* DWORD dwTime // current system time //*-* //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- TTimer *ti = (TTimer *)idEvent; if (ti) { if (ti->IsAsync()) ti->Notify(); else gROOT->ProcessLine(Form("((TTimer *)0x%lx)->Notify();",(Long_t)ti)); } } //______________________________________________________________________________ static LRESULT APIENTRY WndTimer(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { ////////////////////////////////////////////////////////////////////////// // // // Main Universal Windows procedure to manage all dispatched events // // // ////////////////////////////////////////////////////////////////////////// return ::DefWindowProc(hwnd, uMsg, wParam, lParam); } //______________________________________________________________________________ static unsigned int _stdcall ROOT_TimerLoop(void *threadcmd) { //--------------------------------------- // Create windows HWND fhdTimerWindow = CreateWindowEx(NULL, TIMERCLASS, NULL, // address of window name WS_DISABLED , // window style 0,0, // start positio of the window, 0, 0, // size of the window NULL, // handle of parent of owner window NULL, // handle of menu, or child-window identifier GetModuleHandle(NULL), // handle of application instance NULL); // address of window-creation data HANDLE ThrSem = ((WIN32TIMETHREAD *)threadcmd)->ThrSem; ((WIN32TIMETHREAD *)threadcmd)->ti->SetHWND(fhdTimerWindow); //--------------------------------------- MSG msg; int erret; // GetMessage result ReleaseSemaphore(ThrSem, 1, NULL); Bool_t EventLoopStop = kFALSE; // create timer while(!EventLoopStop) { if (EventLoopStop = (!(erret=GetMessage(&msg,NULL,0,0)) || erret == -1)) continue; if (msg.hwnd == NULL && (msg.message == ROOT_CMD || msg.message == ROOT_SYNCH_CMD)) if (TWin32HookViaThread::ExecuteEvent(&msg, msg.message==ROOT_SYNCH_CMD)) continue; TranslateMessage(&msg); DispatchMessage(&msg); } if (erret == -1) { erret = GetLastError(); fprintf(stderr," *** Error **** TimerLoop: %d \n", erret); } if (msg.wParam) ReleaseSemaphore((HANDLE) msg.wParam, 1, NULL); _endthreadex(0); return 0; } /* ROOT_MsgLoop */ //______________________________________________________________________________ TWin32Timer::TWin32Timer() { fhdTimerWindow = 0; fhdTimerThread = 0; fhdTimerThreadId = 0; } //______________________________________________________________________________ TWin32Timer::~TWin32Timer() { if (fhdTimerThreadId) { PostThreadMessage(fhdTimerThreadId,WM_QUIT,0,0); if (WaitForSingleObject(fhdTimerThread,10000)==WAIT_FAILED) TerminateThread(fhdTimerThread, -1); CloseHandle(fhdTimerThread); } } //______________________________________________________________________________ Int_t TWin32Timer::CreateTimerThread() { // Register class "Timer" HMODULE instance = GetModuleHandle(NULL); static const WNDCLASS timerwindowclass = { CS_GLOBALCLASS , WndTimer , 0, 0 , instance , NULL, NULL, NULL, NULL , TIMERCLASS}; WNDCLASSEX timerinfo; if (GetClassInfoEx(instance,TIMERCLASS,&timerinfo)) return 0; if (!RegisterClass( &timerwindowclass)) { DWORD l_err = GetLastError(); printf(" Last Error is %d \n", l_err); return -1; } WIN32TIMETHREAD threadcmd; // // Create thread to do the cmd loop // threadcmd.ThrSem = CreateSemaphore(NULL, 0, 1, NULL); threadcmd.ti = this; // fhdTimerThread = (HANDLE)_beginthreadex(NULL,0, ROOT_TimerLoop, fhdTimerThread = (unsigned long *) _beginthreadex(NULL,0, ROOT_TimerLoop, (LPVOID) &threadcmd, 0, ((unsigned *)&fhdTimerThreadId)); if (Int_t(fhdTimerThread) == -1){ int erret = GetLastError(); printf(" *** Error *** CreatTimerThread <Thread was not created> %d \n", erret); } WaitForSingleObject(threadcmd.ThrSem, INFINITE); CloseHandle(threadcmd.ThrSem); return 0; } //______________________________________________________________________________ UInt_t TWin32Timer::CreateTimer(TTimer *timer) { if(!fhdTimerThreadId) CreateTimerThread(); CallWindowMethod1(CreateTimer,timer); return 0; } //______________________________________________________________________________ void TWin32Timer::CreateTimerCB(TTimer *timer) { if (timer) timer->SetTimerID((UInt_t)(::SetTimer(fhdTimerWindow,(UINT)timer,timer->GetTime() , (TIMERPROC) ::DispatchTimers)) ); } //______________________________________________________________________________ void TWin32Timer::ExecTimerThread(TGWin32Command *command) { //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* //*-* Execute command via "Timer" thread //*-* //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* // Some extra flag is needed to mark the command = 0 turn !!! TGWin32Command *code = command; if (!code) code = new TWin32SendClass(this); fSendFlag = 1; int i = ExecCommand(code,kFALSE); } //______________________________________________________________________________ Bool_t TWin32Timer::ExecCommand(TGWin32Command *command,Bool_t synch) { // To exec a command coming from the other threads BOOL postresult; ERoot_Msgs cmd = ROOT_CMD; if (fhdTimerThreadId == GetCurrentThreadId()) printf("TWin32Timer::ExecCommand --- > The dead lock danger\n"); if (synch) cmd = ROOT_SYNCH_CMD; while (!(postresult = PostThreadMessage(fhdTimerThreadId, cmd, (WPARAM)command->GetCOP(), (LPARAM)command)) ){ ; } return postresult; } //______________________________________________________________________________ Bool_t TWin32Timer::IsTimeThread(){ return fhdTimerThreadId == GetCurrentThreadId(); } //______________________________________________________________________________ void TWin32Timer::KillTimer(TTimer *timer) { CallWindowMethod1(KillTimer,timer); } //______________________________________________________________________________ void TWin32Timer::KillTimerCB(TTimer *timer) { if(timer) { // ::KillTimer(NULL,timer->GetTimerID()); ::KillTimer(fhdTimerWindow,(UINT)timer); timer->SetTimerID(0); } } //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* Callback methods: //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //______________________________________________________________________________ void TWin32Timer::ExecThreadCB(TWin32SendClass *command) { ETimerCallbackCmd cmd = (ETimerCallbackCmd)(command->GetData(0)); Bool_t debug = kFALSE; char *listcmd[] = { "CreateTimer" ,"KillTimer" }; if (gDebug) printf("TWin32Timer: commamd %d: %s",cmd,listcmd[cmd]); switch (cmd) { case kCreateTimer: { TTimer *ti = (TTimer *)(command->GetData(1)); if (gDebug) printf(" %lx ", (Long_t)ti); CreateTimerCB(ti); break; } case kKillTimer: { TTimer *ti = (TTimer *)(command->GetData(1)); if (gDebug) printf(" %lx ", (Long_t)ti); KillTimerCB(ti); break; } default: break; } if (gDebug) printf(" \n"); if (LOWORD(command->GetCOP()) == kSendWaitClass) ((TWin32SendWaitClass *)command)->Release(); else delete command; } <commit_msg>explicit cast to (unsigned long) for a TTime argument.<commit_after>// @(#)root/winnt:$Name: $:$Id: TWin32Timer.cxx,v 1.2 2001/05/16 08:53:16 brun Exp $ // Author: Valery Fine(fine@mail.cern.ch) 29/09/98 #include <process.h> #include "Windows4Root.h" #include "TTimer.h" #include "TROOT.h" #include "TWin32Timer.h" #include "TWin32HookViaThread.h" #include "TGWin32Command.h" #include "TInterpreter.h" struct WIN32TIMETHREAD { HANDLE ThrSem; TWin32Timer *ti; } ; enum ETimerCallbackCmd {kCreateTimer, kKillTimer}; const Char_t *TIMERCLASS = "Timer"; //*-* //*-* Macros to call the Callback methods via Timer thread: //*-* #define CallMethodThread(_function,_p1,_p2,_p3) \ else \ { \ TWin32SendWaitClass code(this,(UInt_t)k##_function,(UInt_t)(_p1),(UInt_t)(_p2),(UInt_t)(_p3)); \ ExecTimerThread(&code); \ code.Wait(); \ } #define ReturnMethodThread(_type,_function,_p1,_p2) \ else \ { \ _type _local; \ TWin32SendWaitClass code(this,(UInt_t)k##_function,(UInt_t)(_p1),(UInt_t)(_p2),(UInt_t)(&_local)); \ ExecTimerThread(&code); \ code.Wait(); \ return _local; \ } //*-* #define CallWindowMethod1(_function,_p1) \ if ( IsTimeThread()) \ {TWin32Timer::_function(_p1);} \ CallMethodThread(_function,_p1,0,0) //*-* #define CallWindowMethod(_function) \ if ( IsTimeThread()) \ {TWin32Timer::_function();} \ CallMethodThread(_function,0,0,0) //*-* #define ReturnWindowMethod1(_type,_function,_p1) \ if ( IsTimeThread()) \ {return TWin32Timer::_function(_p1);} \ ReturnMethodThread(_type,_function,_p1,0) //*-* #define ReturnWindowMethod(_type,_function) \ if ( IsTimeThread()) \ {return TWin32Timer::_function();} \ ReturnMethodThread(_type,_function,0,0) //______________________________________________________________________________ static VOID CALLBACK DispatchTimers(HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime) { //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- //*-* //*-* HWND hwnd, // handle of window for timer messages //*-* UINT uMsg, // WM_TIMER message //*-* UINT idEvent, // timer identifier (pointer to TTimer object) //*-* DWORD dwTime // current system time //*-* //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- TTimer *ti = (TTimer *)idEvent; if (ti) { if (ti->IsAsync()) ti->Notify(); else gROOT->ProcessLine(Form("((TTimer *)0x%lx)->Notify();",(Long_t)ti)); } } //______________________________________________________________________________ static LRESULT APIENTRY WndTimer(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { ////////////////////////////////////////////////////////////////////////// // // // Main Universal Windows procedure to manage all dispatched events // // // ////////////////////////////////////////////////////////////////////////// return ::DefWindowProc(hwnd, uMsg, wParam, lParam); } //______________________________________________________________________________ static unsigned int _stdcall ROOT_TimerLoop(void *threadcmd) { //--------------------------------------- // Create windows HWND fhdTimerWindow = CreateWindowEx(NULL, TIMERCLASS, NULL, // address of window name WS_DISABLED , // window style 0,0, // start positio of the window, 0, 0, // size of the window NULL, // handle of parent of owner window NULL, // handle of menu, or child-window identifier GetModuleHandle(NULL), // handle of application instance NULL); // address of window-creation data HANDLE ThrSem = ((WIN32TIMETHREAD *)threadcmd)->ThrSem; ((WIN32TIMETHREAD *)threadcmd)->ti->SetHWND(fhdTimerWindow); //--------------------------------------- MSG msg; int erret; // GetMessage result ReleaseSemaphore(ThrSem, 1, NULL); Bool_t EventLoopStop = kFALSE; // create timer while(!EventLoopStop) { if (EventLoopStop = (!(erret=GetMessage(&msg,NULL,0,0)) || erret == -1)) continue; if (msg.hwnd == NULL && (msg.message == ROOT_CMD || msg.message == ROOT_SYNCH_CMD)) if (TWin32HookViaThread::ExecuteEvent(&msg, msg.message==ROOT_SYNCH_CMD)) continue; TranslateMessage(&msg); DispatchMessage(&msg); } if (erret == -1) { erret = GetLastError(); fprintf(stderr," *** Error **** TimerLoop: %d \n", erret); } if (msg.wParam) ReleaseSemaphore((HANDLE) msg.wParam, 1, NULL); _endthreadex(0); return 0; } /* ROOT_MsgLoop */ //______________________________________________________________________________ TWin32Timer::TWin32Timer() { fhdTimerWindow = 0; fhdTimerThread = 0; fhdTimerThreadId = 0; } //______________________________________________________________________________ TWin32Timer::~TWin32Timer() { if (fhdTimerThreadId) { PostThreadMessage(fhdTimerThreadId,WM_QUIT,0,0); if (WaitForSingleObject(fhdTimerThread,10000)==WAIT_FAILED) TerminateThread(fhdTimerThread, -1); CloseHandle(fhdTimerThread); } } //______________________________________________________________________________ Int_t TWin32Timer::CreateTimerThread() { // Register class "Timer" HMODULE instance = GetModuleHandle(NULL); static const WNDCLASS timerwindowclass = { CS_GLOBALCLASS , WndTimer , 0, 0 , instance , NULL, NULL, NULL, NULL , TIMERCLASS}; WNDCLASSEX timerinfo; if (GetClassInfoEx(instance,TIMERCLASS,&timerinfo)) return 0; if (!RegisterClass( &timerwindowclass)) { DWORD l_err = GetLastError(); printf(" Last Error is %d \n", l_err); return -1; } WIN32TIMETHREAD threadcmd; // // Create thread to do the cmd loop // threadcmd.ThrSem = CreateSemaphore(NULL, 0, 1, NULL); threadcmd.ti = this; // fhdTimerThread = (HANDLE)_beginthreadex(NULL,0, ROOT_TimerLoop, fhdTimerThread = (unsigned long *) _beginthreadex(NULL,0, ROOT_TimerLoop, (LPVOID) &threadcmd, 0, ((unsigned *)&fhdTimerThreadId)); if (Int_t(fhdTimerThread) == -1){ int erret = GetLastError(); printf(" *** Error *** CreatTimerThread <Thread was not created> %d \n", erret); } WaitForSingleObject(threadcmd.ThrSem, INFINITE); CloseHandle(threadcmd.ThrSem); return 0; } //______________________________________________________________________________ UInt_t TWin32Timer::CreateTimer(TTimer *timer) { if(!fhdTimerThreadId) CreateTimerThread(); CallWindowMethod1(CreateTimer,timer); return 0; } //______________________________________________________________________________ void TWin32Timer::CreateTimerCB(TTimer *timer) { if (timer) timer->SetTimerID((UInt_t)(::SetTimer(fhdTimerWindow,(UINT)timer, (unsigned long)timer->GetTime(), (TIMERPROC) ::DispatchTimers)) ); } //______________________________________________________________________________ void TWin32Timer::ExecTimerThread(TGWin32Command *command) { //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* //*-* Execute command via "Timer" thread //*-* //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* // Some extra flag is needed to mark the command = 0 turn !!! TGWin32Command *code = command; if (!code) code = new TWin32SendClass(this); fSendFlag = 1; int i = ExecCommand(code,kFALSE); } //______________________________________________________________________________ Bool_t TWin32Timer::ExecCommand(TGWin32Command *command,Bool_t synch) { // To exec a command coming from the other threads BOOL postresult; ERoot_Msgs cmd = ROOT_CMD; if (fhdTimerThreadId == GetCurrentThreadId()) printf("TWin32Timer::ExecCommand --- > The dead lock danger\n"); if (synch) cmd = ROOT_SYNCH_CMD; while (!(postresult = PostThreadMessage(fhdTimerThreadId, cmd, (WPARAM)command->GetCOP(), (LPARAM)command)) ){ ; } return postresult; } //______________________________________________________________________________ Bool_t TWin32Timer::IsTimeThread(){ return fhdTimerThreadId == GetCurrentThreadId(); } //______________________________________________________________________________ void TWin32Timer::KillTimer(TTimer *timer) { CallWindowMethod1(KillTimer,timer); } //______________________________________________________________________________ void TWin32Timer::KillTimerCB(TTimer *timer) { if(timer) { // ::KillTimer(NULL,timer->GetTimerID()); ::KillTimer(fhdTimerWindow,(UINT)timer); timer->SetTimerID(0); } } //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* Callback methods: //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //______________________________________________________________________________ void TWin32Timer::ExecThreadCB(TWin32SendClass *command) { ETimerCallbackCmd cmd = (ETimerCallbackCmd)(command->GetData(0)); Bool_t debug = kFALSE; char *listcmd[] = { "CreateTimer" ,"KillTimer" }; if (gDebug) printf("TWin32Timer: commamd %d: %s",cmd,listcmd[cmd]); switch (cmd) { case kCreateTimer: { TTimer *ti = (TTimer *)(command->GetData(1)); if (gDebug) printf(" %lx ", (Long_t)ti); CreateTimerCB(ti); break; } case kKillTimer: { TTimer *ti = (TTimer *)(command->GetData(1)); if (gDebug) printf(" %lx ", (Long_t)ti); KillTimerCB(ti); break; } default: break; } if (gDebug) printf(" \n"); if (LOWORD(command->GetCOP()) == kSendWaitClass) ((TWin32SendWaitClass *)command)->Release(); else delete command; } <|endoftext|>
<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html #include "viewport.hh" #include "factory.hh" #define VDEBUG(...) RAPICORN_KEY_DEBUG ("Viewport", __VA_ARGS__) namespace Rapicorn { ViewportImpl::ViewportImpl () : xoffset_ (0), yoffset_ (0), sig_scrolled (Aida::slot (*this, &ViewportImpl::do_scrolled)) { const_cast<AnchorInfo*> (force_anchor_info())->viewport = this; } ViewportImpl::~ViewportImpl () { const_cast<AnchorInfo*> (force_anchor_info())->viewport = NULL; } void ViewportImpl::scroll_offsets (int deltax, int deltay) { if (deltax != xoffset_ || deltay != yoffset_) { xoffset_ = deltax; yoffset_ = deltay; // FIXME: need to issue 0-distance move here sig_scrolled.emit(); } } void ViewportImpl::do_scrolled () { expose(); } Allocation ViewportImpl::child_viewport () { const Allocation &area = allocation(); const int xoffset = scroll_offset_x(), yoffset = scroll_offset_y(); return Allocation (xoffset, yoffset, area.width, area.height); } Affine ViewportImpl::child_affine (const WidgetImpl &widget) { const Allocation &area = allocation(); const int xoffset = scroll_offset_x(), yoffset = scroll_offset_y(); return AffineTranslate (-area.x + xoffset, -area.y + yoffset); } void ViewportImpl::render_recursive (RenderContext &rcontext) { // prevent recursive rendering of children by not calling ResizeContainerImpl::render_recursive if (0) ResizeContainerImpl::render_recursive (rcontext); // viewport children are rendered in render() } void ViewportImpl::render (RenderContext &rcontext, const Rect &rect) { if (!has_drawable_child()) return; const Allocation &area = allocation(); WidgetImpl &child = get_child(); const int xoffset = xoffset_, yoffset = yoffset_; // constrain rendering within allocation Region what = rect; // constrain to child allocation (child is allocated relative to Viewport origin) const Allocation carea = child.allocation(); what.intersect (Rect (area.x + carea.x, area.y + carea.y, carea.width, carea.height)); // constrain to exposed region what.intersect (rendering_region (rcontext)); // viewport rendering rectangle const Allocation rarea = what.extents(); // translate area into child space, shifting by scroll offsets what.translate (xoffset - area.x, yoffset - area.y); // render child stack if (!what.empty()) { expose_region_.subtract (what); cairo_t *cr = cairo_context (rcontext, rarea); cairo_translate (cr, area.x - xoffset, area.y - yoffset); child.render_into (cr, what); } } void ViewportImpl::expose_child_region (const Region &region) { if (!region.empty()) { expose_region_.add (region); collapse_expose_region(); if (parent()) { const Allocation &area = allocation(); // propagate exposes, to make child rendering changes visible at toplevel Region vpregion = region; vpregion.translate (area.x - xoffset_, area.y - yoffset_); // translate to viewport coords expose (vpregion); } } } void ViewportImpl::collapse_expose_region () { // check for excess expose fragment scenarios uint n_erects = expose_region_.count_rects(); /* considering O(n^2) collision computation complexity, but also focus frame * exposures which easily consist of 4+ fragments, a hundred rectangles turn * out to be an emperically suitable threshold. */ if (n_erects > 99) { /* aparently the expose fragments we're combining are too small, * so we can end up with spending too much time on expose rectangle * compression (more time than needed for actual rendering). * as a workaround, we simply force everything into a single expose * rectangle which is good enough to avoid worst case explosion. */ expose_region_.add (expose_region_.extents()); VDEBUG ("collapsing expose rectangles due to overflow: %u -> %u\n", n_erects, expose_region_.count_rects()); } } } // Rapicorn <commit_msg>UI: fix newline<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html #include "viewport.hh" #include "factory.hh" #define VDEBUG(...) RAPICORN_KEY_DEBUG ("Viewport", __VA_ARGS__) namespace Rapicorn { ViewportImpl::ViewportImpl () : xoffset_ (0), yoffset_ (0), sig_scrolled (Aida::slot (*this, &ViewportImpl::do_scrolled)) { const_cast<AnchorInfo*> (force_anchor_info())->viewport = this; } ViewportImpl::~ViewportImpl () { const_cast<AnchorInfo*> (force_anchor_info())->viewport = NULL; } void ViewportImpl::scroll_offsets (int deltax, int deltay) { if (deltax != xoffset_ || deltay != yoffset_) { xoffset_ = deltax; yoffset_ = deltay; // FIXME: need to issue 0-distance move here sig_scrolled.emit(); } } void ViewportImpl::do_scrolled () { expose(); } Allocation ViewportImpl::child_viewport () { const Allocation &area = allocation(); const int xoffset = scroll_offset_x(), yoffset = scroll_offset_y(); return Allocation (xoffset, yoffset, area.width, area.height); } Affine ViewportImpl::child_affine (const WidgetImpl &widget) { const Allocation &area = allocation(); const int xoffset = scroll_offset_x(), yoffset = scroll_offset_y(); return AffineTranslate (-area.x + xoffset, -area.y + yoffset); } void ViewportImpl::render_recursive (RenderContext &rcontext) { // prevent recursive rendering of children by not calling ResizeContainerImpl::render_recursive if (0) ResizeContainerImpl::render_recursive (rcontext); // viewport children are rendered in render() } void ViewportImpl::render (RenderContext &rcontext, const Rect &rect) { if (!has_drawable_child()) return; const Allocation &area = allocation(); WidgetImpl &child = get_child(); const int xoffset = xoffset_, yoffset = yoffset_; // constrain rendering within allocation Region what = rect; // constrain to child allocation (child is allocated relative to Viewport origin) const Allocation carea = child.allocation(); what.intersect (Rect (area.x + carea.x, area.y + carea.y, carea.width, carea.height)); // constrain to exposed region what.intersect (rendering_region (rcontext)); // viewport rendering rectangle const Allocation rarea = what.extents(); // translate area into child space, shifting by scroll offsets what.translate (xoffset - area.x, yoffset - area.y); // render child stack if (!what.empty()) { expose_region_.subtract (what); cairo_t *cr = cairo_context (rcontext, rarea); cairo_translate (cr, area.x - xoffset, area.y - yoffset); child.render_into (cr, what); } } void ViewportImpl::expose_child_region (const Region &region) { if (!region.empty()) { expose_region_.add (region); collapse_expose_region(); if (parent()) { const Allocation &area = allocation(); // propagate exposes, to make child rendering changes visible at toplevel Region vpregion = region; vpregion.translate (area.x - xoffset_, area.y - yoffset_); // translate to viewport coords expose (vpregion); } } } void ViewportImpl::collapse_expose_region () { // check for excess expose fragment scenarios uint n_erects = expose_region_.count_rects(); /* considering O(n^2) collision computation complexity, but also focus frame * exposures which easily consist of 4+ fragments, a hundred rectangles turn * out to be an emperically suitable threshold. */ if (n_erects > 99) { /* aparently the expose fragments we're combining are too small, * so we can end up with spending too much time on expose rectangle * compression (more time than needed for actual rendering). * as a workaround, we simply force everything into a single expose * rectangle which is good enough to avoid worst case explosion. */ expose_region_.add (expose_region_.extents()); VDEBUG ("collapsing expose rectangles due to overflow: %u -> %u", n_erects, expose_region_.count_rects()); } } } // Rapicorn <|endoftext|>
<commit_before>/*************************************************************************/ /* image_loader_svg.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "image_loader_svg.h" #include "core/os/memory.h" #include "core/variant/variant.h" #include <thorvg.h> void ImageLoaderSVG::_replace_color_property(const String &p_prefix, String &r_string) { // Replace colors in the SVG based on what is configured in `replace_colors`. // Used to change the colors of editor icons based on the used theme. // The strings being replaced are typically of the form: // fill="#5abbef" // But can also be 3-letter codes, include alpha, be "none" or a named color // string ("blue"). So we convert to Godot Color to compare with `replace_colors`. const int prefix_len = p_prefix.length(); int pos = r_string.find(p_prefix); while (pos != -1) { pos += prefix_len; // Skip prefix. int end_pos = r_string.find("\"", pos); ERR_FAIL_COND_MSG(end_pos == -1, vformat("Malformed SVG string after property \"%s\".", p_prefix)); const String color_code = r_string.substr(pos, end_pos - pos); if (color_code != "none" && !color_code.begins_with("url(")) { const Color color = Color(color_code); // Handles both HTML codes and named colors. if (replace_colors.has(color)) { r_string = r_string.left(pos) + "#" + replace_colors[color].operator Color().to_html(false) + r_string.substr(end_pos); } } // Search for other occurrences. pos = r_string.find(p_prefix, pos); } } void ImageLoaderSVG::create_image_from_string(Ref<Image> p_image, String p_string, float p_scale, bool p_upsample, bool p_convert_color) { ERR_FAIL_COND(Math::is_zero_approx(p_scale)); if (p_convert_color) { _replace_color_property("stop-color=\"", p_string); _replace_color_property("fill=\"", p_string); _replace_color_property("stroke=\"", p_string); } std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen(); PackedByteArray bytes = p_string.to_utf8_buffer(); tvg::Result result = picture->load((const char *)bytes.ptr(), bytes.size(), "svg", true); if (result != tvg::Result::Success) { return; } float fw, fh; picture->size(&fw, &fh); uint32_t width = MIN(fw * p_scale, 16 * 1024); uint32_t height = MIN(fh * p_scale, 16 * 1024); picture->size(width, height); std::unique_ptr<tvg::SwCanvas> sw_canvas = tvg::SwCanvas::gen(); // Note: memalloc here, be sure to memfree before any return. uint32_t *buffer = (uint32_t *)memalloc(sizeof(uint32_t) * width * height); tvg::Result res = sw_canvas->target(buffer, width, width, height, tvg::SwCanvas::ARGB8888_STRAIGHT); if (res != tvg::Result::Success) { memfree(buffer); ERR_FAIL_MSG("ImageLoaderSVG can't create image."); } res = sw_canvas->push(std::move(picture)); if (res != tvg::Result::Success) { memfree(buffer); ERR_FAIL_MSG("ImageLoaderSVG can't create image."); } res = sw_canvas->draw(); if (res != tvg::Result::Success) { memfree(buffer); ERR_FAIL_MSG("ImageLoaderSVG can't create image."); } res = sw_canvas->sync(); if (res != tvg::Result::Success) { memfree(buffer); ERR_FAIL_MSG("ImageLoaderSVG can't create image."); } Vector<uint8_t> image; image.resize(width * height * sizeof(uint32_t)); for (uint32_t y = 0; y < height; y++) { for (uint32_t x = 0; x < width; x++) { uint32_t n = buffer[y * width + x]; const size_t offset = sizeof(uint32_t) * width * y + sizeof(uint32_t) * x; image.write[offset + 0] = (n >> 16) & 0xff; image.write[offset + 1] = (n >> 8) & 0xff; image.write[offset + 2] = n & 0xff; image.write[offset + 3] = (n >> 24) & 0xff; } } res = sw_canvas->clear(true); memfree(buffer); p_image->create(width, height, false, Image::FORMAT_RGBA8, image); } void ImageLoaderSVG::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("svg"); } Error ImageLoaderSVG::load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, bool p_force_linear, float p_scale) { String svg = p_fileaccess->get_as_utf8_string(); create_image_from_string(p_image, svg, p_scale, false, false); ERR_FAIL_COND_V(p_image->is_empty(), FAILED); if (p_force_linear) { p_image->srgb_to_linear(); } return OK; } <commit_msg>round dimensions of svg<commit_after>/*************************************************************************/ /* image_loader_svg.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "image_loader_svg.h" #include "core/os/memory.h" #include "core/variant/variant.h" #include <thorvg.h> void ImageLoaderSVG::_replace_color_property(const String &p_prefix, String &r_string) { // Replace colors in the SVG based on what is configured in `replace_colors`. // Used to change the colors of editor icons based on the used theme. // The strings being replaced are typically of the form: // fill="#5abbef" // But can also be 3-letter codes, include alpha, be "none" or a named color // string ("blue"). So we convert to Godot Color to compare with `replace_colors`. const int prefix_len = p_prefix.length(); int pos = r_string.find(p_prefix); while (pos != -1) { pos += prefix_len; // Skip prefix. int end_pos = r_string.find("\"", pos); ERR_FAIL_COND_MSG(end_pos == -1, vformat("Malformed SVG string after property \"%s\".", p_prefix)); const String color_code = r_string.substr(pos, end_pos - pos); if (color_code != "none" && !color_code.begins_with("url(")) { const Color color = Color(color_code); // Handles both HTML codes and named colors. if (replace_colors.has(color)) { r_string = r_string.left(pos) + "#" + replace_colors[color].operator Color().to_html(false) + r_string.substr(end_pos); } } // Search for other occurrences. pos = r_string.find(p_prefix, pos); } } void ImageLoaderSVG::create_image_from_string(Ref<Image> p_image, String p_string, float p_scale, bool p_upsample, bool p_convert_color) { ERR_FAIL_COND(Math::is_zero_approx(p_scale)); if (p_convert_color) { _replace_color_property("stop-color=\"", p_string); _replace_color_property("fill=\"", p_string); _replace_color_property("stroke=\"", p_string); } std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen(); PackedByteArray bytes = p_string.to_utf8_buffer(); tvg::Result result = picture->load((const char *)bytes.ptr(), bytes.size(), "svg", true); if (result != tvg::Result::Success) { return; } float fw, fh; picture->size(&fw, &fh); uint32_t width = MIN(round(fw * p_scale), 16 * 1024); uint32_t height = MIN(round(fh * p_scale), 16 * 1024); picture->size(width, height); std::unique_ptr<tvg::SwCanvas> sw_canvas = tvg::SwCanvas::gen(); // Note: memalloc here, be sure to memfree before any return. uint32_t *buffer = (uint32_t *)memalloc(sizeof(uint32_t) * width * height); tvg::Result res = sw_canvas->target(buffer, width, width, height, tvg::SwCanvas::ARGB8888_STRAIGHT); if (res != tvg::Result::Success) { memfree(buffer); ERR_FAIL_MSG("ImageLoaderSVG can't create image."); } res = sw_canvas->push(std::move(picture)); if (res != tvg::Result::Success) { memfree(buffer); ERR_FAIL_MSG("ImageLoaderSVG can't create image."); } res = sw_canvas->draw(); if (res != tvg::Result::Success) { memfree(buffer); ERR_FAIL_MSG("ImageLoaderSVG can't create image."); } res = sw_canvas->sync(); if (res != tvg::Result::Success) { memfree(buffer); ERR_FAIL_MSG("ImageLoaderSVG can't create image."); } Vector<uint8_t> image; image.resize(width * height * sizeof(uint32_t)); for (uint32_t y = 0; y < height; y++) { for (uint32_t x = 0; x < width; x++) { uint32_t n = buffer[y * width + x]; const size_t offset = sizeof(uint32_t) * width * y + sizeof(uint32_t) * x; image.write[offset + 0] = (n >> 16) & 0xff; image.write[offset + 1] = (n >> 8) & 0xff; image.write[offset + 2] = n & 0xff; image.write[offset + 3] = (n >> 24) & 0xff; } } res = sw_canvas->clear(true); memfree(buffer); p_image->create(width, height, false, Image::FORMAT_RGBA8, image); } void ImageLoaderSVG::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("svg"); } Error ImageLoaderSVG::load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, bool p_force_linear, float p_scale) { String svg = p_fileaccess->get_as_utf8_string(); create_image_from_string(p_image, svg, p_scale, false, false); ERR_FAIL_COND_V(p_image->is_empty(), FAILED); if (p_force_linear) { p_image->srgb_to_linear(); } return OK; } <|endoftext|>
<commit_before>/*========================================================================= Library: CTK Copyright (c) 2010 Kitware 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.commontk.org/LICENSE 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. =========================================================================*/ // Qt includes #include <QTimer> #include <QVBoxLayout> // CTK includes #include "ctkVTKRenderView.h" #include "ctkVTKRenderView_p.h" #include "ctkLogger.h" // VTK includes #include <vtkRendererCollection.h> #include <vtkRenderWindowInteractor.h> #include <vtkTextProperty.h> //-------------------------------------------------------------------------- static ctkLogger logger("org.commontk.visualization.vtk.widgets.ctkVTKRenderView"); //-------------------------------------------------------------------------- // -------------------------------------------------------------------------- // ctkVTKRenderViewPrivate methods // -------------------------------------------------------------------------- ctkVTKRenderViewPrivate::ctkVTKRenderViewPrivate() { this->Renderer = vtkSmartPointer<vtkRenderer>::New(); this->RenderWindow = vtkSmartPointer<vtkRenderWindow>::New(); this->Axes = vtkSmartPointer<vtkAxesActor>::New(); this->Orientation = vtkSmartPointer<vtkOrientationMarkerWidget>::New(); this->CornerAnnotation = vtkSmartPointer<vtkCornerAnnotation>::New(); this->RenderPending = false; this->RenderEnabled = false; } // -------------------------------------------------------------------------- void ctkVTKRenderViewPrivate::setupCornerAnnotation() { logger.trace("setupCornerAnnotation"); if (!this->Renderer->HasViewProp(this->CornerAnnotation)) { this->Renderer->AddViewProp(this->CornerAnnotation); this->CornerAnnotation->SetMaximumLineHeight(0.07); vtkTextProperty *tprop = this->CornerAnnotation->GetTextProperty(); tprop->ShadowOn(); } this->CornerAnnotation->ClearAllTexts(); } //--------------------------------------------------------------------------- void ctkVTKRenderViewPrivate::setupRendering() { logger.trace("setupRendering"); Q_ASSERT(this->RenderWindow); this->RenderWindow->SetAlphaBitPlanes(1); this->RenderWindow->SetMultiSamples(0); this->RenderWindow->StereoCapableWindowOn(); this->RenderWindow->GetRenderers()->RemoveAllItems(); // Add renderer this->RenderWindow->AddRenderer(this->Renderer); // Setup the corner annotation this->setupCornerAnnotation(); this->VTKWidget->SetRenderWindow(this->RenderWindow); } //--------------------------------------------------------------------------- void ctkVTKRenderViewPrivate::setupDefaultInteractor() { logger.trace("setupDefaultInteractor"); CTK_P(ctkVTKRenderView); p->setInteractor(this->RenderWindow->GetInteractor()); } //--------------------------------------------------------------------------- // ctkVTKRenderView methods // -------------------------------------------------------------------------- ctkVTKRenderView::ctkVTKRenderView(QWidget* _parent) : Superclass(_parent) { CTK_INIT_PRIVATE(ctkVTKRenderView); CTK_D(ctkVTKRenderView); d->VTKWidget = new QVTKWidget(this); this->setLayout(new QVBoxLayout); this->layout()->setMargin(0); this->layout()->setSpacing(0); this->layout()->addWidget(d->VTKWidget); d->setupRendering(); d->setupDefaultInteractor(); } // -------------------------------------------------------------------------- ctkVTKRenderView::~ctkVTKRenderView() { } //---------------------------------------------------------------------------- void ctkVTKRenderView::scheduleRender() { CTK_D(ctkVTKRenderView); logger.trace(QString("scheduleRender - RenderEnabled: %1 - RenderPending: %2"). arg(d->RenderEnabled).arg(d->RenderPending)); if (!d->RenderEnabled) { return; } if (!d->RenderPending) { d->RenderPending = true; QTimer::singleShot(0, this, SLOT(forceRender())); } } //---------------------------------------------------------------------------- void ctkVTKRenderView::forceRender() { CTK_D(ctkVTKRenderView); logger.trace(QString("forceRender - RenderEnabled: %1").arg(d->RenderEnabled)); if (!d->RenderEnabled) { return; } d->RenderWindow->Render(); d->RenderPending = false; } //---------------------------------------------------------------------------- CTK_GET_CXX(ctkVTKRenderView, vtkRenderWindow*, renderWindow, RenderWindow); //---------------------------------------------------------------------------- CTK_GET_CXX(ctkVTKRenderView, vtkRenderWindowInteractor*, interactor, CurrentInteractor); //---------------------------------------------------------------------------- void ctkVTKRenderView::setInteractor(vtkRenderWindowInteractor* newInteractor) { CTK_D(ctkVTKRenderView); logger.trace("setInteractor"); d->RenderWindow->SetInteractor(newInteractor); d->Orientation->SetOrientationMarker(d->Axes); d->Orientation->SetInteractor(newInteractor); d->Orientation->SetEnabled(1); d->Orientation->InteractiveOff(); d->CurrentInteractor = newInteractor; } //---------------------------------------------------------------------------- vtkInteractorObserver* ctkVTKRenderView::interactorStyle() { CTK_D(ctkVTKRenderView); if (d->CurrentInteractor) { return d->CurrentInteractor->GetInteractorStyle(); } else { return 0; } } //---------------------------------------------------------------------------- void ctkVTKRenderView::setCornerAnnotationText(const QString& text) { CTK_D(ctkVTKRenderView); logger.trace(QString("setCornerAnnotationText: %1").arg(text)); d->CornerAnnotation->ClearAllTexts(); d->CornerAnnotation->SetText(2, text.toLatin1()); } //---------------------------------------------------------------------------- QString ctkVTKRenderView::cornerAnnotationText() const { CTK_D(const ctkVTKRenderView); return QLatin1String(d->CornerAnnotation->GetText(2)); } // -------------------------------------------------------------------------- void ctkVTKRenderView::setBackgroundColor(const QColor& newBackgroundColor) { CTK_D(ctkVTKRenderView); logger.trace(QString("setBackgroundColor: %1").arg(newBackgroundColor.name())); d->Renderer->SetBackground(newBackgroundColor.redF(), newBackgroundColor.greenF(), newBackgroundColor.blueF()); } //---------------------------------------------------------------------------- QColor ctkVTKRenderView::backgroundColor() const { CTK_D(const ctkVTKRenderView); double color[3] = {0, 0, 0}; d->Renderer->GetBackground(color); return QColor::fromRgbF(color[0], color[1], color[2]); } //---------------------------------------------------------------------------- void ctkVTKRenderView::setOrientationWidgetVisible(bool visible) { CTK_D(ctkVTKRenderView); d->Orientation->SetEnabled(visible); } //---------------------------------------------------------------------------- bool ctkVTKRenderView::orientationWidgetVisible() { CTK_D(ctkVTKRenderView); return d->Orientation->GetEnabled(); } //---------------------------------------------------------------------------- vtkCamera* ctkVTKRenderView::activeCamera() { CTK_D(ctkVTKRenderView); if (d->Renderer->IsActiveCameraCreated()) { return d->Renderer->GetActiveCamera(); } else { return 0; } } //---------------------------------------------------------------------------- void ctkVTKRenderView::resetCamera() { CTK_D(ctkVTKRenderView); logger.trace("resetCamera"); d->Renderer->ResetCamera(); } //---------------------------------------------------------------------------- CTK_GET_CXX(ctkVTKRenderView, vtkRenderer*, renderer, Renderer); //---------------------------------------------------------------------------- CTK_SET_CXX(ctkVTKRenderView, bool, setRenderEnabled, RenderEnabled); CTK_GET_CXX(ctkVTKRenderView, bool, renderEnabled, RenderEnabled); <commit_msg>COMP: Remove warning in ctkVTKRenderView, booleans are not well handled<commit_after>/*========================================================================= Library: CTK Copyright (c) 2010 Kitware 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.commontk.org/LICENSE 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. =========================================================================*/ // Qt includes #include <QTimer> #include <QVBoxLayout> // CTK includes #include "ctkVTKRenderView.h" #include "ctkVTKRenderView_p.h" #include "ctkLogger.h" // VTK includes #include <vtkRendererCollection.h> #include <vtkRenderWindowInteractor.h> #include <vtkTextProperty.h> //-------------------------------------------------------------------------- static ctkLogger logger("org.commontk.visualization.vtk.widgets.ctkVTKRenderView"); //-------------------------------------------------------------------------- // -------------------------------------------------------------------------- // ctkVTKRenderViewPrivate methods // -------------------------------------------------------------------------- ctkVTKRenderViewPrivate::ctkVTKRenderViewPrivate() { this->Renderer = vtkSmartPointer<vtkRenderer>::New(); this->RenderWindow = vtkSmartPointer<vtkRenderWindow>::New(); this->Axes = vtkSmartPointer<vtkAxesActor>::New(); this->Orientation = vtkSmartPointer<vtkOrientationMarkerWidget>::New(); this->CornerAnnotation = vtkSmartPointer<vtkCornerAnnotation>::New(); this->RenderPending = false; this->RenderEnabled = false; } // -------------------------------------------------------------------------- void ctkVTKRenderViewPrivate::setupCornerAnnotation() { logger.trace("setupCornerAnnotation"); if (!this->Renderer->HasViewProp(this->CornerAnnotation)) { this->Renderer->AddViewProp(this->CornerAnnotation); this->CornerAnnotation->SetMaximumLineHeight(0.07); vtkTextProperty *tprop = this->CornerAnnotation->GetTextProperty(); tprop->ShadowOn(); } this->CornerAnnotation->ClearAllTexts(); } //--------------------------------------------------------------------------- void ctkVTKRenderViewPrivate::setupRendering() { logger.trace("setupRendering"); Q_ASSERT(this->RenderWindow); this->RenderWindow->SetAlphaBitPlanes(1); this->RenderWindow->SetMultiSamples(0); this->RenderWindow->StereoCapableWindowOn(); this->RenderWindow->GetRenderers()->RemoveAllItems(); // Add renderer this->RenderWindow->AddRenderer(this->Renderer); // Setup the corner annotation this->setupCornerAnnotation(); this->VTKWidget->SetRenderWindow(this->RenderWindow); } //--------------------------------------------------------------------------- void ctkVTKRenderViewPrivate::setupDefaultInteractor() { logger.trace("setupDefaultInteractor"); CTK_P(ctkVTKRenderView); p->setInteractor(this->RenderWindow->GetInteractor()); } //--------------------------------------------------------------------------- // ctkVTKRenderView methods // -------------------------------------------------------------------------- ctkVTKRenderView::ctkVTKRenderView(QWidget* _parent) : Superclass(_parent) { CTK_INIT_PRIVATE(ctkVTKRenderView); CTK_D(ctkVTKRenderView); d->VTKWidget = new QVTKWidget(this); this->setLayout(new QVBoxLayout); this->layout()->setMargin(0); this->layout()->setSpacing(0); this->layout()->addWidget(d->VTKWidget); d->setupRendering(); d->setupDefaultInteractor(); } // -------------------------------------------------------------------------- ctkVTKRenderView::~ctkVTKRenderView() { } //---------------------------------------------------------------------------- void ctkVTKRenderView::scheduleRender() { CTK_D(ctkVTKRenderView); logger.trace(QString("scheduleRender - RenderEnabled: %1 - RenderPending: %2"). arg(d->RenderEnabled ? "true" : "false") .arg(d->RenderPending ? "true:" : "false")); if (!d->RenderEnabled) { return; } if (!d->RenderPending) { d->RenderPending = true; QTimer::singleShot(0, this, SLOT(forceRender())); } } //---------------------------------------------------------------------------- void ctkVTKRenderView::forceRender() { CTK_D(ctkVTKRenderView); logger.trace(QString("forceRender - RenderEnabled: %1") .arg(d->RenderEnabled ? "true" : "false")); if (!d->RenderEnabled) { return; } d->RenderWindow->Render(); d->RenderPending = false; } //---------------------------------------------------------------------------- CTK_GET_CXX(ctkVTKRenderView, vtkRenderWindow*, renderWindow, RenderWindow); //---------------------------------------------------------------------------- CTK_GET_CXX(ctkVTKRenderView, vtkRenderWindowInteractor*, interactor, CurrentInteractor); //---------------------------------------------------------------------------- void ctkVTKRenderView::setInteractor(vtkRenderWindowInteractor* newInteractor) { CTK_D(ctkVTKRenderView); logger.trace("setInteractor"); d->RenderWindow->SetInteractor(newInteractor); d->Orientation->SetOrientationMarker(d->Axes); d->Orientation->SetInteractor(newInteractor); d->Orientation->SetEnabled(1); d->Orientation->InteractiveOff(); d->CurrentInteractor = newInteractor; } //---------------------------------------------------------------------------- vtkInteractorObserver* ctkVTKRenderView::interactorStyle() { CTK_D(ctkVTKRenderView); if (d->CurrentInteractor) { return d->CurrentInteractor->GetInteractorStyle(); } else { return 0; } } //---------------------------------------------------------------------------- void ctkVTKRenderView::setCornerAnnotationText(const QString& text) { CTK_D(ctkVTKRenderView); logger.trace(QString("setCornerAnnotationText: %1").arg(text)); d->CornerAnnotation->ClearAllTexts(); d->CornerAnnotation->SetText(2, text.toLatin1()); } //---------------------------------------------------------------------------- QString ctkVTKRenderView::cornerAnnotationText() const { CTK_D(const ctkVTKRenderView); return QLatin1String(d->CornerAnnotation->GetText(2)); } // -------------------------------------------------------------------------- void ctkVTKRenderView::setBackgroundColor(const QColor& newBackgroundColor) { CTK_D(ctkVTKRenderView); logger.trace(QString("setBackgroundColor: %1").arg(newBackgroundColor.name())); d->Renderer->SetBackground(newBackgroundColor.redF(), newBackgroundColor.greenF(), newBackgroundColor.blueF()); } //---------------------------------------------------------------------------- QColor ctkVTKRenderView::backgroundColor() const { CTK_D(const ctkVTKRenderView); double color[3] = {0, 0, 0}; d->Renderer->GetBackground(color); return QColor::fromRgbF(color[0], color[1], color[2]); } //---------------------------------------------------------------------------- void ctkVTKRenderView::setOrientationWidgetVisible(bool visible) { CTK_D(ctkVTKRenderView); d->Orientation->SetEnabled(visible); } //---------------------------------------------------------------------------- bool ctkVTKRenderView::orientationWidgetVisible() { CTK_D(ctkVTKRenderView); return d->Orientation->GetEnabled(); } //---------------------------------------------------------------------------- vtkCamera* ctkVTKRenderView::activeCamera() { CTK_D(ctkVTKRenderView); if (d->Renderer->IsActiveCameraCreated()) { return d->Renderer->GetActiveCamera(); } else { return 0; } } //---------------------------------------------------------------------------- void ctkVTKRenderView::resetCamera() { CTK_D(ctkVTKRenderView); logger.trace("resetCamera"); d->Renderer->ResetCamera(); } //---------------------------------------------------------------------------- CTK_GET_CXX(ctkVTKRenderView, vtkRenderer*, renderer, Renderer); //---------------------------------------------------------------------------- CTK_SET_CXX(ctkVTKRenderView, bool, setRenderEnabled, RenderEnabled); CTK_GET_CXX(ctkVTKRenderView, bool, renderEnabled, RenderEnabled); <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbConfigurationManager.h" #include "itksys/SystemTools.hxx" #include <cstdlib> namespace otb { std::string ConfigurationManager::GetDEMDirectory() { std::string svalue; itksys::SystemTools::GetEnv("OTB_DEM_DIRECTORY",svalue); return svalue; } std::string ConfigurationManager::GetGeoidFile() { std::string svalue; itksys::SystemTools::GetEnv("OTB_GEOID_FILE",svalue); return svalue; } ConfigurationManager::RAMValueType ConfigurationManager::GetMaxRAMHint() { std::string svalue; uint64_t value = 128; if(itksys::SystemTools::GetEnv("OTB_MAX_RAM_HINT",svalue)) { char ** dummy(NULL); unsigned long int tmp = strtoul(svalue.c_str(),dummy,10); if(tmp) { value = static_cast<uint64_t>(tmp); } } return value; } } <commit_msg>BUG: replace uint64_t with RAMValueType<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbConfigurationManager.h" #include "itksys/SystemTools.hxx" #include <cstdlib> namespace otb { std::string ConfigurationManager::GetDEMDirectory() { std::string svalue; itksys::SystemTools::GetEnv("OTB_DEM_DIRECTORY",svalue); return svalue; } std::string ConfigurationManager::GetGeoidFile() { std::string svalue; itksys::SystemTools::GetEnv("OTB_GEOID_FILE",svalue); return svalue; } ConfigurationManager::RAMValueType ConfigurationManager::GetMaxRAMHint() { std::string svalue; RAMValueType value = 128; if(itksys::SystemTools::GetEnv("OTB_MAX_RAM_HINT",svalue)) { char ** dummy(NULL); unsigned long int tmp = strtoul(svalue.c_str(),dummy,10); if(tmp) { value = static_cast<RAMValueType>(tmp); } } return value; } } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSimulationTemplate.h" #include "mitkSimulationTemplateReader.h" #include <algorithm> #include <fstream> #include <string> static std::string ReadFile(const std::string& fileName) { std::ifstream file(fileName); if (!file.is_open()) mitkThrow() << "Could not load '" << fileName << "'!"; std::string contents; file.seekg(0, std::ios::end); contents.resize(file.tellg()); file.seekg(0, std::ios::beg); file.read(&contents[0], contents.size()); file.close(); if (contents.empty()) mitkThrow() << fileName << " is empty!"; return contents; } bool mitk::SimulationTemplateReader::CanReadFile(const std::string& filename, const std::string&, const std::string&) { std::string::size_type length = filename.length(); if (length < 14) return false; std::string ext = filename.substr(length - 13); std::transform(ext.begin(), ext.end(), ext.begin(), tolower); if (ext == ".scn.template" || ext == ".xml.template") return true; return false; } mitk::SimulationTemplateReader::SimulationTemplateReader() { mitk::SimulationTemplate::Pointer output = mitk::SimulationTemplate::New(); this->SetNumberOfRequiredOutputs(1); this->SetNthOutput(0, output.GetPointer()); } mitk::SimulationTemplateReader::~SimulationTemplateReader() { } void mitk::SimulationTemplateReader::GenerateData() { SimulationTemplate::Pointer simulationTemplate = dynamic_cast<mitk::SimulationTemplate*>(this->GetOutput(0)); std::string contents = ReadFile(m_FileName); simulationTemplate->Parse(contents); } void mitk::SimulationTemplateReader::GenerateOutputInformation() { } const char* mitk::SimulationTemplateReader::GetFileName() const { return m_FileName.c_str(); } void mitk::SimulationTemplateReader::SetFileName(const char* aFileName) { m_FileName = aFileName; } const char* mitk::SimulationTemplateReader::GetFilePattern() const { return m_FilePattern.c_str(); } void mitk::SimulationTemplateReader::SetFilePattern(const char* aFilePattern) { m_FilePattern = aFilePattern; } const char* mitk::SimulationTemplateReader::GetFilePrefix() const { return m_FilePrefix.c_str(); } void mitk::SimulationTemplateReader::SetFilePrefix(const char* aFilePrefix) { m_FilePrefix = aFilePrefix; } <commit_msg>COMP: Changed std string to char string for ifstream ctor.<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSimulationTemplate.h" #include "mitkSimulationTemplateReader.h" #include <algorithm> #include <fstream> #include <string> static std::string ReadFile(const std::string& fileName) { std::ifstream file(fileName.c_str()); if (!file.is_open()) mitkThrow() << "Could not load '" << fileName << "'!"; std::string contents; file.seekg(0, std::ios::end); contents.resize(file.tellg()); file.seekg(0, std::ios::beg); file.read(&contents[0], contents.size()); file.close(); if (contents.empty()) mitkThrow() << fileName << " is empty!"; return contents; } bool mitk::SimulationTemplateReader::CanReadFile(const std::string& filename, const std::string&, const std::string&) { std::string::size_type length = filename.length(); if (length < 14) return false; std::string ext = filename.substr(length - 13); std::transform(ext.begin(), ext.end(), ext.begin(), tolower); if (ext == ".scn.template" || ext == ".xml.template") return true; return false; } mitk::SimulationTemplateReader::SimulationTemplateReader() { mitk::SimulationTemplate::Pointer output = mitk::SimulationTemplate::New(); this->SetNumberOfRequiredOutputs(1); this->SetNthOutput(0, output.GetPointer()); } mitk::SimulationTemplateReader::~SimulationTemplateReader() { } void mitk::SimulationTemplateReader::GenerateData() { SimulationTemplate::Pointer simulationTemplate = dynamic_cast<mitk::SimulationTemplate*>(this->GetOutput(0)); std::string contents = ReadFile(m_FileName); simulationTemplate->Parse(contents); } void mitk::SimulationTemplateReader::GenerateOutputInformation() { } const char* mitk::SimulationTemplateReader::GetFileName() const { return m_FileName.c_str(); } void mitk::SimulationTemplateReader::SetFileName(const char* aFileName) { m_FileName = aFileName; } const char* mitk::SimulationTemplateReader::GetFilePattern() const { return m_FilePattern.c_str(); } void mitk::SimulationTemplateReader::SetFilePattern(const char* aFilePattern) { m_FilePattern = aFilePattern; } const char* mitk::SimulationTemplateReader::GetFilePrefix() const { return m_FilePrefix.c_str(); } void mitk::SimulationTemplateReader::SetFilePrefix(const char* aFilePrefix) { m_FilePrefix = aFilePrefix; } <|endoftext|>
<commit_before>/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashMatrix. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <boost/format.hpp> #include "log.h" #include "mem_data_frame.h" #include "mem_vector.h" #include "mem_vector_vector.h" namespace fm { vector_vector::ptr mem_data_frame::groupby(const std::string &col_name, gr_apply_operate<data_frame> &op) const { vector::ptr col = get_vec(col_name); if (col == NULL) { BOOST_LOG_TRIVIAL(error) << boost::format( "The column %1% doesn't exist") % col_name; return vector_vector::ptr(); } mem_vector::ptr sorted_col = mem_vector::cast(col->deep_copy()); type_mem_vector<off_t>::ptr idxs = type_mem_vector<off_t>::cast( sorted_col->sort_with_index()); mem_data_frame::ptr sorted_df = mem_data_frame::create(); sorted_df->add_vec(col_name, sorted_col); for (size_t i = 0; i < get_num_vecs(); i++) { mem_vector::ptr mem_vec = mem_vector::cast(get_vec(i)); if (mem_vec == col) continue; sorted_df->add_vec(get_vec_name(i), mem_vec->get(*idxs)); } vector_vector::ptr ret = std::static_pointer_cast<vector_vector>( op.get_output_type().create_mem_vec_vec()); mem_vector::ptr row = op.get_output_type().create_mem_vec(0); const agg_operate &find_next = sorted_col->get_type().get_agg_ops().get_find_next(); size_t loc = 0; const mem_vector *const_sorted_col = sorted_col.get(); size_t col_len = sorted_col->get_length(); const char *start = const_sorted_col->get_raw_arr(); size_t entry_size = sorted_col->get_entry_size(); while (loc < col_len) { size_t curr_length = col_len - loc; const char *curr_ptr = start + entry_size * loc; size_t rel_end; find_next.run(curr_length, curr_ptr, &rel_end); // This expose a portion of the data frame. sorted_df->expose_portion(loc, rel_end); // The first argument is the key and the second one is the value // (a data frame) op.run(curr_ptr, *sorted_df, *row); ret->append(*row); loc += rel_end; } return ret; } } <commit_msg>[Matrix]: avoid adding empty vectors to groupby result of data frame.<commit_after>/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashMatrix. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <boost/format.hpp> #include "log.h" #include "mem_data_frame.h" #include "mem_vector.h" #include "mem_vector_vector.h" namespace fm { vector_vector::ptr mem_data_frame::groupby(const std::string &col_name, gr_apply_operate<data_frame> &op) const { vector::ptr col = get_vec(col_name); if (col == NULL) { BOOST_LOG_TRIVIAL(error) << boost::format( "The column %1% doesn't exist") % col_name; return vector_vector::ptr(); } mem_vector::ptr sorted_col = mem_vector::cast(col->deep_copy()); type_mem_vector<off_t>::ptr idxs = type_mem_vector<off_t>::cast( sorted_col->sort_with_index()); mem_data_frame::ptr sorted_df = mem_data_frame::create(); sorted_df->add_vec(col_name, sorted_col); for (size_t i = 0; i < get_num_vecs(); i++) { mem_vector::ptr mem_vec = mem_vector::cast(get_vec(i)); if (mem_vec == col) continue; sorted_df->add_vec(get_vec_name(i), mem_vec->get(*idxs)); } vector_vector::ptr ret = std::static_pointer_cast<vector_vector>( op.get_output_type().create_mem_vec_vec()); mem_vector::ptr row = op.get_output_type().create_mem_vec(0); const agg_operate &find_next = sorted_col->get_type().get_agg_ops().get_find_next(); size_t loc = 0; const mem_vector *const_sorted_col = sorted_col.get(); size_t col_len = sorted_col->get_length(); const char *start = const_sorted_col->get_raw_arr(); size_t entry_size = sorted_col->get_entry_size(); while (loc < col_len) { size_t curr_length = col_len - loc; const char *curr_ptr = start + entry_size * loc; size_t rel_end; find_next.run(curr_length, curr_ptr, &rel_end); // This expose a portion of the data frame. sorted_df->expose_portion(loc, rel_end); // The first argument is the key and the second one is the value // (a data frame) op.run(curr_ptr, *sorted_df, *row); if (row->get_length() > 0) ret->append(*row); loc += rel_end; } return ret; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: EnhancedCustomShapeToken.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2004-11-26 14:09:29 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _ENHANCED_CUSTOMSHAPE_TOKEN_HXX #include "EnhancedCustomShapeToken.hxx" #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #include <hash_map> namespace xmloff { namespace EnhancedCustomShapeToken { struct TCheck { bool operator()( const char* s1, const char* s2 ) const { return strcmp( s1, s2 ) == 0; } }; typedef std::hash_map< const char*, EnhancedCustomShapeTokenEnum, std::hash<const char*>, TCheck> TypeNameHashMap; static TypeNameHashMap* pHashMap = NULL; static ::osl::Mutex& getHashMapMutex() { static osl::Mutex s_aHashMapProtection; return s_aHashMapProtection; } struct TokenTable { char* pS; EnhancedCustomShapeTokenEnum pE; }; static const TokenTable pTokenTableArray[] = { { "type", EAS_type }, { "name", EAS_name }, { "mirror-horizontal", EAS_mirror_horizontal }, { "mirror-vertical", EAS_mirror_vertical }, { "viewBox", EAS_viewBox }, { "text-rotate-angle", EAS_text_rotate_angle }, { "extrusion-allowed", EAS_extrusion_allowed }, { "extrusion-text-path-allowed", EAS_text_path_allowed }, { "extrusion-concentric-gradient-fill", EAS_concentric_gradient_fill_allowed }, { "extrusion", EAS_extrusion }, { "extrusion-brightness", EAS_extrusion_brightness }, { "extrusion-depth", EAS_extrusion_depth }, { "extrusion-diffusion", EAS_extrusion_diffusion }, { "extrusion-number-of-line-segments", EAS_extrusion_number_of_line_segments }, { "extrusion-light-face", EAS_extrusion_light_face }, { "extrusion-first-light-harsh", EAS_extrusion_first_light_harsh }, { "extrusion-second-light-harsh", EAS_extrusion_second_light_harsh }, { "extrusion-first-light-livel", EAS_extrusion_first_light_level }, { "extrusion-second-light-level", EAS_extrusion_second_light_level }, { "extrusion-first-light-direction", EAS_extrusion_first_light_direction }, { "extrusion-second-light-direction", EAS_extrusion_second_light_direction }, { "extrusion-metal", EAS_extrusion_metal }, { "shade-mode", EAS_shade_mode }, { "extrusion-rotation-angle", EAS_extrusion_rotation_angle }, { "extrusion-rotation-center", EAS_extrusion_rotation_center }, { "extrusion-shininess", EAS_extrusion_shininess }, { "extrusion-skew", EAS_extrusion_skew }, { "extrusion-specularity", EAS_extrusion_specularity }, { "projection", EAS_projection }, { "extrusion-viewpoint", EAS_extrusion_viewpoint }, { "extrusion-origin", EAS_extrusion_origin }, { "extrusion-color", EAS_extrusion_color }, { "enhanced-path", EAS_enhanced_path }, { "path-stretchpoint-x", EAS_path_stretchpoint_x }, { "path-stretchpoint-y", EAS_path_stretchpoint_y }, { "text-areas", EAS_text_areas }, { "glue-points", EAS_glue_points }, { "glue-point-type", EAS_glue_point_type }, { "glue-point-leaving-directions", EAS_glue_point_leaving_directions }, { "text-path", EAS_text_path }, { "text-path-mode", EAS_text_path_mode }, { "text-path-scale-x", EAS_text_path_scale_x }, { "text-path-same-letter-heights", EAS_text_path_same_letter_heights }, { "modifiers", EAS_modifiers }, { "equation", EAS_equation }, { "formula", EAS_formula }, { "handle", EAS_handle }, { "handle-mirror-horizontal", EAS_handle_mirror_horizontal }, { "handle-mirror-vertical", EAS_handle_mirror_vertical }, { "handle-switched", EAS_handle_switched }, { "handle-position", EAS_handle_position }, { "handle-range-x-minimum", EAS_handle_range_x_minimum }, { "handle-range-x-maximum", EAS_handle_range_x_maximum }, { "handle-range-y-minimum", EAS_handle_range_y_minimum }, { "handle-range-y-maximum", EAS_handle_range_y_maximum }, { "handle-polar", EAS_handle_polar }, { "handle-radius-range-minimum", EAS_handle_radius_range_minimum }, { "handle-radius-range-maximum", EAS_handle_radius_range_maximum }, { "CustomShapeEngine", EAS_CustomShapeEngine }, { "CustomShapeData", EAS_CustomShapeData }, { "Type", EAS_Type }, { "MirroredX", EAS_MirroredX }, { "MirroredY", EAS_MirroredY }, { "ViewBox", EAS_ViewBox }, { "TextRotateAngle", EAS_TextRotateAngle }, { "ExtrusionAllowed", EAS_ExtrusionAllowed }, { "TextPathAllowed", EAS_TextPathAllowed }, { "ConcentricGradientFillAllowed", EAS_ConcentricGradientFillAllowed }, { "Extrusion", EAS_Extrusion }, { "Equations", EAS_Equations }, { "Equation", EAS_Equation }, { "Path", EAS_Path }, { "TextPath", EAS_TextPath }, { "Handles", EAS_Handles }, { "Handle", EAS_Handle }, { "Brightness", EAS_Brightness }, { "Depth", EAS_Depth }, { "Diffusion", EAS_Diffusion }, { "NumberOfLineSegments", EAS_NumberOfLineSegments }, { "LightFace", EAS_LightFace }, { "FirstLightHarsh", EAS_FirstLightHarsh }, { "SecondLightHarsh", EAS_SecondLightHarsh }, { "FirstLightLevel", EAS_FirstLightLevel }, { "SecondLightLevel", EAS_SecondLightLevel }, { "FirstLightDirection", EAS_FirstLightDirection }, { "SecondLightDirection", EAS_SecondLightDirection }, { "Metal", EAS_Metal }, { "ShadeMode", EAS_ShadeMode }, { "RotateAngle", EAS_RotateAngle }, { "RotationCenter", EAS_RotationCenter }, { "Shininess", EAS_Shininess }, { "Skew", EAS_Skew }, { "Specularity", EAS_Specularity }, { "ProjectionMode", EAS_ProjectionMode }, { "ViewPoint", EAS_ViewPoint }, { "Origin", EAS_Origin }, { "Color", EAS_Color }, { "Switched", EAS_Switched }, { "Polar", EAS_Polar }, { "RangeXMinimum", EAS_RangeXMinimum }, { "RangeXMaximum", EAS_RangeXMaximum }, { "RangeYMinimum", EAS_RangeYMinimum }, { "RangeYMaximum", EAS_RangeYMaximum }, { "RadiusRangeMinimum", EAS_RadiusRangeMinimum }, { "RadiusRangeMaximum", EAS_RadiusRangeMaximum }, { "Coordinates", EAS_Coordinates }, { "Segments", EAS_Segments }, { "StretchX", EAS_StretchX }, { "StretchY", EAS_StretchY }, { "TextFrames", EAS_TextFrames }, { "GluePoints", EAS_GluePoints }, { "GluePointLeavingDirections", EAS_GluePointLeavingDirections }, { "GluePointType", EAS_GluePointType }, { "TextPathMode", EAS_TextPathMode }, { "ScaleX", EAS_ScaleX }, { "SameLetterHeights", EAS_SameLetterHeights }, { "Position", EAS_Position }, { "AdjustmentValues", EAS_AdjustmentValues }, { "Last", EAS_Last }, { "NotFound", EAS_NotFound } }; EnhancedCustomShapeTokenEnum EASGet( const rtl::OUString& rShapeType ) { if ( !pHashMap ) { // init hash map ::osl::MutexGuard aGuard( getHashMapMutex() ); if ( !pHashMap ) { TypeNameHashMap* pH = new TypeNameHashMap; const TokenTable* pPtr = pTokenTableArray; const TokenTable* pEnd = pPtr + ( sizeof( pTokenTableArray ) / sizeof( TokenTable ) ); for ( ; pPtr < pEnd; pPtr++ ) (*pH)[ pPtr->pS ] = pPtr->pE; pHashMap = pH; } } EnhancedCustomShapeTokenEnum eRetValue = EAS_NotFound; int i, nLen = rShapeType.getLength(); char* pBuf = new char[ nLen + 1 ]; for ( i = 0; i < nLen; i++ ) pBuf[ i ] = (char)rShapeType[ i ]; pBuf[ i ] = 0; TypeNameHashMap::iterator aHashIter( pHashMap->find( pBuf ) ); delete[] pBuf; if ( aHashIter != pHashMap->end() ) eRetValue = (*aHashIter).second; return eRetValue; } rtl::OUString EASGet( const EnhancedCustomShapeTokenEnum eToken ) { sal_uInt32 i = eToken >= EAS_Last ? (sal_uInt32)EAS_NotFound : (sal_uInt32)eToken; return rtl::OUString::createFromAscii( pTokenTableArray[ i ].pS ); } } } <commit_msg>INTEGRATION: CWS sj15 (1.5.70); FILE MERGED 2005/02/03 18:54:32 sj 1.5.70.1: #i41918# changed property name text-path-scale-x to text-path-scale<commit_after>/************************************************************************* * * $RCSfile: EnhancedCustomShapeToken.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2005-02-21 16:03:43 $ * * 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 _ENHANCED_CUSTOMSHAPE_TOKEN_HXX #include "EnhancedCustomShapeToken.hxx" #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #include <hash_map> namespace xmloff { namespace EnhancedCustomShapeToken { struct TCheck { bool operator()( const char* s1, const char* s2 ) const { return strcmp( s1, s2 ) == 0; } }; typedef std::hash_map< const char*, EnhancedCustomShapeTokenEnum, std::hash<const char*>, TCheck> TypeNameHashMap; static TypeNameHashMap* pHashMap = NULL; static ::osl::Mutex& getHashMapMutex() { static osl::Mutex s_aHashMapProtection; return s_aHashMapProtection; } struct TokenTable { char* pS; EnhancedCustomShapeTokenEnum pE; }; static const TokenTable pTokenTableArray[] = { { "type", EAS_type }, { "name", EAS_name }, { "mirror-horizontal", EAS_mirror_horizontal }, { "mirror-vertical", EAS_mirror_vertical }, { "viewBox", EAS_viewBox }, { "text-rotate-angle", EAS_text_rotate_angle }, { "extrusion-allowed", EAS_extrusion_allowed }, { "extrusion-text-path-allowed", EAS_text_path_allowed }, { "extrusion-concentric-gradient-fill", EAS_concentric_gradient_fill_allowed }, { "extrusion", EAS_extrusion }, { "extrusion-brightness", EAS_extrusion_brightness }, { "extrusion-depth", EAS_extrusion_depth }, { "extrusion-diffusion", EAS_extrusion_diffusion }, { "extrusion-number-of-line-segments", EAS_extrusion_number_of_line_segments }, { "extrusion-light-face", EAS_extrusion_light_face }, { "extrusion-first-light-harsh", EAS_extrusion_first_light_harsh }, { "extrusion-second-light-harsh", EAS_extrusion_second_light_harsh }, { "extrusion-first-light-livel", EAS_extrusion_first_light_level }, { "extrusion-second-light-level", EAS_extrusion_second_light_level }, { "extrusion-first-light-direction", EAS_extrusion_first_light_direction }, { "extrusion-second-light-direction", EAS_extrusion_second_light_direction }, { "extrusion-metal", EAS_extrusion_metal }, { "shade-mode", EAS_shade_mode }, { "extrusion-rotation-angle", EAS_extrusion_rotation_angle }, { "extrusion-rotation-center", EAS_extrusion_rotation_center }, { "extrusion-shininess", EAS_extrusion_shininess }, { "extrusion-skew", EAS_extrusion_skew }, { "extrusion-specularity", EAS_extrusion_specularity }, { "projection", EAS_projection }, { "extrusion-viewpoint", EAS_extrusion_viewpoint }, { "extrusion-origin", EAS_extrusion_origin }, { "extrusion-color", EAS_extrusion_color }, { "enhanced-path", EAS_enhanced_path }, { "path-stretchpoint-x", EAS_path_stretchpoint_x }, { "path-stretchpoint-y", EAS_path_stretchpoint_y }, { "text-areas", EAS_text_areas }, { "glue-points", EAS_glue_points }, { "glue-point-type", EAS_glue_point_type }, { "glue-point-leaving-directions", EAS_glue_point_leaving_directions }, { "text-path", EAS_text_path }, { "text-path-mode", EAS_text_path_mode }, { "text-path-scale", EAS_text_path_scale }, { "text-path-same-letter-heights", EAS_text_path_same_letter_heights }, { "modifiers", EAS_modifiers }, { "equation", EAS_equation }, { "formula", EAS_formula }, { "handle", EAS_handle }, { "handle-mirror-horizontal", EAS_handle_mirror_horizontal }, { "handle-mirror-vertical", EAS_handle_mirror_vertical }, { "handle-switched", EAS_handle_switched }, { "handle-position", EAS_handle_position }, { "handle-range-x-minimum", EAS_handle_range_x_minimum }, { "handle-range-x-maximum", EAS_handle_range_x_maximum }, { "handle-range-y-minimum", EAS_handle_range_y_minimum }, { "handle-range-y-maximum", EAS_handle_range_y_maximum }, { "handle-polar", EAS_handle_polar }, { "handle-radius-range-minimum", EAS_handle_radius_range_minimum }, { "handle-radius-range-maximum", EAS_handle_radius_range_maximum }, { "CustomShapeEngine", EAS_CustomShapeEngine }, { "CustomShapeData", EAS_CustomShapeData }, { "Type", EAS_Type }, { "MirroredX", EAS_MirroredX }, { "MirroredY", EAS_MirroredY }, { "ViewBox", EAS_ViewBox }, { "TextRotateAngle", EAS_TextRotateAngle }, { "ExtrusionAllowed", EAS_ExtrusionAllowed }, { "TextPathAllowed", EAS_TextPathAllowed }, { "ConcentricGradientFillAllowed", EAS_ConcentricGradientFillAllowed }, { "Extrusion", EAS_Extrusion }, { "Equations", EAS_Equations }, { "Equation", EAS_Equation }, { "Path", EAS_Path }, { "TextPath", EAS_TextPath }, { "Handles", EAS_Handles }, { "Handle", EAS_Handle }, { "Brightness", EAS_Brightness }, { "Depth", EAS_Depth }, { "Diffusion", EAS_Diffusion }, { "NumberOfLineSegments", EAS_NumberOfLineSegments }, { "LightFace", EAS_LightFace }, { "FirstLightHarsh", EAS_FirstLightHarsh }, { "SecondLightHarsh", EAS_SecondLightHarsh }, { "FirstLightLevel", EAS_FirstLightLevel }, { "SecondLightLevel", EAS_SecondLightLevel }, { "FirstLightDirection", EAS_FirstLightDirection }, { "SecondLightDirection", EAS_SecondLightDirection }, { "Metal", EAS_Metal }, { "ShadeMode", EAS_ShadeMode }, { "RotateAngle", EAS_RotateAngle }, { "RotationCenter", EAS_RotationCenter }, { "Shininess", EAS_Shininess }, { "Skew", EAS_Skew }, { "Specularity", EAS_Specularity }, { "ProjectionMode", EAS_ProjectionMode }, { "ViewPoint", EAS_ViewPoint }, { "Origin", EAS_Origin }, { "Color", EAS_Color }, { "Switched", EAS_Switched }, { "Polar", EAS_Polar }, { "RangeXMinimum", EAS_RangeXMinimum }, { "RangeXMaximum", EAS_RangeXMaximum }, { "RangeYMinimum", EAS_RangeYMinimum }, { "RangeYMaximum", EAS_RangeYMaximum }, { "RadiusRangeMinimum", EAS_RadiusRangeMinimum }, { "RadiusRangeMaximum", EAS_RadiusRangeMaximum }, { "Coordinates", EAS_Coordinates }, { "Segments", EAS_Segments }, { "StretchX", EAS_StretchX }, { "StretchY", EAS_StretchY }, { "TextFrames", EAS_TextFrames }, { "GluePoints", EAS_GluePoints }, { "GluePointLeavingDirections", EAS_GluePointLeavingDirections }, { "GluePointType", EAS_GluePointType }, { "TextPathMode", EAS_TextPathMode }, { "ScaleX", EAS_ScaleX }, { "SameLetterHeights", EAS_SameLetterHeights }, { "Position", EAS_Position }, { "AdjustmentValues", EAS_AdjustmentValues }, { "Last", EAS_Last }, { "NotFound", EAS_NotFound } }; EnhancedCustomShapeTokenEnum EASGet( const rtl::OUString& rShapeType ) { if ( !pHashMap ) { // init hash map ::osl::MutexGuard aGuard( getHashMapMutex() ); if ( !pHashMap ) { TypeNameHashMap* pH = new TypeNameHashMap; const TokenTable* pPtr = pTokenTableArray; const TokenTable* pEnd = pPtr + ( sizeof( pTokenTableArray ) / sizeof( TokenTable ) ); for ( ; pPtr < pEnd; pPtr++ ) (*pH)[ pPtr->pS ] = pPtr->pE; pHashMap = pH; } } EnhancedCustomShapeTokenEnum eRetValue = EAS_NotFound; int i, nLen = rShapeType.getLength(); char* pBuf = new char[ nLen + 1 ]; for ( i = 0; i < nLen; i++ ) pBuf[ i ] = (char)rShapeType[ i ]; pBuf[ i ] = 0; TypeNameHashMap::iterator aHashIter( pHashMap->find( pBuf ) ); delete[] pBuf; if ( aHashIter != pHashMap->end() ) eRetValue = (*aHashIter).second; return eRetValue; } rtl::OUString EASGet( const EnhancedCustomShapeTokenEnum eToken ) { sal_uInt32 i = eToken >= EAS_Last ? (sal_uInt32)EAS_NotFound : (sal_uInt32)eToken; return rtl::OUString::createFromAscii( pTokenTableArray[ i ].pS ); } } } <|endoftext|>
<commit_before>namespace Bull { template <typename T> Angle<T> Angle<T>::degree(T value) { return Angle<T>(value, true); } template <typename T> Angle<T> Angle<T>::radian(T value) { return Angle<T>(value); } template <typename T> Angle<T> Angle<T>::normalize(const Angle<T>& angle) { return Angle<T>(angle).normalize(); } template <typename T> Angle<T> Angle<T>::clamp(const Angle<T>& angle, const Angle<T>& min, const Angle<T>& max) { return Angle<T>(angle).clamp(min, max); } template <typename T> Angle<T>::Angle() : Angle(0, false) { /// Nothing } template <typename T> Angle<T>& Angle<T>::normalize() { while(m_value >= 2 * Pi) { m_value /= 2 * Pi; } return (*this); } template <typename T> Angle<T>& Angle<T>::clamp(const Angle<T>& min, const Angle<T>& max) { if(m_value < min.m_value) { m_value = min.m_value; } else if(m_value > max.m_value) { m_value = max.m_value; } return (*this); } template <typename T> bool Angle<T>::operator==(const Angle<T>& right) { return m_value == right.m_value; } template <typename T> bool Angle<T>::operator!=(const Angle<T>& right) { return m_value != right.m_value; } template <typename T> bool Angle<T>::operator<(const Angle<T>& right) { return m_value < right.m_value; } template <typename T> bool Angle<T>::operator<=(const Angle<T>& right) { return m_value <= right.m_value; } template <typename T> bool Angle<T>::operator>(const Angle<T>& right) { return m_value > right.m_value; } template <typename T> bool Angle<T>::operator>=(const Angle<T>& right) { return m_value >= right.m_value; } template <typename T> Angle<T> Angle<T>::operator+(const Angle<T>& right) { return Angle<T>(m_value + right.m_value); } template <typename T> Angle<T> Angle<T>::operator-(const Angle<T>& right) { return Angle<T>(m_value - right.m_value); } template <typename U> Angle<U> operator*(U left, const Angle<U>& right) { return Angle<U>(left * right.m_value); } template <typename U> Angle<U> operator*(const Angle<U>& left, U right) { return Angle<U>(left.m_value * right); } template <typename U> Angle<U> operator/(U left, const Angle<U>& right) { return Angle<U>(left / right.m_value); } template <typename U> Angle<U> operator/(const Angle<U>& left, U right) { return Angle<U>(left.m_value * right); } template <typename T> Angle<T>& Angle<T>::operator+=(const Angle<T>& right) { m_value += right.m_value; return (*this); } template <typename T> Angle<T>& Angle<T>::operator-=(const Angle<T>& right) { m_value -= right.m_value; return (*this); } template <typename T> Angle<T>& Angle<T>::operator*=(T right) { m_value *= right; return (*this); } template <typename T> Angle<T>& Angle<T>::operator/=(T right) { m_value /= right; return (*this); } template <typename T> Angle<T>::Angle(T value, bool convert) { if(convert) { value = value * Pi / 180; } m_value = value; } } namespace std { template <typename U> float cos(const Bull::Angle<U>& angle) { return std::cos(angle.m_value); } template <typename U> float acos(const Bull::Angle<U>& angle) { return std::acos(angle.m_value); } template <typename U> float sin(const Bull::Angle<U>& angle) { return std::sin(angle.m_value); } template <typename U> float asin(const Bull::Angle<U>& angle) { return std::asin(angle.m_value); } template <typename U> float tan(const Bull::Angle<U>& angle) { return std::tan(angle.m_value); } template <typename U> float atan(const Bull::Angle<U>& angle) { return std::atan(angle.m_value); } }<commit_msg>[Math/Angle] Fix / operator<commit_after>namespace Bull { template <typename T> Angle<T> Angle<T>::degree(T value) { return Angle<T>(value, true); } template <typename T> Angle<T> Angle<T>::radian(T value) { return Angle<T>(value); } template <typename T> Angle<T> Angle<T>::normalize(const Angle<T>& angle) { return Angle<T>(angle).normalize(); } template <typename T> Angle<T> Angle<T>::clamp(const Angle<T>& angle, const Angle<T>& min, const Angle<T>& max) { return Angle<T>(angle).clamp(min, max); } template <typename T> Angle<T>::Angle() : Angle(0, false) { /// Nothing } template <typename T> Angle<T>& Angle<T>::normalize() { while(m_value >= 2 * Pi) { m_value /= 2 * Pi; } return (*this); } template <typename T> Angle<T>& Angle<T>::clamp(const Angle<T>& min, const Angle<T>& max) { if(m_value < min.m_value) { m_value = min.m_value; } else if(m_value > max.m_value) { m_value = max.m_value; } return (*this); } template <typename T> bool Angle<T>::operator==(const Angle<T>& right) { return m_value == right.m_value; } template <typename T> bool Angle<T>::operator!=(const Angle<T>& right) { return m_value != right.m_value; } template <typename T> bool Angle<T>::operator<(const Angle<T>& right) { return m_value < right.m_value; } template <typename T> bool Angle<T>::operator<=(const Angle<T>& right) { return m_value <= right.m_value; } template <typename T> bool Angle<T>::operator>(const Angle<T>& right) { return m_value > right.m_value; } template <typename T> bool Angle<T>::operator>=(const Angle<T>& right) { return m_value >= right.m_value; } template <typename T> Angle<T> Angle<T>::operator+(const Angle<T>& right) { return Angle<T>(m_value + right.m_value); } template <typename T> Angle<T> Angle<T>::operator-(const Angle<T>& right) { return Angle<T>(m_value - right.m_value); } template <typename U> Angle<U> operator*(U left, const Angle<U>& right) { return Angle<U>(left * right.m_value); } template <typename U> Angle<U> operator*(const Angle<U>& left, U right) { return Angle<U>(left.m_value * right); } template <typename U> Angle<U> operator/(U left, const Angle<U>& right) { return Angle<U>(left / right.m_value); } template <typename U> Angle<U> operator/(const Angle<U>& left, U right) { return Angle<U>(left.m_value / right); } template <typename T> Angle<T>& Angle<T>::operator+=(const Angle<T>& right) { m_value += right.m_value; return (*this); } template <typename T> Angle<T>& Angle<T>::operator-=(const Angle<T>& right) { m_value -= right.m_value; return (*this); } template <typename T> Angle<T>& Angle<T>::operator*=(T right) { m_value *= right; return (*this); } template <typename T> Angle<T>& Angle<T>::operator/=(T right) { m_value /= right; return (*this); } template <typename T> Angle<T>::Angle(T value, bool convert) { if(convert) { value = value * Pi / 180; } m_value = value; } } namespace std { template <typename U> float cos(const Bull::Angle<U>& angle) { return std::cos(angle.m_value); } template <typename U> float acos(const Bull::Angle<U>& angle) { return std::acos(angle.m_value); } template <typename U> float sin(const Bull::Angle<U>& angle) { return std::sin(angle.m_value); } template <typename U> float asin(const Bull::Angle<U>& angle) { return std::asin(angle.m_value); } template <typename U> float tan(const Bull::Angle<U>& angle) { return std::tan(angle.m_value); } template <typename U> float atan(const Bull::Angle<U>& angle) { return std::atan(angle.m_value); } }<|endoftext|>
<commit_before>/// @brief provides a proxy class to deal with integer below fixed-point number #ifndef INC_CORE_AS_NATIVE_PROXY_HPP_ #define INC_CORE_AS_NATIVE_PROXY_HPP_ #include <boost/integer/integer_mask.hpp> namespace core { template<typename T, size_t n, size_t f, class op, class up> class fixed_point; /// @brief proxy class for dealing with fixed-point numbers as with integers template<typename T, size_t n, size_t f, class op, class up> class as_native_proxy { typedef as_native_proxy<T, n, f, op, up> this_class; typedef fixed_point<T, n, f, op, up> fixed_point_class; public: template<typename U> operator U() const { BOOST_STATIC_ASSERT((boost::is_arithmetic<U>::value)); return U(this->value()); } /// @brief copy operator template<typename U> void operator =(U val) { BOOST_STATIC_ASSERT((boost::is_integral<U>::value)); this->m_value = val; } // motivation: boost ordered operators from operators.hpp are not the option // because it need the copy operator #define OPERATOR(f) \ template<typename U> \ bool operator ##f(U const& x) const \ { \ BOOST_STATIC_ASSERT((boost::is_integral<U>::value)); \ return x ##f this->value(); \ } \ template<> \ bool operator ##f(this_class const& x) const{ return x.value() ##f this->value(); } OPERATOR(<); OPERATOR(>); OPERATOR(==); OPERATOR(<=); OPERATOR(>=); #undef OPERATOR #define CHECKED_ARITHMETICS(f, val) \ fixed_point_class::handle_underflow( \ this->value(), \ fixed_point_class::handle_overflow(this->value() f val, op()), \ up() \ ) #define OPERATOR(f) \ template<typename U> \ this_class& operator ##f(U const& x) \ { \ CHECKED_ARITHMETICS(##f, x); \ return *this; \ } \ template<> \ this_class& operator ##f(this_class const& x) \ { \ CHECKED_ARITHMETICS(##f, x.value()); \ return *this; \ } OPERATOR(+=); OPERATOR(-=); OPERATOR(*=); OPERATOR(/=); OPERATOR(%=); OPERATOR(^=); OPERATOR(&=); OPERATOR(|=); OPERATOR(<<=); OPERATOR(>>=); #undef OPERATOR #undef CHECKED_ARITHMETICS /// @brief increment operator. It checks if result fits the bounds drawn /// from n bits of length. this_class& operator ++() { fixed_point_class::handle_overflow(this->value()++, op()); return *this; } /// @brief decrement operator. It checks if result fits the bounds drawn /// from n bits of length. this_class& operator --() { fixed_point_class::handle_overflow(this->value()--, op()); return *this; } #define OPERATOR(f) \ template<typename U> \ friend T operator ##f(this_class const& x, U const& y) \ { \ BOOST_STATIC_ASSERT((boost::is_integral<U>::value)); \ return x.value() + y; \ } \ template<typename U> \ friend U operator ##f(U const& x, this_class const& y) \ { \ BOOST_STATIC_ASSERT((boost::is_integral<U>::value)); \ return y.value() + x; \ } OPERATOR(+); OPERATOR(-); OPERATOR(*); OPERATOR(/); OPERATOR(%); OPERATOR(^); OPERATOR(|); OPERATOR(&); #undef OPERATOR this_class& operator ~() { this->m_value ^= boost::low_bits_mask_t<n>::value; return *this; } private: T& m_value; T& value(){ return this->m_value; } T value() const{ return this->m_value; } as_native_proxy(fixed_point_class& x) : m_value(x.m_value){}; as_native_proxy(this_class const&){}; template<typename T1, size_t n1, size_t f1, class op1, class up1> friend as_native_proxy<T1, n1, f1, op1, up1> as_native(fixed_point<T1, n1, f1, op1, up1>&); template<typename T1, size_t n1, size_t f1, class op1, class up1> friend class fixed_point; }; } #endif <commit_msg>as_native_proxy.hpp: unary operator ~<commit_after>/// @brief provides a proxy class to deal with integer below fixed-point number #ifndef INC_CORE_AS_NATIVE_PROXY_HPP_ #define INC_CORE_AS_NATIVE_PROXY_HPP_ #include <boost/integer/integer_mask.hpp> namespace core { template<typename T, size_t n, size_t f, class op, class up> class fixed_point; /// @brief proxy class for dealing with fixed-point numbers as with integers template<typename T, size_t n, size_t f, class op, class up> class as_native_proxy { typedef as_native_proxy<T, n, f, op, up> this_class; typedef fixed_point<T, n, f, op, up> fixed_point_class; public: template<typename U> operator U() const { BOOST_STATIC_ASSERT((boost::is_arithmetic<U>::value)); return U(this->value()); } /// @brief copy operator template<typename U> void operator =(U val) { BOOST_STATIC_ASSERT((boost::is_integral<U>::value)); this->m_value = val; } // motivation: boost ordered operators from operators.hpp are not the option // because it need the copy operator #define OPERATOR(f) \ template<typename U> \ bool operator ##f(U const& x) const \ { \ BOOST_STATIC_ASSERT((boost::is_integral<U>::value)); \ return x ##f this->value(); \ } \ template<> \ bool operator ##f(this_class const& x) const{ return x.value() ##f this->value(); } OPERATOR(<); OPERATOR(>); OPERATOR(==); OPERATOR(<=); OPERATOR(>=); #undef OPERATOR #define CHECKED_ARITHMETICS(f, val) \ fixed_point_class::handle_underflow( \ this->value(), \ fixed_point_class::handle_overflow(this->value() f val, op()), \ up() \ ) #define OPERATOR(f) \ template<typename U> \ this_class& operator ##f(U const& x) \ { \ CHECKED_ARITHMETICS(##f, x); \ return *this; \ } \ template<> \ this_class& operator ##f(this_class const& x) \ { \ CHECKED_ARITHMETICS(##f, x.value()); \ return *this; \ } OPERATOR(+=); OPERATOR(-=); OPERATOR(*=); OPERATOR(/=); OPERATOR(%=); OPERATOR(^=); OPERATOR(&=); OPERATOR(|=); OPERATOR(<<=); OPERATOR(>>=); #undef OPERATOR #undef CHECKED_ARITHMETICS /// @brief increment operator. It checks if result fits the bounds drawn /// from n bits of length. this_class& operator ++() { fixed_point_class::handle_overflow(this->value()++, op()); return *this; } /// @brief decrement operator. It checks if result fits the bounds drawn /// from n bits of length. this_class& operator --() { fixed_point_class::handle_overflow(this->value()--, op()); return *this; } #define OPERATOR(f) \ template<typename U> \ friend T operator ##f(this_class const& x, U const& y) \ { \ BOOST_STATIC_ASSERT((boost::is_integral<U>::value)); \ return x.value() + y; \ } \ template<typename U> \ friend U operator ##f(U const& x, this_class const& y) \ { \ BOOST_STATIC_ASSERT((boost::is_integral<U>::value)); \ return y.value() + x; \ } OPERATOR(+); OPERATOR(-); OPERATOR(*); OPERATOR(/); OPERATOR(%); OPERATOR(^); OPERATOR(|); OPERATOR(&); #undef OPERATOR T operator ~() const{ return this->m_value ^ T(boost::low_bits_mask_t<n>::sig_bits); } private: T& m_value; T& value(){ return this->m_value; } T value() const{ return this->m_value; } as_native_proxy(fixed_point_class& x) : m_value(x.m_value){}; as_native_proxy(this_class const&){}; template<typename T1, size_t n1, size_t f1, class op1, class up1> friend as_native_proxy<T1, n1, f1, op1, up1> as_native(fixed_point<T1, n1, f1, op1, up1>&); template<typename T1, size_t n1, size_t f1, class op1, class up1> friend class fixed_point; }; } #endif <|endoftext|>
<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH #define DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH //#ifdef HAVE_EIGEN #include <dune/common/shared_ptr.hh> #include <dune/stuff/la/container/pattern.hh> #include <dune/stuff/la/container/eigen.hh> namespace Dune { namespace Detailed { namespace Discretizations { namespace LA { namespace Container { namespace Factory { template <class ElementType> class Eigen { public: typedef Dune::Stuff::LA::Container::EigenRowMajorSparseMatrix<ElementType> RowMajorSparseMatrixType; typedef Dune::Stuff::LA::Container::EigenDenseMatrix<ElementType> DenseMatrixType; typedef Dune::Stuff::LA::Container::EigenDenseVector<ElementType> DenseVectorType; template <class TestSpaceType, class AnsatzSpaceType> static Dune::shared_ptr<RowMajorSparseMatrixType> createRowMajorSparseMatrix(const TestSpaceType& testSpace, const AnsatzSpaceType& ansatzSpace) { typedef Dune::Stuff::LA::Container::SparsityPatternDefault PatternType; const Dune::shared_ptr<const PatternType> pattern = testSpace.computePattern(ansatzSpace); //! TODO uses naked deref'ed pointer return Dune::shared_ptr<RowMajorSparseMatrixType>( new RowMajorSparseMatrixType(testSpace.map().size(), ansatzSpace.map().size(), *pattern)); } // static ... createRowMajorSparseMatrix(...) template <class TestSpaceType, class AnsatzSpaceType> static Dune::shared_ptr<DenseMatrixType> createDenseMatrix(const TestSpaceType& testSpace, const AnsatzSpaceType& ansatzSpace) { return Dune::make_shared<DenseMatrixType>(testSpace.map().size(), ansatzSpace.map().size()); } // static ... createDenseMatrix(...) template <class SpaceType> static Dune::shared_ptr<DenseVectorType> createDenseVector(const SpaceType& space) { return Dune::make_shared<DenseVectorType>(space.map().size()); } // static Dune::shared_ptr< DenseVectorType > createDenseVector(const SpaceType& space) }; // class Eigen } // namespace Factory } // namespace Conatiner } // namespace LA } // namespace Discretizations } // namespace Detailed } // namespace Dune //#endif // HAVE_EIGEN #endif // DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH <commit_msg>[la.container.factory.eigen] some cosmetic changes and another create...()<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH #define DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH //#ifdef HAVE_EIGEN #include <dune/common/shared_ptr.hh> #include <dune/stuff/la/container/pattern.hh> #include <dune/stuff/la/container/eigen.hh> namespace Dune { namespace Detailed { namespace Discretizations { namespace LA { namespace Container { namespace Factory { template <class ElementType> class Eigen { public: typedef Dune::Stuff::LA::Container::EigenRowMajorSparseMatrix<ElementType> RowMajorSparseMatrixType; typedef Dune::Stuff::LA::Container::EigenDenseMatrix<ElementType> DenseMatrixType; typedef Dune::Stuff::LA::Container::EigenDenseVector<ElementType> DenseVectorType; typedef Dune::Stuff::LA::Container::SparsityPatternDefault PatternType; template <class TestSpaceType, class AnsatzSpaceType> static Dune::shared_ptr<RowMajorSparseMatrixType> createRowMajorSparseMatrix(const TestSpaceType& testSpace, const AnsatzSpaceType& ansatzSpace) { typedef Dune::Stuff::LA::Container::SparsityPatternDefault PatternType; const Dune::shared_ptr<const PatternType> pattern = testSpace.computePattern(ansatzSpace); return createRowMajorSparseMatrix(testSpace, ansatzSpace, *pattern); } // static ... createRowMajorSparseMatrix(...) template <class TestSpaceType, class AnsatzSpaceType> static Dune::shared_ptr<RowMajorSparseMatrixType> createRowMajorSparseMatrix(const TestSpaceType& testSpace, const AnsatzSpaceType& ansatzSpace, const PatternType& pattern) { return Dune::make_shared<RowMajorSparseMatrixType>(testSpace.map().size(), ansatzSpace.map().size(), pattern); } // static ... createRowMajorSparseMatrix(...) template <class TestSpaceType, class AnsatzSpaceType> static Dune::shared_ptr<DenseMatrixType> createDenseMatrix(const TestSpaceType& testSpace, const AnsatzSpaceType& ansatzSpace) { return Dune::make_shared<DenseMatrixType>(testSpace.map().size(), ansatzSpace.map().size()); } // static ... createDenseMatrix(...) template <class SpaceType> static Dune::shared_ptr<DenseVectorType> createDenseVector(const SpaceType& space) { return Dune::make_shared<DenseVectorType>(space.map().size()); } // static Dune::shared_ptr< DenseVectorType > createDenseVector(const SpaceType& space) }; // class Eigen } // namespace Factory } // namespace Conatiner } // namespace LA } // namespace Discretizations } // namespace Detailed } // namespace Dune //#endif // HAVE_EIGEN #endif // DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH <|endoftext|>
<commit_before>/** * This file implements a command line utility to interact * with the `d2` library. */ #include <boost/exception/diagnostic_information.hpp> #include <boost/exception/get_error_info.hpp> #include <boost/filesystem/operations.hpp> #include <boost/format.hpp> #include <boost/lexical_cast.hpp> #include <boost/make_shared.hpp> #include <boost/program_options.hpp> #include <boost/shared_ptr.hpp> #include <cstdlib> // EXIT_FAILURE, EXIT_SUCCESS #include <d2/core/diagnostic.hpp> #include <d2/core/exceptions.hpp> #include <d2/core/filesystem.hpp> #include <d2/core/synchronization_skeleton.hpp> #include <exception> #include <iostream> #include <string> namespace { namespace po = boost::program_options; class Driver { /** * Return a string representation of the data associated to an `ErrorTag`. * * If no data associated to that tag is present in the exception object, * `default_` is returned instead. */ template <typename ErrorTag, typename Exception> static std::string get_error_info(Exception const& e, std::string default_ = "unavailable") { typedef typename ErrorTag::value_type Info; Info const* info = boost::get_error_info<ErrorTag>(e); return info ? boost::lexical_cast<std::string>(*info) : default_; } typedef d2::core::synchronization_skeleton Skeleton; /** * Return a pointer to a `synchronization_skeleton` loaded with the data * found in the repository, or a default initialized `shared_ptr` if * anything goes wrong. */ boost::shared_ptr<Skeleton> create_skeleton() const { if (!boost::filesystem::exists(repo)) { std::cerr << repo << " does not exist\n"; return boost::shared_ptr<Skeleton>(); } try { return boost::make_shared<Skeleton>(repo); } catch (d2::core::filesystem_error const& e) { std::cerr << "unable to open the repository at " << repo << '\n'; if (debug) std::cerr << boost::diagnostic_information(e) << '\n'; } catch (d2::EventTypeException const& e) { std::string actual_type = get_error_info<d2::ActualType>(e); std::string expected_type = get_error_info<d2::ExpectedType>(e); std::cerr << boost::format( "error while loading the data:\n" " encountered an event of type %1%\n" " while expecting an event of type %2%\n") % actual_type % expected_type; if (debug) std::cerr << boost::diagnostic_information(e) << '\n'; } catch (d2::UnexpectedReleaseException const& e) { std::string lock = get_error_info<d2::ReleasedLock>(e); std::string thread = get_error_info<d2::ReleasingThread>(e); std::cerr << boost::format( "error while building the graphs:\n" " lock %1% was unexpectedly released by thread %2%\n") % lock % thread; if (debug) std::cerr << boost::diagnostic_information(e) << '\n'; } return boost::shared_ptr<Skeleton>(); } bool parse_command_line(int argc, char const* argv[]) { po::variables_map args; po::options_description hidden, all; po::positional_options_description positionals; visible.add_options() ( "help,h", po::bool_switch(&help), "produce help message and exit" )( "analyze", po::bool_switch(&analyze)->default_value(true, "true"), "perform the analysis for deadlocks" )( "stats", po::bool_switch(&stats), "produce statistics about the usage of locks and threads" )( "debug", po::bool_switch(&debug), "enable special debugging output" ) ; hidden.add_options() ( "repo-path", po::value<std::string>(&repo), "path of the repository to examine" ) ; positionals.add("repo-path", 1); all.add(visible).add(hidden); po::command_line_parser parser(argc, argv); po::store(parser.options(all).positional(positionals).run(), args); po::notify(args); if (repo.empty()) { std::cerr << "missing input directory\n" << visible; return false; } return true; } po::options_description visible; std::string repo; bool debug, help, analyze, stats; static void print_deadlock(d2::core::potential_deadlock const& dl) { std::cout << // 80 columns "\n--------------------------------------------------------------------------------\n"; d2::core::plain_text_explanation(std::cout, dl); std::cout << '\n'; } public: int run(int argc, char const* argv[]) { if (!parse_command_line(argc, argv)) return EXIT_FAILURE; if (help) { std::cout << visible << '\n'; return EXIT_FAILURE; } boost::shared_ptr<Skeleton> skeleton = create_skeleton(); if (!skeleton) return EXIT_FAILURE; if (analyze) skeleton->deadlocks(print_deadlock); if (stats) { std::cout << boost::format( "number of threads: %1%\n" "number of distinct locks: %2%\n") % skeleton->number_of_threads() % skeleton->number_of_locks(); } return EXIT_SUCCESS; } }; } // end anonymous namespace int main(int argc, char const* argv[]) { try { Driver driver; return driver.run(argc, argv); } catch (std::exception const& e) { std::cerr << "encountered an unknown problem:\n" << boost::diagnostic_information(e) << '\n'; return EXIT_FAILURE; } } <commit_msg>Improve handling of options in the utility.<commit_after>/** * This file implements a command line utility to interact * with the `d2` library. */ #include <boost/exception/diagnostic_information.hpp> #include <boost/exception/get_error_info.hpp> #include <boost/filesystem/operations.hpp> #include <boost/format.hpp> #include <boost/lexical_cast.hpp> #include <boost/make_shared.hpp> #include <boost/program_options.hpp> #include <boost/shared_ptr.hpp> #include <cstdlib> // EXIT_FAILURE, EXIT_SUCCESS #include <d2/core/diagnostic.hpp> #include <d2/core/exceptions.hpp> #include <d2/core/filesystem.hpp> #include <d2/core/synchronization_skeleton.hpp> #include <exception> #include <iostream> #include <string> namespace { namespace po = boost::program_options; class Driver { /** * Return a string representation of the data associated to an `ErrorTag`. * * If no data associated to that tag is present in the exception object, * `default_` is returned instead. */ template <typename ErrorTag, typename Exception> static std::string get_error_info(Exception const& e, std::string default_ = "unavailable") { typedef typename ErrorTag::value_type Info; Info const* info = boost::get_error_info<ErrorTag>(e); return info ? boost::lexical_cast<std::string>(*info) : default_; } typedef d2::core::synchronization_skeleton Skeleton; //! Print an error to the standard error stream with a trailing newline. template <typename Printable> static void error(Printable const& p) { std::cerr << "d2: error: " << p << '\n'; } /** * Return a pointer to a `synchronization_skeleton` loaded with the data * found in the repository, or a default initialized `shared_ptr` if * anything goes wrong. */ boost::shared_ptr<Skeleton> create_skeleton() const { if (!boost::filesystem::exists(repo)) { error(repo + " does not exist"); return boost::shared_ptr<Skeleton>(); } try { return boost::make_shared<Skeleton>(repo); } catch (d2::core::filesystem_error const& e) { error("unable to open the repository at " + repo); if (debug) error(boost::diagnostic_information(e)); } catch (d2::EventTypeException const& e) { std::string actual_type = get_error_info<d2::ActualType>(e); std::string expected_type = get_error_info<d2::ExpectedType>(e); error(boost::format( "while building the graphs:\n" " encountered an event of type %1%\n" " while expecting an event of type %2%") % actual_type % expected_type); if (debug) error(boost::diagnostic_information(e)); } catch (d2::UnexpectedReleaseException const& e) { std::string lock = get_error_info<d2::ReleasedLock>(e); std::string thread = get_error_info<d2::ReleasingThread>(e); error(boost::format( "while building the graphs:\n" " lock %1% was unexpectedly released by thread %2%") % lock % thread); if (debug) error(boost::diagnostic_information(e)); } return boost::shared_ptr<Skeleton>(); } bool parse_command_line(int argc, char const* argv[]) { po::variables_map args; po::options_description visible, hidden, all; po::positional_options_description positionals; bool help = false; visible.add_options() ( "help,h", po::bool_switch(&help), "produce help message and exit" )( "analyze", po::bool_switch(&analyze)->default_value(true, "true"), "perform the analysis for deadlocks" )( "stats", po::bool_switch(&stats), "produce statistics about the usage of locks and threads" )( "debug", po::bool_switch(&debug), "enable special debugging output" ) ; hidden.add_options() ( "repo-path", po::value<std::string>(&repo), "path of the repository to examine" ) ; positionals.add("repo-path", 1); all.add(visible).add(hidden); po::command_line_parser parser(argc, argv); try { po::store(parser.options(all).positional(positionals).run(), args); } catch (po::error const& e) { error(e.what()); return false; } po::notify(args); if (help) { std::cout << visible; return false; } if (repo.empty()) { error("missing input directory"); return false; } return true; } std::string repo; bool debug, analyze, stats; static void print_deadlock(d2::core::potential_deadlock const& dl) { std::cout << // 80 columns "\n--------------------------------------------------------------------------------\n"; d2::core::plain_text_explanation(std::cout, dl); std::cout << '\n'; } public: int run(int argc, char const* argv[]) { try { if (!parse_command_line(argc, argv)) return EXIT_FAILURE; boost::shared_ptr<Skeleton> skeleton = create_skeleton(); if (!skeleton) return EXIT_FAILURE; if (analyze) skeleton->on_deadlocks(print_deadlock); if (stats) { std::cout << boost::format( "number of threads: %1%\n" "number of distinct locks: %2%\n") % skeleton->number_of_threads() % skeleton->number_of_locks(); } } catch (std::exception const& e) { error("unknown problem:"); error(boost::diagnostic_information(e)); } return EXIT_SUCCESS; } }; } // end anonymous namespace int main(int argc, char const* argv[]) { Driver driver; return driver.run(argc, argv); } <|endoftext|>
<commit_before>#ifndef VORIMAGE_H #define VORIMAGE_H #include <tuple> #include <vector> #include <queue> #include <numeric> #include <iterator> #include "detail/heapqueue.hpp" #include "detail/common.hpp" namespace ndtess { namespace vorimage { template <typename T> static void build(T* result, pqueue<T>& _heap, const T* _lab, const std::vector<std::size_t>& _shape, const float* _dist){ static constexpr T epsilon = std::numeric_limits<T>::epsilon(); const std::size_t len = std::accumulate(std::begin(_shape), std::end(_shape), 1, std::multiplies<std::size_t>() ); // std::vector<T> value(_lab, _lab + len); if(_heap.empty() || !len) return; float dist = 0; std::size_t x = 0; std::size_t y = 0; std::size_t offset = 0; std::size_t offset2 = 0; T label = 0; //FOR LATER: check if this cache miss due to first jumping in y and then jumping in x // needs some attention std::int64_t x2 = 0; std::int64_t y2 = 0; while(!_heap.empty()){ std::tie(dist,x,y,label) = _heap.top();_heap.pop(); offset = y*_shape[ndtess::in_x]+x; if(std::abs(result[offset]) > epsilon) continue; result[offset] = label; for(int off = 0;off < 4;++off){ x2 = x + ndtess::offsets_x[off]; y2 = y + ndtess::offsets_y[off]; if(!( x2 >= 0 && x2 < _shape[ndtess::in_x] && y2 >= 0 && y2 < _shape[ndtess::in_y] )) continue; offset2 = y2*_shape[ndtess::in_x]+x2; T newlabel = result[offset2]; if(newlabel <= epsilon){ auto d1 = _dist[offset]; auto d2 = _dist[offset2]; auto newdist = dist + std::abs(d1+d2) + 1.; _heap.push(std::make_tuple(newdist, x2, y2, label)); } } } return ; } template <typename T> static std::vector<T> build(pqueue<T>& _heap, const T* _lab, const std::vector<std::size_t>& _shape, const float* _dist){ const std::size_t len = std::accumulate(std::begin(_shape), std::end(_shape), 1, std::multiplies<std::size_t>() ); std::vector<T> value(_lab, _lab + len); build<T>(value.data(),_heap,_lab,_shape,_dist); return value; } template <typename T> static std::vector<T> build(pqueue<T>& _heap, const T* _lab, const std::vector<std::size_t>& _shape){ const std::size_t len = std::accumulate(std::begin(_shape), std::end(_shape), 1, std::multiplies<std::size_t>() ); std::vector<float> dist(len,0.f); return build<T>(_heap,_lab, _shape,dist.data()); } } } #endif /* VORIMAGE_H */ <commit_msg>adopted ordering of entries<commit_after>#ifndef VORIMAGE_H #define VORIMAGE_H #include <tuple> #include <vector> #include <queue> #include <numeric> #include <iterator> #include "detail/heapqueue.hpp" #include "detail/common.hpp" namespace ndtess { namespace vorimage { template <typename T> static void build(T* result, pqueue<T>& _heap, const T* _lab, const std::vector<std::size_t>& _shape, const float* _dist){ static constexpr T epsilon = std::numeric_limits<T>::epsilon(); const std::size_t len = std::accumulate(std::begin(_shape), std::end(_shape), 1, std::multiplies<std::size_t>() ); // std::vector<T> value(_lab, _lab + len); if(_heap.empty() || !len) return; float dist = 0; std::size_t x = 0; std::size_t y = 0; std::size_t offset = 0; std::size_t offset2 = 0; T label = 0; std::int64_t x2 = 0; std::int64_t y2 = 0; while(!_heap.empty()){ std::tie(dist,y,x,label) = _heap.top();_heap.pop(); offset = y*_shape[ndtess::in_x]+x; if(std::abs(result[offset]) > epsilon) continue; result[offset] = label; for(int off = 0;off < 4;++off){ x2 = x + ndtess::offsets_x[off]; y2 = y + ndtess::offsets_y[off]; if(!( x2 >= 0 && x2 < _shape[ndtess::in_x] && y2 >= 0 && y2 < _shape[ndtess::in_y] )) continue; offset2 = y2*_shape[ndtess::in_x]+x2; T newlabel = result[offset2]; if(newlabel <= epsilon){ auto d1 = _dist[offset]; auto d2 = _dist[offset2]; auto newdist = dist + std::abs(d1+d2) + 1.; _heap.push(std::make_tuple(newdist, y2, x2, label)); } } } return ; } template <typename T> static std::vector<T> build(pqueue<T>& _heap, const T* _lab, const std::vector<std::size_t>& _shape, const float* _dist){ const std::size_t len = std::accumulate(std::begin(_shape), std::end(_shape), 1, std::multiplies<std::size_t>() ); std::vector<T> value(_lab, _lab + len); build<T>(value.data(),_heap,_lab,_shape,_dist); return value; } template <typename T> static std::vector<T> build(pqueue<T>& _heap, const T* _lab, const std::vector<std::size_t>& _shape){ const std::size_t len = std::accumulate(std::begin(_shape), std::end(_shape), 1, std::multiplies<std::size_t>() ); std::vector<float> dist(len,0.f); return build<T>(_heap,_lab, _shape,dist.data()); } } } #endif /* VORIMAGE_H */ <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once namespace etl { template<typename T, typename DT = std::decay_t<T>> struct is_dyn_matrix; template<typename T> struct is_etl_expr; template<typename T> struct is_copy_expr; template<typename T, typename DT = std::decay_t<T>> struct is_temporary_unary_expr; template<typename T, typename DT = std::decay_t<T>> struct is_temporary_binary_expr; template<typename T> struct is_temporary_expr; template<typename T, typename DT = std::decay_t<T>> struct is_view; template<typename T, typename DT = std::decay_t<T>> struct is_magic_view; template<typename T, typename DT = std::decay_t<T>> struct is_transformer; template<typename T> struct is_etl_value; template<typename E, typename Enable = void> struct sub_size_compare; template<typename T, typename Enable = void> struct etl_traits; template<typename T, typename DT = std::decay_t<T>> struct has_direct_access; template<typename E, cpp::disable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> std::size_t size(const E& v); template<typename E, cpp::enable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> constexpr std::size_t size(const E& /*unused*/) noexcept; template<typename E, cpp::disable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> std::size_t dim(const E& e, std::size_t d); template<std::size_t D, typename E, cpp::disable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> std::size_t dim(const E& e); template<std::size_t D, typename E, cpp::enable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> constexpr std::size_t dim(const E& /*unused*/) noexcept; template<std::size_t D, typename E, cpp::enable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> constexpr std::size_t dim() noexcept; template<typename T> struct is_single_precision : std::is_same<typename std::decay_t<T>::value_type, float> {}; template<typename... E> struct all_single_precision : cpp::and_c<is_single_precision<E>...> {}; template<typename T> struct is_double_precision : std::is_same<typename std::decay_t<T>::value_type, double> {}; template<typename... E> struct all_double_precision : cpp::and_c<is_double_precision<E>...> {}; template<typename T> struct is_complex_single_precision : std::is_same<typename std::decay_t<T>::value_type, std::complex<float>> {}; template<typename T> struct is_complex_double_precision : std::is_same<typename std::decay_t<T>::value_type, std::complex<double>> {}; template<typename T> struct is_complex : cpp::or_c<is_complex_single_precision<T>, is_complex_double_precision<T>> {}; template<typename... E> struct all_dma : cpp::and_c<has_direct_access<E>...> {}; template<typename E> using decay_traits = etl_traits<std::decay_t<E>>; template<typename... E> struct all_row_major : cpp::and_u<(decay_traits<E>::storage_order == order::RowMajor)...> {}; template<typename E, typename Enable = void> struct is_fast_safe : std::false_type {}; template<typename E> struct is_fast_safe<E, std::enable_if_t<is_etl_expr<E>::value>> : cpp::bool_constant<decay_traits<E>::is_fast> {}; template<typename... E> struct all_fast : cpp::and_c<is_fast_safe<E>...> {}; template<typename... E> struct all_etl_expr : cpp::and_c<is_etl_expr<E>...> {}; template<typename E> constexpr std::size_t dimensions(const E& /*unused*/) noexcept { return etl_traits<E>::dimensions(); } template<typename E> constexpr std::size_t dimensions() noexcept { return decay_traits<E>::dimensions(); } template<typename E, cpp::disable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> std::size_t rows(const E& v){ return etl_traits<E>::dim(v, 0); } template<typename E, cpp::enable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> constexpr std::size_t rows(const E& /*unused*/) noexcept { return etl_traits<E>::template dim<0>(); } template<typename E, cpp::disable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> std::size_t columns(const E& v){ static_assert(etl_traits<E>::dimensions() > 1, "columns() can only be used on 2D+ matrices"); return etl_traits<E>::dim(v, 1); } template<typename E, cpp::enable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> constexpr std::size_t columns(const E& /*unused*/) noexcept { static_assert(etl_traits<E>::dimensions() > 1, "columns() can only be used on 2D+ matrices"); return etl_traits<E>::template dim<1>(); } } //end of namespace etl <commit_msg>Test if a type is a complex<commit_after>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once namespace etl { template<typename T, typename DT = std::decay_t<T>> struct is_dyn_matrix; template<typename T> struct is_etl_expr; template<typename T> struct is_copy_expr; template<typename T, typename DT = std::decay_t<T>> struct is_temporary_unary_expr; template<typename T, typename DT = std::decay_t<T>> struct is_temporary_binary_expr; template<typename T> struct is_temporary_expr; template<typename T, typename DT = std::decay_t<T>> struct is_view; template<typename T, typename DT = std::decay_t<T>> struct is_magic_view; template<typename T, typename DT = std::decay_t<T>> struct is_transformer; template<typename T> struct is_etl_value; template<typename E, typename Enable = void> struct sub_size_compare; template<typename T, typename Enable = void> struct etl_traits; template<typename T, typename DT = std::decay_t<T>> struct has_direct_access; template<typename E, cpp::disable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> std::size_t size(const E& v); template<typename E, cpp::enable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> constexpr std::size_t size(const E& /*unused*/) noexcept; template<typename E, cpp::disable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> std::size_t dim(const E& e, std::size_t d); template<std::size_t D, typename E, cpp::disable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> std::size_t dim(const E& e); template<std::size_t D, typename E, cpp::enable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> constexpr std::size_t dim(const E& /*unused*/) noexcept; template<std::size_t D, typename E, cpp::enable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> constexpr std::size_t dim() noexcept; template<typename T> struct is_single_precision : std::is_same<typename std::decay_t<T>::value_type, float> {}; template<typename... E> struct all_single_precision : cpp::and_c<is_single_precision<E>...> {}; template<typename T> struct is_double_precision : std::is_same<typename std::decay_t<T>::value_type, double> {}; template<typename... E> struct all_double_precision : cpp::and_c<is_double_precision<E>...> {}; template<typename T> struct is_complex_single_precision : std::is_same<typename std::decay_t<T>::value_type, std::complex<float>> {}; template<typename T> struct is_complex_double_precision : std::is_same<typename std::decay_t<T>::value_type, std::complex<double>> {}; template<typename T> struct is_complex : cpp::or_c<is_complex_single_precision<T>, is_complex_double_precision<T>> {}; template<typename T> struct is_complex_t : std::false_type { }; template<typename T> struct is_complex_t <std::complex<T>> : std::true_type { }; template<typename... E> struct all_dma : cpp::and_c<has_direct_access<E>...> {}; template<typename E> using decay_traits = etl_traits<std::decay_t<E>>; template<typename... E> struct all_row_major : cpp::and_u<(decay_traits<E>::storage_order == order::RowMajor)...> {}; template<typename E, typename Enable = void> struct is_fast_safe : std::false_type {}; template<typename E> struct is_fast_safe<E, std::enable_if_t<is_etl_expr<E>::value>> : cpp::bool_constant<decay_traits<E>::is_fast> {}; template<typename... E> struct all_fast : cpp::and_c<is_fast_safe<E>...> {}; template<typename... E> struct all_etl_expr : cpp::and_c<is_etl_expr<E>...> {}; template<typename E> constexpr std::size_t dimensions(const E& /*unused*/) noexcept { return etl_traits<E>::dimensions(); } template<typename E> constexpr std::size_t dimensions() noexcept { return decay_traits<E>::dimensions(); } template<typename E, cpp::disable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> std::size_t rows(const E& v){ return etl_traits<E>::dim(v, 0); } template<typename E, cpp::enable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> constexpr std::size_t rows(const E& /*unused*/) noexcept { return etl_traits<E>::template dim<0>(); } template<typename E, cpp::disable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> std::size_t columns(const E& v){ static_assert(etl_traits<E>::dimensions() > 1, "columns() can only be used on 2D+ matrices"); return etl_traits<E>::dim(v, 1); } template<typename E, cpp::enable_if_u<etl_traits<E>::is_fast> = cpp::detail::dummy> constexpr std::size_t columns(const E& /*unused*/) noexcept { static_assert(etl_traits<E>::dimensions() > 1, "columns() can only be used on 2D+ matrices"); return etl_traits<E>::template dim<1>(); } } //end of namespace etl <|endoftext|>