text
stringlengths
54
60.6k
<commit_before>/* * File: rigResection.hpp * Author: sgaspari * * Created on January 2, 2016, 5:51 PM */ #pragma once #include <openMVG/types.hpp> #include <openMVG/cameras/Camera_Pinhole_Radial.hpp> #include <openMVG/geometry/pose3.hpp> #include <vector> namespace openMVG{ namespace localization{ #if HAVE_OPENGV bool rigResection(const std::vector<openMVG::Mat2X> &pts2d, const std::vector<openMVG::Mat3X> &pts3d, const std::vector<cameras::Pinhole_Intrinsic_Radial_K3 > &vec_queryIntrinsics, const std::vector<geometry::Pose3 > &vec_subPoses, geometry::Pose3 &rigPose, std::vector<std::vector<std::size_t> > &inliers, double threshold = 1e-6, size_t maxIterations = 100, bool verbosity = true); #endif } } <commit_msg>[localization] doc rigResection<commit_after>/* * File: rigResection.hpp * Author: sgaspari * * Created on January 2, 2016, 5:51 PM */ #pragma once #include <openMVG/types.hpp> #include <openMVG/cameras/Camera_Pinhole_Radial.hpp> #include <openMVG/geometry/pose3.hpp> #include <vector> namespace openMVG{ namespace localization{ #if HAVE_OPENGV /** * @brief It computes the pose of a camera rig given the 2d-3d associations of * each camera along with the internal calibration of each camera and the external * calibration of the cameras wrt the main one. * * @param[in] vec_pts2d A vector of the same size as the number of the camera in * the rig, each element of the vector contains the 2d points of the associations * for each camera. * @param[in] vec_pts3d A vector of the same size as the number of the camera in * the rig, each element of the vector contains the 3d points of the associations * for each camera. A 2d-3d association is represented by (vec_pts2d[i].col(j), vec_pts3d[i].col(j)). * @param[in] vec_queryIntrinsics A vector containing the intrinsics for each * camera of the rig. * @param[in] vec_subPoses A vector containing the subposes of the cameras wrt * the main one, ie the camera 0. This vector has numCameras-1 elements. * @param[out] rigPose The rig pose referred to the position of the main camera. * @param[out] inliers A vector of the same size as the number of cameras c * ontaining the indices of inliers. * @param[in] threshold The threshold to use in the ransac process. Note that the * threshold is an cos(angle), more specifically it's the maximum angle allowed * between the 3D direction of the feature point and the 3D direction of the * associated 3D point. The reprojection error computed in the ransac is 1-cos(angle), * where angle is the angle between the two directions. * @param[in] maxIterations Maximum number of iteration for the ransac process. * @param[in] verbosity Mute/unmute the debugging messages. * @return true if the ransac has success. */ bool rigResection(const std::vector<openMVG::Mat2X> &vec_pts2d, const std::vector<openMVG::Mat3X> &vec_pts3d, const std::vector<cameras::Pinhole_Intrinsic_Radial_K3 > &vec_queryIntrinsics, const std::vector<geometry::Pose3 > &vec_subPoses, geometry::Pose3 &rigPose, std::vector<std::vector<std::size_t> > &inliers, double threshold = 1-std::cos(0.00141421368), // ~0.1deg size_t maxIterations = 100, bool verbosity = true); #endif } } <|endoftext|>
<commit_before>#include "Decoder_polar_SCAN_naive_sys.hpp" namespace aff3ct { namespace module { template <typename B, typename R, tools::proto_i<R> I, tools::proto_f<R> F, tools::proto_v<R> V, tools::proto_h<B,R> H> Decoder_polar_SCAN_naive_sys<B,R,I,F,V,H> ::Decoder_polar_SCAN_naive_sys(const int &K, const int &N, const int &max_iter, const mipp::vector<B> &frozen_bits, const int n_frames, const std::string name) : Decoder_polar_SCAN_naive<B,R,I,F,V,H>(K, N, max_iter, frozen_bits, n_frames, name) { } template <typename B, typename R, tools::proto_i<R> I, tools::proto_f<R> F, tools::proto_v<R> V, tools::proto_h<B,R> H> Decoder_polar_SCAN_naive_sys<B,R,I,F,V,H> ::~Decoder_polar_SCAN_naive_sys() { } template <typename B, typename R, tools::proto_i<R> I, tools::proto_f<R> F, tools::proto_v<R> V, tools::proto_h<B,R> H> void Decoder_polar_SCAN_naive_sys<B,R,I,F,V,H> ::_soft_decode(const R *sys, const R *par, R *ext, const int frame_id) { // ----------------------------------------------------------------------------------------------------------- LOAD this->_load_init(); // init the softGraph (special case for the right most stage) auto sys_idx = 0, par_idx = 0; for (auto i = 0; i < this->N; i++) if (!this->frozen_bits[i]) this->soft_graph[this->layers_count - 1][i] = sys[sys_idx++]; else this->soft_graph[this->layers_count - 1][i] = par[par_idx++]; // --------------------------------------------------------------------------------------------------------- DECODE Decoder_polar_SCAN_naive<B,R,I,F,V,H>::_decode(); // ---------------------------------------------------------------------------------------------------------- STORE sys_idx = 0; for (auto i = 0; i < this->N; i++) if (!this->frozen_bits[i]) // if "i" is NOT a frozen bit (information bit = sytematic bit) ext[sys_idx++] = this->feedback_graph[this->layers_count -1][i]; } template <typename B, typename R, tools::proto_i<R> I, tools::proto_f<R> F, tools::proto_v<R> V, tools::proto_h<B,R> H> void Decoder_polar_SCAN_naive_sys<B,R,I,F,V,H> ::_soft_decode(const R *Y_N1, R *Y_N2, const int frame_id) { // ----------------------------------------------------------------------------------------------------------- LOAD this->_load(Y_N1); // --------------------------------------------------------------------------------------------------------- DECODE Decoder_polar_SCAN_naive<B,R,I,F,V,H>::_decode(); // ---------------------------------------------------------------------------------------------------------- STORE for (auto i = 0; i < this->N; i++) Y_N2[i] = this->feedback_graph[this->layers_count -1][i]; } template <typename B, typename R, tools::proto_i<R> I, tools::proto_f<R> F, tools::proto_v<R> V, tools::proto_h<B,R> H> void Decoder_polar_SCAN_naive_sys<B,R,I,F,V,H> ::_store(B *V_N) const { auto k = 0; for (auto i = 0; i < this->N; i++) { if (!this->frozen_bits[i]) // if i is not a frozen bit V_N[k++] = (H(this->feedback_graph[this->layers_count -1][i]) == 0) ? (B)0 : (B)1; } } } } <commit_msg>Modification of the SCAN store function.<commit_after>#include "Decoder_polar_SCAN_naive_sys.hpp" namespace aff3ct { namespace module { template <typename B, typename R, tools::proto_i<R> I, tools::proto_f<R> F, tools::proto_v<R> V, tools::proto_h<B,R> H> Decoder_polar_SCAN_naive_sys<B,R,I,F,V,H> ::Decoder_polar_SCAN_naive_sys(const int &K, const int &N, const int &max_iter, const mipp::vector<B> &frozen_bits, const int n_frames, const std::string name) : Decoder_polar_SCAN_naive<B,R,I,F,V,H>(K, N, max_iter, frozen_bits, n_frames, name) { } template <typename B, typename R, tools::proto_i<R> I, tools::proto_f<R> F, tools::proto_v<R> V, tools::proto_h<B,R> H> Decoder_polar_SCAN_naive_sys<B,R,I,F,V,H> ::~Decoder_polar_SCAN_naive_sys() { } template <typename B, typename R, tools::proto_i<R> I, tools::proto_f<R> F, tools::proto_v<R> V, tools::proto_h<B,R> H> void Decoder_polar_SCAN_naive_sys<B,R,I,F,V,H> ::_soft_decode(const R *sys, const R *par, R *ext, const int frame_id) { // ----------------------------------------------------------------------------------------------------------- LOAD this->_load_init(); // init the softGraph (special case for the right most stage) auto sys_idx = 0, par_idx = 0; for (auto i = 0; i < this->N; i++) if (!this->frozen_bits[i]) this->soft_graph[this->layers_count - 1][i] = sys[sys_idx++]; else this->soft_graph[this->layers_count - 1][i] = par[par_idx++]; // --------------------------------------------------------------------------------------------------------- DECODE Decoder_polar_SCAN_naive<B,R,I,F,V,H>::_decode(); // ---------------------------------------------------------------------------------------------------------- STORE sys_idx = 0; for (auto i = 0; i < this->N; i++) if (!this->frozen_bits[i]) // if "i" is NOT a frozen bit (information bit = sytematic bit) ext[sys_idx++] = this->feedback_graph[this->layers_count -1][i]; } template <typename B, typename R, tools::proto_i<R> I, tools::proto_f<R> F, tools::proto_v<R> V, tools::proto_h<B,R> H> void Decoder_polar_SCAN_naive_sys<B,R,I,F,V,H> ::_soft_decode(const R *Y_N1, R *Y_N2, const int frame_id) { // ----------------------------------------------------------------------------------------------------------- LOAD this->_load(Y_N1); // --------------------------------------------------------------------------------------------------------- DECODE Decoder_polar_SCAN_naive<B,R,I,F,V,H>::_decode(); // ---------------------------------------------------------------------------------------------------------- STORE for (auto i = 0; i < this->N; i++) Y_N2[i] = this->feedback_graph[this->layers_count -1][i]; } template <typename B, typename R, tools::proto_i<R> I, tools::proto_f<R> F, tools::proto_v<R> V, tools::proto_h<B,R> H> void Decoder_polar_SCAN_naive_sys<B,R,I,F,V,H> ::_store(B *V_N) const { auto k = 0; for (auto i = 0; i < this->N; i++) { if (!this->frozen_bits[i]) // if i is not a frozen bit V_N[k++] = (H(this->feedback_graph[this->layers_count -1][i] + this->soft_graph[this->layers_count -1][i]) == 0) ? (B)0 : (B)1; } } } } <|endoftext|>
<commit_before>/** * Author: derselbst * Description: provides functions that are used by the worker processes to check whether a bruteforced string generated by the master process matches pwdHash */ #include <iostream> #include <cstring> // memcmp() #include <string> #include <queue> #include <limits> #include <iomanip> #include <openssl/sha.h> #include <byteswap.h> #include <mpi.h> using namespace std; #include "worker.h" #include "master.h" #include "alphabet.h" // contains the hash of the unknown password char pwdHash[SHA256_DIGEST_LENGTH]; // contains the hash of a bruteforced string char bruteHash[SHA256_DIGEST_LENGTH]; // used when sending messages enum MpiMsgTag { task, success // hashes match, unused ATM }; /** * @brief prints 32 bytes of memory * * prints a hex dump of 32 bytes of memory pointed to * * @param[in] pbuf: pointer to some memory, usually containing an SHA256 hash */ void printSHAHash(const unsigned int *const pbuf) { // byteswap the integer pointed to, to display hex dump in correct order // TODO: how to deal with big endian machines cout << std::hex << std::uppercase << setw(8) << setfill('0') << bswap_32(*(pbuf)) << bswap_32(*(pbuf+1)) << bswap_32(*(pbuf+2)) << bswap_32(*(pbuf+3)) << bswap_32(*(pbuf+4)) << bswap_32(*(pbuf+5)) << bswap_32(*(pbuf+6)) << bswap_32(*(pbuf+7)) << endl; } /** * @brief generates an SHA256 hash * * generates an SHA256 hash using openSSL * * @param[in] input: a const pointer to const block of data, usually a char array of which the hash is being generated * @param[in] length: the number of bytes the that input points to holds * @param[in,out] hashStr: const pointer to an array of SHA256_DIGEST_LENGTH bytes that will receive the hash * * @return returns true if the hash has been generated successfully; returns false if input or hashStr is NULL or length==0; else: false */ bool generateSHA256(const void *const input, const size_t &length, char *const hashStr) { if(!hashStr || !input || length==0) { return false; } SHA256_CTX hash; if(!SHA256_Init(&hash)) { return false; } if(!SHA256_Update(&hash, input, length)) { return false; } if(!SHA256_Final(reinterpret_cast<unsigned char*>(hashStr), &hash)) { return false; } return true; } /** * @brief checks equality of two hashes * * calculates the SHA256 hash of 'password' and compares it * with the initial password hash * * @param[in] password: a const string containing a guessed password * * @return returns true if hashes match; false if generation of hash failed or hashes not match */ bool checkPassword(const string &password) { #ifdef VERBOSE cout << "checking " << password << endl; #endif // VERBOSE // generate sha hash from entered string and write it to pwdHash if(!generateSHA256(password.c_str(), password.length(), bruteHash)) { cerr << "Error when generating SHA256 from \"" << password << "\"" << endl; return false; } if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH)) { cout << "match [" << password << "]" << endl << "hash: " << endl; printSHAHash((unsigned int*)bruteHash); return true; } return false; } /** * @brief the main loop for a worker process * * continuously looks for incoming strings, generates the SHA * hash of it and checks if it matches the secret hash */ void worker() { char buf[MaxChars]; MPI_Status state; while(true) { // check for new msg MPI_Probe(MasterProcess, task, MPI_COMM_WORLD, &state); int len; // now check status to determine how many bytes were actually received MPI_Get_count(&state, MPI_BYTE, &len); // receive len bytes MPI_Recv(buf, len, MPI_BYTE, MasterProcess, task, MPI_COMM_WORLD, &state); string baseStr(buf, len); for(int i=0; i<SizeAlphabet; i++) { if(checkPassword(baseStr+alphabet[i])) { //success, tell master //MPI_Send(const_cast<char*>(baseStr+alphabet[i].c_str()), baseStr+alphabet[i].length(), MPI_CHAR, MasterProcess, success, MPI_COMM_WORLD); cout << "Password found: " << baseStr+alphabet[i] << endl; MPI_Abort(MPI_COMM_WORLD, 0); break; } } } } <commit_msg>receive MPI_ANY_TAG<commit_after>/** * Author: derselbst * Description: provides functions that are used by the worker processes to check whether a bruteforced string generated by the master process matches pwdHash */ #include <iostream> #include <cstring> // memcmp() #include <string> #include <queue> #include <limits> #include <iomanip> #include <openssl/sha.h> #include <byteswap.h> #include <mpi.h> using namespace std; #include "worker.h" #include "master.h" #include "alphabet.h" // contains the hash of the unknown password char pwdHash[SHA256_DIGEST_LENGTH]; // contains the hash of a bruteforced string char bruteHash[SHA256_DIGEST_LENGTH]; // used when sending messages enum MpiMsgTag { task, success // hashes match, unused ATM }; /** * @brief prints 32 bytes of memory * * prints a hex dump of 32 bytes of memory pointed to * * @param[in] pbuf: pointer to some memory, usually containing an SHA256 hash */ void printSHAHash(const unsigned int *const pbuf) { // byteswap the integer pointed to, to display hex dump in correct order // TODO: how to deal with big endian machines cout << std::hex << std::uppercase << setw(8) << setfill('0') << bswap_32(*(pbuf)) << bswap_32(*(pbuf+1)) << bswap_32(*(pbuf+2)) << bswap_32(*(pbuf+3)) << bswap_32(*(pbuf+4)) << bswap_32(*(pbuf+5)) << bswap_32(*(pbuf+6)) << bswap_32(*(pbuf+7)) << endl; } /** * @brief generates an SHA256 hash * * generates an SHA256 hash using openSSL * * @param[in] input: a const pointer to const block of data, usually a char array of which the hash is being generated * @param[in] length: the number of bytes the that input points to holds * @param[in,out] hashStr: const pointer to an array of SHA256_DIGEST_LENGTH bytes that will receive the hash * * @return returns true if the hash has been generated successfully; returns false if input or hashStr is NULL or length==0; else: false */ bool generateSHA256(const void *const input, const size_t &length, char *const hashStr) { if(!hashStr || !input || length==0) { return false; } SHA256_CTX hash; if(!SHA256_Init(&hash)) { return false; } if(!SHA256_Update(&hash, input, length)) { return false; } if(!SHA256_Final(reinterpret_cast<unsigned char*>(hashStr), &hash)) { return false; } return true; } /** * @brief checks equality of two hashes * * calculates the SHA256 hash of 'password' and compares it * with the initial password hash * * @param[in] password: a const string containing a guessed password * * @return returns true if hashes match; false if generation of hash failed or hashes not match */ bool checkPassword(const string &password) { #ifdef VERBOSE cout << "checking " << password << endl; #endif // VERBOSE // generate sha hash from entered string and write it to pwdHash if(!generateSHA256(password.c_str(), password.length(), bruteHash)) { cerr << "Error when generating SHA256 from \"" << password << "\"" << endl; return false; } if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH)) { cout << "match [" << password << "]" << endl << "hash: " << endl; printSHAHash((unsigned int*)bruteHash); return true; } return false; } /** * @brief the main loop for a worker process * * continuously looks for incoming strings, generates the SHA * hash of it and checks if it matches the secret hash */ void worker() { char buf[MaxChars]; MPI_Status state; while(true) { // check for new msg MPI_Probe(MasterProcess, MPI_ANY_TAG, MPI_COMM_WORLD, &state); int len; // now check status to determine how many bytes were actually received MPI_Get_count(&state, MPI_BYTE, &len); // receive len bytes MPI_Recv(buf, len, MPI_BYTE, MasterProcess, MPI_ANY_TAG, MPI_COMM_WORLD, &state); string baseStr(buf, len); for(int i=0; i<SizeAlphabet; i++) { if(checkPassword(baseStr+alphabet[i])) { //success, tell master //MPI_Send(const_cast<char*>(baseStr+alphabet[i].c_str()), baseStr+alphabet[i].length(), MPI_CHAR, MasterProcess, success, MPI_COMM_WORLD); cout << "Password found: " << baseStr+alphabet[i] << endl; MPI_Abort(MPI_COMM_WORLD, 0); break; } } } } <|endoftext|>
<commit_before><commit_msg>new macro for MC gen train, Pythia with shoving and flavour ropes<commit_after><|endoftext|>
<commit_before><commit_msg>Updated maximum histogram bucket for UseCountering of CSS properties.<commit_after><|endoftext|>
<commit_before>/** * @file head_finder.cpp * @author Chase Geigle */ #include <unordered_set> #include <vector> #include "logging/logger.h" #include "meta.h" #include "parser/trees/visitors/head_finder.h" #include "parser/trees/internal_node.h" #include "parser/trees/leaf_node.h" #include "util/optional.h" namespace meta { namespace parser { namespace { /** * A normal head rule following Collins' head finding algorithm. */ struct normal_head_rule : public head_rule { template <class... Args> normal_head_rule(Args&&... args) : candidates_{{std::forward<Args>(args)...}} { // nothing } std::vector<class_label> candidates_; }; /** * A head rule that starts its search from the leftmost child. */ struct head_initial : public normal_head_rule { using normal_head_rule::normal_head_rule; uint64_t find_head(const internal_node& inode) const override { for (const auto& cand : candidates_) { for (uint64_t idx = 0; idx < inode.num_children(); ++idx) { auto child = inode.child(idx); if (child->category() == cand) return idx; } } // no matches, use left most node return 0; } }; /** * A head rule that starts its search from the rightmost child. */ struct head_final : public normal_head_rule { using normal_head_rule::normal_head_rule; uint64_t find_head(const internal_node& inode) const override { for (const auto& cand : candidates_) { for (uint64_t idx = 0; idx < inode.num_children(); ++idx) { // iterate in reverse, from right to left auto ridx = inode.num_children() - 1 - idx; auto child = inode.child(ridx); if (child->category() == cand) return ridx; } } // no matches, use right most node return inode.num_children() - 1; } }; /** * The special case for noun phrases in Collins' head finding algorithm. * @see Collins' thesis, page 238-239 */ struct head_np : public head_rule { struct head_final_np { std::unordered_set<class_label> candidates_; util::optional<uint64_t> find_head(const internal_node& inode) const { for (uint64_t idx = 0; idx < inode.num_children(); ++idx) { auto ridx = inode.num_children() - 1 - idx; auto child = inode.child(ridx); if (candidates_.find(child->category()) != candidates_.end()) return {ridx}; } return util::nullopt; } }; struct head_initial_np { std::unordered_set<class_label> candidates_; util::optional<uint64_t> find_head(const internal_node& inode) const { for (uint64_t idx = 0; idx < inode.num_children(); ++idx) { auto child = inode.child(idx); if (candidates_.find(child->category()) != candidates_.end()) return {idx}; } return util::nullopt; } }; uint64_t find_head(const internal_node& inode) const override { head_final_np first_pass{{"NN"_cl, "NNP"_cl, "NNPS"_cl, "NNS"_cl, "NX"_cl, "POS"_cl, "JJR"_cl}}; if (auto idx = first_pass.find_head(inode)) return *idx; head_initial_np second_pass{{"NP"_cl}}; if (auto idx = second_pass.find_head(inode)) return *idx; head_final_np third_pass{{"$"_cl, "ADJP"_cl, "PRN"_cl}}; if (auto idx = third_pass.find_head(inode)) return *idx; head_final_np fourth_pass{{"CD"_cl}}; if (auto idx = fourth_pass.find_head(inode)) return *idx; head_final_np fifth_pass{{"JJ"_cl, "JJS"_cl, "RB"_cl, "QP"_cl}}; if (auto idx = fifth_pass.find_head(inode)) return *idx; // no matches, just use last child return inode.num_children() - 1; } }; } head_finder::head_finder() { /// @see: http://www.cs.columbia.edu/~mcollins/papers/heads /// @see Collins' thesis, page 240 rules_["ADJP"_cl] = make_unique<head_initial>( "NNS"_cl, "QP"_cl, "NN"_cl, "$"_cl, "ADVP"_cl, "JJ"_cl, "VBN"_cl, "VBG"_cl, "ADJP"_cl, "JJR"_cl, "NP"_cl, "JJS"_cl, "DT"_cl, "FW"_cl, "RBR"_cl, "RBS"_cl, "SBAR"_cl, "RB"_cl); rules_["ADVP"_cl] = make_unique<head_final>( "RB"_cl, "RBR"_cl, "RBS"_cl, "FW"_cl, "ADVP"_cl, "TO"_cl, "CD"_cl, "JJR"_cl, "JJ"_cl, "IN"_cl, "NP"_cl, "JJS"_cl, "NN"_cl); rules_["CONJP"_cl] = make_unique<head_final>("CC"_cl, "RB"_cl, "IN"_cl); rules_["FRAG"_cl] = make_unique<head_final>(); rules_["INTJ"_cl] = make_unique<head_initial>(); rules_["LST"_cl] = make_unique<head_final>("LS"_cl, ":"_cl); rules_["NAC"_cl] = make_unique<head_initial>( "NN"_cl, "NNS"_cl, "NNP"_cl, "NNPS"_cl, "NP"_cl, "NAC"_cl, "EX"_cl, "$"_cl, "CD"_cl, "QP"_cl, "PRP"_cl, "VBG"_cl, "JJ"_cl, "JJS"_cl, "JJR"_cl, "ADJP"_cl, "FW"_cl); rules_["PP"_cl] = make_unique<head_final>("IN"_cl, "TO"_cl, "VBG"_cl, "VBN"_cl, "RP"_cl, "FW"_cl); rules_["PRN"_cl] = make_unique<head_initial>(); rules_["PRT"_cl] = make_unique<head_final>("RP"_cl); rules_["QP"_cl] = make_unique<head_initial>( "$"_cl, "IN"_cl, "NNS"_cl, "NN"_cl, "JJ"_cl, "RB"_cl, "DT"_cl, "CD"_cl, "NCD"_cl, "QP"_cl, "JJR"_cl, "JJS"_cl); rules_["RRC"_cl] = make_unique<head_final>("VP"_cl, "NP"_cl, "ADVP"_cl, "ADJP"_cl, "PP"_cl); rules_["S"_cl] = make_unique<head_initial>("TO"_cl, "IN"_cl, "VP"_cl, "S"_cl, "SBAR"_cl, "ADJP"_cl, "UCP"_cl, "NP"_cl); rules_["SBAR"_cl] = make_unique<head_initial>( "WHNP"_cl, "WHPP"_cl, "WHADVP"_cl, "WHADJP"_cl, "IN"_cl, "DT"_cl, "S"_cl, "SQ"_cl, "SINV"_cl, "SBAR"_cl, "FRAG"_cl); rules_["SBARQ"_cl] = make_unique<head_initial>("SQ"_cl, "S"_cl, "SINV"_cl, "SBARQ"_cl, "FRAG"_cl); rules_["SINV"_cl] = make_unique<head_initial>( "VBZ"_cl, "VBD"_cl, "VBP"_cl, "VB"_cl, "MD"_cl, "VP"_cl, "S"_cl, "SINV"_cl, "ADJP"_cl, "NP"_cl); rules_["SQ"_cl] = make_unique<head_initial>( "VBZ"_cl, "VBD"_cl, "VBP"_cl, "VB"_cl, "MD"_cl, "VP"_cl, "SQ"_cl); rules_["UCP"_cl] = make_unique<head_final>(); rules_["VP"_cl] = make_unique<head_initial>( "TO"_cl, "VBD"_cl, "VBN"_cl, "MD"_cl, "VBZ"_cl, "VB"_cl, "VBG"_cl, "VBP"_cl, "VP"_cl, "ADJP"_cl, "NN"_cl, "NNS"_cl, "NP"_cl); rules_["WHADJP"_cl] = make_unique<head_initial>("CC"_cl, "WRB"_cl, "JJ"_cl, "ADJP"_cl); rules_["WHADVP"_cl] = make_unique<head_final>("CC"_cl, "WRB"_cl); rules_["WHNP"_cl] = make_unique<head_initial>( "WDT"_cl, "WP"_cl, "WP$"_cl, "WHADJP"_cl, "WHPP"_cl, "WHNP"_cl); rules_["WHPP"_cl] = make_unique<head_final>("IN"_cl, "TO"_cl, "FW"_cl); rules_["NP"_cl] = make_unique<head_np>(); rules_["NX"_cl] = make_unique<head_initial>(); // not present in collins' thesis... rules_["X"_cl] = make_unique<head_final>(); // not present in collins' thesis... rules_["ROOT"_cl] = make_unique<head_initial>(); } head_finder::head_finder(rule_table&& table) : rules_{std::move(table)} { // nothing } void head_finder::operator()(leaf_node&) { // head annotations are only populated for internal nodes; leaf nodes // are the trivial case return; } void head_finder::operator()(internal_node& inode) { // recurse, as we need the head annotations of all child nodes first inode.each_child([&](node* child) { child->accept(*this); }); if (rules_.find(inode.category()) == rules_.end()) LOG(fatal) << "No rule found for category " << inode.category() << " in rule table" << ENDLG; // run the head finder for the syntactic category of the current node auto idx = rules_.at(inode.category())->find_head(inode); inode.head(inode.child(idx)); // clean up stage for handling coordinating clauses if (idx > 1 && inode.child(idx - 1)->category() == class_label{"CC"}) inode.head(inode.child(idx - 2)); } } } <commit_msg>Appease the compilers when in release mode.<commit_after>/** * @file head_finder.cpp * @author Chase Geigle */ #include <unordered_set> #include <vector> #include "logging/logger.h" #include "meta.h" #include "parser/trees/visitors/head_finder.h" #include "parser/trees/internal_node.h" #include "parser/trees/leaf_node.h" #include "util/optional.h" namespace meta { namespace parser { namespace { /** * A normal head rule following Collins' head finding algorithm. */ struct normal_head_rule : public head_rule { template <class... Args> normal_head_rule(Args&&... args) : candidates_({std::forward<Args>(args)...}) { // nothing } std::vector<class_label> candidates_; }; /** * A head rule that starts its search from the leftmost child. */ struct head_initial : public normal_head_rule { using normal_head_rule::normal_head_rule; uint64_t find_head(const internal_node& inode) const override { for (const auto& cand : candidates_) { for (uint64_t idx = 0; idx < inode.num_children(); ++idx) { auto child = inode.child(idx); if (child->category() == cand) return idx; } } // no matches, use left most node return 0; } }; /** * A head rule that starts its search from the rightmost child. */ struct head_final : public normal_head_rule { using normal_head_rule::normal_head_rule; uint64_t find_head(const internal_node& inode) const override { for (const auto& cand : candidates_) { for (uint64_t idx = 0; idx < inode.num_children(); ++idx) { // iterate in reverse, from right to left auto ridx = inode.num_children() - 1 - idx; auto child = inode.child(ridx); if (child->category() == cand) return ridx; } } // no matches, use right most node return inode.num_children() - 1; } }; /** * The special case for noun phrases in Collins' head finding algorithm. * @see Collins' thesis, page 238-239 */ struct head_np : public head_rule { struct head_final_np { std::unordered_set<class_label> candidates_; util::optional<uint64_t> find_head(const internal_node& inode) const { for (uint64_t idx = 0; idx < inode.num_children(); ++idx) { auto ridx = inode.num_children() - 1 - idx; auto child = inode.child(ridx); if (candidates_.find(child->category()) != candidates_.end()) return {ridx}; } return util::nullopt; } }; struct head_initial_np { std::unordered_set<class_label> candidates_; util::optional<uint64_t> find_head(const internal_node& inode) const { for (uint64_t idx = 0; idx < inode.num_children(); ++idx) { auto child = inode.child(idx); if (candidates_.find(child->category()) != candidates_.end()) return {idx}; } return util::nullopt; } }; uint64_t find_head(const internal_node& inode) const override { head_final_np first_pass{{"NN"_cl, "NNP"_cl, "NNPS"_cl, "NNS"_cl, "NX"_cl, "POS"_cl, "JJR"_cl}}; if (auto idx = first_pass.find_head(inode)) return *idx; head_initial_np second_pass{{"NP"_cl}}; if (auto idx = second_pass.find_head(inode)) return *idx; head_final_np third_pass{{"$"_cl, "ADJP"_cl, "PRN"_cl}}; if (auto idx = third_pass.find_head(inode)) return *idx; head_final_np fourth_pass{{"CD"_cl}}; if (auto idx = fourth_pass.find_head(inode)) return *idx; head_final_np fifth_pass{{"JJ"_cl, "JJS"_cl, "RB"_cl, "QP"_cl}}; if (auto idx = fifth_pass.find_head(inode)) return *idx; // no matches, just use last child return inode.num_children() - 1; } }; } head_finder::head_finder() { /// @see: http://www.cs.columbia.edu/~mcollins/papers/heads /// @see Collins' thesis, page 240 rules_["ADJP"_cl] = make_unique<head_initial>( "NNS"_cl, "QP"_cl, "NN"_cl, "$"_cl, "ADVP"_cl, "JJ"_cl, "VBN"_cl, "VBG"_cl, "ADJP"_cl, "JJR"_cl, "NP"_cl, "JJS"_cl, "DT"_cl, "FW"_cl, "RBR"_cl, "RBS"_cl, "SBAR"_cl, "RB"_cl); rules_["ADVP"_cl] = make_unique<head_final>( "RB"_cl, "RBR"_cl, "RBS"_cl, "FW"_cl, "ADVP"_cl, "TO"_cl, "CD"_cl, "JJR"_cl, "JJ"_cl, "IN"_cl, "NP"_cl, "JJS"_cl, "NN"_cl); rules_["CONJP"_cl] = make_unique<head_final>("CC"_cl, "RB"_cl, "IN"_cl); rules_["FRAG"_cl] = make_unique<head_final>(); rules_["INTJ"_cl] = make_unique<head_initial>(); rules_["LST"_cl] = make_unique<head_final>("LS"_cl, ":"_cl); rules_["NAC"_cl] = make_unique<head_initial>( "NN"_cl, "NNS"_cl, "NNP"_cl, "NNPS"_cl, "NP"_cl, "NAC"_cl, "EX"_cl, "$"_cl, "CD"_cl, "QP"_cl, "PRP"_cl, "VBG"_cl, "JJ"_cl, "JJS"_cl, "JJR"_cl, "ADJP"_cl, "FW"_cl); rules_["PP"_cl] = make_unique<head_final>("IN"_cl, "TO"_cl, "VBG"_cl, "VBN"_cl, "RP"_cl, "FW"_cl); rules_["PRN"_cl] = make_unique<head_initial>(); rules_["PRT"_cl] = make_unique<head_final>("RP"_cl); rules_["QP"_cl] = make_unique<head_initial>( "$"_cl, "IN"_cl, "NNS"_cl, "NN"_cl, "JJ"_cl, "RB"_cl, "DT"_cl, "CD"_cl, "NCD"_cl, "QP"_cl, "JJR"_cl, "JJS"_cl); rules_["RRC"_cl] = make_unique<head_final>("VP"_cl, "NP"_cl, "ADVP"_cl, "ADJP"_cl, "PP"_cl); rules_["S"_cl] = make_unique<head_initial>("TO"_cl, "IN"_cl, "VP"_cl, "S"_cl, "SBAR"_cl, "ADJP"_cl, "UCP"_cl, "NP"_cl); rules_["SBAR"_cl] = make_unique<head_initial>( "WHNP"_cl, "WHPP"_cl, "WHADVP"_cl, "WHADJP"_cl, "IN"_cl, "DT"_cl, "S"_cl, "SQ"_cl, "SINV"_cl, "SBAR"_cl, "FRAG"_cl); rules_["SBARQ"_cl] = make_unique<head_initial>("SQ"_cl, "S"_cl, "SINV"_cl, "SBARQ"_cl, "FRAG"_cl); rules_["SINV"_cl] = make_unique<head_initial>( "VBZ"_cl, "VBD"_cl, "VBP"_cl, "VB"_cl, "MD"_cl, "VP"_cl, "S"_cl, "SINV"_cl, "ADJP"_cl, "NP"_cl); rules_["SQ"_cl] = make_unique<head_initial>( "VBZ"_cl, "VBD"_cl, "VBP"_cl, "VB"_cl, "MD"_cl, "VP"_cl, "SQ"_cl); rules_["UCP"_cl] = make_unique<head_final>(); rules_["VP"_cl] = make_unique<head_initial>( "TO"_cl, "VBD"_cl, "VBN"_cl, "MD"_cl, "VBZ"_cl, "VB"_cl, "VBG"_cl, "VBP"_cl, "VP"_cl, "ADJP"_cl, "NN"_cl, "NNS"_cl, "NP"_cl); rules_["WHADJP"_cl] = make_unique<head_initial>("CC"_cl, "WRB"_cl, "JJ"_cl, "ADJP"_cl); rules_["WHADVP"_cl] = make_unique<head_final>("CC"_cl, "WRB"_cl); rules_["WHNP"_cl] = make_unique<head_initial>( "WDT"_cl, "WP"_cl, "WP$"_cl, "WHADJP"_cl, "WHPP"_cl, "WHNP"_cl); rules_["WHPP"_cl] = make_unique<head_final>("IN"_cl, "TO"_cl, "FW"_cl); rules_["NP"_cl] = make_unique<head_np>(); rules_["NX"_cl] = make_unique<head_initial>(); // not present in collins' thesis... rules_["X"_cl] = make_unique<head_final>(); // not present in collins' thesis... rules_["ROOT"_cl] = make_unique<head_initial>(); } head_finder::head_finder(rule_table&& table) : rules_{std::move(table)} { // nothing } void head_finder::operator()(leaf_node&) { // head annotations are only populated for internal nodes; leaf nodes // are the trivial case return; } void head_finder::operator()(internal_node& inode) { // recurse, as we need the head annotations of all child nodes first inode.each_child([&](node* child) { child->accept(*this); }); if (rules_.find(inode.category()) == rules_.end()) LOG(fatal) << "No rule found for category " << inode.category() << " in rule table" << ENDLG; // run the head finder for the syntactic category of the current node auto idx = rules_.at(inode.category())->find_head(inode); inode.head(inode.child(idx)); // clean up stage for handling coordinating clauses if (idx > 1 && inode.child(idx - 1)->category() == class_label{"CC"}) inode.head(inode.child(idx - 2)); } } } <|endoftext|>
<commit_before>/* * This file is part of the UnTech Editor Suite. * Copyright (c) 2016 - 2018, Marcus Rowe <[email protected]>. * Distributed under The MIT License: https://opensource.org/licenses/MIT */ #pragma once #include "models/common/vectorset.h" #include "models/metasprite/metasprite.h" #include "models/metasprite/spriteimporter.h" #include <cstring> #include <iomanip> #include <map> #include <sstream> #include <stdexcept> namespace UnTech { namespace MetaSprite { namespace Utsi2UtmsPrivate { namespace MS = UnTech::MetaSprite::MetaSprite; namespace SI = UnTech::MetaSprite::SpriteImporter; class PaletteConverter { const SI::FrameSet& siFrameSet; const Image& image; MS::FrameSet& msFrameSet; ErrorList& errorList; // Faster than std::unordered_map, only contains a max of 16 elements std::map<rgba, unsigned> _colorMap; public: PaletteConverter(const SI::FrameSet& siFrameSet, const Image& image, MS::FrameSet& msFrameSet, ErrorList& errorList) : siFrameSet(siFrameSet) , image(image) , msFrameSet(msFrameSet) , errorList(errorList) , _colorMap() { } const auto& colorMap() const { return _colorMap; } void process() { try { if (siFrameSet.palette.usesUserSuppliedPalette()) { buildUserSuppliedPalettes(); } else { buildAutomaticPalette(); } } catch (const std::exception& ex) { errorList.addError(siFrameSet, ex.what()); } } private: vectorset<rgba> getColorsFromImage() const { assert(image.empty() == false); vectorset<rgba> colors; for (const auto& siFrameIt : siFrameSet.frames) { const SI::Frame& siFrame = siFrameIt.second; for (const SI::FrameObject& obj : siFrame.objects) { unsigned lx = siFrame.location.aabb.x + obj.location.x; unsigned ly = siFrame.location.aabb.y + obj.location.y; for (unsigned y = 0; y < obj.sizePx(); y++) { const rgba* p = image.scanline(ly + y) + lx; for (unsigned x = 0; x < obj.sizePx(); x++) { colors.insert(*p++); } } if (colors.size() > (PALETTE_COLORS)) { throw std::runtime_error("Too many colors, expected a max of 16"); } } } // remove transparent from colors list auto tIt = colors.find(siFrameSet.transparentColor); if (tIt != colors.end()) { colors.erase(tIt); } else { errorList.addWarning(siFrameSet, "Transparent color is not in frame objects"); } return colors; } inline void buildUserSuppliedPalettes() { validateUserSuppliedPalettes(); const unsigned colorSize = siFrameSet.palette.colorSize; for (unsigned pal = 0; pal < siFrameSet.palette.nPalettes; pal++) { const unsigned yPos = image.size().height - pal * colorSize - 1; msFrameSet.palettes.emplace_back(); Snes::Palette4bpp& palette = msFrameSet.palettes.back(); for (unsigned i = 0; i < PALETTE_COLORS; i++) { const rgba c = image.getPixel(i * colorSize, yPos); palette.color(i).setRgb(c); if (pal == 0) { _colorMap.insert({ c, i }); } } } } inline void validateUserSuppliedPalettes() const { const usize imageSize = image.size(); const usize paletteSize = siFrameSet.palette.paletteSize(); if (imageSize.width < paletteSize.width || imageSize.height < paletteSize.height) { throw std::runtime_error("Cannot load custom palette, image is too small"); } for (unsigned pal = 0; pal < siFrameSet.palette.nPalettes; pal++) { validateUserSuppliedPalette(pal); } validateFirstUserSuppliedPalette(); } inline void validateUserSuppliedPalette(unsigned pal) const { const unsigned colorSize = siFrameSet.palette.colorSize; const unsigned yPos = image.size().height - pal * colorSize - 1; const rgba* scanline = image.scanline(yPos); // ensure the scanlines of the palette equal for (unsigned l = 1; l < colorSize; l++) { const rgba* linetoTest = image.scanline(yPos - l); if (std::memcmp(scanline, linetoTest, sizeof(rgba) * colorSize * PALETTE_COLORS) != 0) { throw std::runtime_error("Custom Palette is invalid A"); } } // ensure each of the palette colors are equally colored squares for (unsigned c = 0; c < PALETTE_COLORS; c++) { const rgba* imgBits = scanline + c * colorSize; for (unsigned i = 1; i < colorSize; i++) { if (imgBits[0] != imgBits[i]) { throw std::runtime_error("Custom Palette is invalid"); } } } // ensure first color is transparent if (scanline[0] != siFrameSet.transparentColor) { throw std::runtime_error("First color of custom palette " + std::to_string(pal) + " is not the transparent color"); } } inline void validateFirstUserSuppliedPalette() const { const unsigned colorSize = siFrameSet.palette.colorSize; vectorset<rgba> colorSet = getColorsFromImage(); const rgba* scanline = image.scanline(image.size().height - 1); for (unsigned i = 0; i < PALETTE_COLORS; i++) { const rgba c = scanline[i * colorSize]; colorSet.erase(c); } if (colorSet.size() > 0) { std::stringstream out; out << "Palette 0 is invalid (missing"; for (const rgba& c : colorSet) { out << " " << std::hex << std::setfill('0') << std::setw(6) << c.rgb(); } out << ")"; throw std::runtime_error(out.str()); } } inline void buildAutomaticPalette() { vectorset<rgba> colors = getColorsFromImage(); assert(colors.size() <= PALETTE_COLORS - 1); // Store palette in MetaSprite msFrameSet.palettes.emplace_back(); Snes::Palette4bpp& palette = msFrameSet.palettes.back(); _colorMap.insert({ siFrameSet.transparentColor, 0 }); palette.color(0).setRgb(siFrameSet.transparentColor); int i = 1; for (auto& c : colors) { _colorMap.insert({ c, i }); palette.color(i).setRgb(c); i++; } } }; } } } <commit_msg>Fix crash in utsi2utms palette converter<commit_after>/* * This file is part of the UnTech Editor Suite. * Copyright (c) 2016 - 2018, Marcus Rowe <[email protected]>. * Distributed under The MIT License: https://opensource.org/licenses/MIT */ #pragma once #include "models/common/vectorset.h" #include "models/metasprite/metasprite.h" #include "models/metasprite/spriteimporter.h" #include <cstring> #include <iomanip> #include <map> #include <sstream> #include <stdexcept> namespace UnTech { namespace MetaSprite { namespace Utsi2UtmsPrivate { namespace MS = UnTech::MetaSprite::MetaSprite; namespace SI = UnTech::MetaSprite::SpriteImporter; class PaletteConverter { const SI::FrameSet& siFrameSet; const Image& image; MS::FrameSet& msFrameSet; ErrorList& errorList; // Faster than std::unordered_map, only contains a max of 16 elements std::map<rgba, unsigned> _colorMap; public: PaletteConverter(const SI::FrameSet& siFrameSet, const Image& image, MS::FrameSet& msFrameSet, ErrorList& errorList) : siFrameSet(siFrameSet) , image(image) , msFrameSet(msFrameSet) , errorList(errorList) , _colorMap() { } const auto& colorMap() const { return _colorMap; } void process() { try { if (siFrameSet.palette.usesUserSuppliedPalette()) { buildUserSuppliedPalettes(); } else { buildAutomaticPalette(); } } catch (const std::exception& ex) { errorList.addError(siFrameSet, ex.what()); } } private: vectorset<rgba> getColorsFromImage() const { assert(image.empty() == false); vectorset<rgba> colors; for (const auto& siFrameIt : siFrameSet.frames) { const SI::Frame& siFrame = siFrameIt.second; for (const SI::FrameObject& obj : siFrame.objects) { unsigned lx = siFrame.location.aabb.x + obj.location.x; unsigned ly = siFrame.location.aabb.y + obj.location.y; for (unsigned y = 0; y < obj.sizePx(); y++) { const rgba* p = image.scanline(ly + y) + lx; for (unsigned x = 0; x < obj.sizePx(); x++) { const bool newColor = colors.insert(*p++); if (newColor) { if (colors.size() > PALETTE_COLORS) { throw std::runtime_error("Too many colors, expected a maximum of 16 colors"); } } } } } } // remove transparent from colors list auto tIt = colors.find(siFrameSet.transparentColor); if (tIt != colors.end()) { colors.erase(tIt); } else { errorList.addWarning(siFrameSet, "Transparent color is not in frame objects"); if (colors.size() > (PALETTE_COLORS - 1)) { throw std::runtime_error("Too many colors, expected a maximum of 15 colors after removing transparency"); } } return colors; } inline void buildUserSuppliedPalettes() { validateUserSuppliedPalettes(); const unsigned colorSize = siFrameSet.palette.colorSize; for (unsigned pal = 0; pal < siFrameSet.palette.nPalettes; pal++) { const unsigned yPos = image.size().height - pal * colorSize - 1; msFrameSet.palettes.emplace_back(); Snes::Palette4bpp& palette = msFrameSet.palettes.back(); for (unsigned i = 0; i < PALETTE_COLORS; i++) { const rgba c = image.getPixel(i * colorSize, yPos); palette.color(i).setRgb(c); if (pal == 0) { _colorMap.insert({ c, i }); } } } } inline void validateUserSuppliedPalettes() const { const usize imageSize = image.size(); const usize paletteSize = siFrameSet.palette.paletteSize(); if (imageSize.width < paletteSize.width || imageSize.height < paletteSize.height) { throw std::runtime_error("Cannot load custom palette, image is too small"); } for (unsigned pal = 0; pal < siFrameSet.palette.nPalettes; pal++) { validateUserSuppliedPalette(pal); } validateFirstUserSuppliedPalette(); } inline void validateUserSuppliedPalette(unsigned pal) const { const unsigned colorSize = siFrameSet.palette.colorSize; const unsigned yPos = image.size().height - pal * colorSize - 1; const rgba* scanline = image.scanline(yPos); // ensure the scanlines of the palette equal for (unsigned l = 1; l < colorSize; l++) { const rgba* linetoTest = image.scanline(yPos - l); if (std::memcmp(scanline, linetoTest, sizeof(rgba) * colorSize * PALETTE_COLORS) != 0) { throw std::runtime_error("Custom Palette is invalid A"); } } // ensure each of the palette colors are equally colored squares for (unsigned c = 0; c < PALETTE_COLORS; c++) { const rgba* imgBits = scanline + c * colorSize; for (unsigned i = 1; i < colorSize; i++) { if (imgBits[0] != imgBits[i]) { throw std::runtime_error("Custom Palette is invalid"); } } } // ensure first color is transparent if (scanline[0] != siFrameSet.transparentColor) { throw std::runtime_error("First color of custom palette " + std::to_string(pal) + " is not the transparent color"); } } inline void validateFirstUserSuppliedPalette() const { const unsigned colorSize = siFrameSet.palette.colorSize; vectorset<rgba> colorSet = getColorsFromImage(); assert(colorSet.size() <= PALETTE_COLORS - 1); const rgba* scanline = image.scanline(image.size().height - 1); for (unsigned i = 0; i < PALETTE_COLORS; i++) { const rgba c = scanline[i * colorSize]; colorSet.erase(c); } if (colorSet.size() > 0) { std::stringstream out; out << "Palette 0 is invalid (missing"; for (const rgba& c : colorSet) { out << " " << std::hex << std::setfill('0') << std::setw(6) << c.rgb(); } out << ")"; throw std::runtime_error(out.str()); } } inline void buildAutomaticPalette() { vectorset<rgba> colors = getColorsFromImage(); assert(colors.size() <= PALETTE_COLORS - 1); // Store palette in MetaSprite msFrameSet.palettes.emplace_back(); Snes::Palette4bpp& palette = msFrameSet.palettes.back(); _colorMap.insert({ siFrameSet.transparentColor, 0 }); palette.color(0).setRgb(siFrameSet.transparentColor); int i = 1; for (auto& c : colors) { _colorMap.insert({ c, i }); palette.color(i).setRgb(c); i++; } } }; } } } <|endoftext|>
<commit_before>extern "C" { #include "halide_hexagon_remote.h" #include <sys/mman.h> #include <memory.h> #include <stdlib.h> #include <stdio.h> #define FARF_LOW 1 #include "HAP_farf.h" } #include "../HalideRuntime.h" void halide_print(void *user_context, const char *str) { FARF(LOW, "%s", str); } void halide_error(void *user_context, const char *str) { halide_print(user_context, str); } void *halide_malloc(void *user_context, size_t x) { // Allocate enough space for aligning the pointer we return. const size_t alignment = 128; void *orig = malloc(x + alignment); if (orig == NULL) { // Will result in a failed assertion and a call to halide_error return NULL; } // We want to store the original pointer prior to the pointer we return. void *ptr = (void *)(((size_t)orig + alignment + sizeof(void*) - 1) & ~(alignment - 1)); ((void **)ptr)[-1] = orig; return ptr; } void halide_free(void *user_context, void *ptr) { free(((void**)ptr)[-1]); } int halide_do_task(void *user_context, halide_task_t f, int idx, uint8_t *closure) { return f(user_context, idx, closure); } int halide_do_par_for(void *user_context, halide_task_t f, int min, int size, uint8_t *closure) { for (int x = min; x < min + size; x++) { int result = halide_do_task(user_context, f, x, closure); if (result) { return result; } } return 0; } static const int alignment = 4096; extern "C" { int halide_hexagon_remote_initialize_kernels(const unsigned char *code, int codeLen, int init_runtime_offset, halide_hexagon_remote_uintptr_t *module_ptr) { // Map some memory for the code and copy it in. int aligned_codeLen = (codeLen + alignment - 1) & ~(alignment - 1); void *executable = mmap(0, aligned_codeLen, PROT_READ | PROT_WRITE, MAP_ANON, -1, 0); if (executable == MAP_FAILED) { return -1; } memcpy(executable, code, codeLen); // Change memory to be executable (but not writable). if (mprotect(executable, aligned_codeLen, PROT_READ | PROT_EXEC) < 0) { munmap(executable, aligned_codeLen); return -1; } // Initialize the runtime. The Hexagon runtime can't call any // system functions (because we can't link them), so we put all // the implementations that need to do so here, and pass poiners // to them in here. typedef int (*init_runtime_t)(halide_malloc_t user_malloc, halide_free_t custom_free, halide_print_t print, halide_error_handler_t error_handler, halide_do_par_for_t do_par_for, halide_do_task_t do_task); init_runtime_t init_runtime = (init_runtime_t)((char *)executable + init_runtime_offset); int result = init_runtime(halide_malloc, halide_free, halide_print, halide_error, halide_do_par_for, halide_do_task); if (result != 0) { munmap(executable, aligned_codeLen); return result; } *module_ptr = (halide_hexagon_remote_uintptr_t)executable; return 0; } int halide_hexagon_remote_run(halide_hexagon_remote_uintptr_t module_ptr, int offset, const halide_hexagon_remote_buffer *arg_ptrs, int arg_ptrsLen, halide_hexagon_remote_buffer *outputs, int outputsLen) { // Get a pointer to the argv version of the pipeline. typedef int (*pipeline_argv_t)(void **); pipeline_argv_t pipeline = (pipeline_argv_t)(module_ptr + offset); // Construct a list of arguments. void **args = (void **)__builtin_alloca((arg_ptrsLen + outputsLen) * sizeof(void *)); for (int i = 0; i < arg_ptrsLen; i++) { args[i] = arg_ptrs[i].data; } for (int i = 0; i < outputsLen; i++) { args[i + arg_ptrsLen] = outputs[i].data; } // Call the pipeline and return the result. return pipeline(args); } int halide_hexagon_remote_release_kernels(halide_hexagon_remote_uintptr_t module_ptr, int codeLen) { void *executable = (void *)module_ptr; codeLen = (codeLen + alignment - 1) & (alignment - 1); munmap(executable, codeLen); return 0; } } // extern "C" <commit_msg>Reduced confusion between two alignment constants.<commit_after>extern "C" { #include "halide_hexagon_remote.h" #include <sys/mman.h> #include <memory.h> #include <stdlib.h> #include <stdio.h> #define FARF_LOW 1 #include "HAP_farf.h" } #include "../HalideRuntime.h" void halide_print(void *user_context, const char *str) { FARF(LOW, "%s", str); } void halide_error(void *user_context, const char *str) { halide_print(user_context, str); } void *halide_malloc(void *user_context, size_t x) { // Allocate enough space for aligning the pointer we return. const size_t alignment = 128; void *orig = malloc(x + alignment); if (orig == NULL) { // Will result in a failed assertion and a call to halide_error return NULL; } // We want to store the original pointer prior to the pointer we return. void *ptr = (void *)(((size_t)orig + alignment + sizeof(void*) - 1) & ~(alignment - 1)); ((void **)ptr)[-1] = orig; return ptr; } void halide_free(void *user_context, void *ptr) { free(((void**)ptr)[-1]); } int halide_do_task(void *user_context, halide_task_t f, int idx, uint8_t *closure) { return f(user_context, idx, closure); } int halide_do_par_for(void *user_context, halide_task_t f, int min, int size, uint8_t *closure) { for (int x = min; x < min + size; x++) { int result = halide_do_task(user_context, f, x, closure); if (result) { return result; } } return 0; } extern "C" { const int map_alignment = 4096; int halide_hexagon_remote_initialize_kernels(const unsigned char *code, int codeLen, int init_runtime_offset, halide_hexagon_remote_uintptr_t *module_ptr) { // Map some memory for the code and copy it in. int aligned_codeLen = (codeLen + map_alignment - 1) & ~(map_alignment - 1); void *executable = mmap(0, aligned_codeLen, PROT_READ | PROT_WRITE, MAP_ANON, -1, 0); if (executable == MAP_FAILED) { return -1; } memcpy(executable, code, codeLen); // Change memory to be executable (but not writable). if (mprotect(executable, aligned_codeLen, PROT_READ | PROT_EXEC) < 0) { munmap(executable, aligned_codeLen); return -1; } // Initialize the runtime. The Hexagon runtime can't call any // system functions (because we can't link them), so we put all // the implementations that need to do so here, and pass poiners // to them in here. typedef int (*init_runtime_t)(halide_malloc_t user_malloc, halide_free_t custom_free, halide_print_t print, halide_error_handler_t error_handler, halide_do_par_for_t do_par_for, halide_do_task_t do_task); init_runtime_t init_runtime = (init_runtime_t)((char *)executable + init_runtime_offset); int result = init_runtime(halide_malloc, halide_free, halide_print, halide_error, halide_do_par_for, halide_do_task); if (result != 0) { munmap(executable, aligned_codeLen); return result; } *module_ptr = (halide_hexagon_remote_uintptr_t)executable; return 0; } int halide_hexagon_remote_run(halide_hexagon_remote_uintptr_t module_ptr, int offset, const halide_hexagon_remote_buffer *arg_ptrs, int arg_ptrsLen, halide_hexagon_remote_buffer *outputs, int outputsLen) { // Get a pointer to the argv version of the pipeline. typedef int (*pipeline_argv_t)(void **); pipeline_argv_t pipeline = (pipeline_argv_t)(module_ptr + offset); // Construct a list of arguments. void **args = (void **)__builtin_alloca((arg_ptrsLen + outputsLen) * sizeof(void *)); for (int i = 0; i < arg_ptrsLen; i++) { args[i] = arg_ptrs[i].data; } for (int i = 0; i < outputsLen; i++) { args[i + arg_ptrsLen] = outputs[i].data; } // Call the pipeline and return the result. return pipeline(args); } int halide_hexagon_remote_release_kernels(halide_hexagon_remote_uintptr_t module_ptr, int codeLen) { void *executable = (void *)module_ptr; codeLen = (codeLen + map_alignment - 1) & (map_alignment - 1); munmap(executable, codeLen); return 0; } } // extern "C" <|endoftext|>
<commit_before> #include "yeseulWhitneyScene.h" void yeseulWhitneyScene::setup(){ setAuthor("Yeseul Song"); setOriginalArtist("John Whitney"); parameters.add(spinSpeed.set("spinSpeed", 10, 20, 70)); parameters.add(diffusionInterval.set("diffusionInterval", 5, 5, 10)); parameters.add(diffusionSize.set("diffusionSize", 1.3, 1, 3)); lastDiffusionTime = 0; integratedTime = 0; lastTime = 0; loadCode("scenes/yeseulWhitneyScene/exampleCode.cpp"); } void yeseulWhitneyScene::update(){ } void yeseulWhitneyScene::draw(){ ofPushMatrix(); ofTranslate(dimensions.width/2, dimensions.height/2); drawPattern(); diffusion(); ofPopMatrix(); } void yeseulWhitneyScene::drawPattern(){ ofSetColor(255); ofFill(); float now = getElapsedTimef(); if (lastTime == 0) { lastTime = now; } float dt = now - lastTime; lastTime = now; integratedTime += spinSpeed * dt; float k = integratedTime; for (int r=0; r<35; r+=1) { ofRotate(k*sin(r)); for (int a=0; a<20; a+=1) { ofRotate(360/20); ofDrawCircle(0, r*10, 1); } } } void yeseulWhitneyScene::diffusion() { float t = getElapsedTimef(); if (lastDiffusionTime == 0 || diffusionInterval <= t - lastDiffusionTime) { diffs.push_back(circlesDiffusion(t, diffusionSize)); cout << "add difff" << diffusionInterval << endl; lastDiffusionTime = t; } for(int i = 0; i < diffs.size(); i++){ if(diffs[i].bKill){ cout << "kill diff: " << i << endl; diffs.erase(diffs.begin() + i); i--; } } for(int i = 0; i < diffs.size(); i++){ diffs[i].draw(t); } } <commit_msg>Update yeseulWhitneyScene.cpp<commit_after> #include "yeseulWhitneyScene.h" void yeseulWhitneyScene::setup(){ setAuthor("Yeseul Song"); setOriginalArtist("John Whitney"); parameters.add(spinSpeed.set("spinSpeed", 10, 10, 70)); parameters.add(diffusionInterval.set("diffusionInterval", 5, 5, 10)); parameters.add(diffusionSize.set("diffusionSize", 1.3, 1, 3)); lastDiffusionTime = 0; integratedTime = 0; lastTime = 0; loadCode("scenes/yeseulWhitneyScene/exampleCode.cpp"); } void yeseulWhitneyScene::update(){ } void yeseulWhitneyScene::draw(){ ofPushMatrix(); ofTranslate(dimensions.width/2, dimensions.height/2); drawPattern(); diffusion(); ofPopMatrix(); } void yeseulWhitneyScene::drawPattern(){ ofSetColor(255); ofFill(); float now = getElapsedTimef(); if (lastTime == 0) { lastTime = now; } float dt = now - lastTime; lastTime = now; integratedTime += spinSpeed * dt; float k = integratedTime; for (int r=0; r<35; r+=1) { ofRotate(k*sin(r)); for (int a=0; a<20; a+=1) { ofRotate(360/20); ofDrawCircle(0, r*10, 1); } } } void yeseulWhitneyScene::diffusion() { float t = getElapsedTimef(); if (lastDiffusionTime == 0 || diffusionInterval <= t - lastDiffusionTime) { diffs.push_back(circlesDiffusion(t, diffusionSize)); cout << "add difff" << diffusionInterval << endl; lastDiffusionTime = t; } for(int i = 0; i < diffs.size(); i++){ if(diffs[i].bKill){ cout << "kill diff: " << i << endl; diffs.erase(diffs.begin() + i); i--; } } for(int i = 0; i < diffs.size(); i++){ diffs[i].draw(t); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 SeNDA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * FILE BundleProcessor.cpp * AUTHOR Blackcatn13 * DATE Dec 17, 2015 * VERSION 1 * */ #include "Node/BundleProcessor/BundleProcessor.h" #include <memory> #include <string> #include <vector> #include "Node/BundleQueue/BundleQueue.h" #include "Node/Neighbour/NeighbourTable.h" #include "Node/Config.h" #include "Node/BundleQueue/BundleContainer.h" #include "Bundle/Bundle.h" BundleProcessor::BundleProcessor( Config config, std::shared_ptr<BundleQueue> bundleQueue, std::shared_ptr<NeighbourTable> neighbourTable /*, std::shared_ptr<ListeningAppsTable> listeningAppsTable*/) : m_config(config), m_bundleQueue(bundleQueue), m_neighbourTable(neighbourTable) { } BundleProcessor::~BundleProcessor() { } void BundleProcessor::processBundles() { } void BundleProcessor::receiveBundles() { } void dispatch(std::shared_ptr<Bundle> bundle, std::vector<std::string> destinations) { } void forward(std::shared_ptr<Bundle> bundle, std::vector<std::string> nextHop) { } void discard(std::shared_ptr<Bundle> bundle) { } void restore(std::shared_ptr<Bundle> bundle) { } <commit_msg>Implements constructor and processBundles.<commit_after>/* * Copyright (c) 2015 SeNDA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * FILE BundleProcessor.cpp * AUTHOR Blackcatn13 * DATE Dec 17, 2015 * VERSION 1 * */ #include "Node/BundleProcessor/BundleProcessor.h" #include <memory> #include <string> #include <vector> #include <thread> #include "Node/BundleQueue/BundleQueue.h" #include "Node/Neighbour/NeighbourTable.h" #include "Node/Config.h" #include "Node/BundleQueue/BundleContainer.h" #include "Bundle/Bundle.h" #include "Utils/globals.h" BundleProcessor::BundleProcessor( Config config, std::shared_ptr<BundleQueue> bundleQueue, std::shared_ptr<NeighbourTable> neighbourTable /*, std::shared_ptr<ListeningAppsTable> listeningAppsTable*/) : m_config(config), m_bundleQueue(bundleQueue), m_neighbourTable(neighbourTable) { std::thread t = std::thread(&BundleProcessor::processBundles, this); t.detach(); t = std::thread(&BundleProcessor::receiveBundles, this); t.detach(); } BundleProcessor::~BundleProcessor() { } void BundleProcessor::processBundles() { while (!g_stop.load()) { try { std::shared_ptr<BundleContainer> bc = m_bundleQueue->dequeue(); processBundle(bc); } catch (const std::exception &e) { } } } void BundleProcessor::receiveBundles() { } void BundleProcessor::dispatch(std::shared_ptr<Bundle> bundle, std::vector<std::string> destinations) { } void BundleProcessor::forward(std::shared_ptr<Bundle> bundle, std::vector<std::string> nextHop) { } void BundleProcessor::discard(std::shared_ptr<Bundle> bundle) { } void BundleProcessor::restore(std::shared_ptr<Bundle> bundle) { } <|endoftext|>
<commit_before>// Important do not use this FilterTask for final Filtered AOD productions! // Due to the variability of the used config file, it is to easy to loose track of the used settings! AliAnalysisTask *AddTask_caklein_LMEEFilter_PbPb( TString cfg="ConfigLMEE_nano_PbPb.C", Bool_t gridconf=kFALSE, TString period="", Bool_t storeLS = kFALSE, Bool_t hasMC_aod = kFALSE, // ULong64_t triggers=AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral+AliVEvent::kEMCEGA+AliVEvent::kEMCEJE ULong64_t triggers=AliVEvent::kINT7 ){ //get the current analysis manager AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskLMEEFilter", "No analysis manager found."); return 0; } //check for output aod handler if (!mgr->GetOutputEventHandler()||mgr->GetOutputEventHandler()->IsA()!=AliAODHandler::Class()) { Warning("AddTaskLMEEFilter","No AOD output handler available. Not adding the task!"); return 0; } //Do we have an MC handler? Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0)||hasMC_aod; //Do we run on AOD? Bool_t isAOD=mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class(); //Allow merging of the filtered aods on grid trains if(mgr->GetGridHandler()) { printf(" SET MERGE FILTERED AODs \n"); //mgr->GetGridHandler()->SetMergeAOD(kTRUE); } TString configFile(""); printf("pwd: %s \n",gSystem->pwd()); if(cfg.IsNull()) cfg="ConfigLMEE_nano_PbPb.C"; TString alienPath("alien:///alice/cern.ch/user/c/cklein/PWGDQ/dielectron/macrosLMEE/"); TString alirootPath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/"); ////////// >>>>>>>>>> alien config if(gridconf) { if(!gSystem->Exec(Form("alien_cp %s/%s .",alienPath.Data(),cfg.Data()))) { gSystem->Exec(Form("ls -l %s",gSystem->pwd())); configFile=gSystem->pwd(); } else { printf("ERROR: couldn't copy file %s/%s from grid \n", alienPath.Data(),cfg.Data() ); return; } } ///////// >>>>>>>>> aliroot config else if(!gridconf) configFile=alirootPath.Data(); ///////// add config to path configFile+="/"; configFile+=cfg.Data(); //load dielectron configuration file (only once) TString checkconfig="ConfigLMEE_nano_PbPb"; if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data())) gROOT->LoadMacro(configFile.Data()); AliDielectron *diEle=ConfigLMEE_nano_PbPb(0,hasMC,period); if(isAOD) { //add options to AliAODHandler to duplicate input event AliAODHandler *aodHandler = (AliAODHandler*)mgr->GetOutputEventHandler(); aodHandler->SetCreateNonStandardAOD(); aodHandler->SetNeedsHeaderReplication(); if(!period.Contains("LHC10h")) aodHandler->SetNeedsTOFHeaderReplication(); aodHandler->SetNeedsVZEROReplication(); /*aodHandler->SetNeedsTracksBranchReplication(); aodHandler->SetNeedsCaloClustersBranchReplication(); aodHandler->SetNeedsVerticesBranchReplication(); aodHandler->SetNeedsCascadesBranchReplication(); aodHandler->SetNeedsTrackletsBranchReplication(); aodHandler->SetNeedsPMDClustersBranchReplication(); aodHandler->SetNeedsJetsBranchReplication(); aodHandler->SetNeedsFMDClustersBranchReplication(); //aodHandler->SetNeedsMCParticlesBranchReplication(); aodHandler->SetNeedsDimuonsBranchReplication();*/ // deactivates several branches // if(hasMC) aodHandler->SetNeedsV0sBranchReplication(); if(hasMC) aodHandler->SetNeedsMCParticlesBranchReplication(); diEle->SetHasMC(hasMC); } //Create task and add it to the analysis manager AliAnalysisTaskDielectronFilter *task=new AliAnalysisTaskDielectronFilter("LMEE_DielectronFilter"); task->SetTriggerMask(triggers); if (!hasMC) task->UsePhysicsSelection(); task->SetDielectron(diEle); if(storeLS) task->SetStoreLikeSignCandidates(storeLS); task->SetCreateNanoAODs(kTRUE); task->SetStoreEventplanes(kTRUE); task->SetStoreEventsWithSingleTracks(kTRUE); // task->SetStoreHeader(kTRUE); mgr->AddTask(task); //---------------------- //create data containers //---------------------- TString containerName = mgr->GetCommonFileName(); containerName += ":PWGDQ_dielectronFilter"; //create output container AliAnalysisDataContainer *cOutputHist1 = mgr->CreateContainer("LMEE_FilterQA", THashList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); AliAnalysisDataContainer *cOutputHist2 = mgr->CreateContainer("LMEE_FilterEventStat", TH1D::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 0, mgr->GetCommonOutputContainer()); mgr->ConnectOutput(task, 1, cOutputHist1); mgr->ConnectOutput(task, 2, cOutputHist2); return task; } <commit_msg>correcting macro name<commit_after>// Important do not use this FilterTask for final Filtered AOD productions! // Due to the variability of the used config file, it is to easy to loose track of the used settings! AliAnalysisTask *AddTaskLMEEFilter_PbPb( TString cfg="ConfigLMEE_nano_PbPb.C", Bool_t gridconf=kFALSE, TString period="", Bool_t storeLS = kFALSE, Bool_t hasMC_aod = kFALSE, // ULong64_t triggers=AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral+AliVEvent::kEMCEGA+AliVEvent::kEMCEJE ULong64_t triggers=AliVEvent::kINT7 ){ //get the current analysis manager AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskLMEEFilter", "No analysis manager found."); return 0; } //check for output aod handler if (!mgr->GetOutputEventHandler()||mgr->GetOutputEventHandler()->IsA()!=AliAODHandler::Class()) { Warning("AddTaskLMEEFilter","No AOD output handler available. Not adding the task!"); return 0; } //Do we have an MC handler? Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0)||hasMC_aod; //Do we run on AOD? Bool_t isAOD=mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class(); //Allow merging of the filtered aods on grid trains if(mgr->GetGridHandler()) { printf(" SET MERGE FILTERED AODs \n"); //mgr->GetGridHandler()->SetMergeAOD(kTRUE); } TString configFile(""); printf("pwd: %s \n",gSystem->pwd()); if(cfg.IsNull()) cfg="ConfigLMEE_nano_PbPb.C"; TString alienPath("alien:///alice/cern.ch/user/c/cklein/PWGDQ/dielectron/macrosLMEE/"); TString alirootPath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/"); ////////// >>>>>>>>>> alien config if(gridconf) { if(!gSystem->Exec(Form("alien_cp %s/%s .",alienPath.Data(),cfg.Data()))) { gSystem->Exec(Form("ls -l %s",gSystem->pwd())); configFile=gSystem->pwd(); } else { printf("ERROR: couldn't copy file %s/%s from grid \n", alienPath.Data(),cfg.Data() ); return; } } ///////// >>>>>>>>> aliroot config else if(!gridconf) configFile=alirootPath.Data(); ///////// add config to path configFile+="/"; configFile+=cfg.Data(); //load dielectron configuration file (only once) TString checkconfig="ConfigLMEE_nano_PbPb"; if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data())) gROOT->LoadMacro(configFile.Data()); AliDielectron *diEle=ConfigLMEE_nano_PbPb(0,hasMC,period); if(isAOD) { //add options to AliAODHandler to duplicate input event AliAODHandler *aodHandler = (AliAODHandler*)mgr->GetOutputEventHandler(); aodHandler->SetCreateNonStandardAOD(); aodHandler->SetNeedsHeaderReplication(); if(!period.Contains("LHC10h")) aodHandler->SetNeedsTOFHeaderReplication(); aodHandler->SetNeedsVZEROReplication(); /*aodHandler->SetNeedsTracksBranchReplication(); aodHandler->SetNeedsCaloClustersBranchReplication(); aodHandler->SetNeedsVerticesBranchReplication(); aodHandler->SetNeedsCascadesBranchReplication(); aodHandler->SetNeedsTrackletsBranchReplication(); aodHandler->SetNeedsPMDClustersBranchReplication(); aodHandler->SetNeedsJetsBranchReplication(); aodHandler->SetNeedsFMDClustersBranchReplication(); //aodHandler->SetNeedsMCParticlesBranchReplication(); aodHandler->SetNeedsDimuonsBranchReplication();*/ // deactivates several branches // if(hasMC) aodHandler->SetNeedsV0sBranchReplication(); if(hasMC) aodHandler->SetNeedsMCParticlesBranchReplication(); diEle->SetHasMC(hasMC); } //Create task and add it to the analysis manager AliAnalysisTaskDielectronFilter *task=new AliAnalysisTaskDielectronFilter("LMEE_DielectronFilter"); task->SetTriggerMask(triggers); if (!hasMC) task->UsePhysicsSelection(); task->SetDielectron(diEle); if(storeLS) task->SetStoreLikeSignCandidates(storeLS); task->SetCreateNanoAODs(kTRUE); task->SetStoreEventplanes(kTRUE); task->SetStoreEventsWithSingleTracks(kTRUE); // task->SetStoreHeader(kTRUE); mgr->AddTask(task); //---------------------- //create data containers //---------------------- TString containerName = mgr->GetCommonFileName(); containerName += ":PWGDQ_dielectronFilter"; //create output container AliAnalysisDataContainer *cOutputHist1 = mgr->CreateContainer("LMEE_FilterQA", THashList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); AliAnalysisDataContainer *cOutputHist2 = mgr->CreateContainer("LMEE_FilterEventStat", TH1D::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 0, mgr->GetCommonOutputContainer()); mgr->ConnectOutput(task, 1, cOutputHist1); mgr->ConnectOutput(task, 2, cOutputHist2); return task; } <|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS tl01 (1.2.38); FILE MERGED 2004/04/20 14:41:59 tl 1.2.38.5: RESYNC: (1.2-1.3); FILE MERGED 2004/04/02 10:29:22 tl 1.2.38.4: #110762# change in Hangul/Hanja text conversion API 2004/03/22 11:18:21 tl 1.2.38.3: #111082# eDirection for Hangul/Hanja conversion fixed 2003/07/31 10:57:30 tl 1.2.38.2: #110762# make use of Hangul/Hanja user dictionaries 2003/07/31 10:56:09 tl 1.2.38.1: #110763# make use of Hangul/Hanja user dictionaries<commit_after><|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_set_fsi_gp_shadow.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_set_fsi_gp_shadow.C /// /// @brief --IPL step 0.8 proc_prep_ipl //------------------------------------------------------------------------------ // *HWP HW Owner : Anusha Reddy Rangareddygari <[email protected]> // *HWP HW Backup Owner : Srinivas V Naga <[email protected]> // *HWP FW Owner : Brian Silver <[email protected]> // *HWP Team : Perv // *HWP Level : 2 // *HWP Consumed by : SBE //------------------------------------------------------------------------------ //## auto_generated #include "p9_set_fsi_gp_shadow.H" //## auto_generated #include "p9_const_common.H" #include <p9_perv_scom_addresses.H> #include <p9n2_perv_scom_addresses_fld.H> fapi2::ReturnCode p9_set_fsi_gp_shadow(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip) { fapi2::buffer<uint8_t> l_read_attr; fapi2::buffer<uint32_t> l_cfam_data; FAPI_INF("p9_set_fsi_gp_shadow: Entering ..."); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_FSI_GP_SHADOWS_OVERWRITE, i_target_chip, l_read_attr)); if ( l_read_attr ) { FAPI_DBG("Setting flush values for root_ctrl_copy and perv_ctrl_copy registers"); //Setting ROOT_CTRL0_COPY register value //CFAM.ROOT_CTRL0_COPY = p9SetFsiGpShadow::ROOT_CTRL0_FLUSHVALUE FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL0_COPY_FSI, p9SetFsiGpShadow::ROOT_CTRL0_FLUSHVALUE)); //Setting ROOT_CTRL1_COPY register value //CFAM.ROOT_CTRL1_COPY = p9SetFsiGpShadow::ROOT_CTRL1_FLUSHVALUE FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL1_COPY_FSI, p9SetFsiGpShadow::ROOT_CTRL1_FLUSHVALUE)); //Setting ROOT_CTRL2_COPY register value //CFAM.ROOT_CTRL2_COPY = p9SetFsiGpShadow::ROOT_CTRL2_FLUSHVALUE FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL2_COPY_FSI, p9SetFsiGpShadow::ROOT_CTRL2_FLUSHVALUE)); //Setting ROOT_CTRL3_COPY register value //CFAM.ROOT_CTRL3_COPY = p9SetFsiGpShadow::ROOT_CTRL3_FLUSHVALUE FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL3_COPY_FSI, p9SetFsiGpShadow::ROOT_CTRL3_FLUSHVALUE)); //Setting ROOT_CTRL4_COPY register value //CFAM.ROOT_CTRL4_COPY = p9SetFsiGpShadow::ROOT_CTRL4_FLUSHVALUE FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL4_COPY_FSI, p9SetFsiGpShadow::ROOT_CTRL4_FLUSHVALUE)); //Setting ROOT_CTRL5_COPY register value //CFAM.ROOT_CTRL5_COPY = p9SetFsiGpShadow::ROOT_CTRL5_FLUSHVALUE FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL5_COPY_FSI, l_cfam_data)); l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL5_MASK) | p9SetFsiGpShadow::ROOT_CTRL5_FLUSHVALUE; FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL5_COPY_FSI, l_cfam_data)); //Setting ROOT_CTRL6_COPY register value //CFAM.ROOT_CTRL6_COPY = p9SetFsiGpShadow::ROOT_CTRL6_FLUSHVALUE FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL6_COPY_FSI, l_cfam_data)); l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL6_MASK) | p9SetFsiGpShadow::ROOT_CTRL6_FLUSHVALUE; FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL6_COPY_FSI, l_cfam_data)); //Setting ROOT_CTRL7_COPY register value //CFAM.ROOT_CTRL7_COPY = p9SetFsiGpShadow::ROOT_CTRL7_FLUSHVALUE FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL7_COPY_FSI, p9SetFsiGpShadow::ROOT_CTRL7_FLUSHVALUE)); //Setting ROOT_CTRL8_COPY register value //CFAM.ROOT_CTRL8_COPY = p9SetFsiGpShadow::ROOT_CTRL8_FLUSHVALUE FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL8_COPY_FSI, l_cfam_data)); l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL8_MASK) | p9SetFsiGpShadow::ROOT_CTRL8_FLUSHVALUE; FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL8_COPY_FSI, l_cfam_data)); //Setting PERV_CTRL0_COPY register value //CFAM.PERV_CTRL0_COPY = p9SetFsiGpShadow::PERV_CTRL0_FLUSHVALUE FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI, p9SetFsiGpShadow::PERV_CTRL0_FLUSHVALUE)); //Setting PERV_CTRL1_COPY register value //CFAM.PERV_CTRL1_COPY = p9SetFsiGpShadow::PERV_CTRL1_FLUSHVALUE FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL1_COPY_FSI, p9SetFsiGpShadow::PERV_CTRL1_FLUSHVALUE)); } /* Write the value of FUSED_CORE_MODE into PERV_CTRL0(23) regardless of chip EC; the bit is nonfunctional on Nimbus DD1 */ FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FUSED_CORE_MODE, fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>(), l_read_attr)); FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI, l_cfam_data)); if (l_read_attr) { l_cfam_data.setBit<P9N2_PERV_PERV_CTRL0_TP_OTP_SCOM_FUSED_CORE_MODE>(); } else { l_cfam_data.clearBit<P9N2_PERV_PERV_CTRL0_TP_OTP_SCOM_FUSED_CORE_MODE>(); } FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI, l_cfam_data)); FAPI_INF("p9_set_fsi_gp_shadow: Exiting ..."); fapi_try_exit: return fapi2::current_err; } <commit_msg>Update hardware procedure metadata<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_set_fsi_gp_shadow.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_set_fsi_gp_shadow.C /// /// @brief --IPL step 0.8 proc_prep_ipl //------------------------------------------------------------------------------ // *HWP HW Owner : Anusha Reddy Rangareddygari <[email protected]> // *HWP HW Backup Owner : Srinivas V Naga <[email protected]> // *HWP FW Owner : Brian Silver <[email protected]> // *HWP Team : Perv // *HWP Level : 3 // *HWP Consumed by : SBE //------------------------------------------------------------------------------ //## auto_generated #include "p9_set_fsi_gp_shadow.H" //## auto_generated #include "p9_const_common.H" #include <p9_perv_scom_addresses.H> #include <p9n2_perv_scom_addresses_fld.H> fapi2::ReturnCode p9_set_fsi_gp_shadow(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip) { fapi2::buffer<uint8_t> l_read_attr; fapi2::buffer<uint32_t> l_cfam_data; FAPI_INF("p9_set_fsi_gp_shadow: Entering ..."); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_FSI_GP_SHADOWS_OVERWRITE, i_target_chip, l_read_attr)); if ( l_read_attr ) { FAPI_DBG("Setting flush values for root_ctrl_copy and perv_ctrl_copy registers"); //Setting ROOT_CTRL0_COPY register value //CFAM.ROOT_CTRL0_COPY = p9SetFsiGpShadow::ROOT_CTRL0_FLUSHVALUE FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL0_COPY_FSI, p9SetFsiGpShadow::ROOT_CTRL0_FLUSHVALUE)); //Setting ROOT_CTRL1_COPY register value //CFAM.ROOT_CTRL1_COPY = p9SetFsiGpShadow::ROOT_CTRL1_FLUSHVALUE FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL1_COPY_FSI, p9SetFsiGpShadow::ROOT_CTRL1_FLUSHVALUE)); //Setting ROOT_CTRL2_COPY register value //CFAM.ROOT_CTRL2_COPY = p9SetFsiGpShadow::ROOT_CTRL2_FLUSHVALUE FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL2_COPY_FSI, p9SetFsiGpShadow::ROOT_CTRL2_FLUSHVALUE)); //Setting ROOT_CTRL3_COPY register value //CFAM.ROOT_CTRL3_COPY = p9SetFsiGpShadow::ROOT_CTRL3_FLUSHVALUE FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL3_COPY_FSI, p9SetFsiGpShadow::ROOT_CTRL3_FLUSHVALUE)); //Setting ROOT_CTRL4_COPY register value //CFAM.ROOT_CTRL4_COPY = p9SetFsiGpShadow::ROOT_CTRL4_FLUSHVALUE FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL4_COPY_FSI, p9SetFsiGpShadow::ROOT_CTRL4_FLUSHVALUE)); //Setting ROOT_CTRL5_COPY register value //CFAM.ROOT_CTRL5_COPY = p9SetFsiGpShadow::ROOT_CTRL5_FLUSHVALUE FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL5_COPY_FSI, l_cfam_data)); l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL5_MASK) | p9SetFsiGpShadow::ROOT_CTRL5_FLUSHVALUE; FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL5_COPY_FSI, l_cfam_data)); //Setting ROOT_CTRL6_COPY register value //CFAM.ROOT_CTRL6_COPY = p9SetFsiGpShadow::ROOT_CTRL6_FLUSHVALUE FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL6_COPY_FSI, l_cfam_data)); l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL6_MASK) | p9SetFsiGpShadow::ROOT_CTRL6_FLUSHVALUE; FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL6_COPY_FSI, l_cfam_data)); //Setting ROOT_CTRL7_COPY register value //CFAM.ROOT_CTRL7_COPY = p9SetFsiGpShadow::ROOT_CTRL7_FLUSHVALUE FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL7_COPY_FSI, p9SetFsiGpShadow::ROOT_CTRL7_FLUSHVALUE)); //Setting ROOT_CTRL8_COPY register value //CFAM.ROOT_CTRL8_COPY = p9SetFsiGpShadow::ROOT_CTRL8_FLUSHVALUE FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_ROOT_CTRL8_COPY_FSI, l_cfam_data)); l_cfam_data = (l_cfam_data & p9SetFsiGpShadow::ROOT_CTRL8_MASK) | p9SetFsiGpShadow::ROOT_CTRL8_FLUSHVALUE; FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_ROOT_CTRL8_COPY_FSI, l_cfam_data)); //Setting PERV_CTRL0_COPY register value //CFAM.PERV_CTRL0_COPY = p9SetFsiGpShadow::PERV_CTRL0_FLUSHVALUE FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI, p9SetFsiGpShadow::PERV_CTRL0_FLUSHVALUE)); //Setting PERV_CTRL1_COPY register value //CFAM.PERV_CTRL1_COPY = p9SetFsiGpShadow::PERV_CTRL1_FLUSHVALUE FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL1_COPY_FSI, p9SetFsiGpShadow::PERV_CTRL1_FLUSHVALUE)); } /* Write the value of FUSED_CORE_MODE into PERV_CTRL0(23) regardless of chip EC; the bit is nonfunctional on Nimbus DD1 */ FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FUSED_CORE_MODE, fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>(), l_read_attr)); FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI, l_cfam_data)); if (l_read_attr) { l_cfam_data.setBit<P9N2_PERV_PERV_CTRL0_TP_OTP_SCOM_FUSED_CORE_MODE>(); } else { l_cfam_data.clearBit<P9N2_PERV_PERV_CTRL0_TP_OTP_SCOM_FUSED_CORE_MODE>(); } FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_PERV_CTRL0_COPY_FSI, l_cfam_data)); FAPI_INF("p9_set_fsi_gp_shadow: Exiting ..."); fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before><commit_msg>ProjectionToPlaneMultiMapping: minor improvments<commit_after><|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo 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 <cstdint> #include <iostream> #include <memory> #include <thread> #include "cyber/common/file.h" #include "cyber/common/log.h" #include "gflags/gflags.h" #include "modules/common/proto/error_code.pb.h" #include "modules/common/time/time.h" #include "modules/common/util/factory.h" #include "modules/drivers/canbus/can_client/can_client.h" #include "modules/drivers/canbus/can_client/can_client_factory.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/proto/can_card_parameter.pb.h" DEFINE_bool(only_one_send, false, "only send test."); DEFINE_string(can_client_conf_file_a, "modules/canbus/conf/can_client_conf_a.pb.txt", "can client conf for client a"); DEFINE_string(can_client_conf_file_b, "modules/canbus/conf/can_client_conf_b.pb.txt", "can client conf for client b"); DEFINE_int64(agent_mutual_send_frames, 1000, "Every agent send frame num"); const int32_t MAX_CAN_SEND_FRAME_LEN = 1; const int32_t MAX_CAN_RECV_FRAME_LEN = 10; namespace apollo { namespace drivers { namespace canbus { struct TestCanParam { CANCardParameter conf; bool is_first_agent = false; int32_t recv_cnt = 0; int32_t recv_err_cnt = 0; int32_t send_cnt = 0; int32_t send_err_cnt = 0; int32_t send_lost_cnt = 0; int32_t send_time = 0; int32_t recv_time = 0; CanClient *can_client = nullptr; TestCanParam() = default; void print() { AINFO << "conf: " << conf.ShortDebugString() << ", total send: " << send_cnt + send_err_cnt << "/" << FLAGS_agent_mutual_send_frames << ", send_ok: " << send_cnt << " , send_err_cnt: " << send_err_cnt << ", send_lost_cnt: " << send_lost_cnt << ", recv_cnt: " << recv_cnt << ", send_time: " << send_time << ", recv_time: " << recv_time; } }; class CanAgent { public: explicit CanAgent(TestCanParam *param_ptr) : param_ptr_(param_ptr) {} TestCanParam *param_ptr() { return param_ptr_; } CanAgent *other_agent() { return other_agent_; } bool Start() { thread_recv_.reset(new std::thread([this] { RecvThreadFunc(); })); if (thread_recv_ == nullptr) { AERROR << "Unable to create recv thread."; return false; } thread_send_.reset(new std::thread([this] { SendThreadFunc(); })); if (thread_send_ == nullptr) { AERROR << "Unable to create send thread."; return false; } return true; } void SendThreadFunc() { using common::ErrorCode; using common::time::AsInt64; using common::time::Clock; using common::time::micros; AINFO << "Send thread starting..."; TestCanParam *param = param_ptr(); CanClient *client = param->can_client; std::vector<CanFrame> frames; frames.resize(MAX_CAN_SEND_FRAME_LEN); int32_t count = 0; int32_t start_id = 0; int32_t end_id = 0; int32_t id = 0; if (param->is_first_agent) { start_id = 1; end_id = 128; } else { start_id = 129; end_id = start_id + 127; } id = start_id; int32_t send_id = id; AINFO << "port:" << param->conf.ShortDebugString() << ", start_id:" << start_id << ", end_id:" << end_id; // wait for other agent receiving is ok. while (!other_agent()->is_receiving()) { std::this_thread::yield(); } int64_t start = AsInt64<micros>(Clock::Now()); while (true) { // param->print(); if (count >= FLAGS_agent_mutual_send_frames) { break; } for (int32_t i = 0; i < MAX_CAN_SEND_FRAME_LEN; ++i) { // frames[i].id = id_count & 0x3FF; send_id = id; frames[i].id = id; frames[i].len = 8; frames[i].data[7] = static_cast<uint8_t>(count % 256); for (uint8_t j = 0; j < 7; ++j) { frames[i].data[j] = j; } ++count; ++id; if (id > end_id) { id = start_id; } } int32_t frame_num = MAX_CAN_SEND_FRAME_LEN; if (client->Send(frames, &frame_num) != ErrorCode::OK) { param->send_err_cnt += MAX_CAN_SEND_FRAME_LEN; AERROR << "send_thread send msg failed!, id:" << send_id << ", conf:" << param->conf.ShortDebugString(); } else { param->send_cnt += frame_num; param->send_lost_cnt += MAX_CAN_SEND_FRAME_LEN - frame_num; AINFO << "send_frames: " << frame_num << "send_frame#" << frames[0].CanFrameString() << " send lost:" << MAX_CAN_SEND_FRAME_LEN - frame_num << ", conf:" << param->conf.ShortDebugString(); } } int64_t end = AsInt64<micros>(Clock::Now()); param->send_time = static_cast<int32_t>(end - start); // In case for finish too quick to receiver miss some msg sleep(2); AINFO << "Send thread stopping..." << param->conf.ShortDebugString(); is_sending_finish(true); return; } void AddOtherAgent(CanAgent *agent) { other_agent_ = agent; } bool is_receiving() const { return is_receiving_; } void is_receiving(bool val) { is_receiving_ = val; } bool is_sending_finish() const { return is_sending_finish_; } void is_sending_finish(bool val) { is_sending_finish_ = val; } void RecvThreadFunc() { using common::ErrorCode; using common::time::AsInt64; using common::time::Clock; using common::time::micros; AINFO << "Receive thread starting..."; TestCanParam *param = param_ptr(); CanClient *client = param->can_client; int64_t start = 0; std::vector<CanFrame> buf; bool first = true; while (!other_agent()->is_sending_finish()) { is_receiving(true); int32_t len = MAX_CAN_RECV_FRAME_LEN; ErrorCode ret = client->Receive(&buf, &len); if (len == 0) { AINFO << "recv frame:0"; continue; } if (first) { start = AsInt64<micros>(Clock::Now()); first = false; } if (ret != ErrorCode::OK || len == 0) { // AINFO << "channel:" << param->conf.channel_id() // << ", recv frame:failed, code:" << ret; AINFO << "recv error:" << ret; continue; } for (int32_t i = 0; i < len; ++i) { param->recv_cnt = param->recv_cnt + 1; AINFO << "recv_frame#" << buf[i].CanFrameString() << " conf:" << param->conf.ShortDebugString() << ",recv_cnt: " << param->recv_cnt; } } int64_t end = AsInt64<micros>(Clock::Now()); param->recv_time = static_cast<int32_t>(end - start); AINFO << "Recv thread stopping..., conf:" << param->conf.ShortDebugString(); return; } void WaitForFinish() { if (thread_send_ != nullptr && thread_send_->joinable()) { thread_send_->join(); thread_send_.reset(); AINFO << "Send thread stopped. conf:" << param_ptr_->conf.ShortDebugString(); } if (thread_recv_ != nullptr && thread_recv_->joinable()) { thread_recv_->join(); thread_recv_.reset(); AINFO << "Recv thread stopped. conf:" << param_ptr_->conf.ShortDebugString(); } } private: bool is_receiving_ = false; bool is_sending_finish_ = false; CanAgent *other_agent_ = nullptr; TestCanParam *param_ptr_ = nullptr; std::unique_ptr<std::thread> thread_recv_; std::unique_ptr<std::thread> thread_send_; }; } // namespace canbus } // namespace drivers } // namespace apollo int main(int32_t argc, char **argv) { google::InitGoogleLogging(argv[0]); google::ParseCommandLineFlags(&argc, &argv, true); using apollo::common::ErrorCode; using apollo::drivers::canbus::CanAgent; using apollo::drivers::canbus::CANCardParameter; using apollo::drivers::canbus::CanClient; using apollo::drivers::canbus::CanClientFactory; using apollo::drivers::canbus::TestCanParam; CANCardParameter can_client_conf_a; std::shared_ptr<TestCanParam> param_ptr_a(new TestCanParam()); std::shared_ptr<TestCanParam> param_ptr_b(new TestCanParam()); auto can_client_factory = CanClientFactory::Instance(); can_client_factory->RegisterCanClients(); if (!apollo::cyber::common::GetProtoFromFile(FLAGS_can_client_conf_file_a, &can_client_conf_a)) { AERROR << "Unable to load canbus conf file: " << FLAGS_can_client_conf_file_a; return 1; } else { AINFO << "Conf file is loaded: " << FLAGS_can_client_conf_file_a; } AINFO << can_client_conf_a.ShortDebugString(); auto client_a = can_client_factory->CreateObject(can_client_conf_a.brand()); if (!client_a || !client_a->Init(can_client_conf_a) || client_a->Start() != ErrorCode::OK) { AERROR << "Create can client a failed."; return 1; } param_ptr_a->can_client = client_a.get(); param_ptr_a->is_first_agent = true; param_ptr_a->conf = can_client_conf_a; CANCardParameter can_client_conf_b; std::unique_ptr<CanClient> client_b; if (!FLAGS_only_one_send) { if (!apollo::cyber::common::GetProtoFromFile(FLAGS_can_client_conf_file_b, &can_client_conf_b)) { AERROR << "Unable to load canbus conf file: " << FLAGS_can_client_conf_file_b; return 1; } else { AINFO << "Conf file is loaded: " << FLAGS_can_client_conf_file_b; } AINFO << can_client_conf_b.ShortDebugString(); client_b = can_client_factory->CreateObject(can_client_conf_b.brand()); if (!client_b || !client_b->Init(can_client_conf_b) || client_b->Start() != ErrorCode::OK) { AERROR << "Create can client b failed."; return 1; } param_ptr_b->can_client = client_b.get(); param_ptr_b->conf = can_client_conf_b; } CanAgent agent_a(param_ptr_a.get()); CanAgent agent_b(param_ptr_b.get()); agent_a.AddOtherAgent(&agent_b); agent_b.AddOtherAgent(&agent_a); if (!agent_a.Start()) { AERROR << "Agent a start failed."; return -1; } if (FLAGS_only_one_send) { agent_b.is_receiving(true); agent_b.is_sending_finish(true); } else { if (!agent_b.Start()) { AERROR << "Agent b start failed."; return -1; } } agent_a.WaitForFinish(); if (!FLAGS_only_one_send) { agent_b.WaitForFinish(); } param_ptr_a->print(); if (!FLAGS_only_one_send) { param_ptr_b->print(); } return 0; } <commit_msg>Drivers: fix return value<commit_after>/****************************************************************************** * Copyright 2017 The Apollo 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 <cstdint> #include <iostream> #include <memory> #include <thread> #include "cyber/common/file.h" #include "cyber/common/log.h" #include "gflags/gflags.h" #include "modules/common/proto/error_code.pb.h" #include "modules/common/time/time.h" #include "modules/common/util/factory.h" #include "modules/drivers/canbus/can_client/can_client.h" #include "modules/drivers/canbus/can_client/can_client_factory.h" #include "modules/drivers/canbus/common/byte.h" #include "modules/drivers/canbus/proto/can_card_parameter.pb.h" DEFINE_bool(only_one_send, false, "only send test."); DEFINE_string(can_client_conf_file_a, "modules/canbus/conf/can_client_conf_a.pb.txt", "can client conf for client a"); DEFINE_string(can_client_conf_file_b, "modules/canbus/conf/can_client_conf_b.pb.txt", "can client conf for client b"); DEFINE_int64(agent_mutual_send_frames, 1000, "Every agent send frame num"); const int32_t MAX_CAN_SEND_FRAME_LEN = 1; const int32_t MAX_CAN_RECV_FRAME_LEN = 10; namespace apollo { namespace drivers { namespace canbus { struct TestCanParam { CANCardParameter conf; bool is_first_agent = false; int32_t recv_cnt = 0; int32_t recv_err_cnt = 0; int32_t send_cnt = 0; int32_t send_err_cnt = 0; int32_t send_lost_cnt = 0; int32_t send_time = 0; int32_t recv_time = 0; CanClient *can_client = nullptr; TestCanParam() = default; void print() { AINFO << "conf: " << conf.ShortDebugString() << ", total send: " << send_cnt + send_err_cnt << "/" << FLAGS_agent_mutual_send_frames << ", send_ok: " << send_cnt << " , send_err_cnt: " << send_err_cnt << ", send_lost_cnt: " << send_lost_cnt << ", recv_cnt: " << recv_cnt << ", send_time: " << send_time << ", recv_time: " << recv_time; } }; class CanAgent { public: explicit CanAgent(TestCanParam *param_ptr) : param_ptr_(param_ptr) {} TestCanParam *param_ptr() { return param_ptr_; } CanAgent *other_agent() { return other_agent_; } bool Start() { thread_recv_.reset(new std::thread([this] { RecvThreadFunc(); })); if (thread_recv_ == nullptr) { AERROR << "Unable to create recv thread."; return false; } thread_send_.reset(new std::thread([this] { SendThreadFunc(); })); if (thread_send_ == nullptr) { AERROR << "Unable to create send thread."; return false; } return true; } void SendThreadFunc() { using common::ErrorCode; using common::time::AsInt64; using common::time::Clock; using common::time::micros; AINFO << "Send thread starting..."; TestCanParam *param = param_ptr(); CanClient *client = param->can_client; std::vector<CanFrame> frames; frames.resize(MAX_CAN_SEND_FRAME_LEN); int32_t count = 0; int32_t start_id = 0; int32_t end_id = 0; int32_t id = 0; if (param->is_first_agent) { start_id = 1; end_id = 128; } else { start_id = 129; end_id = start_id + 127; } id = start_id; int32_t send_id = id; AINFO << "port:" << param->conf.ShortDebugString() << ", start_id:" << start_id << ", end_id:" << end_id; // wait for other agent receiving is ok. while (!other_agent()->is_receiving()) { std::this_thread::yield(); } int64_t start = AsInt64<micros>(Clock::Now()); while (true) { // param->print(); if (count >= FLAGS_agent_mutual_send_frames) { break; } for (int32_t i = 0; i < MAX_CAN_SEND_FRAME_LEN; ++i) { // frames[i].id = id_count & 0x3FF; send_id = id; frames[i].id = id; frames[i].len = 8; frames[i].data[7] = static_cast<uint8_t>(count % 256); for (uint8_t j = 0; j < 7; ++j) { frames[i].data[j] = j; } ++count; ++id; if (id > end_id) { id = start_id; } } int32_t frame_num = MAX_CAN_SEND_FRAME_LEN; if (client->Send(frames, &frame_num) != ErrorCode::OK) { param->send_err_cnt += MAX_CAN_SEND_FRAME_LEN; AERROR << "send_thread send msg failed!, id:" << send_id << ", conf:" << param->conf.ShortDebugString(); } else { param->send_cnt += frame_num; param->send_lost_cnt += MAX_CAN_SEND_FRAME_LEN - frame_num; AINFO << "send_frames: " << frame_num << "send_frame#" << frames[0].CanFrameString() << " send lost:" << MAX_CAN_SEND_FRAME_LEN - frame_num << ", conf:" << param->conf.ShortDebugString(); } } int64_t end = AsInt64<micros>(Clock::Now()); param->send_time = static_cast<int32_t>(end - start); // In case for finish too quick to receiver miss some msg sleep(2); AINFO << "Send thread stopping..." << param->conf.ShortDebugString(); is_sending_finish(true); return; } void AddOtherAgent(CanAgent *agent) { other_agent_ = agent; } bool is_receiving() const { return is_receiving_; } void is_receiving(bool val) { is_receiving_ = val; } bool is_sending_finish() const { return is_sending_finish_; } void is_sending_finish(bool val) { is_sending_finish_ = val; } void RecvThreadFunc() { using common::ErrorCode; using common::time::AsInt64; using common::time::Clock; using common::time::micros; AINFO << "Receive thread starting..."; TestCanParam *param = param_ptr(); CanClient *client = param->can_client; int64_t start = 0; std::vector<CanFrame> buf; bool first = true; while (!other_agent()->is_sending_finish()) { is_receiving(true); int32_t len = MAX_CAN_RECV_FRAME_LEN; ErrorCode ret = client->Receive(&buf, &len); if (len == 0) { AINFO << "recv frame:0"; continue; } if (first) { start = AsInt64<micros>(Clock::Now()); first = false; } if (ret != ErrorCode::OK || len == 0) { // AINFO << "channel:" << param->conf.channel_id() // << ", recv frame:failed, code:" << ret; AINFO << "recv error:" << ret; continue; } for (int32_t i = 0; i < len; ++i) { param->recv_cnt = param->recv_cnt + 1; AINFO << "recv_frame#" << buf[i].CanFrameString() << " conf:" << param->conf.ShortDebugString() << ",recv_cnt: " << param->recv_cnt; } } int64_t end = AsInt64<micros>(Clock::Now()); param->recv_time = static_cast<int32_t>(end - start); AINFO << "Recv thread stopping..., conf:" << param->conf.ShortDebugString(); return; } void WaitForFinish() { if (thread_send_ != nullptr && thread_send_->joinable()) { thread_send_->join(); thread_send_.reset(); AINFO << "Send thread stopped. conf:" << param_ptr_->conf.ShortDebugString(); } if (thread_recv_ != nullptr && thread_recv_->joinable()) { thread_recv_->join(); thread_recv_.reset(); AINFO << "Recv thread stopped. conf:" << param_ptr_->conf.ShortDebugString(); } } private: bool is_receiving_ = false; bool is_sending_finish_ = false; CanAgent *other_agent_ = nullptr; TestCanParam *param_ptr_ = nullptr; std::unique_ptr<std::thread> thread_recv_; std::unique_ptr<std::thread> thread_send_; }; } // namespace canbus } // namespace drivers } // namespace apollo int main(int32_t argc, char **argv) { google::InitGoogleLogging(argv[0]); google::ParseCommandLineFlags(&argc, &argv, true); using apollo::common::ErrorCode; using apollo::drivers::canbus::CanAgent; using apollo::drivers::canbus::CANCardParameter; using apollo::drivers::canbus::CanClient; using apollo::drivers::canbus::CanClientFactory; using apollo::drivers::canbus::TestCanParam; CANCardParameter can_client_conf_a; std::shared_ptr<TestCanParam> param_ptr_a(new TestCanParam()); std::shared_ptr<TestCanParam> param_ptr_b(new TestCanParam()); auto can_client_factory = CanClientFactory::Instance(); can_client_factory->RegisterCanClients(); if (!apollo::cyber::common::GetProtoFromFile(FLAGS_can_client_conf_file_a, &can_client_conf_a)) { AERROR << "Unable to load canbus conf file: " << FLAGS_can_client_conf_file_a; return -1; } AINFO << "Conf file is loaded: " << FLAGS_can_client_conf_file_a; AINFO << can_client_conf_a.ShortDebugString(); auto client_a = can_client_factory->CreateObject(can_client_conf_a.brand()); if (!client_a || !client_a->Init(can_client_conf_a) || client_a->Start() != ErrorCode::OK) { AERROR << "Create can client a failed."; return -1; } param_ptr_a->can_client = client_a.get(); param_ptr_a->is_first_agent = true; param_ptr_a->conf = can_client_conf_a; CANCardParameter can_client_conf_b; std::unique_ptr<CanClient> client_b; if (!FLAGS_only_one_send) { if (!apollo::cyber::common::GetProtoFromFile(FLAGS_can_client_conf_file_b, &can_client_conf_b)) { AERROR << "Unable to load canbus conf file: " << FLAGS_can_client_conf_file_b; return -1; } AINFO << "Conf file is loaded: " << FLAGS_can_client_conf_file_b; AINFO << can_client_conf_b.ShortDebugString(); client_b = can_client_factory->CreateObject(can_client_conf_b.brand()); if (!client_b || !client_b->Init(can_client_conf_b) || client_b->Start() != ErrorCode::OK) { AERROR << "Create can client b failed."; return -1; } param_ptr_b->can_client = client_b.get(); param_ptr_b->conf = can_client_conf_b; } CanAgent agent_a(param_ptr_a.get()); CanAgent agent_b(param_ptr_b.get()); agent_a.AddOtherAgent(&agent_b); agent_b.AddOtherAgent(&agent_a); if (!agent_a.Start()) { AERROR << "Agent a start failed."; return -1; } if (FLAGS_only_one_send) { agent_b.is_receiving(true); agent_b.is_sending_finish(true); } else { if (!agent_b.Start()) { AERROR << "Agent b start failed."; return -1; } } agent_a.WaitForFinish(); if (!FLAGS_only_one_send) { agent_b.WaitForFinish(); } param_ptr_a->print(); if (!FLAGS_only_one_send) { param_ptr_b->print(); } return 0; } <|endoftext|>
<commit_before>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2005 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/Thread/UncaughtThreadException.h> namespace vpr { UncaughtThreadException::UncaughtThreadException(const std::string& msg, const std::string& location) throw() : Exception(msg, location) { /* Do nothing. */ ; } UncaughtThreadException::~UncaughtThreadException() throw() { /* Do nothing. */ ; } void UncaughtThreadException::setException(const vpr::Exception& ex) { mDescription = ex.getExceptionName() + ": " + ex.getDescription(); mLocation = ex.getLocation(); mStackTrace = ex.getStackTrace(); } void UncaughtThreadException::setException(const std::exception& ex) { mDescription = ex.what(); mLocation = "Location not availible with std::exception."; mStackTrace = "Stacktrace not availible with std::exception."; } } <commit_msg>Fixed Visual C++ 7.0 compile error.<commit_after>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2005 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <sstream> #include <vpr/Thread/UncaughtThreadException.h> namespace vpr { UncaughtThreadException::UncaughtThreadException(const std::string& msg, const std::string& location) throw() : Exception(msg, location) { /* Do nothing. */ ; } UncaughtThreadException::~UncaughtThreadException() throw() { /* Do nothing. */ ; } void UncaughtThreadException::setException(const vpr::Exception& ex) { std::stringstream desc_stream; desc_stream << ex.getExceptionName() << ": " + ex.getDescription(); mDescription = desc_stream.str(); mLocation = ex.getLocation(); mStackTrace = ex.getStackTrace(); } void UncaughtThreadException::setException(const std::exception& ex) { mDescription = ex.what(); mLocation = "Location not availible with std::exception."; mStackTrace = "Stacktrace not availible with std::exception."; } } <|endoftext|>
<commit_before><commit_msg>new_client: updated xtfs_send against Yield changes<commit_after><|endoftext|>
<commit_before> #pragma once #include <cppassist/logging/logging.h> #include <cppexpose/typed/Typed.h> #include <gloperate/pipeline/Stage.h> #include <gloperate/pipeline/Slot.h> namespace gloperate { template <typename T> template <typename U> auto Slot<T>::DereferenceHelper<U>::pointer(U * value) -> Pointer { return value; } template <typename T> template <typename U> auto Slot<T>::DereferenceHelper<U*>::pointer(U ** value) -> Pointer { return *value; } template <typename T> template <typename U> auto Slot<T>::DereferenceHelper<U*>::pointer(U * const * value) -> Pointer { return *value; } template <typename T> Slot<T>::Slot(SlotType slotType, const std::string & name, Stage * parent, const T & value) : cppexpose::DirectValue<T, AbstractSlot>(value) , m_valid(true) , m_source(nullptr) { // Do not add property to object, yet. Just initialize the property itself this->initProperty(name, nullptr); // Initialize slot, will also add slot as a property this->initSlot(slotType, parent); } template <typename T> Slot<T>::Slot(SlotType slotType, const std::string & name, const T & value) : cppexpose::DirectValue<T, AbstractSlot>(value) , m_valid(true) , m_source(nullptr) { // Make as a dynamic slot this->m_dynamic = true; // Do not add property to object, yet. Just initialize the property itself this->initProperty(name, nullptr); // Initialize slot this->initSlot(slotType, nullptr); } template <typename T> Slot<T>::~Slot() { } template <typename T> bool Slot<T>::connect(Slot<T> * source) { assert(source != nullptr); cppassist::debug(2, "gloperate") << this->qualifiedName() << ": connect slot " << source->qualifiedName(); // Check if source is valid if (!source) { return false; } // Set source m_source = source; // Connect to data container; no direct binding of member function to achive virtual lookup m_valueConnection = m_source->valueChanged.connect([this] (const T & value) { this->onValueChanged(value); } ); m_validConnection = m_source->valueInvalidated.connect([this] () { this->onValueInvalidated(); } ); // Emit events this->promoteConnection(); this->promoteRequired(); this->onValueChanged(m_source->value()); // Success return true; } template <typename T> Slot<T> & Slot<T>::operator<<(Slot<T> & source) { this->connect(&source); return *this; } template <typename T> const T & Slot<T>::operator*() const { return *this->ptr(); } template <typename T> auto Slot<T>::operator->() -> typename DereferenceHelper<T>::Pointer { return DereferenceHelper<T>::pointer(this->ptr()); } template <typename T> auto Slot<T>::operator->() const -> const typename DereferenceHelper<T>::Pointer { return DereferenceHelper<T>::pointer(this->ptr()); } template <typename T> bool Slot<T>::isCompatible(const AbstractSlot * source) const { // Check if source is valid and compatible data container if (!source) { return false; } // Check if types are equal return this->type() == source->type(); } template <typename T> bool Slot<T>::connect(AbstractSlot * source) { // Check if source is valid and compatible data container if (!source || !isCompatible(source)) { cppassist::debug(2, "gloperate") << this->qualifiedName() << ": connect slot failed for " << source->qualifiedName(); return false; } // Connect to source data return connect(static_cast< Slot<T> * >(source)); } template <typename T> void Slot<T>::disconnect() { // Reset source property m_source = nullptr; m_valueConnection = cppexpose::ScopedConnection(); m_validConnection = cppexpose::ScopedConnection(); cppassist::debug(2, "gloperate") << this->qualifiedName() << ": disconnect slot"; // Emit events this->promoteConnection(); this->onValueChanged(this->m_value); } template <typename T> const AbstractSlot * Slot<T>::source() const { return m_source; } template <typename T> bool Slot<T>::isValid() const { // If connected, return validity of source slot if (m_source) { return m_source->isValid(); } // Return validity of own data return m_valid; } template <typename T> void Slot<T>::invalidate() { if (!m_valid) { return; } // If connected, abort function if (!m_source) { m_valid = false; } // Emit signal if it was invalidated this->onValueInvalidated(); } template <typename T> bool Slot<T>::hasChanged() const { return m_changed; } template <typename T> void Slot<T>::setChanged(bool hasChanged) { m_changed = hasChanged; } template <typename T> void Slot<T>::onRequiredChanged() { promoteRequired(); } template <typename T> T Slot<T>::value() const { // If connected, return value of source slot if (m_source) { return m_source->value(); } // Return own data return this->m_value; } template <typename T> void Slot<T>::setValue(const T & value) { // If connected, abort function if (m_source) { return; } // Set own data this->m_value = value; this->m_valid = true; // Emit signal this->onValueChanged(this->m_value); } template <typename T> const T * Slot<T>::ptr() const { // If connected, return value of source slot if (m_source) { return m_source->ptr(); } // Return own data return &this->m_value; } template <typename T> T * Slot<T>::ptr() { // If connected, return value of source slot if (m_source) { return m_source->ptr(); } // Return own data return &this->m_value; } template <typename T> std::unique_ptr<cppexpose::AbstractTyped> Slot<T>::clone() const { return nullptr; } template <typename T> bool Slot<T>::isObject() const { return false; } template <typename T> void Slot<T>::promoteConnection() { // Emit signal this->connectionChanged(); this->parentStage()->invalidateInputConnections(); } template <typename T> void Slot<T>::promoteRequired() { // Check if input slot is connected if (!m_source) { return; } // Promote required-flag to connected slot m_source->setRequired(this->m_required); } } // namespace gloperate <commit_msg>Fix Slot<T>::promoteConnection behavior<commit_after> #pragma once #include <cppassist/logging/logging.h> #include <cppexpose/typed/Typed.h> #include <gloperate/pipeline/Stage.h> #include <gloperate/pipeline/Slot.h> namespace gloperate { template <typename T> template <typename U> auto Slot<T>::DereferenceHelper<U>::pointer(U * value) -> Pointer { return value; } template <typename T> template <typename U> auto Slot<T>::DereferenceHelper<U*>::pointer(U ** value) -> Pointer { return *value; } template <typename T> template <typename U> auto Slot<T>::DereferenceHelper<U*>::pointer(U * const * value) -> Pointer { return *value; } template <typename T> Slot<T>::Slot(SlotType slotType, const std::string & name, Stage * parent, const T & value) : cppexpose::DirectValue<T, AbstractSlot>(value) , m_valid(true) , m_source(nullptr) { // Do not add property to object, yet. Just initialize the property itself this->initProperty(name, nullptr); // Initialize slot, will also add slot as a property this->initSlot(slotType, parent); } template <typename T> Slot<T>::Slot(SlotType slotType, const std::string & name, const T & value) : cppexpose::DirectValue<T, AbstractSlot>(value) , m_valid(true) , m_source(nullptr) { // Make as a dynamic slot this->m_dynamic = true; // Do not add property to object, yet. Just initialize the property itself this->initProperty(name, nullptr); // Initialize slot this->initSlot(slotType, nullptr); } template <typename T> Slot<T>::~Slot() { } template <typename T> bool Slot<T>::connect(Slot<T> * source) { assert(source != nullptr); cppassist::debug(2, "gloperate") << this->qualifiedName() << ": connect slot " << source->qualifiedName(); // Check if source is valid if (!source) { return false; } // Set source m_source = source; // Connect to data container; no direct binding of member function to achive virtual lookup m_valueConnection = m_source->valueChanged.connect([this] (const T & value) { this->onValueChanged(value); } ); m_validConnection = m_source->valueInvalidated.connect([this] () { this->onValueInvalidated(); } ); // Emit events this->promoteConnection(); this->promoteRequired(); this->onValueChanged(m_source->value()); // Success return true; } template <typename T> Slot<T> & Slot<T>::operator<<(Slot<T> & source) { this->connect(&source); return *this; } template <typename T> const T & Slot<T>::operator*() const { return *this->ptr(); } template <typename T> auto Slot<T>::operator->() -> typename DereferenceHelper<T>::Pointer { return DereferenceHelper<T>::pointer(this->ptr()); } template <typename T> auto Slot<T>::operator->() const -> const typename DereferenceHelper<T>::Pointer { return DereferenceHelper<T>::pointer(this->ptr()); } template <typename T> bool Slot<T>::isCompatible(const AbstractSlot * source) const { // Check if source is valid and compatible data container if (!source) { return false; } // Check if types are equal return this->type() == source->type(); } template <typename T> bool Slot<T>::connect(AbstractSlot * source) { // Check if source is valid and compatible data container if (!source || !isCompatible(source)) { cppassist::debug(2, "gloperate") << this->qualifiedName() << ": connect slot failed for " << source->qualifiedName(); return false; } // Connect to source data return connect(static_cast< Slot<T> * >(source)); } template <typename T> void Slot<T>::disconnect() { // Reset source property m_source = nullptr; m_valueConnection = cppexpose::ScopedConnection(); m_validConnection = cppexpose::ScopedConnection(); cppassist::debug(2, "gloperate") << this->qualifiedName() << ": disconnect slot"; // Emit events this->promoteConnection(); this->onValueChanged(this->m_value); } template <typename T> const AbstractSlot * Slot<T>::source() const { return m_source; } template <typename T> bool Slot<T>::isValid() const { // If connected, return validity of source slot if (m_source) { return m_source->isValid(); } // Return validity of own data return m_valid; } template <typename T> void Slot<T>::invalidate() { if (!m_valid) { return; } // If connected, abort function if (!m_source) { m_valid = false; } // Emit signal if it was invalidated this->onValueInvalidated(); } template <typename T> bool Slot<T>::hasChanged() const { return m_changed; } template <typename T> void Slot<T>::setChanged(bool hasChanged) { m_changed = hasChanged; } template <typename T> void Slot<T>::onRequiredChanged() { promoteRequired(); } template <typename T> T Slot<T>::value() const { // If connected, return value of source slot if (m_source) { return m_source->value(); } // Return own data return this->m_value; } template <typename T> void Slot<T>::setValue(const T & value) { // If connected, abort function if (m_source) { return; } // Set own data this->m_value = value; this->m_valid = true; // Emit signal this->onValueChanged(this->m_value); } template <typename T> const T * Slot<T>::ptr() const { // If connected, return value of source slot if (m_source) { return m_source->ptr(); } // Return own data return &this->m_value; } template <typename T> T * Slot<T>::ptr() { // If connected, return value of source slot if (m_source) { return m_source->ptr(); } // Return own data return &this->m_value; } template <typename T> std::unique_ptr<cppexpose::AbstractTyped> Slot<T>::clone() const { return nullptr; } template <typename T> bool Slot<T>::isObject() const { return false; } template <typename T> void Slot<T>::promoteConnection() { // Emit signal this->connectionChanged(); if (this->parentStage()) { this->parentStage()->invalidateInputConnections(); } } template <typename T> void Slot<T>::promoteRequired() { // Check if input slot is connected if (!m_source) { return; } // Promote required-flag to connected slot m_source->setRequired(this->m_required); } } // namespace gloperate <|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. #include "config.h" #include "Font.h" #include "FloatRect.h" #include "GlyphBuffer.h" #include "GraphicsContext.h" #include "NotImplemented.h" #include "PlatformContextSkia.h" #include "SimpleFontData.h" #include "SkCanvas.h" #include "SkPaint.h" #include "SkTemplates.h" #include "SkTypeface.h" #include "SkUtils.h" namespace WebCore { void Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font, const GlyphBuffer& glyphBuffer, int from, int numGlyphs, const FloatPoint& point) const { SkCanvas* canvas = gc->platformContext()->canvas(); SkPaint paint; font->platformData().setupPaint(&paint); paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding); paint.setColor(gc->fillColor().rgb()); SkASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t)); // compile-time assert const GlyphBufferGlyph* glyphs = glyphBuffer.glyphs(from); SkScalar x = SkFloatToScalar(point.x()); SkScalar y = SkFloatToScalar(point.y()); // TODO(port): Android WebCore has patches for PLATFORM(SGL) which involves // this, however we don't have these patches and it's unclear when Android // may upstream them. #if 0 if (glyphBuffer.hasAdjustedWidths()) { const GlyphBufferAdvance* adv = glyphBuffer.advances(from); SkAutoSTMalloc<32, SkPoint> storage(numGlyphs); SkPoint* pos = storage.get(); for (int i = 0; i < numGlyphs; i++) { pos[i].set(x, y); x += SkFloatToScalar(adv[i].width()); y += SkFloatToScalar(adv[i].height()); } canvas->drawPosText(glyphs, numGlyphs << 1, pos, paint); } else { canvas->drawText(glyphs, numGlyphs << 1, x, y, paint); } #endif canvas->drawText(glyphs, numGlyphs << 1, x, y, paint); } void Font::drawComplexText(GraphicsContext* context, const TextRun& run, const FloatPoint& point, int from, int to) const { notImplemented(); } float Font::floatWidthForComplexText(const TextRun& run) const { notImplemented(); return 0; } int Font::offsetForPositionForComplexText(const TextRun& run, int x, bool includePartialGlyphs) const { notImplemented(); return 0; } FloatRect Font::selectionRectForComplexText(const TextRun& run, const IntPoint& point, int h, int from, int to) const { notImplemented(); return FloatRect(); } } // namespace WebCore <commit_msg>Linux: respect non-standard advance widths for glyphs.<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. #include "config.h" #include "Font.h" #include "FloatRect.h" #include "GlyphBuffer.h" #include "GraphicsContext.h" #include "NotImplemented.h" #include "PlatformContextSkia.h" #include "SimpleFontData.h" #include "SkCanvas.h" #include "SkPaint.h" #include "SkTemplates.h" #include "SkTypeface.h" #include "SkUtils.h" namespace WebCore { void Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font, const GlyphBuffer& glyphBuffer, int from, int numGlyphs, const FloatPoint& point) const { SkCanvas* canvas = gc->platformContext()->canvas(); SkPaint paint; font->platformData().setupPaint(&paint); paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding); paint.setColor(gc->fillColor().rgb()); SkASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t)); // compile-time assert const GlyphBufferGlyph* glyphs = glyphBuffer.glyphs(from); SkScalar x = SkFloatToScalar(point.x()); SkScalar y = SkFloatToScalar(point.y()); // TODO(port): text rendering speed: // Android has code in their WebCore fork to special case when the // GlyphBuffer has no advances other than the defaults. In that case the // text drawing can proceed faster. However, it's unclear when those // patches may be upstreamed to WebKit so we always use the slower path // here. const GlyphBufferAdvance* adv = glyphBuffer.advances(from); SkAutoSTMalloc<32, SkPoint> storage(numGlyphs); SkPoint* pos = storage.get(); for (int i = 0; i < numGlyphs; i++) { pos[i].set(x, y); x += SkFloatToScalar(adv[i].width()); y += SkFloatToScalar(adv[i].height()); } canvas->drawPosText(glyphs, numGlyphs << 1, pos, paint); } void Font::drawComplexText(GraphicsContext* context, const TextRun& run, const FloatPoint& point, int from, int to) const { notImplemented(); } float Font::floatWidthForComplexText(const TextRun& run) const { notImplemented(); return 0; } int Font::offsetForPositionForComplexText(const TextRun& run, int x, bool includePartialGlyphs) const { notImplemented(); return 0; } FloatRect Font::selectionRectForComplexText(const TextRun& run, const IntPoint& point, int h, int from, int to) const { notImplemented(); return FloatRect(); } } // namespace WebCore <|endoftext|>
<commit_before>#include "stdafx.h" #include "CppUnitTest.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace EffiData_Test { TEST_CLASS(EffiData_Test) { protected: streambuf * oldStdoutBuf; stringstream consoleOutput; string consoleDump(){ std::istreambuf_iterator<char> eos; std::string sout(std::istreambuf_iterator<char>(consoleOutput), eos); return sout; } public: //Redirect cout. TEST_METHOD_INITIALIZE(pre) { oldStdoutBuf = std::cout.rdbuf(); std::cout.rdbuf(consoleOutput.rdbuf()); } //Restore redirect cout TEST_METHOD_CLEANUP(post) { std::cout.rdbuf(oldStdoutBuf); } TEST_METHOD(BasicPrintCheck) {//id = 0 Event e("test event"); string expected = "{\n" " \"name\": \"test event\",\n" " \"id\": \"0\",\n" " \"priority\": \"5\",\n" " \"tags\": \"\",\n" //Should be [], but boost property tree doesn't support it. " \"complete\": \"false\",\n" " \"start\": \"0\",\n" " \"end\": \"0\",\n" " \"parent\": \"0\",\n" " \"content\": \"0\"\n" "}\n"; std::cout<<e; string result = consoleDump(); Logger::WriteMessage(result.c_str()); Assert::AreEqual(expected, result); } //WARNING: DO NOT RE-ORDER TESTS. ADD TO THE END. TEST_METHOD(TagCheck) {//id = 1 Event e("test event"); e.addTag("tag 1"); e.addTag("nextTag"); auto tags = e.getTags(); Assert::AreEqual(2, (int)tags.size()); Assert::IsTrue(std::find(tags.begin(), tags.end(), "tag 1")!=tags.end()); Assert::IsTrue(std::find(tags.begin(), tags.end(), "nextTag")!=tags.end()); } TEST_METHOD(TagPrintCheck) { //id = 2 Event e("test event"); e.addTag("tag 1"); e.addTag("nextTag"); std::cout<<e; string result = consoleDump(); Logger::WriteMessage(result.c_str()); std::string expected = "{\n" " \"name\": \"test event\",\n" " \"id\": \"2\",\n" " \"priority\": \"5\",\n" " \"tags\": [\n" " \"tag 1\",\n" " \"nextTag\"\n" " ],\n" " \"complete\": \"false\",\n" " \"start\": \"0\",\n" " \"end\": \"0\",\n" " \"parent\": \"0\",\n" " \"content\": \"0\"\n" "}\n"; Assert::AreEqual(expected, result); } TEST_METHOD(IDIncrementCheck) { //id = 3,4 Event e("test event"); Event e2("test event"); Assert::AreEqual(e.getId() +1 ,e2.getId()); } TEST_METHOD(InputTest) { //id=5. string contents = "{\n" " \"name\": \"test event\",\n" " \"id\": \"40\",\n" " \"priority\": \"3\",\n" " \"tags\": \"\",\n" " \"complete\": \"true\",\n" " \"start\": \"0\",\n" " \"end\": \"0\",\n" " \"parent\": \"0\",\n" " \"content\": \"0\"\n" "}\n"; Event e(""); stringstream ss; ss.str(contents); ss>>e; std::cout<<e; string result = consoleDump(); Logger::WriteMessage(result.c_str()); Assert::AreEqual(contents, result); } TEST_METHOD(TagDeleteCheck) {//id = 6 Event e("test event"); e.addTag("tag 1"); e.addTag("nextTag"); e.addTag("final tag"); e.removeTag("nextTag"); e.removeTag("noexisttag"); auto tags = e.getTags(); Assert::AreEqual(2, (int)tags.size()); Assert::IsTrue(std::find(tags.begin(), tags.end(), "tag 1")!=tags.end()); Assert::IsTrue(std::find(tags.begin(), tags.end(), "final tag")!=tags.end()); } }; }<commit_msg>[DB] Test changes<commit_after>#include "stdafx.h" #include "CppUnitTest.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace EffiData_Test { TEST_CLASS(EffiData_Test) { protected: streambuf * oldStdoutBuf; stringstream consoleOutput; string consoleDump(){ std::istreambuf_iterator<char> eos; std::string sout(std::istreambuf_iterator<char>(consoleOutput), eos); return sout; } public: //Redirect cout. TEST_METHOD_INITIALIZE(pre) { oldStdoutBuf = std::cout.rdbuf(); std::cout.rdbuf(consoleOutput.rdbuf()); } //Restore redirect cout TEST_METHOD_CLEANUP(post) { std::cout.rdbuf(oldStdoutBuf); } TEST_METHOD(BasicPrintCheck) {//id = 1 Event e("test event"); string expected = "{\n" " \"name\": \"test event\",\n" " \"id\": \"1\",\n" " \"priority\": \"5\",\n" " \"tags\": \"\",\n" //Should be [], but boost property tree doesn't support it. " \"complete\": \"false\",\n" " \"start\": \"0\",\n" " \"end\": \"0\",\n" " \"parent\": \"0\",\n" " \"content\": \"0\"\n" "}\n"; std::cout<<e; string result = consoleDump(); Logger::WriteMessage(result.c_str()); Assert::AreEqual(expected, result); } //WARNING: DO NOT RE-ORDER TESTS. ADD TO THE END. TEST_METHOD(TagCheck) {//id = 2 Event e("test event"); e.addTag("tag 1"); e.addTag("nextTag"); auto tags = e.getTags(); Assert::AreEqual(2, (int)tags.size()); Assert::IsTrue(std::find(tags.begin(), tags.end(), "tag 1")!=tags.end()); Assert::IsTrue(std::find(tags.begin(), tags.end(), "nextTag")!=tags.end()); } TEST_METHOD(TagPrintCheck) { //id = 3 Event e("test event"); e.addTag("tag 1"); e.addTag("nextTag"); std::cout<<e; string result = consoleDump(); Logger::WriteMessage(result.c_str()); std::string expected = "{\n" " \"name\": \"test event\",\n" " \"id\": \"3\",\n" " \"priority\": \"5\",\n" " \"tags\": [\n" " \"tag 1\",\n" " \"nextTag\"\n" " ],\n" " \"complete\": \"false\",\n" " \"start\": \"0\",\n" " \"end\": \"0\",\n" " \"parent\": \"0\",\n" " \"content\": \"0\"\n" "}\n"; Assert::AreEqual(expected, result); } TEST_METHOD(IDIncrementCheck) { //id = 4,5 Event e("test event"); Event e2("test event"); Assert::AreEqual(e.getId() +1 ,e2.getId()); } TEST_METHOD(InputTest) { //id=6. string contents = "{\n" " \"name\": \"test event\",\n" " \"id\": \"40\",\n" " \"priority\": \"3\",\n" " \"tags\": \"\",\n" " \"complete\": \"true\",\n" " \"start\": \"0\",\n" " \"end\": \"0\",\n" " \"parent\": \"0\",\n" " \"content\": \"0\"\n" "}\n"; Event e(""); stringstream ss; ss.str(contents); ss>>e; std::cout<<e; string result = consoleDump(); Logger::WriteMessage(result.c_str()); Assert::AreEqual(contents, result); } TEST_METHOD(TagDeleteCheck) {//id = 6 Event e("test event"); e.addTag("tag 1"); e.addTag("nextTag"); e.addTag("final tag"); e.removeTag("nextTag"); e.removeTag("noexisttag"); auto tags = e.getTags(); Assert::AreEqual(2, (int)tags.size()); Assert::IsTrue(std::find(tags.begin(), tags.end(), "tag 1")!=tags.end()); Assert::IsTrue(std::find(tags.begin(), tags.end(), "final tag")!=tags.end()); } }; }<|endoftext|>
<commit_before>//@author A0097630B #include "stdafx.h" #include <unordered_map> #include "You-NLP/parse_tree/task_priority.h" #include "internal/query_executor.h" #include "internal/query_executor_builder_visitor.h" #include "exceptions/context_index_out_of_range_exception.h" #include "../mocks/task_list.h" #include "../mocks/query.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework { std::wstring ToString(You::Controller::Task::Priority priority) { return ToString(static_cast<int>(priority)); } } // namespace CppUnitTestFramework } // namespace VisualStudio } // namespace Microsoft namespace You { namespace Controller { namespace Internal { namespace UnitTests { namespace Mocks { // NOLINTNEXTLINE(build/namespaces) using namespace You::Controller::UnitTests::Mocks; } using Task = You::Controller::Task; using TaskPriority = You::NLP::TaskPriority; TEST_CLASS(QueryExecutorBuilderVisitorTests) { TEST_METHOD(getsCorrectTypeForAddQueries) { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::ADD_QUERY); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); ADD_RESULT result( boost::get<ADD_RESULT>(executor->execute())); Assert::AreEqual( Mocks::Queries::ADD_QUERY.description, result.task.getDescription()); Assert::AreEqual( Task::Priority::NORMAL, result.task.getPriority()); Assert::AreEqual( Mocks::Queries::ADD_QUERY.deadline.get(), result.task.getDeadline()); You::NLP::ADD_QUERY queryWithoutDeadline(Mocks::Queries::ADD_QUERY); queryWithoutDeadline.deadline = You::Utils::Option<boost::posix_time::ptime>(); query = queryWithoutDeadline; executor = boost::apply_visitor(visitor, query); result = boost::get<ADD_RESULT>(executor->execute()); Assert::AreEqual( Mocks::Queries::ADD_QUERY.description, result.task.getDescription()); Assert::AreEqual( Task::Priority::NORMAL, result.task.getPriority()); Assert::AreEqual( Task::DEFAULT_DEADLINE, result.task.getDeadline()); You::NLP::ADD_QUERY queryWithPriority(Mocks::Queries::ADD_QUERY); queryWithPriority.priority = TaskPriority::HIGH; query = queryWithPriority; executor = boost::apply_visitor(visitor, query); result = boost::get<ADD_RESULT>(executor->execute()); Assert::AreEqual( Mocks::Queries::ADD_QUERY.description, result.task.getDescription()); Assert::AreEqual( Task::Priority::HIGH, result.task.getPriority()); Assert::AreEqual( Mocks::Queries::ADD_QUERY.deadline.get(), result.task.getDeadline()); } TEST_METHOD(getsCorrectTypeForShowQueries) { Mocks::TaskList taskList(5); QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::SHOW_QUERY); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); SHOW_RESULT result( boost::get<SHOW_RESULT>(executor->execute())); Assert::IsTrue( std::is_sorted(begin(result.tasks), end(result.tasks), [](const Task& left, const Task& right) { return left.getDeadline() >= right.getDeadline(); })); { // NOLINT(whitespace/braces) You::NLP::SHOW_QUERY templ = Mocks::Queries::SHOW_QUERY; templ.order = { { You::NLP::TaskField::DESCRIPTION, You::NLP::SHOW_QUERY::Order::ASCENDING } }; query = std::move(templ); } executor = boost::apply_visitor(visitor, query); result = boost::get<SHOW_RESULT>(executor->execute()); Assert::IsTrue( std::is_sorted(begin(result.tasks), end(result.tasks), [](const Task& left, const Task& right) { return left.getDescription() <= right.getDescription(); })); { // NOLINT(whitespace/braces) You::NLP::SHOW_QUERY templ = Mocks::Queries::SHOW_QUERY; templ.order = { { You::NLP::TaskField::PRIORITY, You::NLP::SHOW_QUERY::Order::DESCENDING } }; query = std::move(templ); } executor = boost::apply_visitor(visitor, query); result = boost::get<SHOW_RESULT>(executor->execute()); Assert::IsTrue( std::is_sorted(begin(result.tasks), end(result.tasks), [](const Task& left, const Task& right) { return left.getPriority() >= right.getPriority(); })); } TEST_METHOD(getsCorrectTypeForEditQueries) { getsCorrectTypeForEditQueries1(); getsCorrectTypeForEditQueries2(); getsCorrectTypeForEditQueries3(); getsCorrectTypeForEditQueries4(); } void getsCorrectTypeForEditQueries1() { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::EDIT_QUERY); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); EDIT_RESULT result( boost::get<EDIT_RESULT>(executor->execute())); Assert::AreEqual(taskList.front().getID(), result.task.getID()); Assert::AreEqual(Mocks::Queries::EDIT_QUERY.description.get(), result.task.getDescription()); Assert::AreEqual(nlpPriorityToTaskPriority( Mocks::Queries::EDIT_QUERY.priority.get()), result.task.getPriority()); Assert::AreEqual(Mocks::Queries::EDIT_QUERY.deadline.get(), result.task.getDeadline()); } void getsCorrectTypeForEditQueries2() { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::EDIT_QUERY query2(Mocks::Queries::EDIT_QUERY); query2.deadline = You::Utils::Option<boost::posix_time::ptime>(); You::NLP::QUERY query(query2); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); EDIT_RESULT result( boost::get<EDIT_RESULT>(executor->execute())); Assert::AreEqual(taskList.front().getID(), result.task.getID()); Assert::AreEqual(Mocks::Queries::EDIT_QUERY.description.get(), result.task.getDescription()); Assert::AreEqual(nlpPriorityToTaskPriority( Mocks::Queries::EDIT_QUERY.priority.get()), result.task.getPriority()); Assert::AreEqual(taskList.front().getDeadline(), result.task.getDeadline()); } void getsCorrectTypeForEditQueries3() { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::EDIT_QUERY query2(Mocks::Queries::EDIT_QUERY); query2.description = You::Utils::Option<std::wstring>(); You::NLP::QUERY query(query2); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); EDIT_RESULT result( boost::get<EDIT_RESULT>(executor->execute())); Assert::AreEqual(taskList.front().getID(), result.task.getID()); Assert::AreEqual(taskList.front().getDescription(), result.task.getDescription()); Assert::AreEqual(nlpPriorityToTaskPriority( Mocks::Queries::EDIT_QUERY.priority.get()), result.task.getPriority()); Assert::AreEqual(Mocks::Queries::EDIT_QUERY.deadline.get(), result.task.getDeadline()); } void getsCorrectTypeForEditQueries4() { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::EDIT_QUERY query2(Mocks::Queries::EDIT_QUERY); query2.priority = You::Utils::Option<You::NLP::TaskPriority>(); You::NLP::QUERY query(query2); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); EDIT_RESULT result( boost::get<EDIT_RESULT>(executor->execute())); Assert::AreEqual(taskList.front().getID(), result.task.getID()); Assert::AreEqual(Mocks::Queries::EDIT_QUERY.description.get(), result.task.getDescription()); Assert::AreEqual(taskList.front().getPriority(), result.task.getPriority()); Assert::AreEqual(Mocks::Queries::EDIT_QUERY.deadline.get(), result.task.getDeadline()); } TEST_METHOD(editQueriesOutOfBoundsThrowsContextOutOfRange) { Mocks::TaskList taskList(0); QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::EDIT_QUERY); Assert::ExpectException<ContextIndexOutOfRangeException>([&]() { boost::apply_visitor(visitor, query); }); } TEST_METHOD(getsCorrectTypeForDeleteQueries) { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::DELETE_QUERY); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); DELETE_RESULT result( boost::get<DELETE_RESULT>(executor->execute())); Assert::AreEqual(taskList.front().getID(), result.task); } TEST_METHOD(deleteQueriesOutOfBoundsThrowsContextOutOfRange) { Mocks::TaskList taskList(0); QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::DELETE_QUERY); Assert::ExpectException<ContextIndexOutOfRangeException>([&]() { boost::apply_visitor(visitor, query); }); } TEST_METHOD(getsCorrectTypeForUndoQueries) { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::UNDO_QUERY); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); UNDO_RESULT result( boost::get<UNDO_RESULT>(executor->execute())); // TODO(lowjoel): test for..? } private: Task::Priority nlpPriorityToTaskPriority(NLP::TaskPriority priority) { auto iterator = nlpPriorityToTaskPriorityMap.find(priority); assert(iterator != end(nlpPriorityToTaskPriorityMap)); return iterator->second; } private: static const std::unordered_map<NLP::TaskPriority, Task::Priority> nlpPriorityToTaskPriorityMap; }; const std::unordered_map<NLP::TaskPriority, Task::Priority> QueryExecutorBuilderVisitorTests::nlpPriorityToTaskPriorityMap({ { NLP::TaskPriority::NORMAL, Task::Priority::NORMAL }, { NLP::TaskPriority::HIGH, Task::Priority::HIGH } }); } // namespace UnitTests } // namespace Internal } // namespace Controller } // namespace You <commit_msg>Comparators in C++ never check for equality.<commit_after>//@author A0097630B #include "stdafx.h" #include <unordered_map> #include "You-NLP/parse_tree/task_priority.h" #include "internal/query_executor.h" #include "internal/query_executor_builder_visitor.h" #include "exceptions/context_index_out_of_range_exception.h" #include "../mocks/task_list.h" #include "../mocks/query.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework { std::wstring ToString(You::Controller::Task::Priority priority) { return ToString(static_cast<int>(priority)); } } // namespace CppUnitTestFramework } // namespace VisualStudio } // namespace Microsoft namespace You { namespace Controller { namespace Internal { namespace UnitTests { namespace Mocks { // NOLINTNEXTLINE(build/namespaces) using namespace You::Controller::UnitTests::Mocks; } using Task = You::Controller::Task; using TaskPriority = You::NLP::TaskPriority; TEST_CLASS(QueryExecutorBuilderVisitorTests) { TEST_METHOD(getsCorrectTypeForAddQueries) { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::ADD_QUERY); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); ADD_RESULT result( boost::get<ADD_RESULT>(executor->execute())); Assert::AreEqual( Mocks::Queries::ADD_QUERY.description, result.task.getDescription()); Assert::AreEqual( Task::Priority::NORMAL, result.task.getPriority()); Assert::AreEqual( Mocks::Queries::ADD_QUERY.deadline.get(), result.task.getDeadline()); You::NLP::ADD_QUERY queryWithoutDeadline(Mocks::Queries::ADD_QUERY); queryWithoutDeadline.deadline = You::Utils::Option<boost::posix_time::ptime>(); query = queryWithoutDeadline; executor = boost::apply_visitor(visitor, query); result = boost::get<ADD_RESULT>(executor->execute()); Assert::AreEqual( Mocks::Queries::ADD_QUERY.description, result.task.getDescription()); Assert::AreEqual( Task::Priority::NORMAL, result.task.getPriority()); Assert::AreEqual( Task::DEFAULT_DEADLINE, result.task.getDeadline()); You::NLP::ADD_QUERY queryWithPriority(Mocks::Queries::ADD_QUERY); queryWithPriority.priority = TaskPriority::HIGH; query = queryWithPriority; executor = boost::apply_visitor(visitor, query); result = boost::get<ADD_RESULT>(executor->execute()); Assert::AreEqual( Mocks::Queries::ADD_QUERY.description, result.task.getDescription()); Assert::AreEqual( Task::Priority::HIGH, result.task.getPriority()); Assert::AreEqual( Mocks::Queries::ADD_QUERY.deadline.get(), result.task.getDeadline()); } TEST_METHOD(getsCorrectTypeForShowQueries) { Mocks::TaskList taskList(5); QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::SHOW_QUERY); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); SHOW_RESULT result( boost::get<SHOW_RESULT>(executor->execute())); Assert::IsTrue( std::is_sorted(begin(result.tasks), end(result.tasks), [](const Task& left, const Task& right) { return left.getDeadline() > right.getDeadline(); })); { // NOLINT(whitespace/braces) You::NLP::SHOW_QUERY templ = Mocks::Queries::SHOW_QUERY; templ.order = { { You::NLP::TaskField::DESCRIPTION, You::NLP::SHOW_QUERY::Order::ASCENDING } }; query = std::move(templ); } executor = boost::apply_visitor(visitor, query); result = boost::get<SHOW_RESULT>(executor->execute()); Assert::IsTrue( std::is_sorted(begin(result.tasks), end(result.tasks), [](const Task& left, const Task& right) { return left.getDescription() < right.getDescription(); })); { // NOLINT(whitespace/braces) You::NLP::SHOW_QUERY templ = Mocks::Queries::SHOW_QUERY; templ.order = { { You::NLP::TaskField::PRIORITY, You::NLP::SHOW_QUERY::Order::DESCENDING } }; query = std::move(templ); } executor = boost::apply_visitor(visitor, query); result = boost::get<SHOW_RESULT>(executor->execute()); Assert::IsTrue( std::is_sorted(begin(result.tasks), end(result.tasks), [](const Task& left, const Task& right) { return left.getPriority() > right.getPriority(); })); } TEST_METHOD(getsCorrectTypeForEditQueries) { getsCorrectTypeForEditQueries1(); getsCorrectTypeForEditQueries2(); getsCorrectTypeForEditQueries3(); getsCorrectTypeForEditQueries4(); } void getsCorrectTypeForEditQueries1() { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::EDIT_QUERY); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); EDIT_RESULT result( boost::get<EDIT_RESULT>(executor->execute())); Assert::AreEqual(taskList.front().getID(), result.task.getID()); Assert::AreEqual(Mocks::Queries::EDIT_QUERY.description.get(), result.task.getDescription()); Assert::AreEqual(nlpPriorityToTaskPriority( Mocks::Queries::EDIT_QUERY.priority.get()), result.task.getPriority()); Assert::AreEqual(Mocks::Queries::EDIT_QUERY.deadline.get(), result.task.getDeadline()); } void getsCorrectTypeForEditQueries2() { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::EDIT_QUERY query2(Mocks::Queries::EDIT_QUERY); query2.deadline = You::Utils::Option<boost::posix_time::ptime>(); You::NLP::QUERY query(query2); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); EDIT_RESULT result( boost::get<EDIT_RESULT>(executor->execute())); Assert::AreEqual(taskList.front().getID(), result.task.getID()); Assert::AreEqual(Mocks::Queries::EDIT_QUERY.description.get(), result.task.getDescription()); Assert::AreEqual(nlpPriorityToTaskPriority( Mocks::Queries::EDIT_QUERY.priority.get()), result.task.getPriority()); Assert::AreEqual(taskList.front().getDeadline(), result.task.getDeadline()); } void getsCorrectTypeForEditQueries3() { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::EDIT_QUERY query2(Mocks::Queries::EDIT_QUERY); query2.description = You::Utils::Option<std::wstring>(); You::NLP::QUERY query(query2); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); EDIT_RESULT result( boost::get<EDIT_RESULT>(executor->execute())); Assert::AreEqual(taskList.front().getID(), result.task.getID()); Assert::AreEqual(taskList.front().getDescription(), result.task.getDescription()); Assert::AreEqual(nlpPriorityToTaskPriority( Mocks::Queries::EDIT_QUERY.priority.get()), result.task.getPriority()); Assert::AreEqual(Mocks::Queries::EDIT_QUERY.deadline.get(), result.task.getDeadline()); } void getsCorrectTypeForEditQueries4() { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::EDIT_QUERY query2(Mocks::Queries::EDIT_QUERY); query2.priority = You::Utils::Option<You::NLP::TaskPriority>(); You::NLP::QUERY query(query2); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); EDIT_RESULT result( boost::get<EDIT_RESULT>(executor->execute())); Assert::AreEqual(taskList.front().getID(), result.task.getID()); Assert::AreEqual(Mocks::Queries::EDIT_QUERY.description.get(), result.task.getDescription()); Assert::AreEqual(taskList.front().getPriority(), result.task.getPriority()); Assert::AreEqual(Mocks::Queries::EDIT_QUERY.deadline.get(), result.task.getDeadline()); } TEST_METHOD(editQueriesOutOfBoundsThrowsContextOutOfRange) { Mocks::TaskList taskList(0); QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::EDIT_QUERY); Assert::ExpectException<ContextIndexOutOfRangeException>([&]() { boost::apply_visitor(visitor, query); }); } TEST_METHOD(getsCorrectTypeForDeleteQueries) { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::DELETE_QUERY); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); DELETE_RESULT result( boost::get<DELETE_RESULT>(executor->execute())); Assert::AreEqual(taskList.front().getID(), result.task); } TEST_METHOD(deleteQueriesOutOfBoundsThrowsContextOutOfRange) { Mocks::TaskList taskList(0); QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::DELETE_QUERY); Assert::ExpectException<ContextIndexOutOfRangeException>([&]() { boost::apply_visitor(visitor, query); }); } TEST_METHOD(getsCorrectTypeForUndoQueries) { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::UNDO_QUERY); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); UNDO_RESULT result( boost::get<UNDO_RESULT>(executor->execute())); // TODO(lowjoel): test for..? } private: Task::Priority nlpPriorityToTaskPriority(NLP::TaskPriority priority) { auto iterator = nlpPriorityToTaskPriorityMap.find(priority); assert(iterator != end(nlpPriorityToTaskPriorityMap)); return iterator->second; } private: static const std::unordered_map<NLP::TaskPriority, Task::Priority> nlpPriorityToTaskPriorityMap; }; const std::unordered_map<NLP::TaskPriority, Task::Priority> QueryExecutorBuilderVisitorTests::nlpPriorityToTaskPriorityMap({ { NLP::TaskPriority::NORMAL, Task::Priority::NORMAL }, { NLP::TaskPriority::HIGH, Task::Priority::HIGH } }); } // namespace UnitTests } // namespace Internal } // namespace Controller } // namespace You <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/process_util.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/find_bar/find_bar_controller.h" #include "chrome/browser/ui/find_bar/find_notification_details.h" #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/find_bar_host.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" #include "net/test/test_server.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/keycodes/keyboard_codes.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/view.h" #include "ui/views/views_delegate.h" using content::WebContents; namespace { // The delay waited after sending an OS simulated event. static const int kActionDelayMs = 500; static const char kSimplePage[] = "files/find_in_page/simple.html"; void Checkpoint(const char* message, const base::TimeTicks& start_time) { LOG(INFO) << message << " : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; } class FindInPageTest : public InProcessBrowserTest { public: FindInPageTest() : #if defined(USE_AURA) location_bar_focus_view_id_(VIEW_ID_OMNIBOX) #else location_bar_focus_view_id_(VIEW_ID_LOCATION_BAR) #endif { set_show_window(true); FindBarHost::disable_animations_during_testing_ = true; } string16 GetFindBarText() { FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); return find_bar->GetFindText(); } string16 GetFindBarSelectedText() { FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); return find_bar->GetFindSelectedText(); } ViewID location_bar_focus_view_id_; private: DISALLOW_COPY_AND_ASSIGN(FindInPageTest); }; } // namespace IN_PROC_BROWSER_TEST_F(FindInPageTest, CrashEscHandlers) { ASSERT_TRUE(test_server()->Start()); // First we navigate to our test page (tab A). GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); browser()->Find(); // Open another tab (tab B). browser()->AddSelectedTabWithURL(url, content::PAGE_TRANSITION_TYPED); browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Select tab A. browser()->ActivateTabAt(0, true); // Close tab B. browser()->CloseTabContents(browser()->GetWebContentsAt(1)); // Click on the location bar so that Find box loses focus. ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(), VIEW_ID_LOCATION_BAR)); // Check the location bar is focused. EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); // This used to crash until bug 1303709 was fixed. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); } IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL("title1.html"); ui_test_utils::NavigateToURL(browser(), url); // Focus the location bar, open and close the find-in-page, focus should // return to the location bar. browser()->FocusLocationBar(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); // Ensure the creation of the find bar controller. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelection); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); // Focus the location bar, find something on the page, close the find box, // focus should go to the page. browser()->FocusLocationBar(); browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(), ASCIIToUTF16("a"), true, false, NULL); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelection); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER_FOCUS_VIEW)); // Focus the location bar, open and close the find box, focus should return to // the location bar (same as before, just checking that http://crbug.com/23599 // is fixed). browser()->FocusLocationBar(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelection); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); } IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestoreOnTabSwitch) { ASSERT_TRUE(test_server()->Start()); // First we navigate to our test page (tab A). GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); // Search for 'a'. ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(), ASCIIToUTF16("a"), true, false, NULL); EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText()); // Open another tab (tab B). ui_test_utils::WindowedNotificationObserver observer( content::NOTIFICATION_LOAD_STOP, content::NotificationService::AllSources()); browser()->AddSelectedTabWithURL(url, content::PAGE_TRANSITION_TYPED); observer.Wait(); // Make sure Find box is open. browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Search for 'b'. ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(), ASCIIToUTF16("b"), true, false, NULL); EXPECT_TRUE(ASCIIToUTF16("b") == find_bar->GetFindSelectedText()); // Set focus away from the Find bar (to the Location bar). browser()->FocusLocationBar(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); // Select tab A. Find bar should get focus. browser()->ActivateTabAt(0, true); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText()); // Select tab B. Location bar should get focus. browser()->ActivateTabAt(1, true); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); } // This tests that whenever you clear values from the Find box and close it that // it respects that and doesn't show you the last search, as reported in bug: // http://crbug.com/40121. IN_PROC_BROWSER_TEST_F(FindInPageTest, PrepopulateRespectBlank) { #if defined(OS_MACOSX) // FindInPage on Mac doesn't use prepopulated values. Search there is global. return; #endif base::TimeTicks start_time = base::TimeTicks::Now(); Checkpoint("Test starting", start_time); ASSERT_TRUE(test_server()->Start()); // Make sure Chrome is in the foreground, otherwise sending input // won't do anything and the test will hang. ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); Checkpoint("Navigate", start_time); // First we navigate to any page. GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); Checkpoint("Show Find bar", start_time); // Show the Find bar. browser()->GetFindBarController()->Show(); Checkpoint("Search for 'a'", start_time); // Search for "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_A, false, false, false, false)); // We should find "a" here. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText()); Checkpoint("Delete 'a'", start_time); // Delete "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_BACK, false, false, false, false)); // Validate we have cleared the text. EXPECT_EQ(string16(), GetFindBarText()); Checkpoint("Close find bar", start_time); // Close the Find box. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); Checkpoint("Show Find bar", start_time); // Show the Find bar. browser()->GetFindBarController()->Show(); Checkpoint("Validate text", start_time); // After the Find box has been reopened, it should not have been prepopulated // with "a" again. EXPECT_EQ(string16(), GetFindBarText()); Checkpoint("Close Find bar", start_time); // Close the Find box. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); Checkpoint("FindNext", start_time); // Press F3 to trigger FindNext. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_F3, false, false, false, false)); Checkpoint("Validate", start_time); // After the Find box has been reopened, it should still have no prepopulate // value. EXPECT_EQ(string16(), GetFindBarText()); Checkpoint("Test done", start_time); } // Flaky on Win. http://crbug.com/92467 #if defined(OS_WIN) #define MAYBE_PasteWithoutTextChange DISABLED_PasteWithoutTextChange #else #define MAYBE_PasteWithoutTextChange PasteWithoutTextChange #endif IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_PasteWithoutTextChange) { ASSERT_TRUE(test_server()->Start()); // Make sure Chrome is in the foreground, otherwise sending input // won't do anything and the test will hang. ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); // First we navigate to any page. GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); // Show the Find bar. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Search for "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_A, false, false, false, false)); // We should find "a" here. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText()); // Reload the page to clear the matching result. browser()->Reload(CURRENT_TAB); // Focus the Find bar again to make sure the text is selected. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // "a" should be selected. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarSelectedText()); // Press Ctrl-C to copy the content. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_C, true, false, false, false)); string16 str; views::ViewsDelegate::views_delegate->GetClipboard()-> ReadText(ui::Clipboard::BUFFER_STANDARD, &str); // Make sure the text is copied successfully. EXPECT_EQ(ASCIIToUTF16("a"), str); // Press Ctrl-V to paste the content back, it should start finding even if the // content is not changed. content::Source<WebContents> notification_source( browser()->GetSelectedWebContents()); ui_test_utils::WindowedNotificationObserverWithDetails <FindNotificationDetails> observer( chrome::NOTIFICATION_FIND_RESULT_AVAILABLE, notification_source); ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_V, true, false, false, false)); ASSERT_NO_FATAL_FAILURE(observer.Wait()); FindNotificationDetails details; ASSERT_TRUE(observer.GetDetailsFor(notification_source.map_key(), &details)); EXPECT_TRUE(details.number_of_matches() > 0); } <commit_msg>Mark FindInPageTest.PasteWithoutTextChange flaky on CrOS<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/process_util.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/find_bar/find_bar_controller.h" #include "chrome/browser/ui/find_bar/find_notification_details.h" #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/find_bar_host.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" #include "net/test/test_server.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/keycodes/keyboard_codes.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/view.h" #include "ui/views/views_delegate.h" using content::WebContents; namespace { // The delay waited after sending an OS simulated event. static const int kActionDelayMs = 500; static const char kSimplePage[] = "files/find_in_page/simple.html"; void Checkpoint(const char* message, const base::TimeTicks& start_time) { LOG(INFO) << message << " : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; } class FindInPageTest : public InProcessBrowserTest { public: FindInPageTest() : #if defined(USE_AURA) location_bar_focus_view_id_(VIEW_ID_OMNIBOX) #else location_bar_focus_view_id_(VIEW_ID_LOCATION_BAR) #endif { set_show_window(true); FindBarHost::disable_animations_during_testing_ = true; } string16 GetFindBarText() { FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); return find_bar->GetFindText(); } string16 GetFindBarSelectedText() { FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); return find_bar->GetFindSelectedText(); } ViewID location_bar_focus_view_id_; private: DISALLOW_COPY_AND_ASSIGN(FindInPageTest); }; } // namespace IN_PROC_BROWSER_TEST_F(FindInPageTest, CrashEscHandlers) { ASSERT_TRUE(test_server()->Start()); // First we navigate to our test page (tab A). GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); browser()->Find(); // Open another tab (tab B). browser()->AddSelectedTabWithURL(url, content::PAGE_TRANSITION_TYPED); browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Select tab A. browser()->ActivateTabAt(0, true); // Close tab B. browser()->CloseTabContents(browser()->GetWebContentsAt(1)); // Click on the location bar so that Find box loses focus. ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(), VIEW_ID_LOCATION_BAR)); // Check the location bar is focused. EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); // This used to crash until bug 1303709 was fixed. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); } IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL("title1.html"); ui_test_utils::NavigateToURL(browser(), url); // Focus the location bar, open and close the find-in-page, focus should // return to the location bar. browser()->FocusLocationBar(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); // Ensure the creation of the find bar controller. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelection); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); // Focus the location bar, find something on the page, close the find box, // focus should go to the page. browser()->FocusLocationBar(); browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(), ASCIIToUTF16("a"), true, false, NULL); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelection); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER_FOCUS_VIEW)); // Focus the location bar, open and close the find box, focus should return to // the location bar (same as before, just checking that http://crbug.com/23599 // is fixed). browser()->FocusLocationBar(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelection); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); } IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestoreOnTabSwitch) { ASSERT_TRUE(test_server()->Start()); // First we navigate to our test page (tab A). GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); // Search for 'a'. ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(), ASCIIToUTF16("a"), true, false, NULL); EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText()); // Open another tab (tab B). ui_test_utils::WindowedNotificationObserver observer( content::NOTIFICATION_LOAD_STOP, content::NotificationService::AllSources()); browser()->AddSelectedTabWithURL(url, content::PAGE_TRANSITION_TYPED); observer.Wait(); // Make sure Find box is open. browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Search for 'b'. ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(), ASCIIToUTF16("b"), true, false, NULL); EXPECT_TRUE(ASCIIToUTF16("b") == find_bar->GetFindSelectedText()); // Set focus away from the Find bar (to the Location bar). browser()->FocusLocationBar(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); // Select tab A. Find bar should get focus. browser()->ActivateTabAt(0, true); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText()); // Select tab B. Location bar should get focus. browser()->ActivateTabAt(1, true); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); } // This tests that whenever you clear values from the Find box and close it that // it respects that and doesn't show you the last search, as reported in bug: // http://crbug.com/40121. IN_PROC_BROWSER_TEST_F(FindInPageTest, PrepopulateRespectBlank) { #if defined(OS_MACOSX) // FindInPage on Mac doesn't use prepopulated values. Search there is global. return; #endif base::TimeTicks start_time = base::TimeTicks::Now(); Checkpoint("Test starting", start_time); ASSERT_TRUE(test_server()->Start()); // Make sure Chrome is in the foreground, otherwise sending input // won't do anything and the test will hang. ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); Checkpoint("Navigate", start_time); // First we navigate to any page. GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); Checkpoint("Show Find bar", start_time); // Show the Find bar. browser()->GetFindBarController()->Show(); Checkpoint("Search for 'a'", start_time); // Search for "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_A, false, false, false, false)); // We should find "a" here. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText()); Checkpoint("Delete 'a'", start_time); // Delete "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_BACK, false, false, false, false)); // Validate we have cleared the text. EXPECT_EQ(string16(), GetFindBarText()); Checkpoint("Close find bar", start_time); // Close the Find box. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); Checkpoint("Show Find bar", start_time); // Show the Find bar. browser()->GetFindBarController()->Show(); Checkpoint("Validate text", start_time); // After the Find box has been reopened, it should not have been prepopulated // with "a" again. EXPECT_EQ(string16(), GetFindBarText()); Checkpoint("Close Find bar", start_time); // Close the Find box. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); Checkpoint("FindNext", start_time); // Press F3 to trigger FindNext. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_F3, false, false, false, false)); Checkpoint("Validate", start_time); // After the Find box has been reopened, it should still have no prepopulate // value. EXPECT_EQ(string16(), GetFindBarText()); Checkpoint("Test done", start_time); } // Flaky on Win. http://crbug.com/92467 // Flaky on ChromeOS. http://crbug.com/118216 #if defined(OS_WIN) || defined(OS_CHROMEOS) #define MAYBE_PasteWithoutTextChange DISABLED_PasteWithoutTextChange #else #define MAYBE_PasteWithoutTextChange PasteWithoutTextChange #endif IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_PasteWithoutTextChange) { ASSERT_TRUE(test_server()->Start()); // Make sure Chrome is in the foreground, otherwise sending input // won't do anything and the test will hang. ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); // First we navigate to any page. GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); // Show the Find bar. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Search for "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_A, false, false, false, false)); // We should find "a" here. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText()); // Reload the page to clear the matching result. browser()->Reload(CURRENT_TAB); // Focus the Find bar again to make sure the text is selected. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // "a" should be selected. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarSelectedText()); // Press Ctrl-C to copy the content. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_C, true, false, false, false)); string16 str; views::ViewsDelegate::views_delegate->GetClipboard()-> ReadText(ui::Clipboard::BUFFER_STANDARD, &str); // Make sure the text is copied successfully. EXPECT_EQ(ASCIIToUTF16("a"), str); // Press Ctrl-V to paste the content back, it should start finding even if the // content is not changed. content::Source<WebContents> notification_source( browser()->GetSelectedWebContents()); ui_test_utils::WindowedNotificationObserverWithDetails <FindNotificationDetails> observer( chrome::NOTIFICATION_FIND_RESULT_AVAILABLE, notification_source); ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_V, true, false, false, false)); ASSERT_NO_FATAL_FAILURE(observer.Wait()); FindNotificationDetails details; ASSERT_TRUE(observer.GetDetailsFor(notification_source.map_key(), &details)); EXPECT_TRUE(details.number_of_matches() > 0); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/options/language_options_handler.h" #include <map> #include <string> #include <utility> #include <vector> #include "base/basictypes.h" #include "base/command_line.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/metrics/user_metrics.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" LanguageOptionsHandler::LanguageOptionsHandler() { } LanguageOptionsHandler::~LanguageOptionsHandler() { } void LanguageOptionsHandler::GetLocalizedValues( DictionaryValue* localized_strings) { LanguageOptionsHandlerCommon::GetLocalizedValues(localized_strings); localized_strings->SetString("restart_button", l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_LANGUAGES_RELAUNCH_BUTTON)); localized_strings->Set("languageList", GetLanguageList()); } void LanguageOptionsHandler::RegisterMessages() { LanguageOptionsHandlerCommon::RegisterMessages(); web_ui_->RegisterMessageCallback("uiLanguageRestart", NewCallback(this, &LanguageOptionsHandler::RestartCallback)); } ListValue* LanguageOptionsHandler::GetLanguageList() { // Collect the language codes from the supported accept-languages. const std::string app_locale = g_browser_process->GetApplicationLocale(); std::vector<std::string> language_codes; l10n_util::GetAcceptLanguagesForLocale(app_locale, &language_codes); // Map of display name -> {language code, native_display_name}. // In theory, we should be able to create a map that is sorted by // display names using ICU comparator, but doing it is hard, thus we'll // use an auxiliary vector to achieve the same result. typedef std::pair<std::string, string16> LanguagePair; typedef std::map<string16, LanguagePair> LanguageMap; LanguageMap language_map; // The auxiliary vector mentioned above. std::vector<string16> display_names; // Build the list of display names, and build the language map. for (size_t i = 0; i < language_codes.size(); ++i) { const string16 display_name = l10n_util::GetDisplayNameForLocale(language_codes[i], app_locale, true); const string16 native_display_name = l10n_util::GetDisplayNameForLocale(language_codes[i], language_codes[i], true); display_names.push_back(display_name); language_map[display_name] = std::make_pair(language_codes[i], native_display_name); } DCHECK_EQ(display_names.size(), language_map.size()); // Sort display names using locale specific sorter. l10n_util::SortStrings16(app_locale, &display_names); // Build the language list from the language map. ListValue* language_list = new ListValue(); for (size_t i = 0; i < display_names.size(); ++i) { const LanguagePair& pair = language_map[display_names[i]]; DictionaryValue* dictionary = new DictionaryValue(); dictionary->SetString("code", pair.first); dictionary->SetString("displayName", display_names[i]); dictionary->SetString("nativeDisplayName", pair.second); language_list->Append(dictionary); } return language_list; } string16 LanguageOptionsHandler::GetProductName() { return l10n_util::GetStringUTF16(IDS_PRODUCT_NAME); } void LanguageOptionsHandler::SetApplicationLocale( const std::string& language_code) { PrefService* pref_service = g_browser_process->local_state(); pref_service->SetString(prefs::kApplicationLocale, language_code); } void LanguageOptionsHandler::RestartCallback(const ListValue* args) { UserMetrics::RecordAction(UserMetricsAction("LanguageOptions_Restart")); // Set the flag to restore state after the restart. PrefService* pref_service = g_browser_process->local_state(); pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, true); BrowserList::CloseAllBrowsersAndExit(); } <commit_msg>web-ui settings: Fix display of languages for RTL systems.<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 "chrome/browser/ui/webui/options/language_options_handler.h" #include <map> #include <string> #include <utility> #include <vector> #include "base/basictypes.h" #include "base/command_line.h" #include "base/i18n/rtl.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/metrics/user_metrics.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" LanguageOptionsHandler::LanguageOptionsHandler() { } LanguageOptionsHandler::~LanguageOptionsHandler() { } void LanguageOptionsHandler::GetLocalizedValues( DictionaryValue* localized_strings) { LanguageOptionsHandlerCommon::GetLocalizedValues(localized_strings); localized_strings->SetString("restart_button", l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_LANGUAGES_RELAUNCH_BUTTON)); localized_strings->Set("languageList", GetLanguageList()); } void LanguageOptionsHandler::RegisterMessages() { LanguageOptionsHandlerCommon::RegisterMessages(); web_ui_->RegisterMessageCallback("uiLanguageRestart", NewCallback(this, &LanguageOptionsHandler::RestartCallback)); } ListValue* LanguageOptionsHandler::GetLanguageList() { // Collect the language codes from the supported accept-languages. const std::string app_locale = g_browser_process->GetApplicationLocale(); std::vector<std::string> language_codes; l10n_util::GetAcceptLanguagesForLocale(app_locale, &language_codes); // Map of display name -> {language code, native_display_name}. // In theory, we should be able to create a map that is sorted by // display names using ICU comparator, but doing it is hard, thus we'll // use an auxiliary vector to achieve the same result. typedef std::pair<std::string, string16> LanguagePair; typedef std::map<string16, LanguagePair> LanguageMap; LanguageMap language_map; // The auxiliary vector mentioned above. std::vector<string16> display_names; // Build the list of display names, and build the language map. for (size_t i = 0; i < language_codes.size(); ++i) { string16 display_name = l10n_util::GetDisplayNameForLocale(language_codes[i], app_locale, false); base::i18n::AdjustStringForLocaleDirection(&display_name); string16 native_display_name = l10n_util::GetDisplayNameForLocale(language_codes[i], language_codes[i], false); base::i18n::AdjustStringForLocaleDirection(&native_display_name); display_names.push_back(display_name); language_map[display_name] = std::make_pair(language_codes[i], native_display_name); } DCHECK_EQ(display_names.size(), language_map.size()); // Sort display names using locale specific sorter. l10n_util::SortStrings16(app_locale, &display_names); // Build the language list from the language map. ListValue* language_list = new ListValue(); for (size_t i = 0; i < display_names.size(); ++i) { const LanguagePair& pair = language_map[display_names[i]]; DictionaryValue* dictionary = new DictionaryValue(); dictionary->SetString("code", pair.first); dictionary->SetString("displayName", display_names[i]); dictionary->SetString("nativeDisplayName", pair.second); language_list->Append(dictionary); } return language_list; } string16 LanguageOptionsHandler::GetProductName() { return l10n_util::GetStringUTF16(IDS_PRODUCT_NAME); } void LanguageOptionsHandler::SetApplicationLocale( const std::string& language_code) { PrefService* pref_service = g_browser_process->local_state(); pref_service->SetString(prefs::kApplicationLocale, language_code); } void LanguageOptionsHandler::RestartCallback(const ListValue* args) { UserMetrics::RecordAction(UserMetricsAction("LanguageOptions_Restart")); // Set the flag to restore state after the restart. PrefService* pref_service = g_browser_process->local_state(); pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, true); BrowserList::CloseAllBrowsersAndExit(); } <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/sessions/sessions_api.h" #include "base/command_line.h" #include "base/path_service.h" #include "base/strings/stringprintf.h" #include "chrome/browser/extensions/api/tabs/tabs_api.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/sync/glue/session_model_associator.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/profile_sync_service_mock.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/test_switches.h" #include "chrome/test/base/testing_browser_process.h" namespace utils = extension_function_test_utils; namespace extensions { namespace { // If more sessions are added to session tags, num sessions should be updated. const char* kSessionTags[] = {"tag0", "tag1", "tag2", "tag3", "tag4"}; const size_t kNumSessions = 5; void BuildSessionSpecifics(const std::string& tag, sync_pb::SessionSpecifics* meta) { meta->set_session_tag(tag); sync_pb::SessionHeader* header = meta->mutable_header(); header->set_device_type(sync_pb::SyncEnums_DeviceType_TYPE_LINUX); header->set_client_name(tag); } void BuildWindowSpecifics(int window_id, const std::vector<int>& tab_list, sync_pb::SessionSpecifics* meta) { sync_pb::SessionHeader* header = meta->mutable_header(); sync_pb::SessionWindow* window = header->add_window(); window->set_window_id(window_id); window->set_selected_tab_index(0); window->set_browser_type(sync_pb::SessionWindow_BrowserType_TYPE_TABBED); for (std::vector<int>::const_iterator iter = tab_list.begin(); iter != tab_list.end(); ++iter) { window->add_tab(*iter); } } void BuildTabSpecifics(const std::string& tag, int window_id, int tab_id, sync_pb::SessionSpecifics* tab_base) { tab_base->set_session_tag(tag); tab_base->set_tab_node_id(0); sync_pb::SessionTab* tab = tab_base->mutable_tab(); tab->set_tab_id(tab_id); tab->set_tab_visual_index(1); tab->set_current_navigation_index(0); tab->set_pinned(true); tab->set_extension_app_id("app_id"); sync_pb::TabNavigation* navigation = tab->add_navigation(); navigation->set_virtual_url("http://foo/1"); navigation->set_referrer("referrer"); navigation->set_title("title"); navigation->set_page_transition(sync_pb::SyncEnums_PageTransition_TYPED); } } // namespace class ExtensionSessionsTest : public InProcessBrowserTest { public: virtual void SetUpOnMainThread() OVERRIDE; protected: void CreateTestProfileSyncService(); void CreateTestExtension(); void CreateSessionModels(); template <class T> scoped_refptr<T> CreateFunction(bool has_callback) { scoped_refptr<T> fn(new T()); fn->set_extension(extension_.get()); fn->set_has_callback(has_callback); return fn; }; Browser* browser_; browser_sync::SessionModelAssociator* associator_; scoped_refptr<extensions::Extension> extension_; }; void ExtensionSessionsTest::SetUpOnMainThread() { CreateTestProfileSyncService(); CreateTestExtension(); } void ExtensionSessionsTest::CreateTestProfileSyncService() { ProfileManager* profile_manager = g_browser_process->profile_manager(); base::FilePath path; PathService::Get(chrome::DIR_USER_DATA, &path); path = path.AppendASCII("test_profile"); if (!base::PathExists(path)) CHECK(file_util::CreateDirectory(path)); Profile* profile = Profile::CreateProfile(path, NULL, Profile::CREATE_MODE_SYNCHRONOUS); profile_manager->RegisterTestingProfile(profile, true, false); browser_ = new Browser(Browser::CreateParams( profile, chrome::HOST_DESKTOP_TYPE_NATIVE)); ProfileSyncServiceMock* service = static_cast<ProfileSyncServiceMock*>( ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse( profile, &ProfileSyncServiceMock::BuildMockProfileSyncService)); associator_ = new browser_sync::SessionModelAssociator( static_cast<ProfileSyncService*>(service), true); syncer::ModelTypeSet preferred_types; preferred_types.Put(syncer::SESSIONS); GoogleServiceAuthError no_error(GoogleServiceAuthError::NONE); ON_CALL(*service, GetSessionModelAssociator()).WillByDefault( testing::Return(associator_)); ON_CALL(*service, GetPreferredDataTypes()).WillByDefault( testing::Return(preferred_types)); EXPECT_CALL(*service, GetAuthError()).WillRepeatedly( testing::ReturnRef(no_error)); ON_CALL(*service, GetActiveDataTypes()).WillByDefault( testing::Return(preferred_types)); EXPECT_CALL(*service, AddObserver(testing::_)).Times(testing::AnyNumber()); EXPECT_CALL(*service, RemoveObserver(testing::_)).Times(testing::AnyNumber()); service->Initialize(); } void ExtensionSessionsTest::CreateTestExtension() { scoped_ptr<base::DictionaryValue> test_extension_value( utils::ParseDictionary( "{\"name\": \"Test\", \"version\": \"1.0\", " "\"permissions\": [\"sessions\", \"tabs\"]}")); extension_ = utils::CreateExtension(test_extension_value.get()); } void ExtensionSessionsTest::CreateSessionModels() { for (size_t index = 0; index < kNumSessions; ++index) { // Fill an instance of session specifics with a foreign session's data. sync_pb::SessionSpecifics meta; BuildSessionSpecifics(kSessionTags[index], &meta); SessionID::id_type tab_nums1[] = {5, 10, 13, 17}; std::vector<SessionID::id_type> tab_list1( tab_nums1, tab_nums1 + arraysize(tab_nums1)); BuildWindowSpecifics(index, tab_list1, &meta); std::vector<sync_pb::SessionSpecifics> tabs1; tabs1.resize(tab_list1.size()); for (size_t i = 0; i < tab_list1.size(); ++i) { BuildTabSpecifics(kSessionTags[index], 0, tab_list1[i], &tabs1[i]); } associator_->SetCurrentMachineTagForTesting(kSessionTags[index]); // Update associator with the session's meta node containing one window. associator_->AssociateForeignSpecifics(meta, base::Time()); // Add tabs for the window. for (std::vector<sync_pb::SessionSpecifics>::iterator iter = tabs1.begin(); iter != tabs1.end(); ++iter) { associator_->AssociateForeignSpecifics(*iter, base::Time()); } } } IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevices) { CreateSessionModels(); scoped_ptr<base::ListValue> result(utils::ToList( utils::RunFunctionAndReturnSingleResult( CreateFunction<SessionsGetDevicesFunction>(true).get(), "[{\"maxResults\": 0}]", browser_))); ASSERT_TRUE(result); ListValue* devices = result.get(); EXPECT_EQ(5u, devices->GetSize()); DictionaryValue* device = NULL; ListValue* sessions = NULL; for (size_t i = 0; i < devices->GetSize(); ++i) { EXPECT_TRUE(devices->GetDictionary(i, &device)); EXPECT_EQ(kSessionTags[i], utils::GetString(device, "info")); EXPECT_TRUE(device->GetList("sessions", &sessions)); EXPECT_EQ(0u, sessions->GetSize()); } } IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevicesMaxResults) { CreateSessionModels(); scoped_ptr<base::ListValue> result(utils::ToList( utils::RunFunctionAndReturnSingleResult( CreateFunction<SessionsGetDevicesFunction>(true).get(), "[]", browser_))); ASSERT_TRUE(result); ListValue* devices = result.get(); EXPECT_EQ(5u, devices->GetSize()); DictionaryValue* device = NULL; ListValue* sessions = NULL; for (size_t i = 0; i < devices->GetSize(); ++i) { EXPECT_TRUE(devices->GetDictionary(i, &device)); EXPECT_EQ(kSessionTags[i], utils::GetString(device, "info")); EXPECT_TRUE(device->GetList("sessions", &sessions)); EXPECT_EQ(1u, sessions->GetSize()); } } IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevicesListEmpty) { scoped_ptr<base::ListValue> result(utils::ToList( utils::RunFunctionAndReturnSingleResult( CreateFunction<SessionsGetDevicesFunction>(true).get(), "[]", browser_))); ASSERT_TRUE(result); ListValue* devices = result.get(); EXPECT_EQ(0u, devices->GetSize()); } IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, RestoreForeignSessionWindow) { CreateSessionModels(); scoped_ptr<base::DictionaryValue> restored_window_session(utils::ToDictionary( utils::RunFunctionAndReturnSingleResult( CreateFunction<SessionsRestoreFunction>(true).get(), "[\"tag3.3\"]", browser_, utils::INCLUDE_INCOGNITO))); ASSERT_TRUE(restored_window_session); scoped_ptr<base::ListValue> result(utils::ToList( utils::RunFunctionAndReturnSingleResult( CreateFunction<WindowsGetAllFunction>(true).get(), "[]", browser_))); ASSERT_TRUE(result); ListValue* windows = result.get(); EXPECT_EQ(2u, windows->GetSize()); DictionaryValue* restored_window = NULL; EXPECT_TRUE(restored_window_session->GetDictionary("window", &restored_window)); DictionaryValue* window = NULL; int restored_id = utils::GetInteger(restored_window, "id"); for (size_t i = 0; i < windows->GetSize(); ++i) { EXPECT_TRUE(windows->GetDictionary(i, &window)); if (utils::GetInteger(window, "id") == restored_id) break; } EXPECT_EQ(restored_id, utils::GetInteger(window, "id")); } IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, RestoreForeignSessionInvalidId) { CreateSessionModels(); EXPECT_TRUE(MatchPattern(utils::RunFunctionAndReturnError( CreateFunction<SessionsRestoreFunction>(true).get(), "[\"tag3.0\"]", browser_), "Invalid session id: \"tag3.0\".")); } // Flaky on ChromeOS, times out on OSX Debug http://crbug.com/251199 #if defined(OS_CHROMEOS) || (defined(OS_MACOSX) && !defined(NDEBUG)) #define MAYBE_SessionsApis DISABLED_SessionsApis #else #define MAYBE_SessionsApis SessionsApis #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_SessionsApis) { #if defined(OS_WIN) && defined(USE_ASH) // Disable this test in Metro+Ash for now (http://crbug.com/262796). if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests)) return; #endif ASSERT_TRUE(RunExtensionSubtest("sessions", "sessions.html")) << message_; } } // namespace extensions <commit_msg>Disable flaky ExtensionSessionsTest.RestoreForeignSessionWindow.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/sessions/sessions_api.h" #include "base/command_line.h" #include "base/path_service.h" #include "base/strings/stringprintf.h" #include "chrome/browser/extensions/api/tabs/tabs_api.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/sync/glue/session_model_associator.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/profile_sync_service_mock.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/test_switches.h" #include "chrome/test/base/testing_browser_process.h" namespace utils = extension_function_test_utils; namespace extensions { namespace { // If more sessions are added to session tags, num sessions should be updated. const char* kSessionTags[] = {"tag0", "tag1", "tag2", "tag3", "tag4"}; const size_t kNumSessions = 5; void BuildSessionSpecifics(const std::string& tag, sync_pb::SessionSpecifics* meta) { meta->set_session_tag(tag); sync_pb::SessionHeader* header = meta->mutable_header(); header->set_device_type(sync_pb::SyncEnums_DeviceType_TYPE_LINUX); header->set_client_name(tag); } void BuildWindowSpecifics(int window_id, const std::vector<int>& tab_list, sync_pb::SessionSpecifics* meta) { sync_pb::SessionHeader* header = meta->mutable_header(); sync_pb::SessionWindow* window = header->add_window(); window->set_window_id(window_id); window->set_selected_tab_index(0); window->set_browser_type(sync_pb::SessionWindow_BrowserType_TYPE_TABBED); for (std::vector<int>::const_iterator iter = tab_list.begin(); iter != tab_list.end(); ++iter) { window->add_tab(*iter); } } void BuildTabSpecifics(const std::string& tag, int window_id, int tab_id, sync_pb::SessionSpecifics* tab_base) { tab_base->set_session_tag(tag); tab_base->set_tab_node_id(0); sync_pb::SessionTab* tab = tab_base->mutable_tab(); tab->set_tab_id(tab_id); tab->set_tab_visual_index(1); tab->set_current_navigation_index(0); tab->set_pinned(true); tab->set_extension_app_id("app_id"); sync_pb::TabNavigation* navigation = tab->add_navigation(); navigation->set_virtual_url("http://foo/1"); navigation->set_referrer("referrer"); navigation->set_title("title"); navigation->set_page_transition(sync_pb::SyncEnums_PageTransition_TYPED); } } // namespace class ExtensionSessionsTest : public InProcessBrowserTest { public: virtual void SetUpOnMainThread() OVERRIDE; protected: void CreateTestProfileSyncService(); void CreateTestExtension(); void CreateSessionModels(); template <class T> scoped_refptr<T> CreateFunction(bool has_callback) { scoped_refptr<T> fn(new T()); fn->set_extension(extension_.get()); fn->set_has_callback(has_callback); return fn; }; Browser* browser_; browser_sync::SessionModelAssociator* associator_; scoped_refptr<extensions::Extension> extension_; }; void ExtensionSessionsTest::SetUpOnMainThread() { CreateTestProfileSyncService(); CreateTestExtension(); } void ExtensionSessionsTest::CreateTestProfileSyncService() { ProfileManager* profile_manager = g_browser_process->profile_manager(); base::FilePath path; PathService::Get(chrome::DIR_USER_DATA, &path); path = path.AppendASCII("test_profile"); if (!base::PathExists(path)) CHECK(file_util::CreateDirectory(path)); Profile* profile = Profile::CreateProfile(path, NULL, Profile::CREATE_MODE_SYNCHRONOUS); profile_manager->RegisterTestingProfile(profile, true, false); browser_ = new Browser(Browser::CreateParams( profile, chrome::HOST_DESKTOP_TYPE_NATIVE)); ProfileSyncServiceMock* service = static_cast<ProfileSyncServiceMock*>( ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse( profile, &ProfileSyncServiceMock::BuildMockProfileSyncService)); associator_ = new browser_sync::SessionModelAssociator( static_cast<ProfileSyncService*>(service), true); syncer::ModelTypeSet preferred_types; preferred_types.Put(syncer::SESSIONS); GoogleServiceAuthError no_error(GoogleServiceAuthError::NONE); ON_CALL(*service, GetSessionModelAssociator()).WillByDefault( testing::Return(associator_)); ON_CALL(*service, GetPreferredDataTypes()).WillByDefault( testing::Return(preferred_types)); EXPECT_CALL(*service, GetAuthError()).WillRepeatedly( testing::ReturnRef(no_error)); ON_CALL(*service, GetActiveDataTypes()).WillByDefault( testing::Return(preferred_types)); EXPECT_CALL(*service, AddObserver(testing::_)).Times(testing::AnyNumber()); EXPECT_CALL(*service, RemoveObserver(testing::_)).Times(testing::AnyNumber()); service->Initialize(); } void ExtensionSessionsTest::CreateTestExtension() { scoped_ptr<base::DictionaryValue> test_extension_value( utils::ParseDictionary( "{\"name\": \"Test\", \"version\": \"1.0\", " "\"permissions\": [\"sessions\", \"tabs\"]}")); extension_ = utils::CreateExtension(test_extension_value.get()); } void ExtensionSessionsTest::CreateSessionModels() { for (size_t index = 0; index < kNumSessions; ++index) { // Fill an instance of session specifics with a foreign session's data. sync_pb::SessionSpecifics meta; BuildSessionSpecifics(kSessionTags[index], &meta); SessionID::id_type tab_nums1[] = {5, 10, 13, 17}; std::vector<SessionID::id_type> tab_list1( tab_nums1, tab_nums1 + arraysize(tab_nums1)); BuildWindowSpecifics(index, tab_list1, &meta); std::vector<sync_pb::SessionSpecifics> tabs1; tabs1.resize(tab_list1.size()); for (size_t i = 0; i < tab_list1.size(); ++i) { BuildTabSpecifics(kSessionTags[index], 0, tab_list1[i], &tabs1[i]); } associator_->SetCurrentMachineTagForTesting(kSessionTags[index]); // Update associator with the session's meta node containing one window. associator_->AssociateForeignSpecifics(meta, base::Time()); // Add tabs for the window. for (std::vector<sync_pb::SessionSpecifics>::iterator iter = tabs1.begin(); iter != tabs1.end(); ++iter) { associator_->AssociateForeignSpecifics(*iter, base::Time()); } } } IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevices) { CreateSessionModels(); scoped_ptr<base::ListValue> result(utils::ToList( utils::RunFunctionAndReturnSingleResult( CreateFunction<SessionsGetDevicesFunction>(true).get(), "[{\"maxResults\": 0}]", browser_))); ASSERT_TRUE(result); ListValue* devices = result.get(); EXPECT_EQ(5u, devices->GetSize()); DictionaryValue* device = NULL; ListValue* sessions = NULL; for (size_t i = 0; i < devices->GetSize(); ++i) { EXPECT_TRUE(devices->GetDictionary(i, &device)); EXPECT_EQ(kSessionTags[i], utils::GetString(device, "info")); EXPECT_TRUE(device->GetList("sessions", &sessions)); EXPECT_EQ(0u, sessions->GetSize()); } } IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevicesMaxResults) { CreateSessionModels(); scoped_ptr<base::ListValue> result(utils::ToList( utils::RunFunctionAndReturnSingleResult( CreateFunction<SessionsGetDevicesFunction>(true).get(), "[]", browser_))); ASSERT_TRUE(result); ListValue* devices = result.get(); EXPECT_EQ(5u, devices->GetSize()); DictionaryValue* device = NULL; ListValue* sessions = NULL; for (size_t i = 0; i < devices->GetSize(); ++i) { EXPECT_TRUE(devices->GetDictionary(i, &device)); EXPECT_EQ(kSessionTags[i], utils::GetString(device, "info")); EXPECT_TRUE(device->GetList("sessions", &sessions)); EXPECT_EQ(1u, sessions->GetSize()); } } IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevicesListEmpty) { scoped_ptr<base::ListValue> result(utils::ToList( utils::RunFunctionAndReturnSingleResult( CreateFunction<SessionsGetDevicesFunction>(true).get(), "[]", browser_))); ASSERT_TRUE(result); ListValue* devices = result.get(); EXPECT_EQ(0u, devices->GetSize()); } // Flaky timeout: http://crbug.com/278372 IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, DISABLED_RestoreForeignSessionWindow) { CreateSessionModels(); scoped_ptr<base::DictionaryValue> restored_window_session(utils::ToDictionary( utils::RunFunctionAndReturnSingleResult( CreateFunction<SessionsRestoreFunction>(true).get(), "[\"tag3.3\"]", browser_, utils::INCLUDE_INCOGNITO))); ASSERT_TRUE(restored_window_session); scoped_ptr<base::ListValue> result(utils::ToList( utils::RunFunctionAndReturnSingleResult( CreateFunction<WindowsGetAllFunction>(true).get(), "[]", browser_))); ASSERT_TRUE(result); ListValue* windows = result.get(); EXPECT_EQ(2u, windows->GetSize()); DictionaryValue* restored_window = NULL; EXPECT_TRUE(restored_window_session->GetDictionary("window", &restored_window)); DictionaryValue* window = NULL; int restored_id = utils::GetInteger(restored_window, "id"); for (size_t i = 0; i < windows->GetSize(); ++i) { EXPECT_TRUE(windows->GetDictionary(i, &window)); if (utils::GetInteger(window, "id") == restored_id) break; } EXPECT_EQ(restored_id, utils::GetInteger(window, "id")); } IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, RestoreForeignSessionInvalidId) { CreateSessionModels(); EXPECT_TRUE(MatchPattern(utils::RunFunctionAndReturnError( CreateFunction<SessionsRestoreFunction>(true).get(), "[\"tag3.0\"]", browser_), "Invalid session id: \"tag3.0\".")); } // Flaky on ChromeOS, times out on OSX Debug http://crbug.com/251199 #if defined(OS_CHROMEOS) || (defined(OS_MACOSX) && !defined(NDEBUG)) #define MAYBE_SessionsApis DISABLED_SessionsApis #else #define MAYBE_SessionsApis SessionsApis #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_SessionsApis) { #if defined(OS_WIN) && defined(USE_ASH) // Disable this test in Metro+Ash for now (http://crbug.com/262796). if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests)) return; #endif ASSERT_TRUE(RunExtensionSubtest("sessions", "sessions.html")) << message_; } } // namespace extensions <|endoftext|>
<commit_before>/* * Copyright 2016 The Cartographer 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 "cartographer/mapping_3d/pose_graph/constraint_builder.h" #include <cmath> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <memory> #include <sstream> #include <string> #include "Eigen/Eigenvalues" #include "cartographer/common/make_unique.h" #include "cartographer/common/math.h" #include "cartographer/common/thread_pool.h" #include "cartographer/mapping_3d/scan_matching/proto/ceres_scan_matcher_options.pb.h" #include "cartographer/mapping_3d/scan_matching/proto/fast_correlative_scan_matcher_options.pb.h" #include "cartographer/transform/transform.h" #include "glog/logging.h" namespace cartographer { namespace mapping_3d { namespace pose_graph { ConstraintBuilder::ConstraintBuilder( const mapping::pose_graph::proto::ConstraintBuilderOptions& options, common::ThreadPool* const thread_pool) : options_(options), thread_pool_(thread_pool), sampler_(options.sampling_ratio()), ceres_scan_matcher_(options.ceres_scan_matcher_options_3d()) {} ConstraintBuilder::~ConstraintBuilder() { common::MutexLocker locker(&mutex_); CHECK_EQ(constraints_.size(), 0) << "WhenDone() was not called"; CHECK_EQ(pending_computations_.size(), 0); CHECK_EQ(submap_queued_work_items_.size(), 0); CHECK(when_done_ == nullptr); } void ConstraintBuilder::MaybeAddConstraint( const mapping::SubmapId& submap_id, const Submap* const submap, const mapping::NodeId& node_id, const mapping::TrajectoryNode::Data* const constant_data, const std::vector<mapping::TrajectoryNode>& submap_nodes, const transform::Rigid3d& global_node_pose, const transform::Rigid3d& global_submap_pose) { if ((global_node_pose.translation() - global_submap_pose.translation()) .norm() > options_.max_constraint_distance()) { return; } if (sampler_.Pulse()) { common::MutexLocker locker(&mutex_); constraints_.emplace_back(); auto* const constraint = &constraints_.back(); ++pending_computations_[current_computation_]; const int current_computation = current_computation_; ScheduleSubmapScanMatcherConstructionAndQueueWorkItem( submap_id, submap_nodes, submap, [=]() EXCLUDES(mutex_) { ComputeConstraint(submap_id, node_id, false, /* match_full_submap */ constant_data, global_node_pose, global_submap_pose, constraint); FinishComputation(current_computation); }); } } void ConstraintBuilder::MaybeAddGlobalConstraint( const mapping::SubmapId& submap_id, const Submap* const submap, const mapping::NodeId& node_id, const mapping::TrajectoryNode::Data* const constant_data, const std::vector<mapping::TrajectoryNode>& submap_nodes, const Eigen::Quaterniond& global_node_rotation, const Eigen::Quaterniond& global_submap_rotation) { common::MutexLocker locker(&mutex_); constraints_.emplace_back(); auto* const constraint = &constraints_.back(); ++pending_computations_[current_computation_]; const int current_computation = current_computation_; ScheduleSubmapScanMatcherConstructionAndQueueWorkItem( submap_id, submap_nodes, submap, [=]() EXCLUDES(mutex_) { ComputeConstraint( submap_id, node_id, true, /* match_full_submap */ constant_data, transform::Rigid3d::Rotation(global_node_rotation), transform::Rigid3d::Rotation(global_submap_rotation), constraint); FinishComputation(current_computation); }); } void ConstraintBuilder::NotifyEndOfNode() { common::MutexLocker locker(&mutex_); ++current_computation_; } void ConstraintBuilder::WhenDone( const std::function<void(const ConstraintBuilder::Result&)>& callback) { common::MutexLocker locker(&mutex_); CHECK(when_done_ == nullptr); when_done_ = common::make_unique<std::function<void(const Result&)>>(callback); ++pending_computations_[current_computation_]; const int current_computation = current_computation_; thread_pool_->Schedule( [this, current_computation] { FinishComputation(current_computation); }); } void ConstraintBuilder::ScheduleSubmapScanMatcherConstructionAndQueueWorkItem( const mapping::SubmapId& submap_id, const std::vector<mapping::TrajectoryNode>& submap_nodes, const Submap* const submap, const std::function<void()>& work_item) { if (submap_scan_matchers_[submap_id].fast_correlative_scan_matcher != nullptr) { thread_pool_->Schedule(work_item); } else { submap_queued_work_items_[submap_id].push_back(work_item); if (submap_queued_work_items_[submap_id].size() == 1) { thread_pool_->Schedule([=]() { ConstructSubmapScanMatcher(submap_id, submap_nodes, submap); }); } } } void ConstraintBuilder::ConstructSubmapScanMatcher( const mapping::SubmapId& submap_id, const std::vector<mapping::TrajectoryNode>& submap_nodes, const Submap* const submap) { auto submap_scan_matcher = common::make_unique<scan_matching::FastCorrelativeScanMatcher>( submap->high_resolution_hybrid_grid(), &submap->low_resolution_hybrid_grid(), submap_nodes, options_.fast_correlative_scan_matcher_options_3d()); common::MutexLocker locker(&mutex_); submap_scan_matchers_[submap_id] = {&submap->high_resolution_hybrid_grid(), &submap->low_resolution_hybrid_grid(), std::move(submap_scan_matcher)}; for (const std::function<void()>& work_item : submap_queued_work_items_[submap_id]) { thread_pool_->Schedule(work_item); } submap_queued_work_items_.erase(submap_id); } const ConstraintBuilder::SubmapScanMatcher* ConstraintBuilder::GetSubmapScanMatcher(const mapping::SubmapId& submap_id) { common::MutexLocker locker(&mutex_); const SubmapScanMatcher* submap_scan_matcher = &submap_scan_matchers_[submap_id]; CHECK(submap_scan_matcher->fast_correlative_scan_matcher != nullptr); return submap_scan_matcher; } void ConstraintBuilder::ComputeConstraint( const mapping::SubmapId& submap_id, const mapping::NodeId& node_id, bool match_full_submap, const mapping::TrajectoryNode::Data* const constant_data, const transform::Rigid3d& global_node_pose, const transform::Rigid3d& global_submap_pose, std::unique_ptr<OptimizationProblem::Constraint>* constraint) { const SubmapScanMatcher* const submap_scan_matcher = GetSubmapScanMatcher(submap_id); // The 'constraint_transform' (submap i <- node j) is computed from: // - a 'high_resolution_point_cloud' in node j and // - the initial guess 'initial_pose' (submap i <- node j). std::unique_ptr<scan_matching::FastCorrelativeScanMatcher::Result> match_result; // Compute 'pose_estimate' in three stages: // 1. Fast estimate using the fast correlative scan matcher. // 2. Prune if the score is too low. // 3. Refine. if (match_full_submap) { match_result = submap_scan_matcher->fast_correlative_scan_matcher->MatchFullSubmap( global_node_pose.rotation(), global_submap_pose.rotation(), *constant_data, options_.global_localization_min_score()); if (match_result != nullptr) { CHECK_GT(match_result->score, options_.global_localization_min_score()); CHECK_GE(node_id.trajectory_id, 0); CHECK_GE(submap_id.trajectory_id, 0); } else { return; } } else { match_result = submap_scan_matcher->fast_correlative_scan_matcher->Match( global_node_pose, global_submap_pose, *constant_data, options_.min_score()); if (match_result != nullptr) { // We've reported a successful local match. CHECK_GT(match_result->score, options_.min_score()); } else { return; } } { common::MutexLocker locker(&mutex_); score_histogram_.Add(match_result->score); rotational_score_histogram_.Add(match_result->rotational_score); low_resolution_score_histogram_.Add(match_result->low_resolution_score); } // Use the CSM estimate as both the initial and previous pose. This has the // effect that, in the absence of better information, we prefer the original // CSM estimate. ceres::Solver::Summary unused_summary; transform::Rigid3d constraint_transform; ceres_scan_matcher_.Match(match_result->pose_estimate.translation(), match_result->pose_estimate, {{&constant_data->high_resolution_point_cloud, submap_scan_matcher->high_resolution_hybrid_grid}, {&constant_data->low_resolution_point_cloud, submap_scan_matcher->low_resolution_hybrid_grid}}, &constraint_transform, &unused_summary); constraint->reset(new OptimizationProblem::Constraint{ submap_id, node_id, {constraint_transform, options_.loop_closure_translation_weight(), options_.loop_closure_rotation_weight()}, OptimizationProblem::Constraint::INTER_SUBMAP}); if (options_.log_matches()) { std::ostringstream info; info << "Node " << node_id << " with " << constant_data->high_resolution_point_cloud.size() << " points on submap " << submap_id << std::fixed; if (match_full_submap) { info << " matches"; } else { const transform::Rigid3d difference = global_submap_pose.inverse() * global_node_pose * constraint_transform; info << " differs by translation " << std::setprecision(2) << difference.translation().norm() << " rotation " << std::setprecision(3) << transform::GetAngle(difference); } info << " with score " << std::setprecision(1) << 100. * match_result->score << "%."; LOG(INFO) << info.str(); } } void ConstraintBuilder::FinishComputation(const int computation_index) { Result result; std::unique_ptr<std::function<void(const Result&)>> callback; { common::MutexLocker locker(&mutex_); if (--pending_computations_[computation_index] == 0) { pending_computations_.erase(computation_index); } if (pending_computations_.empty()) { CHECK_EQ(submap_queued_work_items_.size(), 0); if (when_done_ != nullptr) { for (const std::unique_ptr<OptimizationProblem::Constraint>& constraint : constraints_) { if (constraint != nullptr) { result.push_back(*constraint); } } if (options_.log_matches()) { LOG(INFO) << constraints_.size() << " computations resulted in " << result.size() << " additional constraints."; LOG(INFO) << "Score histogram:\n" << score_histogram_.ToString(10); LOG(INFO) << "Rotational score histogram:\n" << rotational_score_histogram_.ToString(10); LOG(INFO) << "Low resolution score histogram:\n" << low_resolution_score_histogram_.ToString(10); } constraints_.clear(); callback = std::move(when_done_); when_done_.reset(); } } } if (callback != nullptr) { (*callback)(result); } } int ConstraintBuilder::GetNumFinishedNodes() { common::MutexLocker locker(&mutex_); if (pending_computations_.empty()) { return current_computation_; } return pending_computations_.begin()->first; } void ConstraintBuilder::DeleteScanMatcher(const mapping::SubmapId& submap_id) { common::MutexLocker locker(&mutex_); CHECK(pending_computations_.empty()); submap_scan_matchers_.erase(submap_id); } } // namespace pose_graph } // namespace mapping_3d } // namespace cartographer <commit_msg>Fix debug output for 3D loop closure error. (#826)<commit_after>/* * Copyright 2016 The Cartographer 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 "cartographer/mapping_3d/pose_graph/constraint_builder.h" #include <cmath> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <memory> #include <sstream> #include <string> #include "Eigen/Eigenvalues" #include "cartographer/common/make_unique.h" #include "cartographer/common/math.h" #include "cartographer/common/thread_pool.h" #include "cartographer/mapping_3d/scan_matching/proto/ceres_scan_matcher_options.pb.h" #include "cartographer/mapping_3d/scan_matching/proto/fast_correlative_scan_matcher_options.pb.h" #include "cartographer/transform/transform.h" #include "glog/logging.h" namespace cartographer { namespace mapping_3d { namespace pose_graph { ConstraintBuilder::ConstraintBuilder( const mapping::pose_graph::proto::ConstraintBuilderOptions& options, common::ThreadPool* const thread_pool) : options_(options), thread_pool_(thread_pool), sampler_(options.sampling_ratio()), ceres_scan_matcher_(options.ceres_scan_matcher_options_3d()) {} ConstraintBuilder::~ConstraintBuilder() { common::MutexLocker locker(&mutex_); CHECK_EQ(constraints_.size(), 0) << "WhenDone() was not called"; CHECK_EQ(pending_computations_.size(), 0); CHECK_EQ(submap_queued_work_items_.size(), 0); CHECK(when_done_ == nullptr); } void ConstraintBuilder::MaybeAddConstraint( const mapping::SubmapId& submap_id, const Submap* const submap, const mapping::NodeId& node_id, const mapping::TrajectoryNode::Data* const constant_data, const std::vector<mapping::TrajectoryNode>& submap_nodes, const transform::Rigid3d& global_node_pose, const transform::Rigid3d& global_submap_pose) { if ((global_node_pose.translation() - global_submap_pose.translation()) .norm() > options_.max_constraint_distance()) { return; } if (sampler_.Pulse()) { common::MutexLocker locker(&mutex_); constraints_.emplace_back(); auto* const constraint = &constraints_.back(); ++pending_computations_[current_computation_]; const int current_computation = current_computation_; ScheduleSubmapScanMatcherConstructionAndQueueWorkItem( submap_id, submap_nodes, submap, [=]() EXCLUDES(mutex_) { ComputeConstraint(submap_id, node_id, false, /* match_full_submap */ constant_data, global_node_pose, global_submap_pose, constraint); FinishComputation(current_computation); }); } } void ConstraintBuilder::MaybeAddGlobalConstraint( const mapping::SubmapId& submap_id, const Submap* const submap, const mapping::NodeId& node_id, const mapping::TrajectoryNode::Data* const constant_data, const std::vector<mapping::TrajectoryNode>& submap_nodes, const Eigen::Quaterniond& global_node_rotation, const Eigen::Quaterniond& global_submap_rotation) { common::MutexLocker locker(&mutex_); constraints_.emplace_back(); auto* const constraint = &constraints_.back(); ++pending_computations_[current_computation_]; const int current_computation = current_computation_; ScheduleSubmapScanMatcherConstructionAndQueueWorkItem( submap_id, submap_nodes, submap, [=]() EXCLUDES(mutex_) { ComputeConstraint( submap_id, node_id, true, /* match_full_submap */ constant_data, transform::Rigid3d::Rotation(global_node_rotation), transform::Rigid3d::Rotation(global_submap_rotation), constraint); FinishComputation(current_computation); }); } void ConstraintBuilder::NotifyEndOfNode() { common::MutexLocker locker(&mutex_); ++current_computation_; } void ConstraintBuilder::WhenDone( const std::function<void(const ConstraintBuilder::Result&)>& callback) { common::MutexLocker locker(&mutex_); CHECK(when_done_ == nullptr); when_done_ = common::make_unique<std::function<void(const Result&)>>(callback); ++pending_computations_[current_computation_]; const int current_computation = current_computation_; thread_pool_->Schedule( [this, current_computation] { FinishComputation(current_computation); }); } void ConstraintBuilder::ScheduleSubmapScanMatcherConstructionAndQueueWorkItem( const mapping::SubmapId& submap_id, const std::vector<mapping::TrajectoryNode>& submap_nodes, const Submap* const submap, const std::function<void()>& work_item) { if (submap_scan_matchers_[submap_id].fast_correlative_scan_matcher != nullptr) { thread_pool_->Schedule(work_item); } else { submap_queued_work_items_[submap_id].push_back(work_item); if (submap_queued_work_items_[submap_id].size() == 1) { thread_pool_->Schedule([=]() { ConstructSubmapScanMatcher(submap_id, submap_nodes, submap); }); } } } void ConstraintBuilder::ConstructSubmapScanMatcher( const mapping::SubmapId& submap_id, const std::vector<mapping::TrajectoryNode>& submap_nodes, const Submap* const submap) { auto submap_scan_matcher = common::make_unique<scan_matching::FastCorrelativeScanMatcher>( submap->high_resolution_hybrid_grid(), &submap->low_resolution_hybrid_grid(), submap_nodes, options_.fast_correlative_scan_matcher_options_3d()); common::MutexLocker locker(&mutex_); submap_scan_matchers_[submap_id] = {&submap->high_resolution_hybrid_grid(), &submap->low_resolution_hybrid_grid(), std::move(submap_scan_matcher)}; for (const std::function<void()>& work_item : submap_queued_work_items_[submap_id]) { thread_pool_->Schedule(work_item); } submap_queued_work_items_.erase(submap_id); } const ConstraintBuilder::SubmapScanMatcher* ConstraintBuilder::GetSubmapScanMatcher(const mapping::SubmapId& submap_id) { common::MutexLocker locker(&mutex_); const SubmapScanMatcher* submap_scan_matcher = &submap_scan_matchers_[submap_id]; CHECK(submap_scan_matcher->fast_correlative_scan_matcher != nullptr); return submap_scan_matcher; } void ConstraintBuilder::ComputeConstraint( const mapping::SubmapId& submap_id, const mapping::NodeId& node_id, bool match_full_submap, const mapping::TrajectoryNode::Data* const constant_data, const transform::Rigid3d& global_node_pose, const transform::Rigid3d& global_submap_pose, std::unique_ptr<OptimizationProblem::Constraint>* constraint) { const SubmapScanMatcher* const submap_scan_matcher = GetSubmapScanMatcher(submap_id); // The 'constraint_transform' (submap i <- node j) is computed from: // - a 'high_resolution_point_cloud' in node j and // - the initial guess 'initial_pose' (submap i <- node j). std::unique_ptr<scan_matching::FastCorrelativeScanMatcher::Result> match_result; // Compute 'pose_estimate' in three stages: // 1. Fast estimate using the fast correlative scan matcher. // 2. Prune if the score is too low. // 3. Refine. if (match_full_submap) { match_result = submap_scan_matcher->fast_correlative_scan_matcher->MatchFullSubmap( global_node_pose.rotation(), global_submap_pose.rotation(), *constant_data, options_.global_localization_min_score()); if (match_result != nullptr) { CHECK_GT(match_result->score, options_.global_localization_min_score()); CHECK_GE(node_id.trajectory_id, 0); CHECK_GE(submap_id.trajectory_id, 0); } else { return; } } else { match_result = submap_scan_matcher->fast_correlative_scan_matcher->Match( global_node_pose, global_submap_pose, *constant_data, options_.min_score()); if (match_result != nullptr) { // We've reported a successful local match. CHECK_GT(match_result->score, options_.min_score()); } else { return; } } { common::MutexLocker locker(&mutex_); score_histogram_.Add(match_result->score); rotational_score_histogram_.Add(match_result->rotational_score); low_resolution_score_histogram_.Add(match_result->low_resolution_score); } // Use the CSM estimate as both the initial and previous pose. This has the // effect that, in the absence of better information, we prefer the original // CSM estimate. ceres::Solver::Summary unused_summary; transform::Rigid3d constraint_transform; ceres_scan_matcher_.Match(match_result->pose_estimate.translation(), match_result->pose_estimate, {{&constant_data->high_resolution_point_cloud, submap_scan_matcher->high_resolution_hybrid_grid}, {&constant_data->low_resolution_point_cloud, submap_scan_matcher->low_resolution_hybrid_grid}}, &constraint_transform, &unused_summary); constraint->reset(new OptimizationProblem::Constraint{ submap_id, node_id, {constraint_transform, options_.loop_closure_translation_weight(), options_.loop_closure_rotation_weight()}, OptimizationProblem::Constraint::INTER_SUBMAP}); if (options_.log_matches()) { std::ostringstream info; info << "Node " << node_id << " with " << constant_data->high_resolution_point_cloud.size() << " points on submap " << submap_id << std::fixed; if (match_full_submap) { info << " matches"; } else { // Compute the difference between (submap i <- node j) according to loop // closure ('constraint_transform') and according to global SLAM state. const transform::Rigid3d difference = global_node_pose.inverse() * global_submap_pose * constraint_transform; info << " differs by translation " << std::setprecision(2) << difference.translation().norm() << " rotation " << std::setprecision(3) << transform::GetAngle(difference); } info << " with score " << std::setprecision(1) << 100. * match_result->score << "%."; LOG(INFO) << info.str(); } } void ConstraintBuilder::FinishComputation(const int computation_index) { Result result; std::unique_ptr<std::function<void(const Result&)>> callback; { common::MutexLocker locker(&mutex_); if (--pending_computations_[computation_index] == 0) { pending_computations_.erase(computation_index); } if (pending_computations_.empty()) { CHECK_EQ(submap_queued_work_items_.size(), 0); if (when_done_ != nullptr) { for (const std::unique_ptr<OptimizationProblem::Constraint>& constraint : constraints_) { if (constraint != nullptr) { result.push_back(*constraint); } } if (options_.log_matches()) { LOG(INFO) << constraints_.size() << " computations resulted in " << result.size() << " additional constraints."; LOG(INFO) << "Score histogram:\n" << score_histogram_.ToString(10); LOG(INFO) << "Rotational score histogram:\n" << rotational_score_histogram_.ToString(10); LOG(INFO) << "Low resolution score histogram:\n" << low_resolution_score_histogram_.ToString(10); } constraints_.clear(); callback = std::move(when_done_); when_done_.reset(); } } } if (callback != nullptr) { (*callback)(result); } } int ConstraintBuilder::GetNumFinishedNodes() { common::MutexLocker locker(&mutex_); if (pending_computations_.empty()) { return current_computation_; } return pending_computations_.begin()->first; } void ConstraintBuilder::DeleteScanMatcher(const mapping::SubmapId& submap_id) { common::MutexLocker locker(&mutex_); CHECK(pending_computations_.empty()); submap_scan_matchers_.erase(submap_id); } } // namespace pose_graph } // namespace mapping_3d } // namespace cartographer <|endoftext|>
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/renderer_host/resource_message_filter.h" #include "base/gfx/gtk_native_view_id_manager.h" #include "chrome/browser/chrome_thread.h" #include "chrome/common/render_messages.h" #include "chrome/common/x11_util.h" #include "third_party/WebKit/WebKit/chromium/public/WebScreenInfo.h" #include "third_party/WebKit/WebKit/chromium/public/x11/WebScreenInfoFactory.h" using WebKit::WebScreenInfo; using WebKit::WebScreenInfoFactory; // We get null window_ids passed into the two functions below; please see // http://crbug.com/9060 for more details. // Called on the IO thread. void ResourceMessageFilter::SendBackgroundX11Reply(IPC::Message* reply_msg) { Send(reply_msg); } // Called on the BACKGROUND_X11 thread. void ResourceMessageFilter::DoOnGetScreenInfo(gfx::NativeViewId view, IPC::Message* reply_msg) { Display* display = x11_util::GetSecondaryDisplay(); int screen = x11_util::GetDefaultScreen(display); WebScreenInfo results = WebScreenInfoFactory::screenInfo(display, screen); ViewHostMsg_GetScreenInfo::WriteReplyParams(reply_msg, results); ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask( FROM_HERE, NewRunnableMethod( this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg)); } // Called on the BACKGROUND_X11 thread. void ResourceMessageFilter::DoOnGetWindowRect(gfx::NativeViewId view, IPC::Message* reply_msg) { // This is called to get the x, y offset (in screen coordinates) of the given // view and its width and height. gfx::Rect rect; XID window; if (Singleton<GtkNativeViewManager>()->GetXIDForId(&window, view)) { if (window) { int x, y; unsigned width, height; if (x11_util::GetWindowGeometry(&x, &y, &width, &height, window)) rect = gfx::Rect(x, y, width, height); } } ViewHostMsg_GetWindowRect::WriteReplyParams(reply_msg, rect); ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask( FROM_HERE, NewRunnableMethod( this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg)); } // Return the top-level parent of the given window. Called on the // BACKGROUND_X11 thread. static XID GetTopLevelWindow(XID window) { bool parent_is_root; XID parent_window; if (!x11_util::GetWindowParent(&parent_window, &parent_is_root, window)) return 0; if (parent_is_root) return window; return GetTopLevelWindow(parent_window); } // Called on the BACKGROUND_X11 thread. void ResourceMessageFilter::DoOnGetRootWindowRect(gfx::NativeViewId view, IPC::Message* reply_msg) { // This is called to get the screen coordinates and size of the browser // window itself. gfx::Rect rect; XID window; if (Singleton<GtkNativeViewManager>()->GetXIDForId(&window, view)) { if (window) { const XID toplevel = GetTopLevelWindow(toplevel); int x, y; unsigned width, height; if (x11_util::GetWindowGeometry(&x, &y, &width, &height, window)) rect = gfx::Rect(x, y, width, height); } } ViewHostMsg_GetRootWindowRect::WriteReplyParams(reply_msg, rect); ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask( FROM_HERE, NewRunnableMethod( this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg)); } // Called on the IO thread. void ResourceMessageFilter::OnGetScreenInfo(gfx::NativeViewId view, IPC::Message* reply_msg) { ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask( FROM_HERE, NewRunnableMethod( this, &ResourceMessageFilter::DoOnGetScreenInfo, view, reply_msg)); } // Called on the IO thread. void ResourceMessageFilter::OnGetWindowRect(gfx::NativeViewId view, IPC::Message* reply_msg) { ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask( FROM_HERE, NewRunnableMethod( this, &ResourceMessageFilter::DoOnGetWindowRect, view, reply_msg)); } // Called on the IO thread. void ResourceMessageFilter::OnGetRootWindowRect(gfx::NativeViewId view, IPC::Message* reply_msg) { ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask( FROM_HERE, NewRunnableMethod( this, &ResourceMessageFilter::DoOnGetRootWindowRect, view, reply_msg)); } <commit_msg>Linux: fix root window co-ordinates.<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/renderer_host/resource_message_filter.h" #include "base/gfx/gtk_native_view_id_manager.h" #include "chrome/browser/chrome_thread.h" #include "chrome/common/render_messages.h" #include "chrome/common/x11_util.h" #include "third_party/WebKit/WebKit/chromium/public/WebScreenInfo.h" #include "third_party/WebKit/WebKit/chromium/public/x11/WebScreenInfoFactory.h" using WebKit::WebScreenInfo; using WebKit::WebScreenInfoFactory; // We get null window_ids passed into the two functions below; please see // http://crbug.com/9060 for more details. // Called on the IO thread. void ResourceMessageFilter::SendBackgroundX11Reply(IPC::Message* reply_msg) { Send(reply_msg); } // Called on the BACKGROUND_X11 thread. void ResourceMessageFilter::DoOnGetScreenInfo(gfx::NativeViewId view, IPC::Message* reply_msg) { Display* display = x11_util::GetSecondaryDisplay(); int screen = x11_util::GetDefaultScreen(display); WebScreenInfo results = WebScreenInfoFactory::screenInfo(display, screen); ViewHostMsg_GetScreenInfo::WriteReplyParams(reply_msg, results); ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask( FROM_HERE, NewRunnableMethod( this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg)); } // Called on the BACKGROUND_X11 thread. void ResourceMessageFilter::DoOnGetWindowRect(gfx::NativeViewId view, IPC::Message* reply_msg) { // This is called to get the x, y offset (in screen coordinates) of the given // view and its width and height. gfx::Rect rect; XID window; if (Singleton<GtkNativeViewManager>()->GetXIDForId(&window, view)) { if (window) { int x, y; unsigned width, height; if (x11_util::GetWindowGeometry(&x, &y, &width, &height, window)) rect = gfx::Rect(x, y, width, height); } } ViewHostMsg_GetWindowRect::WriteReplyParams(reply_msg, rect); ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask( FROM_HERE, NewRunnableMethod( this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg)); } // Return the top-level parent of the given window. Called on the // BACKGROUND_X11 thread. static XID GetTopLevelWindow(XID window) { bool parent_is_root; XID parent_window; if (!x11_util::GetWindowParent(&parent_window, &parent_is_root, window)) return 0; if (parent_is_root) return window; return GetTopLevelWindow(parent_window); } // Called on the BACKGROUND_X11 thread. void ResourceMessageFilter::DoOnGetRootWindowRect(gfx::NativeViewId view, IPC::Message* reply_msg) { // This is called to get the screen coordinates and size of the browser // window itself. gfx::Rect rect; XID window; if (Singleton<GtkNativeViewManager>()->GetXIDForId(&window, view)) { if (window) { const XID toplevel = GetTopLevelWindow(window); int x, y; unsigned width, height; if (x11_util::GetWindowGeometry(&x, &y, &width, &height, toplevel)) rect = gfx::Rect(x, y, width, height); } } ViewHostMsg_GetRootWindowRect::WriteReplyParams(reply_msg, rect); ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask( FROM_HERE, NewRunnableMethod( this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg)); } // Called on the IO thread. void ResourceMessageFilter::OnGetScreenInfo(gfx::NativeViewId view, IPC::Message* reply_msg) { ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask( FROM_HERE, NewRunnableMethod( this, &ResourceMessageFilter::DoOnGetScreenInfo, view, reply_msg)); } // Called on the IO thread. void ResourceMessageFilter::OnGetWindowRect(gfx::NativeViewId view, IPC::Message* reply_msg) { ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask( FROM_HERE, NewRunnableMethod( this, &ResourceMessageFilter::DoOnGetWindowRect, view, reply_msg)); } // Called on the IO thread. void ResourceMessageFilter::OnGetRootWindowRect(gfx::NativeViewId view, IPC::Message* reply_msg) { ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask( FROM_HERE, NewRunnableMethod( this, &ResourceMessageFilter::DoOnGetRootWindowRect, view, reply_msg)); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/translate/translate_infobar_base_gtk.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "app/slide_animation.h" #include "base/utf_string_conversions.h" #include "chrome/browser/translate/options_menu_model.h" #include "chrome/browser/translate/translate_infobar_delegate.h" #include "chrome/browser/gtk/translate/after_translate_infobar_gtk.h" #include "chrome/browser/gtk/translate/before_translate_infobar_gtk.h" #include "chrome/browser/gtk/translate/translate_message_infobar_gtk.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/gtk/menu_gtk.h" #include "gfx/canvas.h" #include "gfx/gtk_util.h" #include "grit/generated_resources.h" namespace { // To be able to map from language id <-> entry in the combo box, we // store the language id in the combo box data model in addition to the // displayed name. enum { LANGUAGE_COMBO_COLUMN_ID, LANGUAGE_COMBO_COLUMN_NAME, LANGUAGE_COMBO_COLUMN_COUNT }; } // namespace TranslateInfoBarBase::TranslateInfoBarBase(TranslateInfoBarDelegate* delegate) : InfoBar(delegate) { TranslateInfoBarDelegate::BackgroundAnimationType animation = delegate->background_animation_type(); if (animation != TranslateInfoBarDelegate::kNone) { background_color_animation_.reset(new SlideAnimation(this)); background_color_animation_->SetTweenType(Tween::LINEAR); background_color_animation_->SetSlideDuration(500); if (animation == TranslateInfoBarDelegate::kNormalToError) { background_color_animation_->Show(); } else { DCHECK_EQ(TranslateInfoBarDelegate::kErrorToNormal, animation); // Hide() runs the animation in reverse. background_color_animation_->Reset(1.0); background_color_animation_->Hide(); } } } TranslateInfoBarBase::~TranslateInfoBarBase() { } void TranslateInfoBarBase::Init() { if (!ShowOptionsMenuButton()) return; // The options button sits outside the translate_box so that it can be end // packed in hbox_. GtkWidget* options_menu_button = BuildOptionsMenuButton(); g_signal_connect(options_menu_button, "clicked", G_CALLBACK(&OnOptionsClickedThunk), this); gtk_widget_show_all(options_menu_button); gtk_util::CenterWidgetInHBox(hbox_, options_menu_button, true, 0); } void TranslateInfoBarBase::GetTopColor(InfoBarDelegate::Type type, double* r, double* g, double *b) { if (background_error_percent_ <= 0) { InfoBar::GetTopColor(InfoBarDelegate::PAGE_ACTION_TYPE, r, g, b); } else if (background_error_percent_ >= 1) { InfoBar::GetTopColor(InfoBarDelegate::ERROR_TYPE, r, g, b); } else { double normal_r, normal_g, normal_b; InfoBar::GetTopColor(InfoBarDelegate::PAGE_ACTION_TYPE, &normal_r, &normal_g, &normal_b); double error_r, error_g, error_b; InfoBar::GetTopColor(InfoBarDelegate::ERROR_TYPE, &error_r, &error_g, &error_b); double offset_r = error_r - normal_r; double offset_g = error_g - normal_g; double offset_b = error_b - normal_b; *r = normal_r + (background_error_percent_ * offset_r); *g = normal_g + (background_error_percent_ * offset_g); *b = normal_b + (background_error_percent_ * offset_b); } } void TranslateInfoBarBase::GetBottomColor(InfoBarDelegate::Type type, double* r, double* g, double *b) { if (background_error_percent_ <= 0) { InfoBar::GetBottomColor(InfoBarDelegate::PAGE_ACTION_TYPE, r, g, b); } else if (background_error_percent_ >= 1) { InfoBar::GetBottomColor(InfoBarDelegate::ERROR_TYPE, r, g, b); } else { double normal_r, normal_g, normal_b; InfoBar::GetBottomColor(InfoBarDelegate::PAGE_ACTION_TYPE, &normal_r, &normal_g, &normal_b); double error_r, error_g, error_b; InfoBar::GetBottomColor(InfoBarDelegate::ERROR_TYPE, &error_r, &error_g, &error_b); double offset_r = error_r - normal_r; double offset_g = error_g - normal_g; double offset_b = error_b - normal_b; *r = normal_r + (background_error_percent_ * offset_r); *g = normal_g + (background_error_percent_ * offset_g); *b = normal_b + (background_error_percent_ * offset_b); } } void TranslateInfoBarBase::AnimationProgressed(const Animation* animation) { DCHECK(animation == background_color_animation_.get()); background_error_percent_ = animation->GetCurrentValue(); // Queue the info bar widget for redisplay so it repaints its background. gtk_widget_queue_draw(widget()); } GtkWidget* TranslateInfoBarBase::CreateLabel(const std::string& text) { GtkWidget* label = gtk_label_new(text.c_str()); gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack); return label; } GtkWidget* TranslateInfoBarBase::CreateLanguageCombobox(int selected_language, int exclude_language) { GtkListStore* model = gtk_list_store_new(LANGUAGE_COMBO_COLUMN_COUNT, G_TYPE_INT, G_TYPE_STRING); bool set_selection = false; GtkTreeIter selected_iter; TranslateInfoBarDelegate* delegate = GetDelegate(); for (int i = 0; i < delegate->GetLanguageCount(); ++i) { if (i == exclude_language) continue; GtkTreeIter tree_iter; const string16& name = delegate->GetLanguageDisplayableNameAt(i); gtk_list_store_append(model, &tree_iter); gtk_list_store_set(model, &tree_iter, LANGUAGE_COMBO_COLUMN_ID, i, LANGUAGE_COMBO_COLUMN_NAME, UTF16ToUTF8(name).c_str(), -1); if (i == selected_language) { selected_iter = tree_iter; set_selection = true; } } GtkWidget* combobox = gtk_combo_box_new_with_model(GTK_TREE_MODEL(model)); if (set_selection) gtk_combo_box_set_active_iter(GTK_COMBO_BOX(combobox), &selected_iter); g_object_unref(model); GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combobox), renderer, TRUE); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combobox), renderer, "text", LANGUAGE_COMBO_COLUMN_NAME, NULL); return combobox; } // static int TranslateInfoBarBase::GetLanguageComboboxActiveId(GtkComboBox* combo) { GtkTreeIter iter; if (!gtk_combo_box_get_active_iter(combo, &iter)) return 0; gint id = 0; gtk_tree_model_get(gtk_combo_box_get_model(combo), &iter, LANGUAGE_COMBO_COLUMN_ID, &id, -1); return id; } TranslateInfoBarDelegate* TranslateInfoBarBase::GetDelegate() const { return static_cast<TranslateInfoBarDelegate*>(delegate()); } // static GtkWidget* TranslateInfoBarBase::BuildOptionsMenuButton() { GtkWidget* button = gtk_button_new(); GtkWidget* former_child = gtk_bin_get_child(GTK_BIN(button)); if (former_child) gtk_container_remove(GTK_CONTAINER(button), former_child); GtkWidget* hbox = gtk_hbox_new(FALSE, 0); GtkWidget* label = gtk_label_new( l10n_util::GetStringUTF8(IDS_TRANSLATE_INFOBAR_OPTIONS).c_str()); gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0); GtkWidget* arrow = gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_NONE); gtk_box_pack_start(GTK_BOX(hbox), arrow, FALSE, FALSE, 0); gtk_container_add(GTK_CONTAINER(button), hbox); return button; } void TranslateInfoBarBase::OnOptionsClicked(GtkWidget* sender) { if (!options_menu_model_.get()) { options_menu_model_.reset(new OptionsMenuModel(GetDelegate())); options_menu_menu_.reset(new MenuGtk(NULL, options_menu_model_.get())); } options_menu_menu_->Popup(sender, 1, gtk_get_current_event_time()); } // TranslateInfoBarDelegate specific method: InfoBar* TranslateInfoBarDelegate::CreateInfoBar() { TranslateInfoBarBase* infobar = NULL; switch (type_) { case kBeforeTranslate: infobar = new BeforeTranslateInfoBar(this); break; case kAfterTranslate: infobar = new AfterTranslateInfoBar(this); break; case kTranslating: case kTranslationError: infobar = new TranslateMessageInfoBar(this); break; default: NOTREACHED(); } infobar->Init(); // Set |infobar_view_| so that the model can notify the infobar when it // changes. infobar_view_ = infobar; return infobar; } <commit_msg>Fixing translate infobar background. In some cases the infobar background was not the right color.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/translate/translate_infobar_base_gtk.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "app/slide_animation.h" #include "base/utf_string_conversions.h" #include "chrome/browser/translate/options_menu_model.h" #include "chrome/browser/translate/translate_infobar_delegate.h" #include "chrome/browser/gtk/translate/after_translate_infobar_gtk.h" #include "chrome/browser/gtk/translate/before_translate_infobar_gtk.h" #include "chrome/browser/gtk/translate/translate_message_infobar_gtk.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/gtk/menu_gtk.h" #include "gfx/canvas.h" #include "gfx/gtk_util.h" #include "grit/generated_resources.h" namespace { // To be able to map from language id <-> entry in the combo box, we // store the language id in the combo box data model in addition to the // displayed name. enum { LANGUAGE_COMBO_COLUMN_ID, LANGUAGE_COMBO_COLUMN_NAME, LANGUAGE_COMBO_COLUMN_COUNT }; } // namespace TranslateInfoBarBase::TranslateInfoBarBase(TranslateInfoBarDelegate* delegate) : InfoBar(delegate) { TranslateInfoBarDelegate::BackgroundAnimationType animation = delegate->background_animation_type(); if (animation != TranslateInfoBarDelegate::kNone) { background_color_animation_.reset(new SlideAnimation(this)); background_color_animation_->SetTweenType(Tween::LINEAR); background_color_animation_->SetSlideDuration(500); if (animation == TranslateInfoBarDelegate::kNormalToError) { background_color_animation_->Show(); } else { DCHECK_EQ(TranslateInfoBarDelegate::kErrorToNormal, animation); // Hide() runs the animation in reverse. background_color_animation_->Reset(1.0); background_color_animation_->Hide(); } } else { background_error_percent_ = delegate->IsError() ? 1 : 0; } } TranslateInfoBarBase::~TranslateInfoBarBase() { } void TranslateInfoBarBase::Init() { if (!ShowOptionsMenuButton()) return; // The options button sits outside the translate_box so that it can be end // packed in hbox_. GtkWidget* options_menu_button = BuildOptionsMenuButton(); g_signal_connect(options_menu_button, "clicked", G_CALLBACK(&OnOptionsClickedThunk), this); gtk_widget_show_all(options_menu_button); gtk_util::CenterWidgetInHBox(hbox_, options_menu_button, true, 0); } void TranslateInfoBarBase::GetTopColor(InfoBarDelegate::Type type, double* r, double* g, double *b) { if (background_error_percent_ <= 0) { InfoBar::GetTopColor(InfoBarDelegate::PAGE_ACTION_TYPE, r, g, b); } else if (background_error_percent_ >= 1) { InfoBar::GetTopColor(InfoBarDelegate::ERROR_TYPE, r, g, b); } else { double normal_r, normal_g, normal_b; InfoBar::GetTopColor(InfoBarDelegate::PAGE_ACTION_TYPE, &normal_r, &normal_g, &normal_b); double error_r, error_g, error_b; InfoBar::GetTopColor(InfoBarDelegate::ERROR_TYPE, &error_r, &error_g, &error_b); double offset_r = error_r - normal_r; double offset_g = error_g - normal_g; double offset_b = error_b - normal_b; *r = normal_r + (background_error_percent_ * offset_r); *g = normal_g + (background_error_percent_ * offset_g); *b = normal_b + (background_error_percent_ * offset_b); } } void TranslateInfoBarBase::GetBottomColor(InfoBarDelegate::Type type, double* r, double* g, double *b) { if (background_error_percent_ <= 0) { InfoBar::GetBottomColor(InfoBarDelegate::PAGE_ACTION_TYPE, r, g, b); } else if (background_error_percent_ >= 1) { InfoBar::GetBottomColor(InfoBarDelegate::ERROR_TYPE, r, g, b); } else { double normal_r, normal_g, normal_b; InfoBar::GetBottomColor(InfoBarDelegate::PAGE_ACTION_TYPE, &normal_r, &normal_g, &normal_b); double error_r, error_g, error_b; InfoBar::GetBottomColor(InfoBarDelegate::ERROR_TYPE, &error_r, &error_g, &error_b); double offset_r = error_r - normal_r; double offset_g = error_g - normal_g; double offset_b = error_b - normal_b; *r = normal_r + (background_error_percent_ * offset_r); *g = normal_g + (background_error_percent_ * offset_g); *b = normal_b + (background_error_percent_ * offset_b); } } void TranslateInfoBarBase::AnimationProgressed(const Animation* animation) { DCHECK(animation == background_color_animation_.get()); background_error_percent_ = animation->GetCurrentValue(); // Queue the info bar widget for redisplay so it repaints its background. gtk_widget_queue_draw(widget()); } GtkWidget* TranslateInfoBarBase::CreateLabel(const std::string& text) { GtkWidget* label = gtk_label_new(text.c_str()); gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack); return label; } GtkWidget* TranslateInfoBarBase::CreateLanguageCombobox(int selected_language, int exclude_language) { GtkListStore* model = gtk_list_store_new(LANGUAGE_COMBO_COLUMN_COUNT, G_TYPE_INT, G_TYPE_STRING); bool set_selection = false; GtkTreeIter selected_iter; TranslateInfoBarDelegate* delegate = GetDelegate(); for (int i = 0; i < delegate->GetLanguageCount(); ++i) { if (i == exclude_language) continue; GtkTreeIter tree_iter; const string16& name = delegate->GetLanguageDisplayableNameAt(i); gtk_list_store_append(model, &tree_iter); gtk_list_store_set(model, &tree_iter, LANGUAGE_COMBO_COLUMN_ID, i, LANGUAGE_COMBO_COLUMN_NAME, UTF16ToUTF8(name).c_str(), -1); if (i == selected_language) { selected_iter = tree_iter; set_selection = true; } } GtkWidget* combobox = gtk_combo_box_new_with_model(GTK_TREE_MODEL(model)); if (set_selection) gtk_combo_box_set_active_iter(GTK_COMBO_BOX(combobox), &selected_iter); g_object_unref(model); GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combobox), renderer, TRUE); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combobox), renderer, "text", LANGUAGE_COMBO_COLUMN_NAME, NULL); return combobox; } // static int TranslateInfoBarBase::GetLanguageComboboxActiveId(GtkComboBox* combo) { GtkTreeIter iter; if (!gtk_combo_box_get_active_iter(combo, &iter)) return 0; gint id = 0; gtk_tree_model_get(gtk_combo_box_get_model(combo), &iter, LANGUAGE_COMBO_COLUMN_ID, &id, -1); return id; } TranslateInfoBarDelegate* TranslateInfoBarBase::GetDelegate() const { return static_cast<TranslateInfoBarDelegate*>(delegate()); } // static GtkWidget* TranslateInfoBarBase::BuildOptionsMenuButton() { GtkWidget* button = gtk_button_new(); GtkWidget* former_child = gtk_bin_get_child(GTK_BIN(button)); if (former_child) gtk_container_remove(GTK_CONTAINER(button), former_child); GtkWidget* hbox = gtk_hbox_new(FALSE, 0); GtkWidget* label = gtk_label_new( l10n_util::GetStringUTF8(IDS_TRANSLATE_INFOBAR_OPTIONS).c_str()); gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0); GtkWidget* arrow = gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_NONE); gtk_box_pack_start(GTK_BOX(hbox), arrow, FALSE, FALSE, 0); gtk_container_add(GTK_CONTAINER(button), hbox); return button; } void TranslateInfoBarBase::OnOptionsClicked(GtkWidget* sender) { if (!options_menu_model_.get()) { options_menu_model_.reset(new OptionsMenuModel(GetDelegate())); options_menu_menu_.reset(new MenuGtk(NULL, options_menu_model_.get())); } options_menu_menu_->Popup(sender, 1, gtk_get_current_event_time()); } // TranslateInfoBarDelegate specific method: InfoBar* TranslateInfoBarDelegate::CreateInfoBar() { TranslateInfoBarBase* infobar = NULL; switch (type_) { case kBeforeTranslate: infobar = new BeforeTranslateInfoBar(this); break; case kAfterTranslate: infobar = new AfterTranslateInfoBar(this); break; case kTranslating: case kTranslationError: infobar = new TranslateMessageInfoBar(this); break; default: NOTREACHED(); } infobar->Init(); // Set |infobar_view_| so that the model can notify the infobar when it // changes. infobar_view_ = infobar; return infobar; } <|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/process_util.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/find_bar/find_bar_controller.h" #include "chrome/browser/ui/find_bar/find_notification_details.h" #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/find_bar_host.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/tab_contents/tab_contents.h" #include "net/test/test_server.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/keycodes/keyboard_codes.h" #include "views/focus/focus_manager.h" #include "views/view.h" #include "views/views_delegate.h" namespace { // The delay waited after sending an OS simulated event. static const int kActionDelayMs = 500; static const char kSimplePage[] = "files/find_in_page/simple.html"; void Checkpoint(const char* message, const base::TimeTicks& start_time) { LOG(INFO) << message << " : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; } class FindInPageTest : public InProcessBrowserTest { public: FindInPageTest() { set_show_window(true); FindBarHost::disable_animations_during_testing_ = true; } string16 GetFindBarText() { FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); return find_bar->GetFindText(); } string16 GetFindBarSelectedText() { FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); return find_bar->GetFindSelectedText(); } }; } // namespace #if defined(TOOLKIT_USES_GTK) #define MAYBE_CrashEscHandlers FLAKY_CrashEscHandlers #else #define MAYBE_CrashEscHandlers CrashEscHandlers #endif IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_CrashEscHandlers) { ASSERT_TRUE(test_server()->Start()); // First we navigate to our test page (tab A). GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); browser()->Find(); // Open another tab (tab B). browser()->AddSelectedTabWithURL(url, PageTransition::TYPED); browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Select tab A. browser()->ActivateTabAt(0, true); // Close tab B. browser()->CloseTabContents(browser()->GetTabContentsAt(1)); // Click on the location bar so that Find box loses focus. ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(), VIEW_ID_LOCATION_BAR)); #if defined(TOOLKIT_VIEWS) || defined(OS_WIN) // Check the location bar is focused. EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR)); #endif // This used to crash until bug 1303709 was fixed. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); } IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL("title1.html"); ui_test_utils::NavigateToURL(browser(), url); // Focus the location bar, open and close the find-in-page, focus should // return to the location bar. browser()->FocusLocationBar(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR)); // Ensure the creation of the find bar controller. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelection); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR)); // Focus the location bar, find something on the page, close the find box, // focus should go to the page. browser()->FocusLocationBar(); browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(), ASCIIToUTF16("a"), true, false, NULL); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelection); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER_FOCUS_VIEW)); // Focus the location bar, open and close the find box, focus should return to // the location bar (same as before, just checking that http://crbug.com/23599 // is fixed). browser()->FocusLocationBar(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR)); browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelection); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR)); } IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestoreOnTabSwitch) { ASSERT_TRUE(test_server()->Start()); // First we navigate to our test page (tab A). GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); // Search for 'a'. ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(), ASCIIToUTF16("a"), true, false, NULL); EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText()); // Open another tab (tab B). browser()->AddSelectedTabWithURL(url, PageTransition::TYPED); ASSERT_TRUE(ui_test_utils::WaitForNavigationInCurrentTab(browser())); // Make sure Find box is open. browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Search for 'b'. ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(), ASCIIToUTF16("b"), true, false, NULL); EXPECT_TRUE(ASCIIToUTF16("b") == find_bar->GetFindSelectedText()); // Set focus away from the Find bar (to the Location bar). browser()->FocusLocationBar(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR)); // Select tab A. Find bar should get focus. browser()->ActivateTabAt(0, true); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText()); // Select tab B. Location bar should get focus. browser()->ActivateTabAt(1, true); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR)); } // This tests that whenever you clear values from the Find box and close it that // it respects that and doesn't show you the last search, as reported in bug: // http://crbug.com/40121. IN_PROC_BROWSER_TEST_F(FindInPageTest, PrepopulateRespectBlank) { #if defined(OS_MACOSX) // FindInPage on Mac doesn't use prepopulated values. Search there is global. return; #endif base::TimeTicks start_time = base::TimeTicks::Now(); Checkpoint("Test starting", start_time); ASSERT_TRUE(test_server()->Start()); // Make sure Chrome is in the foreground, otherwise sending input // won't do anything and the test will hang. ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); Checkpoint("Navigate", start_time); // First we navigate to any page. GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); Checkpoint("Show Find bar", start_time); // Show the Find bar. browser()->GetFindBarController()->Show(); Checkpoint("Search for 'a'", start_time); // Search for "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_A, false, false, false, false)); // We should find "a" here. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText()); Checkpoint("Delete 'a'", start_time); // Delete "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_BACK, false, false, false, false)); // Validate we have cleared the text. EXPECT_EQ(string16(), GetFindBarText()); Checkpoint("Close find bar", start_time); // Close the Find box. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); Checkpoint("Show Find bar", start_time); // Show the Find bar. browser()->GetFindBarController()->Show(); Checkpoint("Validate text", start_time); // After the Find box has been reopened, it should not have been prepopulated // with "a" again. EXPECT_EQ(string16(), GetFindBarText()); Checkpoint("Close Find bar", start_time); // Close the Find box. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); Checkpoint("FindNext", start_time); // Press F3 to trigger FindNext. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_F3, false, false, false, false)); Checkpoint("Validate", start_time); // After the Find box has been reopened, it should still have no prepopulate // value. EXPECT_EQ(string16(), GetFindBarText()); Checkpoint("Test done", start_time); } IN_PROC_BROWSER_TEST_F(FindInPageTest, PasteWithoutTextChange) { ASSERT_TRUE(test_server()->Start()); // Make sure Chrome is in the foreground, otherwise sending input // won't do anything and the test will hang. ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); // First we navigate to any page. GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); // Show the Find bar. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Search for "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_A, false, false, false, false)); // We should find "a" here. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText()); // Reload the page to clear the matching result. browser()->Reload(CURRENT_TAB); // Focus the Find bar again to make sure the text is selected. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // "a" should be selected. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarSelectedText()); // Press Ctrl-C to copy the content. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_C, true, false, false, false)); string16 str; views::ViewsDelegate::views_delegate->GetClipboard()-> ReadText(ui::Clipboard::BUFFER_STANDARD, &str); // Make sure the text is copied successfully. EXPECT_EQ(ASCIIToUTF16("a"), str); // Press Ctrl-V to paste the content back, it should start finding even if the // content is not changed. Source<TabContents> notification_source(browser()->GetSelectedTabContents()); ui_test_utils::WindowedNotificationObserverWithDetails <FindNotificationDetails> observer( chrome::NOTIFICATION_FIND_RESULT_AVAILABLE, notification_source); ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_V, true, false, false, false)); ASSERT_NO_FATAL_FAILURE(observer.Wait()); FindNotificationDetails details; ASSERT_TRUE(observer.GetDetailsFor(notification_source.map_key(), &details)); EXPECT_TRUE(details.number_of_matches() > 0); } <commit_msg>Mark FindInPageTest.PasteWithoutTextChange flaky on Win.<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/process_util.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/find_bar/find_bar_controller.h" #include "chrome/browser/ui/find_bar/find_notification_details.h" #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/find_bar_host.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/tab_contents/tab_contents.h" #include "net/test/test_server.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/keycodes/keyboard_codes.h" #include "views/focus/focus_manager.h" #include "views/view.h" #include "views/views_delegate.h" namespace { // The delay waited after sending an OS simulated event. static const int kActionDelayMs = 500; static const char kSimplePage[] = "files/find_in_page/simple.html"; void Checkpoint(const char* message, const base::TimeTicks& start_time) { LOG(INFO) << message << " : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; } class FindInPageTest : public InProcessBrowserTest { public: FindInPageTest() { set_show_window(true); FindBarHost::disable_animations_during_testing_ = true; } string16 GetFindBarText() { FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); return find_bar->GetFindText(); } string16 GetFindBarSelectedText() { FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); return find_bar->GetFindSelectedText(); } }; } // namespace #if defined(TOOLKIT_USES_GTK) #define MAYBE_CrashEscHandlers FLAKY_CrashEscHandlers #else #define MAYBE_CrashEscHandlers CrashEscHandlers #endif IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_CrashEscHandlers) { ASSERT_TRUE(test_server()->Start()); // First we navigate to our test page (tab A). GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); browser()->Find(); // Open another tab (tab B). browser()->AddSelectedTabWithURL(url, PageTransition::TYPED); browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Select tab A. browser()->ActivateTabAt(0, true); // Close tab B. browser()->CloseTabContents(browser()->GetTabContentsAt(1)); // Click on the location bar so that Find box loses focus. ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(), VIEW_ID_LOCATION_BAR)); #if defined(TOOLKIT_VIEWS) || defined(OS_WIN) // Check the location bar is focused. EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR)); #endif // This used to crash until bug 1303709 was fixed. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); } IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL("title1.html"); ui_test_utils::NavigateToURL(browser(), url); // Focus the location bar, open and close the find-in-page, focus should // return to the location bar. browser()->FocusLocationBar(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR)); // Ensure the creation of the find bar controller. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelection); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR)); // Focus the location bar, find something on the page, close the find box, // focus should go to the page. browser()->FocusLocationBar(); browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(), ASCIIToUTF16("a"), true, false, NULL); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelection); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER_FOCUS_VIEW)); // Focus the location bar, open and close the find box, focus should return to // the location bar (same as before, just checking that http://crbug.com/23599 // is fixed). browser()->FocusLocationBar(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR)); browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelection); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR)); } IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestoreOnTabSwitch) { ASSERT_TRUE(test_server()->Start()); // First we navigate to our test page (tab A). GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); // Search for 'a'. ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(), ASCIIToUTF16("a"), true, false, NULL); EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText()); // Open another tab (tab B). browser()->AddSelectedTabWithURL(url, PageTransition::TYPED); ASSERT_TRUE(ui_test_utils::WaitForNavigationInCurrentTab(browser())); // Make sure Find box is open. browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Search for 'b'. ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(), ASCIIToUTF16("b"), true, false, NULL); EXPECT_TRUE(ASCIIToUTF16("b") == find_bar->GetFindSelectedText()); // Set focus away from the Find bar (to the Location bar). browser()->FocusLocationBar(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR)); // Select tab A. Find bar should get focus. browser()->ActivateTabAt(0, true); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText()); // Select tab B. Location bar should get focus. browser()->ActivateTabAt(1, true); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR)); } // This tests that whenever you clear values from the Find box and close it that // it respects that and doesn't show you the last search, as reported in bug: // http://crbug.com/40121. IN_PROC_BROWSER_TEST_F(FindInPageTest, PrepopulateRespectBlank) { #if defined(OS_MACOSX) // FindInPage on Mac doesn't use prepopulated values. Search there is global. return; #endif base::TimeTicks start_time = base::TimeTicks::Now(); Checkpoint("Test starting", start_time); ASSERT_TRUE(test_server()->Start()); // Make sure Chrome is in the foreground, otherwise sending input // won't do anything and the test will hang. ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); Checkpoint("Navigate", start_time); // First we navigate to any page. GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); Checkpoint("Show Find bar", start_time); // Show the Find bar. browser()->GetFindBarController()->Show(); Checkpoint("Search for 'a'", start_time); // Search for "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_A, false, false, false, false)); // We should find "a" here. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText()); Checkpoint("Delete 'a'", start_time); // Delete "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_BACK, false, false, false, false)); // Validate we have cleared the text. EXPECT_EQ(string16(), GetFindBarText()); Checkpoint("Close find bar", start_time); // Close the Find box. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); Checkpoint("Show Find bar", start_time); // Show the Find bar. browser()->GetFindBarController()->Show(); Checkpoint("Validate text", start_time); // After the Find box has been reopened, it should not have been prepopulated // with "a" again. EXPECT_EQ(string16(), GetFindBarText()); Checkpoint("Close Find bar", start_time); // Close the Find box. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); Checkpoint("FindNext", start_time); // Press F3 to trigger FindNext. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_F3, false, false, false, false)); Checkpoint("Validate", start_time); // After the Find box has been reopened, it should still have no prepopulate // value. EXPECT_EQ(string16(), GetFindBarText()); Checkpoint("Test done", start_time); } // Flaky on Win. http://crbug.com/92467 #if defined(OS_WIN) #define MAYBE_PasteWithoutTextChange FLAKY_PasteWithoutTextChange #else #define MAYBE_PasteWithoutTextChange PasteWithoutTextChange #endif IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_PasteWithoutTextChange) { ASSERT_TRUE(test_server()->Start()); // Make sure Chrome is in the foreground, otherwise sending input // won't do anything and the test will hang. ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); // First we navigate to any page. GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); // Show the Find bar. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Search for "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_A, false, false, false, false)); // We should find "a" here. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText()); // Reload the page to clear the matching result. browser()->Reload(CURRENT_TAB); // Focus the Find bar again to make sure the text is selected. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // "a" should be selected. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarSelectedText()); // Press Ctrl-C to copy the content. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_C, true, false, false, false)); string16 str; views::ViewsDelegate::views_delegate->GetClipboard()-> ReadText(ui::Clipboard::BUFFER_STANDARD, &str); // Make sure the text is copied successfully. EXPECT_EQ(ASCIIToUTF16("a"), str); // Press Ctrl-V to paste the content back, it should start finding even if the // content is not changed. Source<TabContents> notification_source(browser()->GetSelectedTabContents()); ui_test_utils::WindowedNotificationObserverWithDetails <FindNotificationDetails> observer( chrome::NOTIFICATION_FIND_RESULT_AVAILABLE, notification_source); ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_V, true, false, false, false)); ASSERT_NO_FATAL_FAILURE(observer.Wait()); FindNotificationDetails details; ASSERT_TRUE(observer.GetDetailsFor(notification_source.map_key(), &details)); EXPECT_TRUE(details.number_of_matches() > 0); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/constrained_window_frame_simple.h" #include "chrome/browser/ui/constrained_window.h" #include "chrome/browser/ui/views/constrained_window_views.h" #include "grit/ui_resources.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/google_chrome_strings.h" #include "grit/shared_resources.h" #include "grit/theme_resources.h" #include "ui/base/hit_test.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas.h" #include "ui/gfx/rect.h" #include "ui/gfx/path.h" #include "ui/views/background.h" #include "ui/views/controls/label.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/layout/layout_manager.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" namespace { typedef ConstrainedWindowFrameSimple::HeaderViews HeaderViews; // A layout manager that lays out the header view with proper padding, // and sized to the widget's client view. class HeaderLayout : public views::LayoutManager { public: explicit HeaderLayout(views::Widget* container) : container_(container) {} virtual ~HeaderLayout() {} // Overridden from LayoutManager virtual void Layout(views::View* host); virtual gfx::Size GetPreferredSize(views::View* host); private: views::Widget* container_; DISALLOW_COPY_AND_ASSIGN(HeaderLayout); }; void HeaderLayout::Layout(views::View* host) { if (!host->has_children()) return; int horizontal_padding = ConstrainedWindow::kHorizontalPadding; int vertical_padding = ConstrainedWindow::kVerticalPadding; int row_padding = ConstrainedWindow::kRowPadding; views::View* header = host->child_at(0); gfx::Size preferred_size = GetPreferredSize(host); int width = preferred_size.width() - 2 * horizontal_padding; int height = preferred_size.height() - vertical_padding - row_padding; header->SetBounds(horizontal_padding, vertical_padding, width, height); } gfx::Size HeaderLayout::GetPreferredSize(views::View* host) { int horizontal_padding = ConstrainedWindow::kHorizontalPadding; int vertical_padding = ConstrainedWindow::kVerticalPadding; int row_padding = ConstrainedWindow::kRowPadding; views::View* header = host->child_at(0); views::View* client_view = container_->client_view(); gfx::Size header_size = header ? header->GetPreferredSize() : gfx::Size(); gfx::Size client_size = client_view ? client_view->GetPreferredSize() : gfx::Size(); int width = std::max(client_size.width(), header_size.width()) + 2 * horizontal_padding; int height = vertical_padding + header_size.height() + row_padding; return gfx::Size(width, height); } } // namespace ConstrainedWindowFrameSimple::HeaderViews::HeaderViews( views::View* header, views::Label* title_label, views::Button* close_button) : header(header), title_label(title_label), close_button(close_button) { DCHECK(header); } ConstrainedWindowFrameSimple::ConstrainedWindowFrameSimple( ConstrainedWindowViews* container) : container_(container) { container_->set_frame_type(views::Widget::FRAME_TYPE_FORCE_CUSTOM); layout_ = new HeaderLayout(container_); SetLayoutManager(layout_); SetHeaderView(CreateDefaultHeaderView()); set_background(views::Background::CreateSolidBackground( ConstrainedWindow::GetBackgroundColor())); } ConstrainedWindowFrameSimple::~ConstrainedWindowFrameSimple() { } void ConstrainedWindowFrameSimple::SetHeaderView(HeaderViews* header_views) { RemoveAllChildViews(true); header_views_.reset(header_views); AddChildView(header_views_->header); } HeaderViews* ConstrainedWindowFrameSimple::CreateDefaultHeaderView() { views::View* header_view = new views::View; views::GridLayout* grid_layout = new views::GridLayout(header_view); header_view->SetLayoutManager(grid_layout); views::ColumnSet* header_cs = grid_layout->AddColumnSet(0); header_cs->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0); // Title. header_cs->AddPaddingColumn(1, views::kUnrelatedControlHorizontalSpacing); header_cs->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0); // Close Button. // Header row. ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); grid_layout->StartRow(0, 0); views::Label* title_label = new views::Label(); title_label->SetHorizontalAlignment(views::Label::ALIGN_LEFT); title_label->SetFont(rb.GetFont(ConstrainedWindow::kTitleFontStyle)); title_label->SetEnabledColor(ConstrainedWindow::GetTextColor()); title_label->SetText(container_->widget_delegate()->GetWindowTitle()); grid_layout->AddView(title_label); views::Button* close_button = CreateCloseButton(); grid_layout->AddView(close_button); return new HeaderViews(header_view, title_label, close_button); } gfx::Rect ConstrainedWindowFrameSimple::GetBoundsForClientView() const { int horizontal_padding = ConstrainedWindow::kHorizontalPadding; int vertical_padding = ConstrainedWindow::kVerticalPadding; int row_padding = ConstrainedWindow::kRowPadding; gfx::Size header_size = header_views_->header ? header_views_->header->GetPreferredSize() : gfx::Size(); return gfx::Rect(horizontal_padding, vertical_padding + header_size.height() + row_padding, std::max(0, width() - 2 * horizontal_padding), std::max(0, (height() - 2 * vertical_padding - header_size.height() - row_padding))); } gfx::Rect ConstrainedWindowFrameSimple::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { int horizontal_padding = ConstrainedWindow::kHorizontalPadding; int vertical_padding = ConstrainedWindow::kVerticalPadding; int row_padding = ConstrainedWindow::kRowPadding; gfx::Size header_size = header_views_->header ? header_views_->header->GetPreferredSize() : gfx::Size(); int x = client_bounds.x() - horizontal_padding; int y = client_bounds.y() - vertical_padding - header_size.height() - row_padding; int width = client_bounds.width() + 2 * horizontal_padding; int height = client_bounds.height() + 2 * vertical_padding + header_size.height() + row_padding; return gfx::Rect(x, y, width, height); } int ConstrainedWindowFrameSimple::NonClientHitTest(const gfx::Point& point) { if (!bounds().Contains(point)) return HTNOWHERE; return HTCLIENT; } void ConstrainedWindowFrameSimple::GetWindowMask(const gfx::Size& size, gfx::Path* window_mask) { SkRect rect = {0, 0, size.width() - 1, size.height() - 1}; SkScalar radius = SkIntToScalar(ConstrainedWindow::kBorderRadius); SkScalar radii[8] = {radius, radius, radius, radius, radius, radius, radius, radius}; // NB: We're not using the addRoundRect uniform radius overload as it // mishandles the bottom corners on Windows window_mask->addRoundRect(rect, radii); } void ConstrainedWindowFrameSimple::ResetWindowControls() { } void ConstrainedWindowFrameSimple::UpdateWindowIcon() { } void ConstrainedWindowFrameSimple::UpdateWindowTitle() { if (!header_views_->title_label) return; string16 text = container_->widget_delegate()->GetWindowTitle(); header_views_->title_label->SetText(text); } gfx::Size ConstrainedWindowFrameSimple::GetPreferredSize() { return container_->non_client_view()->GetWindowBoundsForClientBounds( gfx::Rect(container_->client_view()->GetPreferredSize())).size(); } void ConstrainedWindowFrameSimple::ButtonPressed(views::Button* sender, const ui::Event& event) { if (header_views_->close_button && sender == header_views_->close_button) sender->GetWidget()->Close(); } views::ImageButton* ConstrainedWindowFrameSimple::CreateCloseButton() { ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); views::ImageButton* close_button = new views::ImageButton(this); close_button->SetImage(views::CustomButton::BS_NORMAL, rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X)); close_button->SetImage(views::CustomButton::BS_HOT, rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X_HOVER)); close_button->SetImage(views::CustomButton::BS_PUSHED, rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X_HOVER)); return close_button; } <commit_msg>Add workaround for window mask off-by-one bug<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/ui/views/constrained_window_frame_simple.h" #include "chrome/browser/ui/constrained_window.h" #include "chrome/browser/ui/views/constrained_window_views.h" #include "grit/ui_resources.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/google_chrome_strings.h" #include "grit/shared_resources.h" #include "grit/theme_resources.h" #include "ui/base/hit_test.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas.h" #include "ui/gfx/rect.h" #include "ui/gfx/path.h" #include "ui/views/background.h" #include "ui/views/controls/label.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/layout/layout_manager.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" namespace { typedef ConstrainedWindowFrameSimple::HeaderViews HeaderViews; // A layout manager that lays out the header view with proper padding, // and sized to the widget's client view. class HeaderLayout : public views::LayoutManager { public: explicit HeaderLayout(views::Widget* container) : container_(container) {} virtual ~HeaderLayout() {} // Overridden from LayoutManager virtual void Layout(views::View* host); virtual gfx::Size GetPreferredSize(views::View* host); private: views::Widget* container_; DISALLOW_COPY_AND_ASSIGN(HeaderLayout); }; void HeaderLayout::Layout(views::View* host) { if (!host->has_children()) return; int horizontal_padding = ConstrainedWindow::kHorizontalPadding; int vertical_padding = ConstrainedWindow::kVerticalPadding; int row_padding = ConstrainedWindow::kRowPadding; views::View* header = host->child_at(0); gfx::Size preferred_size = GetPreferredSize(host); int width = preferred_size.width() - 2 * horizontal_padding; int height = preferred_size.height() - vertical_padding - row_padding; header->SetBounds(horizontal_padding, vertical_padding, width, height); } gfx::Size HeaderLayout::GetPreferredSize(views::View* host) { int horizontal_padding = ConstrainedWindow::kHorizontalPadding; int vertical_padding = ConstrainedWindow::kVerticalPadding; int row_padding = ConstrainedWindow::kRowPadding; views::View* header = host->child_at(0); views::View* client_view = container_->client_view(); gfx::Size header_size = header ? header->GetPreferredSize() : gfx::Size(); gfx::Size client_size = client_view ? client_view->GetPreferredSize() : gfx::Size(); int width = std::max(client_size.width(), header_size.width()) + 2 * horizontal_padding; int height = vertical_padding + header_size.height() + row_padding; return gfx::Size(width, height); } } // namespace ConstrainedWindowFrameSimple::HeaderViews::HeaderViews( views::View* header, views::Label* title_label, views::Button* close_button) : header(header), title_label(title_label), close_button(close_button) { DCHECK(header); } ConstrainedWindowFrameSimple::ConstrainedWindowFrameSimple( ConstrainedWindowViews* container) : container_(container) { container_->set_frame_type(views::Widget::FRAME_TYPE_FORCE_CUSTOM); layout_ = new HeaderLayout(container_); SetLayoutManager(layout_); SetHeaderView(CreateDefaultHeaderView()); set_background(views::Background::CreateSolidBackground( ConstrainedWindow::GetBackgroundColor())); } ConstrainedWindowFrameSimple::~ConstrainedWindowFrameSimple() { } void ConstrainedWindowFrameSimple::SetHeaderView(HeaderViews* header_views) { RemoveAllChildViews(true); header_views_.reset(header_views); AddChildView(header_views_->header); } HeaderViews* ConstrainedWindowFrameSimple::CreateDefaultHeaderView() { views::View* header_view = new views::View; views::GridLayout* grid_layout = new views::GridLayout(header_view); header_view->SetLayoutManager(grid_layout); views::ColumnSet* header_cs = grid_layout->AddColumnSet(0); header_cs->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0); // Title. header_cs->AddPaddingColumn(1, views::kUnrelatedControlHorizontalSpacing); header_cs->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0); // Close Button. // Header row. ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); grid_layout->StartRow(0, 0); views::Label* title_label = new views::Label(); title_label->SetHorizontalAlignment(views::Label::ALIGN_LEFT); title_label->SetFont(rb.GetFont(ConstrainedWindow::kTitleFontStyle)); title_label->SetEnabledColor(ConstrainedWindow::GetTextColor()); title_label->SetText(container_->widget_delegate()->GetWindowTitle()); grid_layout->AddView(title_label); views::Button* close_button = CreateCloseButton(); grid_layout->AddView(close_button); return new HeaderViews(header_view, title_label, close_button); } gfx::Rect ConstrainedWindowFrameSimple::GetBoundsForClientView() const { int horizontal_padding = ConstrainedWindow::kHorizontalPadding; int vertical_padding = ConstrainedWindow::kVerticalPadding; int row_padding = ConstrainedWindow::kRowPadding; gfx::Size header_size = header_views_->header ? header_views_->header->GetPreferredSize() : gfx::Size(); return gfx::Rect(horizontal_padding, vertical_padding + header_size.height() + row_padding, std::max(0, width() - 2 * horizontal_padding), std::max(0, (height() - 2 * vertical_padding - header_size.height() - row_padding))); } gfx::Rect ConstrainedWindowFrameSimple::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { int horizontal_padding = ConstrainedWindow::kHorizontalPadding; int vertical_padding = ConstrainedWindow::kVerticalPadding; int row_padding = ConstrainedWindow::kRowPadding; gfx::Size header_size = header_views_->header ? header_views_->header->GetPreferredSize() : gfx::Size(); int x = client_bounds.x() - horizontal_padding; int y = client_bounds.y() - vertical_padding - header_size.height() - row_padding; int width = client_bounds.width() + 2 * horizontal_padding; int height = client_bounds.height() + 2 * vertical_padding + header_size.height() + row_padding; return gfx::Rect(x, y, width, height); } int ConstrainedWindowFrameSimple::NonClientHitTest(const gfx::Point& point) { if (!bounds().Contains(point)) return HTNOWHERE; return HTCLIENT; } void ConstrainedWindowFrameSimple::GetWindowMask(const gfx::Size& size, gfx::Path* window_mask) { #if defined(USE_AURA) SkRect rect = {0, 0, size.width() - 1, size.height() - 1}; #else // There appears to be a bug in the window mask calculation on Windows // which causes the width, but not the height, to be off by one. SkRect rect = {0, 0, size.width(), size.height() - 1}; #endif SkScalar radius = SkIntToScalar(ConstrainedWindow::kBorderRadius); SkScalar radii[8] = {radius, radius, radius, radius, radius, radius, radius, radius}; // NB: We're not using the addRoundRect uniform radius overload as it // mishandles the bottom corners on Windows window_mask->addRoundRect(rect, radii); } void ConstrainedWindowFrameSimple::ResetWindowControls() { } void ConstrainedWindowFrameSimple::UpdateWindowIcon() { } void ConstrainedWindowFrameSimple::UpdateWindowTitle() { if (!header_views_->title_label) return; string16 text = container_->widget_delegate()->GetWindowTitle(); header_views_->title_label->SetText(text); } gfx::Size ConstrainedWindowFrameSimple::GetPreferredSize() { return container_->non_client_view()->GetWindowBoundsForClientBounds( gfx::Rect(container_->client_view()->GetPreferredSize())).size(); } void ConstrainedWindowFrameSimple::ButtonPressed(views::Button* sender, const ui::Event& event) { if (header_views_->close_button && sender == header_views_->close_button) sender->GetWidget()->Close(); } views::ImageButton* ConstrainedWindowFrameSimple::CreateCloseButton() { ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); views::ImageButton* close_button = new views::ImageButton(this); close_button->SetImage(views::CustomButton::BS_NORMAL, rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X)); close_button->SetImage(views::CustomButton::BS_HOT, rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X_HOVER)); close_button->SetImage(views::CustomButton::BS_PUSHED, rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X_HOVER)); return close_button; } <|endoftext|>
<commit_before>#include "EditorApp.h" #include "ECS/Component.h" #include "Engine/Clock.h" #include "Components/Transform.h" #include "ECS/Entity.h" #include <string> #include "Engine/Input.h" #include "Components/Camera.h" #include "Components/Physics/Rigidbody.h" #include "Components/Graphics/Model.h" #include "Components/Lighting/Light.h" #include <memory> #include "Engine/World.h" #include "Path.h" #include "Cores/EditorCore.h" #include "Engine/Engine.h" #include "Havana.h" #include "Cores/SceneGraph.h" #include "Events/SceneEvents.h" #include "RenderCommands.h" #include "Events/Event.h" #include <SimpleMath.h> #include "Math/Matirx4.h" #include "Math/Frustrum.h" EditorApp::EditorApp() { std::vector<TypeId> events; events.push_back(NewSceneEvent::GetEventId()); events.push_back(SceneLoadedEvent::GetEventId()); EventManager::GetInstance().RegisterReceiver(this, events); } EditorApp::~EditorApp() { } void EditorApp::OnStart() { } void EditorApp::OnUpdate(float DeltaTime) { Editor->NewFrame([this]() { StartGame(); m_isGamePaused = false; m_isGameRunning = true; } , [this]() { m_isGamePaused = true; } , [this]() { StopGame(); m_isGameRunning = false; m_isGamePaused = false; Editor->ClearSelection(); //GetEngine().LoadScene("Assets/Alley.lvl"); }); EditorSceneManager->Update(DeltaTime, GetEngine().SceneNodes->GetRootTransform()); Editor->UpdateWorld(GetEngine().GetWorld().lock().get(), GetEngine().SceneNodes->GetRootTransform(), EditorSceneManager->GetEntities()); UpdateCameras(); } void EditorApp::UpdateCameras() { Vector2 MainOutputSize = Editor->GetGameOutputSize(); if (!Camera::CurrentCamera) { Camera::CurrentCamera = Camera::EditorCamera; } Moonlight::CameraData EditorCamera; Camera::CurrentCamera->OutputSize = MainOutputSize; EditorCamera.Position = EditorSceneManager->GetEditorCameraTransform()->GetWorldPosition(); EditorCamera.Front = EditorSceneManager->GetEditorCameraTransform()->Front(); EditorCamera.Up = Vector3::Up; EditorCamera.OutputSize = Editor->WorldViewRenderSize; EditorCamera.FOV = Camera::EditorCamera->GetFOV(); EditorCamera.Near = Camera::EditorCamera->Near; EditorCamera.Far = Camera::EditorCamera->Far; EditorCamera.Skybox = Camera::CurrentCamera->Skybox; EditorCamera.ClearColor = Camera::CurrentCamera->ClearColor; EditorCamera.ClearType = Camera::CurrentCamera->ClearType; EditorCamera.Projection = Camera::EditorCamera->Projection; EditorCamera.OrthographicSize = Camera::EditorCamera->OrthographicSize; EditorCamera.CameraFrustum = Camera::EditorCamera->CameraFrustum; GetEngine().EditorCamera = EditorCamera; } void EditorApp::OnEnd() { //destroy(mGame); } void EditorApp::OnInitialize() { if (!Editor) { InitialLevel = GetEngine().GetConfig().GetValue("CurrentScene"); Editor = std::make_unique<Havana>(&GetEngine(), this, &GetEngine().GetRenderer()); EditorSceneManager = new EditorCore(Editor.get()); NewSceneEvent evt; evt.Fire(); GetEngine().GetWorld().lock()->AddCore<EditorCore>(*EditorSceneManager); GetEngine().LoadScene(InitialLevel); } else { GetEngine().GetWorld().lock()->AddCore<EditorCore>(*EditorSceneManager); } } void EditorApp::PostRender() { Editor->Render(GetEngine().EditorCamera); } void EditorApp::StartGame() { if (!m_isGameRunning) { GetEngine().GetWorld().lock()->Start(); m_isGameRunning = true; } } void EditorApp::StopGame() { if (m_isGameRunning) { if (GetEngine().GetWorld().lock()) { GetEngine().GetWorld().lock()->Destroy(); } NewSceneEvent evt; evt.Fire(); GetEngine().LoadScene(InitialLevel); GetEngine().GetWorld().lock()->Stop(); m_isGameRunning = false; } } const bool EditorApp::IsGameRunning() const { return m_isGameRunning; } const bool EditorApp::IsGamePaused() const { return m_isGamePaused; } bool EditorApp::OnEvent(const BaseEvent& evt) { if (evt.GetEventId() == NewSceneEvent::GetEventId()) { const NewSceneEvent& test = static_cast<const NewSceneEvent&>(evt); GetEngine().LoadScene(""); GetEngine().InitGame(); GetEngine().GetWorld().lock()->Simulate(); } else if (evt.GetEventId() == SceneLoadedEvent::GetEventId()) { const SceneLoadedEvent& test = static_cast<const SceneLoadedEvent&>(evt); Editor->SetWindowTitle("Havana - " + test.LoadedScene->FilePath.LocalPath); if (m_isGameRunning) { GetEngine().GetWorld().lock()->Start(); } } return false; }<commit_msg>🛑 Fixing a bug when stopping the game and starting game systems<commit_after>#include "EditorApp.h" #include "ECS/Component.h" #include "Engine/Clock.h" #include "Components/Transform.h" #include "ECS/Entity.h" #include <string> #include "Engine/Input.h" #include "Components/Camera.h" #include "Components/Physics/Rigidbody.h" #include "Components/Graphics/Model.h" #include "Components/Lighting/Light.h" #include <memory> #include "Engine/World.h" #include "Path.h" #include "Cores/EditorCore.h" #include "Engine/Engine.h" #include "Havana.h" #include "Cores/SceneGraph.h" #include "Events/SceneEvents.h" #include "RenderCommands.h" #include "Events/Event.h" #include <SimpleMath.h> #include "Math/Matirx4.h" #include "Math/Frustrum.h" EditorApp::EditorApp() { std::vector<TypeId> events; events.push_back(NewSceneEvent::GetEventId()); events.push_back(SceneLoadedEvent::GetEventId()); EventManager::GetInstance().RegisterReceiver(this, events); } EditorApp::~EditorApp() { } void EditorApp::OnStart() { } void EditorApp::OnUpdate(float DeltaTime) { Editor->NewFrame([this]() { StartGame(); m_isGamePaused = false; m_isGameRunning = true; } , [this]() { m_isGamePaused = true; } , [this]() { m_isGamePaused = false; Editor->ClearSelection(); StopGame(); //GetEngine().LoadScene("Assets/Alley.lvl"); }); EditorSceneManager->Update(DeltaTime, GetEngine().SceneNodes->GetRootTransform()); Editor->UpdateWorld(GetEngine().GetWorld().lock().get(), GetEngine().SceneNodes->GetRootTransform(), EditorSceneManager->GetEntities()); UpdateCameras(); } void EditorApp::UpdateCameras() { Vector2 MainOutputSize = Editor->GetGameOutputSize(); if (!Camera::CurrentCamera) { Camera::CurrentCamera = Camera::EditorCamera; } Moonlight::CameraData EditorCamera; Camera::CurrentCamera->OutputSize = MainOutputSize; EditorCamera.Position = EditorSceneManager->GetEditorCameraTransform()->GetWorldPosition(); EditorCamera.Front = EditorSceneManager->GetEditorCameraTransform()->Front(); EditorCamera.Up = Vector3::Up; EditorCamera.OutputSize = Editor->WorldViewRenderSize; EditorCamera.FOV = Camera::EditorCamera->GetFOV(); EditorCamera.Near = Camera::EditorCamera->Near; EditorCamera.Far = Camera::EditorCamera->Far; EditorCamera.Skybox = Camera::CurrentCamera->Skybox; EditorCamera.ClearColor = Camera::CurrentCamera->ClearColor; EditorCamera.ClearType = Camera::CurrentCamera->ClearType; EditorCamera.Projection = Camera::EditorCamera->Projection; EditorCamera.OrthographicSize = Camera::EditorCamera->OrthographicSize; EditorCamera.CameraFrustum = Camera::EditorCamera->CameraFrustum; GetEngine().EditorCamera = EditorCamera; } void EditorApp::OnEnd() { //destroy(mGame); } void EditorApp::OnInitialize() { if (!Editor) { InitialLevel = GetEngine().GetConfig().GetValue("CurrentScene"); Editor = std::make_unique<Havana>(&GetEngine(), this, &GetEngine().GetRenderer()); EditorSceneManager = new EditorCore(Editor.get()); NewSceneEvent evt; evt.Fire(); GetEngine().GetWorld().lock()->AddCore<EditorCore>(*EditorSceneManager); GetEngine().LoadScene(InitialLevel); } else { GetEngine().GetWorld().lock()->AddCore<EditorCore>(*EditorSceneManager); } } void EditorApp::PostRender() { Editor->Render(GetEngine().EditorCamera); } void EditorApp::StartGame() { if (!m_isGameRunning) { GetEngine().GetWorld().lock()->Start(); m_isGameRunning = true; } } void EditorApp::StopGame() { if (m_isGameRunning) { if (GetEngine().GetWorld().lock()) { GetEngine().GetWorld().lock()->Destroy(); } m_isGameRunning = false; NewSceneEvent evt; evt.Fire(); GetEngine().LoadScene(InitialLevel); GetEngine().GetWorld().lock()->Stop(); } } const bool EditorApp::IsGameRunning() const { return m_isGameRunning; } const bool EditorApp::IsGamePaused() const { return m_isGamePaused; } bool EditorApp::OnEvent(const BaseEvent& evt) { if (evt.GetEventId() == NewSceneEvent::GetEventId()) { const NewSceneEvent& test = static_cast<const NewSceneEvent&>(evt); GetEngine().LoadScene(""); GetEngine().InitGame(); GetEngine().GetWorld().lock()->Simulate(); } else if (evt.GetEventId() == SceneLoadedEvent::GetEventId()) { const SceneLoadedEvent& test = static_cast<const SceneLoadedEvent&>(evt); Editor->SetWindowTitle("Havana - " + test.LoadedScene->FilePath.LocalPath); if (m_isGameRunning) { GetEngine().GetWorld().lock()->Start(); } } return false; }<|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "sortedtimelinemodel.h" namespace QmlProfiler { /*! \class QmlProfiler::SortedTimelineModel \brief The SortedTimelineModel class provides a sorted model for timeline data. The SortedTimelineModel lets you keep range data sorted by both start and end times, so that visible ranges can easily be computed. The only precondition for that to work is that the ranges must be perfectly nested. A "parent" range of a range R is defined as a range for which the start time is smaller than R's start time and the end time is greater than R's end time. A set of ranges is perfectly nested if all parent ranges of any given range have a common parent range. Mind that you can always make that happen by defining a range that spans the whole available time span. That, however, will make any code that uses firstStartTime() and lastEndTime() for selecting subsets of the model always select all of it. \note Indices returned from the various methods are only valid until a new range is inserted before them. Inserting a new range before a given index moves the range pointed to by the index by one. Incrementing the index by one will make it point to the item again. */ /*! \fn SortedTimelineModel::clear() Clears the ranges and their end times. */ void SortedTimelineModel::clear() { ranges.clear(); endTimes.clear(); } /*! \fn int SortedTimelineModel::count() const Returns the number of ranges in the model. */ /*! \fn qint64 SortedTimelineModel::firstStartTime() const Returns the begin of the first range in the model. */ /*! \fn qint64 SortedTimelineModel::lastEndTime() const Returns the end of the last range in the model. */ /*! \fn const SortedTimelineModel::Range &SortedTimelineModel::range(int index) const Returns the range data at the specified index. */ /*! \fn int SortedTimelineModel::insert(qint64 startTime, qint64 duration) Inserts a range at the given time position and returns its index. */ /*! \fn int SortedTimelineModel::insertStart(qint64 startTime, const Data &item) Inserts the given data as range start at the given time position and returns its index. The range end is not set. */ /*! \fn int SortedTimelineModel::insertEnd(int index, qint64 duration) Adds a range end for the given start index. */ /*! \fn int SortedTimelineModel::firstIndexNoParents(qint64 startTime) const Looks up the first range with an end time greater than the given time and returns its index. If no such range is found, it returns -1. */ /*! \fn int SortedTimelineModel::firstIndex(qint64 startTime) const Looks up the first range with an end time greater than the given time and returns its parent's index. If no such range is found, it returns -1. If there is no parent, it returns the found range's index. The parent of a range is the range with the lowest start time that completely covers the child range. "Completely covers" means: parent.startTime <= child.startTime && parent.endTime >= child.endTime */ /*! \fn int SortedTimelineModel::lastIndex(qint64 endTime) const Looks up the last range with a start time smaller than the given time and returns its index. If no such range is found, it returns -1. */ /*! \fn void SortedTimelineModel::computeNesting() Compute all ranges' parents. \sa findFirstIndex */ void SortedTimelineModel::computeNesting() { QLinkedList<int> parents; for (int range = 0; range != count(); ++range) { Range &current = ranges[range]; for (QLinkedList<int>::iterator parentIt = parents.begin();;) { Range &parent = ranges[*parentIt]; qint64 parentEnd = parent.start + parent.duration; if (parentEnd < current.start) { if (parent.start == current.start) { if (parent.parent == -1) { parent.parent = range; } else { Range &ancestor = ranges[parent.parent]; if (ancestor.start == current.start && ancestor.duration < current.duration) parent.parent = range; } // Just switch the old parent range for the new, larger one *parentIt = range; break; } else { parentIt = parents.erase(parentIt); } } else if (parentEnd >= current.start + current.duration) { // no need to insert current.parent = *parentIt; break; } else { ++parentIt; } if (parentIt == parents.end()) { parents.append(range); break; } } } } } <commit_msg>QmlProfiler: Fix invalid list access when nesting timeline events<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "sortedtimelinemodel.h" namespace QmlProfiler { /*! \class QmlProfiler::SortedTimelineModel \brief The SortedTimelineModel class provides a sorted model for timeline data. The SortedTimelineModel lets you keep range data sorted by both start and end times, so that visible ranges can easily be computed. The only precondition for that to work is that the ranges must be perfectly nested. A "parent" range of a range R is defined as a range for which the start time is smaller than R's start time and the end time is greater than R's end time. A set of ranges is perfectly nested if all parent ranges of any given range have a common parent range. Mind that you can always make that happen by defining a range that spans the whole available time span. That, however, will make any code that uses firstStartTime() and lastEndTime() for selecting subsets of the model always select all of it. \note Indices returned from the various methods are only valid until a new range is inserted before them. Inserting a new range before a given index moves the range pointed to by the index by one. Incrementing the index by one will make it point to the item again. */ /*! \fn SortedTimelineModel::clear() Clears the ranges and their end times. */ void SortedTimelineModel::clear() { ranges.clear(); endTimes.clear(); } /*! \fn int SortedTimelineModel::count() const Returns the number of ranges in the model. */ /*! \fn qint64 SortedTimelineModel::firstStartTime() const Returns the begin of the first range in the model. */ /*! \fn qint64 SortedTimelineModel::lastEndTime() const Returns the end of the last range in the model. */ /*! \fn const SortedTimelineModel::Range &SortedTimelineModel::range(int index) const Returns the range data at the specified index. */ /*! \fn int SortedTimelineModel::insert(qint64 startTime, qint64 duration) Inserts a range at the given time position and returns its index. */ /*! \fn int SortedTimelineModel::insertStart(qint64 startTime, const Data &item) Inserts the given data as range start at the given time position and returns its index. The range end is not set. */ /*! \fn int SortedTimelineModel::insertEnd(int index, qint64 duration) Adds a range end for the given start index. */ /*! \fn int SortedTimelineModel::firstIndexNoParents(qint64 startTime) const Looks up the first range with an end time greater than the given time and returns its index. If no such range is found, it returns -1. */ /*! \fn int SortedTimelineModel::firstIndex(qint64 startTime) const Looks up the first range with an end time greater than the given time and returns its parent's index. If no such range is found, it returns -1. If there is no parent, it returns the found range's index. The parent of a range is the range with the lowest start time that completely covers the child range. "Completely covers" means: parent.startTime <= child.startTime && parent.endTime >= child.endTime */ /*! \fn int SortedTimelineModel::lastIndex(qint64 endTime) const Looks up the last range with a start time smaller than the given time and returns its index. If no such range is found, it returns -1. */ /*! \fn void SortedTimelineModel::computeNesting() Compute all ranges' parents. \sa findFirstIndex */ void SortedTimelineModel::computeNesting() { QLinkedList<int> parents; for (int range = 0; range != count(); ++range) { Range &current = ranges[range]; for (QLinkedList<int>::iterator parentIt = parents.begin();;) { if (parentIt == parents.end()) { parents.append(range); break; } Range &parent = ranges[*parentIt]; qint64 parentEnd = parent.start + parent.duration; if (parentEnd < current.start) { if (parent.start == current.start) { if (parent.parent == -1) { parent.parent = range; } else { Range &ancestor = ranges[parent.parent]; if (ancestor.start == current.start && ancestor.duration < current.duration) parent.parent = range; } // Just switch the old parent range for the new, larger one *parentIt = range; break; } else { parentIt = parents.erase(parentIt); } } else if (parentEnd >= current.start + current.duration) { // no need to insert current.parent = *parentIt; break; } else { ++parentIt; } } } } } <|endoftext|>
<commit_before>/* * esteid-browser-plugin - a browser plugin for Estonian EID card * * Copyright (C) 2010 Estonian Informatics Centre * Copyright (C) 2010 Smartlink OÜ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "pininputdialog.h" #include "basedialog.h" #include "utf8_tools.h" #include <windows.h> #include <commctrl.h> #include "Win/pininputdialog_res.h" #define BUF_SIZE 100 PinInputDialog::PinInputDialog(HINSTANCE hInst) : BaseDialog(hInst), m_retry(false), m_triesLeft(0), m_minPinLength(5) { } PinInputDialog::~PinInputDialog() { } void PinInputDialog::showPinBlocked(HWND hParent) { MessageBox(hParent, L"PIN2 blocked.\nPlease run ID card Utility to unlock the PIN.", L"Error", MB_OK | MB_ICONHAND); } void PinInputDialog::setSubject(const std::string& subject) { m_subject = FB::utf8_to_wstring(subject) + L" (PIN2)"; } void PinInputDialog::setRetry(bool retry) { m_retry = retry; } void PinInputDialog::setTries(int tries) { m_triesLeft = tries; } std::string PinInputDialog::getPinInternal() { char *buf = new char[BUF_SIZE]; GetDlgItemTextA(m_hWnd, IDC_PINEDIT, buf, BUF_SIZE); std::string ret(buf); delete[] buf; return ret; } std::string PinInputDialog::getPin() { return m_pin; } void PinInputDialog::clearPin() { m_pin = ""; } HICON PinInputDialog::getCreduiIcon() { HMODULE module = LoadLibraryExA("credui.dll", NULL, LOAD_LIBRARY_AS_DATAFILE); if (!module) return NULL; return LoadIcon(module, MAKEINTRESOURCE(1201)); } HICON PinInputDialog::getIcon() { HICON icon = getCreduiIcon(); if (!icon) // fall back to embedded icon icon = LoadIcon(m_hInst, MAKEINTRESOURCE(IDI_PINICON)); return icon; } void PinInputDialog::setFontSize(HWND hText, int fontSize) { HFONT hOldFont = (HFONT)SendMessage(hText, WM_GETFONT, 0, 0); HDC hDC = GetDC(hText); LOGFONT lf; GetObject(hOldFont, sizeof(LOGFONT), &lf); lf.lfHeight = -MulDiv(fontSize, GetDeviceCaps(hDC, LOGPIXELSY), 72); HFONT hNewFont = CreateFontIndirect(&lf); SendMessage(hText, WM_SETFONT, (WPARAM)hNewFont, MAKELPARAM(TRUE, 0)); ReleaseDC(hText, hDC); } // calculate control's width needed to fit text int PinInputDialog::preferredWidth(HWND hWnd, const std::wstring& text) { HDC hdc; SIZE size; hdc = GetDC(hWnd); GetTextExtentPoint32(hdc, text.c_str(), (int)text.size(), &size); ReleaseDC(hWnd, hdc); return size.cx; } // get control's current width int PinInputDialog::currentWidth(HWND hWnd) { RECT rect; POINT ptDiff; GetClientRect(hWnd, &rect); ptDiff.x = (rect.right - rect.left); ptDiff.y = (rect.bottom - rect.top); return ptDiff.x; } void PinInputDialog::resizeWindow(HWND hWnd, int width, int height) { RECT rect; POINT ptDiff; GetWindowRect(hWnd, &rect); ptDiff.x = (rect.right - rect.left); ptDiff.y = (rect.bottom - rect.top); MoveWindow(hWnd, rect.left, rect.top, ptDiff.x + width, ptDiff.y + height, TRUE); } void PinInputDialog::resizeControl(HWND hWnd, HWND hControl, int width, int height) { RECT rect; POINT point; GetWindowRect(hControl, &rect); point.x = rect.left; point.y = rect.top; ScreenToClient(hWnd, &point); GetClientRect(hControl, &rect); MoveWindow(hControl, point.x, point.y, (rect.right - rect.left) + width, (rect.bottom - rect.top) + height, TRUE); } void PinInputDialog::moveControl(HWND hWnd, HWND hControl, int dx, int dy) { RECT rect; POINT point; GetWindowRect(hControl, &rect); point.x = rect.left; point.y = rect.top; ScreenToClient(hWnd, &point); GetClientRect(hControl, &rect); MoveWindow(hControl, point.x + dx, point.y + dy, rect.right - rect.left, rect.bottom - rect.top, TRUE); } void PinInputDialog::showWrongPin(HWND hParent, int tries) { static const std::wstring title = L"Wrong PIN!"; std::wstringstream out; out << L"Tries left: " << m_triesLeft; std::wstring text = out.str(); // mingw doesn't have EDITBALLOONTIP #ifdef EM_SHOWBALLOONTIP EDITBALLOONTIP ebt = {0}; ebt.cbStruct = sizeof(EDITBALLOONTIP); ebt.pszTitle = const_cast<wchar_t *>(title.c_str()); ebt.pszText = const_cast<wchar_t *>(text.c_str()); ebt.ttiIcon = TTI_ERROR; if (!SendMessage(hParent, EM_SHOWBALLOONTIP, 0, (LPARAM)&ebt)) { #endif MessageBox(hParent, const_cast<wchar_t *>((title + L"\n" + text).c_str()), L"Warning", MB_OK | MB_ICONHAND); #ifdef EM_SHOWBALLOONTIP } #endif } LRESULT PinInputDialog::on_initdialog(WPARAM wParam) { HWND hLabel = GetDlgItem(m_hWnd, IDC_LABEL); HWND hPinedit = GetDlgItem(m_hWnd, IDC_PINEDIT); SetDlgItemText(m_hWnd, IDC_LABEL, const_cast<wchar_t *>(m_subject.c_str())); setFontSize(hLabel, 10); // set icon HICON icon = getIcon(); SendDlgItemMessage(m_hWnd, IDI_PINICON, STM_SETIMAGE, IMAGE_ICON, (LPARAM)icon); // set maximum pin length SendDlgItemMessage(m_hWnd, IDC_PINEDIT, EM_SETLIMITTEXT, 12, 0); // resize dialog to fit long names if (currentWidth(hLabel) < preferredWidth(hLabel, m_subject)) { int dx = preferredWidth(hLabel, m_subject) - currentWidth(hLabel); // for reasons unknown, the width of IDC_LABEL and IDC_PINEDIT differ a little bit int dx2 = preferredWidth(hLabel, m_subject) - currentWidth(hPinedit); resizeWindow(m_hWnd, dx, 0); resizeControl(m_hWnd, hLabel, dx, 0); resizeControl(m_hWnd, hPinedit, dx2, 0); moveControl(m_hWnd, GetDlgItem(m_hWnd, IDOK), dx, 0); moveControl(m_hWnd, GetDlgItem(m_hWnd, IDCANCEL), dx, 0); } if (m_retry) showWrongPin(hPinedit, m_triesLeft); if (GetDlgCtrlID((HWND) wParam) != IDC_PINEDIT) { SetFocus(hPinedit); return FALSE; } return TRUE; } LRESULT PinInputDialog::on_command(WPARAM wParam, LPARAM lParam) { switch (LOWORD(wParam)) { case IDC_PINEDIT: if (HIWORD(wParam) == EN_CHANGE) { std::string pin = getPinInternal(); if (pin.size() >= m_minPinLength) EnableWindow(GetDlgItem(m_hWnd, IDOK), TRUE); else EnableWindow(GetDlgItem(m_hWnd, IDOK), FALSE); } break; case IDOK: m_pin = getPinInternal(); SetDlgItemTextA(m_hWnd, IDC_PINEDIT, ""); if (m_modalDialog) { EndDialog(m_hWnd, wParam); } else { DestroyWindow(m_hWnd); releaseIEModalLock(); signalResponse(RESPONSE_OK); } return TRUE; break; case IDCANCEL: m_pin = ""; SetDlgItemTextA(m_hWnd, IDC_PINEDIT, ""); if (m_modalDialog) { EndDialog(m_hWnd, wParam); } else { DestroyWindow(m_hWnd); releaseIEModalLock(); signalResponse(RESPONSE_CANCEL); } return TRUE; break; } return FALSE; } bool PinInputDialog::doDialog(HWND hParent) { return BaseDialog::doDialog(IDD_PINDIALOG, hParent); } int PinInputDialog::doModalDialog(HWND hParent) { int rv = BaseDialog::doModalDialog(IDD_PINDIALOG, hParent); if (rv == IDOK) return RESPONSE_OK; else return RESPONSE_CANCEL; } <commit_msg>esteid-browser-plugin: Use boost::lexical_cast for readability<commit_after>/* * esteid-browser-plugin - a browser plugin for Estonian EID card * * Copyright (C) 2010 Estonian Informatics Centre * Copyright (C) 2010 Smartlink OÜ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "pininputdialog.h" #include "basedialog.h" #include "utf8_tools.h" #include <boost/lexical_cast.hpp> #include <windows.h> #include <commctrl.h> #include "Win/pininputdialog_res.h" #define BUF_SIZE 100 PinInputDialog::PinInputDialog(HINSTANCE hInst) : BaseDialog(hInst), m_retry(false), m_triesLeft(0), m_minPinLength(5) { } PinInputDialog::~PinInputDialog() { } void PinInputDialog::showPinBlocked(HWND hParent) { MessageBox(hParent, L"PIN2 blocked.\nPlease run ID card Utility to unlock the PIN.", L"Error", MB_OK | MB_ICONHAND); } void PinInputDialog::setSubject(const std::string& subject) { m_subject = FB::utf8_to_wstring(subject) + L" (PIN2)"; } void PinInputDialog::setRetry(bool retry) { m_retry = retry; } void PinInputDialog::setTries(int tries) { m_triesLeft = tries; } std::string PinInputDialog::getPinInternal() { char *buf = new char[BUF_SIZE]; GetDlgItemTextA(m_hWnd, IDC_PINEDIT, buf, BUF_SIZE); std::string ret(buf); delete[] buf; return ret; } std::string PinInputDialog::getPin() { return m_pin; } void PinInputDialog::clearPin() { m_pin = ""; } HICON PinInputDialog::getCreduiIcon() { HMODULE module = LoadLibraryExA("credui.dll", NULL, LOAD_LIBRARY_AS_DATAFILE); if (!module) return NULL; return LoadIcon(module, MAKEINTRESOURCE(1201)); } HICON PinInputDialog::getIcon() { HICON icon = getCreduiIcon(); if (!icon) // fall back to embedded icon icon = LoadIcon(m_hInst, MAKEINTRESOURCE(IDI_PINICON)); return icon; } void PinInputDialog::setFontSize(HWND hText, int fontSize) { HFONT hOldFont = (HFONT)SendMessage(hText, WM_GETFONT, 0, 0); HDC hDC = GetDC(hText); LOGFONT lf; GetObject(hOldFont, sizeof(LOGFONT), &lf); lf.lfHeight = -MulDiv(fontSize, GetDeviceCaps(hDC, LOGPIXELSY), 72); HFONT hNewFont = CreateFontIndirect(&lf); SendMessage(hText, WM_SETFONT, (WPARAM)hNewFont, MAKELPARAM(TRUE, 0)); ReleaseDC(hText, hDC); } // calculate control's width needed to fit text int PinInputDialog::preferredWidth(HWND hWnd, const std::wstring& text) { HDC hdc; SIZE size; hdc = GetDC(hWnd); GetTextExtentPoint32(hdc, text.c_str(), (int)text.size(), &size); ReleaseDC(hWnd, hdc); return size.cx; } // get control's current width int PinInputDialog::currentWidth(HWND hWnd) { RECT rect; POINT ptDiff; GetClientRect(hWnd, &rect); ptDiff.x = (rect.right - rect.left); ptDiff.y = (rect.bottom - rect.top); return ptDiff.x; } void PinInputDialog::resizeWindow(HWND hWnd, int width, int height) { RECT rect; POINT ptDiff; GetWindowRect(hWnd, &rect); ptDiff.x = (rect.right - rect.left); ptDiff.y = (rect.bottom - rect.top); MoveWindow(hWnd, rect.left, rect.top, ptDiff.x + width, ptDiff.y + height, TRUE); } void PinInputDialog::resizeControl(HWND hWnd, HWND hControl, int width, int height) { RECT rect; POINT point; GetWindowRect(hControl, &rect); point.x = rect.left; point.y = rect.top; ScreenToClient(hWnd, &point); GetClientRect(hControl, &rect); MoveWindow(hControl, point.x, point.y, (rect.right - rect.left) + width, (rect.bottom - rect.top) + height, TRUE); } void PinInputDialog::moveControl(HWND hWnd, HWND hControl, int dx, int dy) { RECT rect; POINT point; GetWindowRect(hControl, &rect); point.x = rect.left; point.y = rect.top; ScreenToClient(hWnd, &point); GetClientRect(hControl, &rect); MoveWindow(hControl, point.x + dx, point.y + dy, rect.right - rect.left, rect.bottom - rect.top, TRUE); } void PinInputDialog::showWrongPin(HWND hParent, int tries) { static const std::wstring title = L"Wrong PIN!"; std::wstring text(L"Tries left: " + boost::lexical_cast<std::wstring>(tries)); // mingw doesn't have EDITBALLOONTIP #ifdef EM_SHOWBALLOONTIP EDITBALLOONTIP ebt = {0}; ebt.cbStruct = sizeof(EDITBALLOONTIP); ebt.pszTitle = const_cast<wchar_t *>(title.c_str()); ebt.pszText = const_cast<wchar_t *>(text.c_str()); ebt.ttiIcon = TTI_ERROR; if (!SendMessage(hParent, EM_SHOWBALLOONTIP, 0, (LPARAM)&ebt)) { #endif MessageBox(hParent, const_cast<wchar_t *>((title + L"\n" + text).c_str()), L"Warning", MB_OK | MB_ICONHAND); #ifdef EM_SHOWBALLOONTIP } #endif } LRESULT PinInputDialog::on_initdialog(WPARAM wParam) { HWND hLabel = GetDlgItem(m_hWnd, IDC_LABEL); HWND hPinedit = GetDlgItem(m_hWnd, IDC_PINEDIT); SetDlgItemText(m_hWnd, IDC_LABEL, const_cast<wchar_t *>(m_subject.c_str())); setFontSize(hLabel, 10); // set icon HICON icon = getIcon(); SendDlgItemMessage(m_hWnd, IDI_PINICON, STM_SETIMAGE, IMAGE_ICON, (LPARAM)icon); // set maximum pin length SendDlgItemMessage(m_hWnd, IDC_PINEDIT, EM_SETLIMITTEXT, 12, 0); // resize dialog to fit long names if (currentWidth(hLabel) < preferredWidth(hLabel, m_subject)) { int dx = preferredWidth(hLabel, m_subject) - currentWidth(hLabel); // for reasons unknown, the width of IDC_LABEL and IDC_PINEDIT differ a little bit int dx2 = preferredWidth(hLabel, m_subject) - currentWidth(hPinedit); resizeWindow(m_hWnd, dx, 0); resizeControl(m_hWnd, hLabel, dx, 0); resizeControl(m_hWnd, hPinedit, dx2, 0); moveControl(m_hWnd, GetDlgItem(m_hWnd, IDOK), dx, 0); moveControl(m_hWnd, GetDlgItem(m_hWnd, IDCANCEL), dx, 0); } if (m_retry) showWrongPin(hPinedit, m_triesLeft); if (GetDlgCtrlID((HWND) wParam) != IDC_PINEDIT) { SetFocus(hPinedit); return FALSE; } return TRUE; } LRESULT PinInputDialog::on_command(WPARAM wParam, LPARAM lParam) { switch (LOWORD(wParam)) { case IDC_PINEDIT: if (HIWORD(wParam) == EN_CHANGE) { std::string pin = getPinInternal(); if (pin.size() >= m_minPinLength) EnableWindow(GetDlgItem(m_hWnd, IDOK), TRUE); else EnableWindow(GetDlgItem(m_hWnd, IDOK), FALSE); } break; case IDOK: m_pin = getPinInternal(); SetDlgItemTextA(m_hWnd, IDC_PINEDIT, ""); if (m_modalDialog) { EndDialog(m_hWnd, wParam); } else { DestroyWindow(m_hWnd); releaseIEModalLock(); signalResponse(RESPONSE_OK); } return TRUE; break; case IDCANCEL: m_pin = ""; SetDlgItemTextA(m_hWnd, IDC_PINEDIT, ""); if (m_modalDialog) { EndDialog(m_hWnd, wParam); } else { DestroyWindow(m_hWnd); releaseIEModalLock(); signalResponse(RESPONSE_CANCEL); } return TRUE; break; } return FALSE; } bool PinInputDialog::doDialog(HWND hParent) { return BaseDialog::doDialog(IDD_PINDIALOG, hParent); } int PinInputDialog::doModalDialog(HWND hParent) { int rv = BaseDialog::doModalDialog(IDD_PINDIALOG, hParent); if (rv == IDOK) return RESPONSE_OK; else return RESPONSE_CANCEL; } <|endoftext|>
<commit_before><commit_msg>`typedef struct` -> `typedef struct KeyAndCallbackStruct`.<commit_after><|endoftext|>
<commit_before>/* Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_serving/servables/tensorflow/bundle_factory_util.h" #include "google/protobuf/wrappers.pb.h" #include "tensorflow/core/kernels/batching_util/batch_scheduler.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/types.h" #include "tensorflow_serving/resources/resource_values.h" #include "tensorflow_serving/servables/tensorflow/serving_session.h" namespace tensorflow { namespace serving { namespace { using Batcher = SharedBatchScheduler<BatchingSessionTask>; // Constants used in the resource estimation heuristic. See the documentation // on EstimateResourceFromPath(). constexpr double kResourceEstimateRAMMultiplier = 1.2; constexpr int kResourceEstimateRAMPadBytes = 0; // Returns all the descendants, both directories and files, recursively under // 'dirname'. The paths returned are all prefixed with 'dirname'. Status GetAllDescendants(const string& dirname, FileProbingEnv* env, std::vector<string>* const descendants) { descendants->clear(); // Make sure that dirname exists; TF_RETURN_IF_ERROR(env->FileExists(dirname)); std::deque<string> dir_q; // Queue for the BFS std::vector<string> dir_list; // List of all dirs discovered dir_q.push_back(dirname); Status ret; // Status to be returned. // Do a BFS on the directory to discover all immediate children. while (!dir_q.empty()) { string dir = dir_q.front(); dir_q.pop_front(); std::vector<string> children; // GetChildren might fail if we don't have appropriate permissions. TF_RETURN_IF_ERROR(env->GetChildren(dir, &children)); for (const string& child : children) { const string child_path = io::JoinPath(dir, child); descendants->push_back(child_path); // If the child is a directory add it to the queue. if (env->IsDirectory(child_path).ok()) { dir_q.push_back(child_path); } } } return Status::OK(); } } // namespace SessionOptions GetSessionOptions(const SessionBundleConfig& config) { SessionOptions options; options.target = config.session_target(); options.config = config.session_config(); return options; } RunOptions GetRunOptions(const SessionBundleConfig& config) { RunOptions run_options; if (config.has_session_run_load_threadpool_index()) { run_options.set_inter_op_thread_pool( config.session_run_load_threadpool_index().value()); } return run_options; } Status CreateBatchScheduler(const BatchingParameters& batching_config, std::shared_ptr<Batcher>* batch_scheduler) { if (!batching_config.allowed_batch_sizes().empty()) { // Verify that the last allowed batch size matches the max batch size. const int last_allowed_size = batching_config.allowed_batch_sizes( batching_config.allowed_batch_sizes().size() - 1); const int max_size = batching_config.has_max_batch_size() ? batching_config.max_batch_size().value() : Batcher::QueueOptions().max_batch_size; if (last_allowed_size != max_size) { return errors::InvalidArgument( "Last entry in allowed_batch_sizes must match max_batch_size; last " "entry was ", last_allowed_size, "; expected ", max_size); } } Batcher::Options options; if (batching_config.has_num_batch_threads()) { options.num_batch_threads = batching_config.num_batch_threads().value(); } if (batching_config.has_thread_pool_name()) { options.thread_pool_name = batching_config.thread_pool_name().value(); } return Batcher::Create(options, batch_scheduler); } Status EstimateResourceFromPath(const string& path, ResourceAllocation* estimate) { TensorflowFileProbingEnv env(Env::Default()); return EstimateResourceFromPath(path, &env, estimate); } Status EstimateResourceFromPath(const string& path, FileProbingEnv* env, ResourceAllocation* estimate) { if (env == nullptr) { return errors::Internal("FileProbingEnv not set"); } std::vector<string> descendants; TF_RETURN_IF_ERROR(GetAllDescendants(path, env, &descendants)); uint64 total_file_size = 0; for (const string& descendant : descendants) { if (!(env->IsDirectory(descendant).ok())) { uint64 file_size; TF_RETURN_IF_ERROR(env->GetFileSize(descendant, &file_size)); total_file_size += file_size; } } const uint64 ram_requirement = total_file_size * kResourceEstimateRAMMultiplier + kResourceEstimateRAMPadBytes; ResourceAllocation::Entry* ram_entry = estimate->add_resource_quantities(); Resource* ram_resource = ram_entry->mutable_resource(); ram_resource->set_device(device_types::kMain); ram_resource->set_kind(resource_kinds::kRamBytes); ram_entry->set_quantity(ram_requirement); return Status::OK(); } Status WrapSessionForBatching(const BatchingParameters& batching_config, std::shared_ptr<Batcher> batch_scheduler, const std::vector<SignatureDef>& signatures, std::unique_ptr<Session>* session) { LOG(INFO) << "Wrapping session to perform batch processing"; if (batch_scheduler == nullptr) { return errors::Internal("batch_scheduler not set"); } if (*session == nullptr) { return errors::Internal("session not set"); } Batcher::QueueOptions queue_options; if (batching_config.has_max_batch_size()) { queue_options.max_batch_size = batching_config.max_batch_size().value(); } if (batching_config.has_batch_timeout_micros()) { queue_options.batch_timeout_micros = batching_config.batch_timeout_micros().value(); } if (batching_config.has_max_enqueued_batches()) { queue_options.max_enqueued_batches = batching_config.max_enqueued_batches().value(); } BatchingSessionOptions batching_session_options; for (int allowed_batch_size : batching_config.allowed_batch_sizes()) { batching_session_options.allowed_batch_sizes.push_back(allowed_batch_size); } batching_session_options.pad_variable_length_inputs = batching_config.pad_variable_length_inputs(); auto create_queue = [batch_scheduler, queue_options]( std::function<void(std::unique_ptr<Batch<BatchingSessionTask>>)> process_batch_callback, std::unique_ptr<BatchScheduler<BatchingSessionTask>>* queue) { TF_RETURN_IF_ERROR(batch_scheduler->AddQueue( queue_options, process_batch_callback, queue)); return Status::OK(); }; std::vector<SignatureWithBatchingSessionSchedulerCreator> signatures_with_scheduler_creators; for (const SignatureDef& signature : signatures) { const TensorSignature tensor_signature = TensorSignatureFromSignatureDef(signature); signatures_with_scheduler_creators.push_back( {tensor_signature, create_queue}); } return CreateBatchingSession(batching_session_options, signatures_with_scheduler_creators, std::move(*session), session); } Status WrapSession(std::unique_ptr<Session>* session) { session->reset(new ServingSessionWrapper(std::move(*session))); return Status::OK(); } } // namespace serving } // namespace tensorflow <commit_msg>In shared batch scheduler, rename 'max_batch_size' to 'input_batch_size_limit'.<commit_after>/* Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_serving/servables/tensorflow/bundle_factory_util.h" #include "google/protobuf/wrappers.pb.h" #include "tensorflow/core/kernels/batching_util/batch_scheduler.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/types.h" #include "tensorflow_serving/resources/resource_values.h" #include "tensorflow_serving/servables/tensorflow/serving_session.h" namespace tensorflow { namespace serving { namespace { using Batcher = SharedBatchScheduler<BatchingSessionTask>; // Constants used in the resource estimation heuristic. See the documentation // on EstimateResourceFromPath(). constexpr double kResourceEstimateRAMMultiplier = 1.2; constexpr int kResourceEstimateRAMPadBytes = 0; // Returns all the descendants, both directories and files, recursively under // 'dirname'. The paths returned are all prefixed with 'dirname'. Status GetAllDescendants(const string& dirname, FileProbingEnv* env, std::vector<string>* const descendants) { descendants->clear(); // Make sure that dirname exists; TF_RETURN_IF_ERROR(env->FileExists(dirname)); std::deque<string> dir_q; // Queue for the BFS std::vector<string> dir_list; // List of all dirs discovered dir_q.push_back(dirname); Status ret; // Status to be returned. // Do a BFS on the directory to discover all immediate children. while (!dir_q.empty()) { string dir = dir_q.front(); dir_q.pop_front(); std::vector<string> children; // GetChildren might fail if we don't have appropriate permissions. TF_RETURN_IF_ERROR(env->GetChildren(dir, &children)); for (const string& child : children) { const string child_path = io::JoinPath(dir, child); descendants->push_back(child_path); // If the child is a directory add it to the queue. if (env->IsDirectory(child_path).ok()) { dir_q.push_back(child_path); } } } return Status::OK(); } } // namespace SessionOptions GetSessionOptions(const SessionBundleConfig& config) { SessionOptions options; options.target = config.session_target(); options.config = config.session_config(); return options; } RunOptions GetRunOptions(const SessionBundleConfig& config) { RunOptions run_options; if (config.has_session_run_load_threadpool_index()) { run_options.set_inter_op_thread_pool( config.session_run_load_threadpool_index().value()); } return run_options; } Status CreateBatchScheduler(const BatchingParameters& batching_config, std::shared_ptr<Batcher>* batch_scheduler) { if (!batching_config.allowed_batch_sizes().empty()) { // Verify that the last allowed batch size matches the max batch size. const int last_allowed_size = batching_config.allowed_batch_sizes( batching_config.allowed_batch_sizes().size() - 1); const int max_size = batching_config.has_max_batch_size() ? batching_config.max_batch_size().value() : Batcher::QueueOptions().input_batch_size_limit; if (last_allowed_size != max_size) { return errors::InvalidArgument( "Last entry in allowed_batch_sizes must match max_batch_size; last " "entry was ", last_allowed_size, "; expected ", max_size); } } Batcher::Options options; if (batching_config.has_num_batch_threads()) { options.num_batch_threads = batching_config.num_batch_threads().value(); } if (batching_config.has_thread_pool_name()) { options.thread_pool_name = batching_config.thread_pool_name().value(); } return Batcher::Create(options, batch_scheduler); } Status EstimateResourceFromPath(const string& path, ResourceAllocation* estimate) { TensorflowFileProbingEnv env(Env::Default()); return EstimateResourceFromPath(path, &env, estimate); } Status EstimateResourceFromPath(const string& path, FileProbingEnv* env, ResourceAllocation* estimate) { if (env == nullptr) { return errors::Internal("FileProbingEnv not set"); } std::vector<string> descendants; TF_RETURN_IF_ERROR(GetAllDescendants(path, env, &descendants)); uint64 total_file_size = 0; for (const string& descendant : descendants) { if (!(env->IsDirectory(descendant).ok())) { uint64 file_size; TF_RETURN_IF_ERROR(env->GetFileSize(descendant, &file_size)); total_file_size += file_size; } } const uint64 ram_requirement = total_file_size * kResourceEstimateRAMMultiplier + kResourceEstimateRAMPadBytes; ResourceAllocation::Entry* ram_entry = estimate->add_resource_quantities(); Resource* ram_resource = ram_entry->mutable_resource(); ram_resource->set_device(device_types::kMain); ram_resource->set_kind(resource_kinds::kRamBytes); ram_entry->set_quantity(ram_requirement); return Status::OK(); } Status WrapSessionForBatching(const BatchingParameters& batching_config, std::shared_ptr<Batcher> batch_scheduler, const std::vector<SignatureDef>& signatures, std::unique_ptr<Session>* session) { LOG(INFO) << "Wrapping session to perform batch processing"; if (batch_scheduler == nullptr) { return errors::Internal("batch_scheduler not set"); } if (*session == nullptr) { return errors::Internal("session not set"); } Batcher::QueueOptions queue_options; if (batching_config.has_max_batch_size()) { queue_options.input_batch_size_limit = batching_config.max_batch_size().value(); } if (batching_config.has_batch_timeout_micros()) { queue_options.batch_timeout_micros = batching_config.batch_timeout_micros().value(); } if (batching_config.has_max_enqueued_batches()) { queue_options.max_enqueued_batches = batching_config.max_enqueued_batches().value(); } BatchingSessionOptions batching_session_options; for (int allowed_batch_size : batching_config.allowed_batch_sizes()) { batching_session_options.allowed_batch_sizes.push_back(allowed_batch_size); } batching_session_options.pad_variable_length_inputs = batching_config.pad_variable_length_inputs(); auto create_queue = [batch_scheduler, queue_options]( std::function<void(std::unique_ptr<Batch<BatchingSessionTask>>)> process_batch_callback, std::unique_ptr<BatchScheduler<BatchingSessionTask>>* queue) { TF_RETURN_IF_ERROR(batch_scheduler->AddQueue( queue_options, process_batch_callback, queue)); return Status::OK(); }; std::vector<SignatureWithBatchingSessionSchedulerCreator> signatures_with_scheduler_creators; for (const SignatureDef& signature : signatures) { const TensorSignature tensor_signature = TensorSignatureFromSignatureDef(signature); signatures_with_scheduler_creators.push_back( {tensor_signature, create_queue}); } return CreateBatchingSession(batching_session_options, signatures_with_scheduler_creators, std::move(*session), session); } Status WrapSession(std::unique_ptr<Session>* session) { session->reset(new ServingSessionWrapper(std::move(*session))); return Status::OK(); } } // namespace serving } // namespace tensorflow <|endoftext|>
<commit_before>#include <signal.h> #include "commands/HelpCommand.h" #include "commands/LsCommand.h" #include "commands/WatchCommand.h" #include "commands/CdCommand.h" #include "commands/ClearCommand.h" #include "commands/LogCommand.h" #include "commands/SyncCommand.h" #include "commands/PlotCommand.h" #include "commands/DiffCommand.h" #include "commands/LoadCommand.h" #include "commands/SaveCommand.h" #include "commands/TreeCommand.h" #include "commands/CatCommand.h" #include "commands/RepeatCommand.h" #include "commands/DelayCommand.h" #include "commands/PadCommand.h" #ifdef HAS_CURSES #include "commands/TuneCommand.h" #endif #include "Shell.h" using namespace RhIO; Shell *shell = NULL; void shell_quit(int s) { (void) s; if (shell != NULL) { shell->quit(); } exit(1); } int main(int argc, char *argv[]) { signal(SIGINT, shell_quit); std::string server = "localhost"; if (argc > 1) { server = std::string(argv[1]); } shell = new Shell(server); shell->registerCommand(new HelpCommand); shell->registerCommand(new LsCommand); shell->registerCommand(new CdCommand); shell->registerCommand(new ClearCommand); shell->registerCommand(new WatchCommand); shell->registerCommand(new LogCommand); shell->registerCommand(new SyncCommand); shell->registerCommand(new PlotCommand); shell->registerCommand(new DiffCommand); shell->registerCommand(new LoadCommand); shell->registerCommand(new SaveCommand); shell->registerCommand(new TreeCommand); shell->registerCommand(new CatCommand); shell->registerCommand(new RepeatCommand); shell->registerCommand(new DelayCommand); shell->registerCommand(new PadCommand); #ifdef HAS_CURSES shell->registerCommand(new TuneCommand); #endif shell->addAlias("ll", "ls"); if (argc > 2) { std::string args = ""; for (int k=2; k<argc; k++) { args += argv[k]; args += " "; } shell->run(args); } else { shell->run(); } } <commit_msg>Adding aliases<commit_after>#include <signal.h> #include "commands/HelpCommand.h" #include "commands/LsCommand.h" #include "commands/WatchCommand.h" #include "commands/CdCommand.h" #include "commands/ClearCommand.h" #include "commands/LogCommand.h" #include "commands/SyncCommand.h" #include "commands/PlotCommand.h" #include "commands/DiffCommand.h" #include "commands/LoadCommand.h" #include "commands/SaveCommand.h" #include "commands/TreeCommand.h" #include "commands/CatCommand.h" #include "commands/RepeatCommand.h" #include "commands/DelayCommand.h" #include "commands/PadCommand.h" #ifdef HAS_CURSES #include "commands/TuneCommand.h" #endif #include "Shell.h" using namespace RhIO; Shell *shell = NULL; void shell_quit(int s) { (void) s; if (shell != NULL) { shell->quit(); } exit(1); } int main(int argc, char *argv[]) { signal(SIGINT, shell_quit); std::string server = "localhost"; if (argc > 1) { server = std::string(argv[1]); } shell = new Shell(server); shell->registerCommand(new HelpCommand); shell->registerCommand(new LsCommand); shell->registerCommand(new CdCommand); shell->registerCommand(new ClearCommand); shell->registerCommand(new WatchCommand); shell->registerCommand(new LogCommand); shell->registerCommand(new SyncCommand); shell->registerCommand(new PlotCommand); shell->registerCommand(new DiffCommand); shell->registerCommand(new LoadCommand); shell->registerCommand(new SaveCommand); shell->registerCommand(new TreeCommand); shell->registerCommand(new CatCommand); shell->registerCommand(new RepeatCommand); shell->registerCommand(new DelayCommand); shell->registerCommand(new PadCommand); #ifdef HAS_CURSES shell->registerCommand(new TuneCommand); #endif shell->addAlias("ll", "ls"); shell->addAlias("rep", "repeat"); shell->addAlias("del", "delay"); if (argc > 2) { std::string args = ""; for (int k=2; k<argc; k++) { args += argv[k]; args += " "; } shell->run(args); } else { shell->run(); } } <|endoftext|>
<commit_before> #include <nstd/Console.h> #include <nstd/Error.h> #include <nstd/Time.h> #include <nstd/Debug.h> #include <nstd/File.h> #include <zlimdbclient.h> #include "Client.h" #include "ClientProtocol.h" Client::Client() : zdb(0), selectedTable(0) { VERIFY(zlimdb_init() == 0); } Client::~Client() { disconnect(); VERIFY(zlimdb_cleanup() == 0); } bool_t Client::connect(const String& user, const String& password, const String& address) { disconnect(); // create connection zdb = zlimdb_create((void (*)(void*, const zlimdb_header*))(void (*)(void*, const void*))zlimdbCallback, this); if(!zdb) { error = getZlimdbError(); return false; } uint16_t port = 0; String host = address; const char_t* colon = address.find(':'); if(colon) { port = String::toUInt(colon + 1); host = address.substr(0, colon - (const char_t*)address); } if(zlimdb_connect(zdb, host, port, user, password) != 0) { error = getZlimdbError(); return false; } // start receive thread keepRunning = true; if(!thread.start(threadProc, this)) { error = Error::getErrorString(); return false; } return true; } void_t Client::disconnect() { if(zdb) { keepRunning = false; zlimdb_interrupt(zdb); } thread.join(); actions.clear(); selectedTable = 0; } void_t Client::listUsers() { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = listUsersAction; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::addUser(const String& userName, const String& password) { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = addUserAction; action.param1 = userName; action.param2 = password; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::listTables() { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = listTablesAction; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::createTable(const String& name) { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = createTableAction; action.param1 = name; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::selectTable(uint32_t tableId) { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = selectTableAction; action.param1 = tableId; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::query() { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = queryAction; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::query(uint64_t sinceId) { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = queryAction; action.param1 = sinceId; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::add(const String& value) { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = addAction; action.param1 = value; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::subscribe() { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = subscribeAction; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::sync() { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = syncAction; actionMutex.unlock(); zlimdb_interrupt(zdb); } uint_t Client::threadProc(void_t* param) { Client* client = (Client*)param; return client->process();; } uint8_t Client::process() { while(keepRunning && zlimdb_is_connected(zdb) == 0) if(zlimdb_exec(zdb, 5 * 60 * 1000) != 0) switch(zlimdb_errno()) { case zlimdb_local_error_interrupted: { Action action = {quitAction}; bool actionEmpty = true; do { actionMutex.lock(); if(!actions.isEmpty()) { action = actions.front(); actions.removeFront(); actionEmpty = actions.isEmpty(); } actionMutex.unlock(); handleAction(action); } while(!actionEmpty); } break; case zlimdb_local_error_timeout: break; default: Console::errorf("error: Could not receive data: %s\n", (const char_t*)getZlimdbError()); return 1; } return 0; } void_t Client::handleAction(const Action& action) { switch(action.type) { case listUsersAction: { if(zlimdb_query(zdb, zlimdb_table_tables, zlimdb_query_type_all, 0) != 0) { Console::errorf("error: Could not send query: %s\n", (const char_t*)getZlimdbError()); return; } Buffer buffer; buffer.resize(0xffff); uint32_t size; while(zlimdb_get_response(zdb, (zlimdb_entity*)(byte_t*)buffer, buffer.size(), &size) == 0) { for(const zlimdb_table_entity* table = (const zlimdb_table_entity*)(const byte_t*)buffer, * end = (const zlimdb_table_entity*)((const byte_t*)table + size); table < end; table = (const zlimdb_table_entity*)((const byte_t*)table + table->entity.size)) { String tableName; ClientProtocol::getString((const byte_t*)buffer, size, table->entity, sizeof(zlimdb_table_entity), table->name_size, tableName); if(!tableName.startsWith("users/")) continue; tableName.resize(tableName.length()); // enfore NULL termination Console::printf("%6llu: %s\n", table->entity.id, (const char_t*)File::basename(File::dirname(tableName))); } } if(zlimdb_errno() != zlimdb_local_error_none) { Console::errorf("error: Could not receive query response: %s\n", (const char_t*)getZlimdbError()); return; } } break; case addUserAction: { const String userName = action.param1.toString(); const String password = action.param2.toString(); if(zlimdb_add_user(zdb, userName, password) != 0) { Console::errorf("error: Could not send add user request: %s\n", (const char_t*)getZlimdbError()); return; } } break; case listTablesAction: { if(zlimdb_query(zdb, zlimdb_table_tables, zlimdb_query_type_all, 0) != 0) { Console::errorf("error: Could not send query: %s\n", (const char_t*)getZlimdbError()); return; } Buffer buffer; buffer.resize(0xffff); uint32_t size; while(zlimdb_get_response(zdb, (zlimdb_entity*)(byte_t*)buffer, buffer.size(), &size) == 0) { for(const zlimdb_table_entity* table = (const zlimdb_table_entity*)(const byte_t*)buffer, * end = (const zlimdb_table_entity*)((const byte_t*)table + size); table < end; table = (const zlimdb_table_entity*)((const byte_t*)table + table->entity.size)) { String tableName; ClientProtocol::getString((const byte_t*)buffer, size, table->entity, sizeof(zlimdb_table_entity), table->name_size, tableName); tableName.resize(tableName.length()); // enfore NULL termination Console::printf("%6llu: %s\n", table->entity.id, (const char_t*)tableName); } } if(zlimdb_errno() != zlimdb_local_error_none) { Console::errorf("error: Could not receive query response: %s\n", (const char_t*)getZlimdbError()); return; } } break; case selectTableAction: selectedTable = action.param1.toUInt(); //Console::printf("selected table %u\n", action.param); break; case createTableAction: { const String tableName = action.param1.toString(); uint32_t tableId; if(zlimdb_add_table(zdb, tableName, &tableId) != 0) { Console::errorf("error: Could not send add request: %s\n", (const char_t*)getZlimdbError()); return; } Console::printf("%6llu: %s\n", tableId, (const char_t*)tableName); } break; case queryAction: { zlimdb_query_type queryType = zlimdb_query_type_all; uint64_t param = 0; if(!action.param1.isNull()) { queryType = zlimdb_query_type_since_id; param = action.param1.toUInt64(); } if(zlimdb_query(zdb, selectedTable, queryType, param) != 0) { Console::errorf("error: Could not send query: %s\n", (const char_t*)getZlimdbError()); return; } Buffer buffer; buffer.resize(0xffff); uint32_t size; while(zlimdb_get_response(zdb, (zlimdb_entity*)(byte_t*)buffer, buffer.size(), &size) == 0) { for(const zlimdb_entity* entity = (const zlimdb_entity*)(const byte_t*)buffer, * end = (const zlimdb_entity*)((const byte_t*)entity + size); entity < end; entity = (const zlimdb_entity*)((const byte_t*)entity + entity->size)) { Console::printf("id=%llu, size=%u, time=%llu\n", entity->id, (uint_t)entity->size, entity->time); } } if(zlimdb_errno() != zlimdb_local_error_none) { Console::errorf("error: Could not receive query response: %s\n", (const char_t*)getZlimdbError()); return; } } break; case subscribeAction: { if(zlimdb_subscribe(zdb, selectedTable, zlimdb_query_type_all, 0) != 0) { Console::errorf("error: Could not send subscribe request: %s\n", (const char_t*)getZlimdbError()); return; } Buffer buffer; buffer.resize(0xffff); uint32_t size; while(zlimdb_get_response(zdb, (zlimdb_entity*)(byte_t*)buffer, buffer.size(), &size) == 0) { for(const zlimdb_entity* entity = (const zlimdb_entity*)(const byte_t*)buffer, * end = (const zlimdb_entity*)((const byte_t*)entity + size); entity < end; entity = (const zlimdb_entity*)((const byte_t*)entity + entity->size)) { Console::printf("id=%llu, size=%u, time=%llu\n", entity->id, (uint_t)entity->size, entity->time); } } if(zlimdb_errno() != zlimdb_local_error_none) { Console::errorf("error: Could not receive subscribe response: %s\n", (const char_t*)getZlimdbError()); return; } } break; case addAction: { const String value = action.param1.toString(); Buffer buffer; buffer.resize(sizeof(zlimdb_table_entity) + value.length()); zlimdb_table_entity* entity = (zlimdb_table_entity*)(const byte_t*)buffer; ClientProtocol::setEntityHeader(entity->entity, 0, Time::time(), sizeof(zlimdb_table_entity) + value.length()); ClientProtocol::setString(entity->entity, entity->name_size, sizeof(*entity), value); if(zlimdb_add(zdb, selectedTable, &entity->entity)) { Console::errorf("error: Could not send add request: %s\n", (const char_t*)getZlimdbError()); return; } } break; case syncAction: { timestamp_t serverTime, tableTime; if(zlimdb_sync(zdb, selectedTable, &serverTime, &tableTime)) { Console::errorf("error: Could not send sync request: %s\n", (const char_t*)getZlimdbError()); return; } Console::printf("serverTime=%llu, tableTime=%llu\n", serverTime, tableTime); } break; case quitAction: break; } } void_t Client::zlimdbCallback(const void_t* data) { const zlimdb_header* header = (const zlimdb_header*)data; // todo: check sizes switch(header->message_type) { case zlimdb_message_error_response: { const zlimdb_error_response* errorResponse = (const zlimdb_error_response*)header; Console::printf("subscribe: errorResponse=%s (%d)\n", (const char_t*)getZlimdbError(), (int)errorResponse->error); } break; default: Console::printf("subscribe: messageType=%u\n", (uint_t)header->message_type); break; } } String Client::getZlimdbError() { int err = zlimdb_errno(); if(err == zlimdb_local_error_system) return Error::getErrorString(); else { const char* errstr = zlimdb_strerror(err); return String(errstr, String::length(errstr)); } } <commit_msg>Fix create table command<commit_after> #include <nstd/Console.h> #include <nstd/Error.h> #include <nstd/Time.h> #include <nstd/Debug.h> #include <nstd/File.h> #include <zlimdbclient.h> #include "Client.h" #include "ClientProtocol.h" Client::Client() : zdb(0), selectedTable(0) { VERIFY(zlimdb_init() == 0); } Client::~Client() { disconnect(); VERIFY(zlimdb_cleanup() == 0); } bool_t Client::connect(const String& user, const String& password, const String& address) { disconnect(); // create connection zdb = zlimdb_create((void (*)(void*, const zlimdb_header*))(void (*)(void*, const void*))zlimdbCallback, this); if(!zdb) { error = getZlimdbError(); return false; } uint16_t port = 0; String host = address; const char_t* colon = address.find(':'); if(colon) { port = String::toUInt(colon + 1); host = address.substr(0, colon - (const char_t*)address); } if(zlimdb_connect(zdb, host, port, user, password) != 0) { error = getZlimdbError(); return false; } // start receive thread keepRunning = true; if(!thread.start(threadProc, this)) { error = Error::getErrorString(); return false; } return true; } void_t Client::disconnect() { if(zdb) { keepRunning = false; zlimdb_interrupt(zdb); } thread.join(); actions.clear(); selectedTable = 0; } void_t Client::listUsers() { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = listUsersAction; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::addUser(const String& userName, const String& password) { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = addUserAction; action.param1 = userName; action.param2 = password; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::listTables() { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = listTablesAction; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::createTable(const String& name) { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = createTableAction; action.param1 = name; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::selectTable(uint32_t tableId) { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = selectTableAction; action.param1 = tableId; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::query() { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = queryAction; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::query(uint64_t sinceId) { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = queryAction; action.param1 = sinceId; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::add(const String& value) { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = addAction; action.param1 = value; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::subscribe() { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = subscribeAction; actionMutex.unlock(); zlimdb_interrupt(zdb); } void_t Client::sync() { if(!zdb) return; actionMutex.lock(); Action& action = actions.append(Action()); action.type = syncAction; actionMutex.unlock(); zlimdb_interrupt(zdb); } uint_t Client::threadProc(void_t* param) { Client* client = (Client*)param; return client->process();; } uint8_t Client::process() { while(keepRunning && zlimdb_is_connected(zdb) == 0) if(zlimdb_exec(zdb, 5 * 60 * 1000) != 0) switch(zlimdb_errno()) { case zlimdb_local_error_interrupted: { Action action = {quitAction}; bool actionEmpty = true; do { actionMutex.lock(); if(!actions.isEmpty()) { action = actions.front(); actions.removeFront(); actionEmpty = actions.isEmpty(); } actionMutex.unlock(); handleAction(action); } while(!actionEmpty); } break; case zlimdb_local_error_timeout: break; default: Console::errorf("error: Could not receive data: %s\n", (const char_t*)getZlimdbError()); return 1; } return 0; } void_t Client::handleAction(const Action& action) { switch(action.type) { case listUsersAction: { if(zlimdb_query(zdb, zlimdb_table_tables, zlimdb_query_type_all, 0) != 0) { Console::errorf("error: Could not send query: %s\n", (const char_t*)getZlimdbError()); return; } Buffer buffer; buffer.resize(0xffff); uint32_t size; while(zlimdb_get_response(zdb, (zlimdb_entity*)(byte_t*)buffer, buffer.size(), &size) == 0) { for(const zlimdb_table_entity* table = (const zlimdb_table_entity*)(const byte_t*)buffer, * end = (const zlimdb_table_entity*)((const byte_t*)table + size); table < end; table = (const zlimdb_table_entity*)((const byte_t*)table + table->entity.size)) { String tableName; ClientProtocol::getString((const byte_t*)buffer, size, table->entity, sizeof(zlimdb_table_entity), table->name_size, tableName); if(!tableName.startsWith("users/")) continue; tableName.resize(tableName.length()); // enfore NULL termination Console::printf("%6llu: %s\n", table->entity.id, (const char_t*)File::basename(File::dirname(tableName))); } } if(zlimdb_errno() != zlimdb_local_error_none) { Console::errorf("error: Could not receive query response: %s\n", (const char_t*)getZlimdbError()); return; } } break; case addUserAction: { const String userName = action.param1.toString(); const String password = action.param2.toString(); if(zlimdb_add_user(zdb, userName, password) != 0) { Console::errorf("error: Could not send add user request: %s\n", (const char_t*)getZlimdbError()); return; } } break; case listTablesAction: { if(zlimdb_query(zdb, zlimdb_table_tables, zlimdb_query_type_all, 0) != 0) { Console::errorf("error: Could not send query: %s\n", (const char_t*)getZlimdbError()); return; } Buffer buffer; buffer.resize(0xffff); uint32_t size; while(zlimdb_get_response(zdb, (zlimdb_entity*)(byte_t*)buffer, buffer.size(), &size) == 0) { for(const zlimdb_table_entity* table = (const zlimdb_table_entity*)(const byte_t*)buffer, * end = (const zlimdb_table_entity*)((const byte_t*)table + size); table < end; table = (const zlimdb_table_entity*)((const byte_t*)table + table->entity.size)) { String tableName; ClientProtocol::getString((const byte_t*)buffer, size, table->entity, sizeof(zlimdb_table_entity), table->name_size, tableName); tableName.resize(tableName.length()); // enfore NULL termination Console::printf("%6llu: %s\n", table->entity.id, (const char_t*)tableName); } } if(zlimdb_errno() != zlimdb_local_error_none) { Console::errorf("error: Could not receive query response: %s\n", (const char_t*)getZlimdbError()); return; } } break; case selectTableAction: selectedTable = action.param1.toUInt(); //Console::printf("selected table %u\n", action.param); break; case createTableAction: { const String tableName = action.param1.toString(); uint32_t tableId; if(zlimdb_add_table(zdb, tableName, &tableId) != 0) { Console::errorf("error: Could not send add request: %s\n", (const char_t*)getZlimdbError()); return; } Console::printf("%6u: %s\n", tableId, (const char_t*)tableName); } break; case queryAction: { zlimdb_query_type queryType = zlimdb_query_type_all; uint64_t param = 0; if(!action.param1.isNull()) { queryType = zlimdb_query_type_since_id; param = action.param1.toUInt64(); } if(zlimdb_query(zdb, selectedTable, queryType, param) != 0) { Console::errorf("error: Could not send query: %s\n", (const char_t*)getZlimdbError()); return; } Buffer buffer; buffer.resize(0xffff); uint32_t size; while(zlimdb_get_response(zdb, (zlimdb_entity*)(byte_t*)buffer, buffer.size(), &size) == 0) { for(const zlimdb_entity* entity = (const zlimdb_entity*)(const byte_t*)buffer, * end = (const zlimdb_entity*)((const byte_t*)entity + size); entity < end; entity = (const zlimdb_entity*)((const byte_t*)entity + entity->size)) { Console::printf("id=%llu, size=%u, time=%llu\n", entity->id, (uint_t)entity->size, entity->time); } } if(zlimdb_errno() != zlimdb_local_error_none) { Console::errorf("error: Could not receive query response: %s\n", (const char_t*)getZlimdbError()); return; } } break; case subscribeAction: { if(zlimdb_subscribe(zdb, selectedTable, zlimdb_query_type_all, 0) != 0) { Console::errorf("error: Could not send subscribe request: %s\n", (const char_t*)getZlimdbError()); return; } Buffer buffer; buffer.resize(0xffff); uint32_t size; while(zlimdb_get_response(zdb, (zlimdb_entity*)(byte_t*)buffer, buffer.size(), &size) == 0) { for(const zlimdb_entity* entity = (const zlimdb_entity*)(const byte_t*)buffer, * end = (const zlimdb_entity*)((const byte_t*)entity + size); entity < end; entity = (const zlimdb_entity*)((const byte_t*)entity + entity->size)) { Console::printf("id=%llu, size=%u, time=%llu\n", entity->id, (uint_t)entity->size, entity->time); } } if(zlimdb_errno() != zlimdb_local_error_none) { Console::errorf("error: Could not receive subscribe response: %s\n", (const char_t*)getZlimdbError()); return; } } break; case addAction: { const String value = action.param1.toString(); Buffer buffer; buffer.resize(sizeof(zlimdb_table_entity) + value.length()); zlimdb_table_entity* entity = (zlimdb_table_entity*)(const byte_t*)buffer; ClientProtocol::setEntityHeader(entity->entity, 0, Time::time(), sizeof(zlimdb_table_entity) + value.length()); ClientProtocol::setString(entity->entity, entity->name_size, sizeof(*entity), value); if(zlimdb_add(zdb, selectedTable, &entity->entity)) { Console::errorf("error: Could not send add request: %s\n", (const char_t*)getZlimdbError()); return; } } break; case syncAction: { timestamp_t serverTime, tableTime; if(zlimdb_sync(zdb, selectedTable, &serverTime, &tableTime)) { Console::errorf("error: Could not send sync request: %s\n", (const char_t*)getZlimdbError()); return; } Console::printf("serverTime=%llu, tableTime=%llu\n", serverTime, tableTime); } break; case quitAction: break; } } void_t Client::zlimdbCallback(const void_t* data) { const zlimdb_header* header = (const zlimdb_header*)data; // todo: check sizes switch(header->message_type) { case zlimdb_message_error_response: { const zlimdb_error_response* errorResponse = (const zlimdb_error_response*)header; Console::printf("subscribe: errorResponse=%s (%d)\n", (const char_t*)getZlimdbError(), (int)errorResponse->error); } break; default: Console::printf("subscribe: messageType=%u\n", (uint_t)header->message_type); break; } } String Client::getZlimdbError() { int err = zlimdb_errno(); if(err == zlimdb_local_error_system) return Error::getErrorString(); else { const char* errstr = zlimdb_strerror(err); return String(errstr, String::length(errstr)); } } <|endoftext|>
<commit_before>/* * Copyright 2004-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/lib/cpp2/transport/http2/common/HTTP2RoutingHandler.h> #include <gflags/gflags.h> #include <proxygen/httpserver/HTTPServerAcceptor.h> #include <proxygen/httpserver/HTTPServerOptions.h> #include <proxygen/httpserver/RequestHandler.h> #include <proxygen/httpserver/RequestHandlerAdaptor.h> #include <proxygen/lib/http/codec/HTTPCodec.h> #include <proxygen/lib/http/codec/HTTPSettings.h> #include <proxygen/lib/http/session/HTTPDefaultSessionCodecFactory.h> #include <proxygen/lib/http/session/HTTPDownstreamSession.h> #include <proxygen/lib/http/session/HTTPSession.h> #include <proxygen/lib/http/session/SimpleController.h> #include <thrift/lib/cpp2/transport/http2/common/H2ChannelFactory.h> #include <thrift/lib/cpp2/transport/http2/server/ThriftRequestHandler.h> #include <wangle/acceptor/ManagedConnection.h> #include <limits> DECLARE_int32(force_channel_version); namespace apache { namespace thrift { namespace { // Class for managing lifetime of objects supporting an HTTP2 session. class HTTP2RoutingSessionManager : public proxygen::HTTPSession::InfoCallback, public proxygen::SimpleController { public: HTTP2RoutingSessionManager( std::unique_ptr<proxygen::HTTPServerAcceptor> acceptor, ThriftProcessor* processor) : proxygen::HTTPSession::InfoCallback(), proxygen::SimpleController(acceptor.get()), processor_(processor), negotiatedChannelVersion_(FLAGS_force_channel_version) { acceptor_ = std::move(acceptor); if (FLAGS_force_channel_version > 0) { // This prevents the inspection of the HTTP2 header for the channel // version. stableId_ = 0; } else { stableId_ = std::numeric_limits<proxygen::HTTPCodec::StreamID>::max(); } } ~HTTP2RoutingSessionManager() = default; proxygen::HTTPDownstreamSession* createSession( folly::AsyncTransportWrapper::UniquePtr sock, folly::SocketAddress* peerAddress, std::unique_ptr<proxygen::HTTPCodec> h2codec, wangle::TransportInfo const& tinfo) { // Obtain the proper routing address folly::SocketAddress localAddress; try { sock->getLocalAddress(&localAddress); } catch (...) { VLOG(3) << "couldn't get local address for socket"; localAddress = folly::SocketAddress("0.0.0.0", 0); } VLOG(4) << "Created new session for peer " << *peerAddress; // Create the DownstreamSession. Note that "this" occurs twice // because it acts as both a controller as well as a info // callback. auto session = new proxygen::HTTPDownstreamSession( proxygen::WheelTimerInstance(std::chrono::milliseconds(5)), std::move(sock), localAddress, *peerAddress, this, std::move(h2codec), tinfo, this); return session; } // begin HTTPSession::InfoCallback methods // We do not override onDestroy() to self destroy because this object // doubles as both the InfoCallback and the SimpleController. The // session destructor calls onDestroy() first and then detachSession() // so we self destroy at detachSession(). void onSettings( const proxygen::HTTPSessionBase&, const proxygen::SettingsList& settings) override { if (FLAGS_force_channel_version > 0) { // Do not use the negotiated settings. return; } for (auto& setting : settings) { if (setting.id == kChannelSettingId) { negotiatedChannelVersion_ = std::min(setting.value, kMaxSupportedChannelVersion); VLOG(2) << "Peer channel version is " << setting.value; VLOG(2) << "Negotiated channel version is " << negotiatedChannelVersion_; } } if (negotiatedChannelVersion_ == 0) { // Did not receive a channel version, assuming legacy peer. negotiatedChannelVersion_ = 1; } } // end HTTPSession::InfoCallback methods // begin SimpleController methods proxygen::HTTPTransactionHandler* getRequestHandler( proxygen::HTTPTransaction& txn, proxygen::HTTPMessage* msg) override { folly::SocketAddress clientAddr, vipAddr; txn.getPeerAddress(clientAddr); txn.getLocalAddress(vipAddr); msg->setClientAddress(clientAddr); msg->setDstAddress(vipAddr); // This checks that the SETTINGS frame arrives before the first RPC. DCHECK(negotiatedChannelVersion_ > 0); // Determine channel version for this HTTP2 stream. uint32_t version = negotiatedChannelVersion_; if (UNLIKELY(txn.getID() < stableId_)) { auto val = msg->getHeaders().rawGet(kChannelVersionKey); try { version = folly::to<int>(val); } catch (const std::exception& ex) { LOG(WARNING) << "Channel version not set properly in header: " << val; // This could be from a legacy client. version = 1; } DCHECK(version == 1 || version == negotiatedChannelVersion_); if (version == negotiatedChannelVersion_) { stableId_ = txn.getID(); } } proxygen::RequestHandler* handler = new ThriftRequestHandler(processor_, version); return new proxygen::RequestHandlerAdaptor(handler); } void detachSession(const proxygen::HTTPSession*) override { VLOG(4) << "HTTP2RoutingSessionManager::detachSession"; // Session destroyed, so self destroy. delete this; } // end SimpleController methods private: // Supporting objects for HTTP2 session managed by the callback. std::unique_ptr<proxygen::HTTPServerAcceptor> acceptor_; ThriftProcessor* processor_; // The negotiated channel version - 0 means negotiation has not // taken place yet. Negotiation is completed when the server // receives a header with a non-zero channel version. uint32_t negotiatedChannelVersion_; // The stream id after which the server can assume that the channel // version will be the negotiated version. proxygen::HTTPCodec::StreamID stableId_; }; } // anonymous namespace bool HTTP2RoutingHandler::canAcceptConnection( const std::vector<uint8_t>& bytes) { /* * HTTP/2.0 requests start with the following sequence: * Octal: 0x505249202a20485454502f322e300d0a0d0a534d0d0a0d0a * String: "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" * * For more, see: https://tools.ietf.org/html/rfc7540#section-3.5 */ if (bytes[0] == 0x50 && bytes[1] == 0x52 && bytes[2] == 0x49) { return true; } /* * HTTP requests start with the following sequence: * Octal: "0x485454502f..." * String: "HTTP/X.X" * * For more, see: https://tools.ietf.org/html/rfc2616#section-3 */ if (bytes[0] == 0x48 && bytes[1] == 0x54 && bytes[2] == 0x54) { return true; } return false; } bool HTTP2RoutingHandler::canAcceptEncryptedConnection( const std::string& protocolName) { return protocolName == "h2" || protocolName == "http"; } void HTTP2RoutingHandler::handleConnection( wangle::ConnectionManager* connectionManager, folly::AsyncTransportWrapper::UniquePtr sock, folly::SocketAddress* peerAddress, wangle::TransportInfo const& tinfo) { // Create the DownstreamSession manager. auto ipConfig = proxygen::HTTPServer::IPConfig( *peerAddress, proxygen::HTTPServer::Protocol::HTTP2); auto acceptorConfig = proxygen::HTTPServerAcceptor::makeConfig(ipConfig, *options_); auto acceptor = proxygen::HTTPServerAcceptor::make(acceptorConfig, *options_); auto sessionManager = new HTTP2RoutingSessionManager(std::move(acceptor), processor_); // Get the HTTP2 Codec auto codecFactory = proxygen::HTTPDefaultSessionCodecFactory(acceptorConfig); auto h2codec = codecFactory.getCodec("h2", proxygen::TransportDirection::DOWNSTREAM); // Create the DownstreamSession auto session = sessionManager->createSession( std::move(sock), peerAddress, std::move(h2codec), tinfo); // Set HTTP2 priorities flag on session object. session->setHTTP2PrioritiesEnabled(acceptorConfig.HTTP2PrioritiesEnabled); /* if (acceptorConfig.maxConcurrentIncomingStreams) { session->setMaxConcurrentIncomingStreams( acceptorConfig.maxConcurrentIncomingStreams); } */ // TODO: Improve the way max incoming streams is set session->setMaxConcurrentIncomingStreams(100000); // Set flow control parameters. session->setFlowControl( acceptorConfig.initialReceiveWindow, acceptorConfig.receiveStreamWindowSize, acceptorConfig.receiveSessionWindowSize); if (acceptorConfig.writeBufferLimit > 0) { session->setWriteBufferLimit(acceptorConfig.writeBufferLimit); } session->setEgressSettings( {{kChannelSettingId, kMaxSupportedChannelVersion}}); // Route the connection. connectionManager->addConnection(session); session->startNow(); } } // namspace thrift } // namespace apache <commit_msg>Make HTTPSessionController callbacks take HTTPSessionBase<commit_after>/* * Copyright 2004-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/lib/cpp2/transport/http2/common/HTTP2RoutingHandler.h> #include <gflags/gflags.h> #include <proxygen/httpserver/HTTPServerAcceptor.h> #include <proxygen/httpserver/HTTPServerOptions.h> #include <proxygen/httpserver/RequestHandler.h> #include <proxygen/httpserver/RequestHandlerAdaptor.h> #include <proxygen/lib/http/codec/HTTPCodec.h> #include <proxygen/lib/http/codec/HTTPSettings.h> #include <proxygen/lib/http/session/HTTPDefaultSessionCodecFactory.h> #include <proxygen/lib/http/session/HTTPDownstreamSession.h> #include <proxygen/lib/http/session/HTTPSession.h> #include <proxygen/lib/http/session/SimpleController.h> #include <thrift/lib/cpp2/transport/http2/common/H2ChannelFactory.h> #include <thrift/lib/cpp2/transport/http2/server/ThriftRequestHandler.h> #include <wangle/acceptor/ManagedConnection.h> #include <limits> DECLARE_int32(force_channel_version); namespace apache { namespace thrift { namespace { // Class for managing lifetime of objects supporting an HTTP2 session. class HTTP2RoutingSessionManager : public proxygen::HTTPSession::InfoCallback, public proxygen::SimpleController { public: HTTP2RoutingSessionManager( std::unique_ptr<proxygen::HTTPServerAcceptor> acceptor, ThriftProcessor* processor) : proxygen::HTTPSession::InfoCallback(), proxygen::SimpleController(acceptor.get()), processor_(processor), negotiatedChannelVersion_(FLAGS_force_channel_version) { acceptor_ = std::move(acceptor); if (FLAGS_force_channel_version > 0) { // This prevents the inspection of the HTTP2 header for the channel // version. stableId_ = 0; } else { stableId_ = std::numeric_limits<proxygen::HTTPCodec::StreamID>::max(); } } ~HTTP2RoutingSessionManager() = default; proxygen::HTTPDownstreamSession* createSession( folly::AsyncTransportWrapper::UniquePtr sock, folly::SocketAddress* peerAddress, std::unique_ptr<proxygen::HTTPCodec> h2codec, wangle::TransportInfo const& tinfo) { // Obtain the proper routing address folly::SocketAddress localAddress; try { sock->getLocalAddress(&localAddress); } catch (...) { VLOG(3) << "couldn't get local address for socket"; localAddress = folly::SocketAddress("0.0.0.0", 0); } VLOG(4) << "Created new session for peer " << *peerAddress; // Create the DownstreamSession. Note that "this" occurs twice // because it acts as both a controller as well as a info // callback. auto session = new proxygen::HTTPDownstreamSession( proxygen::WheelTimerInstance(std::chrono::milliseconds(5)), std::move(sock), localAddress, *peerAddress, this, std::move(h2codec), tinfo, this); return session; } // begin HTTPSession::InfoCallback methods // We do not override onDestroy() to self destroy because this object // doubles as both the InfoCallback and the SimpleController. The // session destructor calls onDestroy() first and then detachSession() // so we self destroy at detachSession(). void onSettings( const proxygen::HTTPSessionBase&, const proxygen::SettingsList& settings) override { if (FLAGS_force_channel_version > 0) { // Do not use the negotiated settings. return; } for (auto& setting : settings) { if (setting.id == kChannelSettingId) { negotiatedChannelVersion_ = std::min(setting.value, kMaxSupportedChannelVersion); VLOG(2) << "Peer channel version is " << setting.value; VLOG(2) << "Negotiated channel version is " << negotiatedChannelVersion_; } } if (negotiatedChannelVersion_ == 0) { // Did not receive a channel version, assuming legacy peer. negotiatedChannelVersion_ = 1; } } // end HTTPSession::InfoCallback methods // begin SimpleController methods proxygen::HTTPTransactionHandler* getRequestHandler( proxygen::HTTPTransaction& txn, proxygen::HTTPMessage* msg) override { folly::SocketAddress clientAddr, vipAddr; txn.getPeerAddress(clientAddr); txn.getLocalAddress(vipAddr); msg->setClientAddress(clientAddr); msg->setDstAddress(vipAddr); // This checks that the SETTINGS frame arrives before the first RPC. DCHECK(negotiatedChannelVersion_ > 0); // Determine channel version for this HTTP2 stream. uint32_t version = negotiatedChannelVersion_; if (UNLIKELY(txn.getID() < stableId_)) { auto val = msg->getHeaders().rawGet(kChannelVersionKey); try { version = folly::to<int>(val); } catch (const std::exception& ex) { LOG(WARNING) << "Channel version not set properly in header: " << val; // This could be from a legacy client. version = 1; } DCHECK(version == 1 || version == negotiatedChannelVersion_); if (version == negotiatedChannelVersion_) { stableId_ = txn.getID(); } } proxygen::RequestHandler* handler = new ThriftRequestHandler(processor_, version); return new proxygen::RequestHandlerAdaptor(handler); } void detachSession(const proxygen::HTTPSessionBase*) override { VLOG(4) << "HTTP2RoutingSessionManager::detachSession"; // Session destroyed, so self destroy. delete this; } // end SimpleController methods private: // Supporting objects for HTTP2 session managed by the callback. std::unique_ptr<proxygen::HTTPServerAcceptor> acceptor_; ThriftProcessor* processor_; // The negotiated channel version - 0 means negotiation has not // taken place yet. Negotiation is completed when the server // receives a header with a non-zero channel version. uint32_t negotiatedChannelVersion_; // The stream id after which the server can assume that the channel // version will be the negotiated version. proxygen::HTTPCodec::StreamID stableId_; }; } // anonymous namespace bool HTTP2RoutingHandler::canAcceptConnection( const std::vector<uint8_t>& bytes) { /* * HTTP/2.0 requests start with the following sequence: * Octal: 0x505249202a20485454502f322e300d0a0d0a534d0d0a0d0a * String: "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" * * For more, see: https://tools.ietf.org/html/rfc7540#section-3.5 */ if (bytes[0] == 0x50 && bytes[1] == 0x52 && bytes[2] == 0x49) { return true; } /* * HTTP requests start with the following sequence: * Octal: "0x485454502f..." * String: "HTTP/X.X" * * For more, see: https://tools.ietf.org/html/rfc2616#section-3 */ if (bytes[0] == 0x48 && bytes[1] == 0x54 && bytes[2] == 0x54) { return true; } return false; } bool HTTP2RoutingHandler::canAcceptEncryptedConnection( const std::string& protocolName) { return protocolName == "h2" || protocolName == "http"; } void HTTP2RoutingHandler::handleConnection( wangle::ConnectionManager* connectionManager, folly::AsyncTransportWrapper::UniquePtr sock, folly::SocketAddress* peerAddress, wangle::TransportInfo const& tinfo) { // Create the DownstreamSession manager. auto ipConfig = proxygen::HTTPServer::IPConfig( *peerAddress, proxygen::HTTPServer::Protocol::HTTP2); auto acceptorConfig = proxygen::HTTPServerAcceptor::makeConfig(ipConfig, *options_); auto acceptor = proxygen::HTTPServerAcceptor::make(acceptorConfig, *options_); auto sessionManager = new HTTP2RoutingSessionManager(std::move(acceptor), processor_); // Get the HTTP2 Codec auto codecFactory = proxygen::HTTPDefaultSessionCodecFactory(acceptorConfig); auto h2codec = codecFactory.getCodec("h2", proxygen::TransportDirection::DOWNSTREAM); // Create the DownstreamSession auto session = sessionManager->createSession( std::move(sock), peerAddress, std::move(h2codec), tinfo); // Set HTTP2 priorities flag on session object. session->setHTTP2PrioritiesEnabled(acceptorConfig.HTTP2PrioritiesEnabled); /* if (acceptorConfig.maxConcurrentIncomingStreams) { session->setMaxConcurrentIncomingStreams( acceptorConfig.maxConcurrentIncomingStreams); } */ // TODO: Improve the way max incoming streams is set session->setMaxConcurrentIncomingStreams(100000); // Set flow control parameters. session->setFlowControl( acceptorConfig.initialReceiveWindow, acceptorConfig.receiveStreamWindowSize, acceptorConfig.receiveSessionWindowSize); if (acceptorConfig.writeBufferLimit > 0) { session->setWriteBufferLimit(acceptorConfig.writeBufferLimit); } session->setEgressSettings( {{kChannelSettingId, kMaxSupportedChannelVersion}}); // Route the connection. connectionManager->addConnection(session); session->startNow(); } } // namspace thrift } // namespace apache <|endoftext|>
<commit_before>#include <stdio.h> #include <assert.h> #include <string> #include <GroundBase.hpp> #include "Display.h" #include "GXRenderer.hpp" #include "GXContext.hpp" #include "GXLayer.hpp" #include "GXColor.hpp" class C1 : public GXLayer { public: C1(const std::string &fileImg) : file(fileImg), imgH(-1) {} void paint( GXContext* context , const GXRect& bounds) override { context->beginPath(); //nvgBeginPath(context->_ctx); //static int imgH = -1; if( imgH == -1) { imgH = context->createImage(file , 0);// nvgCreateImage(context->_ctx, file.c_str() , 0); } GXPaint imgPaint = context->imagePattern(GXPointMakeNull(), bounds.size, 0.0f/180.0f*M_PI, imgH, 1.f); //nvgImagePattern(context->_ctx, 0, 0, bounds.size.width , bounds.size.height, 0.0f/180.0f*NVG_PI, imgH, 1.f); context->addRoundedRect(GXRectMake(GXPointMakeNull(), bounds.size), 5); //nvgRoundedRect(context->_ctx, 0,0, bounds.size.width , bounds.size.height, 5); context->setFillPainter( imgPaint); //nvgFillPaint(context->_ctx, imgPaint); context->fill(); //nvgFill(context->_ctx); } const std::string file; int imgH; }; class CWin : public GXLayer { public: CWin() { str = "Test"; background = GXColors::DarkGray; } void paint( GXContext* context , const GXRect& bounds) override { context->beginPath(); //nvgBeginPath( context->_ctx ); context->addRoundedRect(bounds, 5); //nvgRoundedRect(context->_ctx, bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height , 5); //nvgFillColor(context->_ctx, background); context->setFillColor(background); context->fill(); //nvgFill( context->_ctx ); const std::string fontName = "Roboto-Regular.ttf"; int fontHandle = context->createFont(fontName); //nvgCreateFont( context->_ctx, fontName.c_str(), fontName.c_str()); assert( fontHandle != -1); context->setFontId( fontHandle); //nvgFontFaceId( context->_ctx, fontHandle); //nvgFontSize(context->_ctx, 20.f); context->setFontSize(20.f); context->setFillColor( GXColors::Red ); //nvgFillColor(context->_ctx, GXColors::Red); //const std::string &str = "Hello World"; //nvgTextBox(context->_ctx, bounds.origin.x, bounds.origin.y, bounds.size.width-20, str.c_str(), NULL); context->addTextBox(GXPointMake(20, 20), bounds.size.width-20, str); //nvgTextBox(context->_ctx, 20 , 20, bounds.size.width-20, str.c_str(), NULL); //nvgText(context->_ctx , bounds.origin.x, bounds.origin.y , str.c_str() , NULL); } std::string str; }; static CWin* mainWidget = nullptr; static CWin* imgWidget = nullptr; static GXContext* context = nullptr; static GXRenderer* renderer = nullptr; static void renderScreen( GXRenderer *render , Display* disp , GXContext *ctx) { //glClearColor(0.0, 0.0f, 0.0f, 1.0f); //glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT); render->draw( ctx ); DisplaySwap( disp ); //DisplayWaitEvents( disp ); DisplayPollEvents( disp ); } static void eventListener(void* d , const GXEvent *evt) { assert(d); assert(evt); Display* disp =(Display* ) d; assert(disp); switch (evt->type) { case GXEventTypeKey: { const GXEventKey* key = (const GXEventKey*) evt; assert(key); if( key->action == GXKeyAction_Press) { static std::string buf; const char* b = GXKeyGetChar(key); if( b) { if( key->code == GXKey_ENTER) { buf.clear(); } else { buf.push_back(b[0]); } } else if( key->code == GXKey_BACKSPACE) { buf.pop_back();// erase(buf.end()); } else { printf("Unkown char %i \n" , key->code); } printf("'%s'\n" , buf.c_str() ); assert(mainWidget); mainWidget->str = buf; mainWidget->setNeedsDisplay(); renderer->renderLayer( context, mainWidget, 1.f); /* assert(renderer); assert(context); widget->str = buf; renderer->renderLayer( context, widget, 1.f); */ } } break; case GXEventTypeMouse: { const GXEventMouse* mouse = (const GXEventMouse*) evt; printf("Mouse button %i state %i at (%f,%f) \n" , mouse->button , mouse->state , mouse->x , mouse->y); assert(imgWidget); imgWidget->bounds.origin = GXPointMake( mouse->x , mouse->y); break; } default: assert(false); break; } } int main() { GXRenderer render; Display disp; { /**/ if( DisplayInit(&disp) == 0) { printf("Display init error \n"); return -1; } int winWidth, winHeight; int fbWidth, fbHeight; float pxRatio; if (!disp._handle) { return -1; } DisplayMakeContextCurrent( &disp ); DisplayGetWindowSize( &disp, &winWidth, &winHeight); DisplayGetFramebufferSize( &disp , &fbWidth, &fbHeight); DisplaySetEventCallback(&disp, eventListener); // Calculate pixel ration for hi-dpi devices. pxRatio = (float)fbWidth / (float)winWidth; GXContext ctx; #ifdef USE_GLFW assert(DisplayGetType(&disp) == DisplayGLFW); #elif defined USE_DISPMAN assert(DisplayGetType(&disp) == DisplayDispman); #endif /**/ CWin mainLayer; CWin t1;//("images/image1.jpg"); C1 t2("images/image2.jpg"); mainWidget = &mainLayer; imgWidget = &t1; renderer = &render; context = &ctx; mainLayer.bounds = GXRectMake(0, 0, winWidth, winHeight); mainLayer.background = GXColors::LightGray; render.setRoot(&mainLayer); mainLayer.addChild(&t1); //mainLayer.addChild(&t2); t1.background = GXColorMake(0.5, 0.5, 0 , 0.5); t1.bounds.size = GXSizeMake(200, 200); t1.bounds.origin = GXPointMake(40, 10); t2.bounds.size = GXSizeMake(200, 200); t2.bounds.origin = GXPointMake(140, 160); t1.addChild(&t2); /* mainLayer.setNeedsDisplay(); t1.setNeedsDisplay(); t2.setNeedsDisplay(); */ GLint defaultFBO = -1; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); assert(defaultFBO == 0); render.renderLayer(&ctx, &mainLayer, pxRatio); render.renderLayer(&ctx, &t1, pxRatio); render.renderLayer(&ctx, &t2, pxRatio); //GLint defaultFBO = -1; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); assert(defaultFBO == 0); DisplayGetWindowSize( &disp, &winWidth, &winHeight); DisplayGetFramebufferSize(&disp, &fbWidth, &fbHeight); pxRatio = (float)fbWidth / (float)winWidth; glViewport(0, 0, fbWidth, fbHeight); GB::RunLoop runL; /**/ GB::Timer t; t.setInterval(40); t.setCallback([&](GB::Timer &timer) { GLint defaultFBO = -1; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); assert(defaultFBO == 0); renderScreen(&render , &disp , &ctx); if( DisplayShouldClose( &disp )) { runL.stop(); } }); runL.addSource(t); /**/ /* GB::Timer animTime; animTime.setInterval(50); animTime.setCallback([&t2](GB::Timer &timer) { t2.bounds.origin += GXPointMake(10, 10); if( t2.bounds.origin.y > 600) { t2.bounds.origin = GXPointMake(10, 10); } }); runL.addSource(animTime); */ /**/ /* GB::FDSource input(fileno(stdin)); input.notification = [&](GBRunLoopSourceNotification notif) { if( notif == GBRunLoopSourceCanRead) { static char buf[128]; if(input.read(buf, 128)) { printf("Read '%s' \n" , buf); } } }; runL.addSource(input); */ /**/ runL.run(); } DisplayRelease(&disp); return 0; } <commit_msg>Test update<commit_after>#include <stdio.h> #include <assert.h> #include <string> #include <GroundBase.hpp> #include "Display.h" #include "GXRenderer.hpp" #include "GXContext.hpp" #include "GXLayer.hpp" #include "GXColor.hpp" class C1 : public GXLayer { public: C1(const std::string &fileImg) : file(fileImg), imgH(-1) {} void paint( GXContext* context , const GXRect& bounds) override { context->beginPath(); //nvgBeginPath(context->_ctx); //static int imgH = -1; if( imgH == -1) { imgH = context->createImage(file , 0);// nvgCreateImage(context->_ctx, file.c_str() , 0); } GXPaint imgPaint = context->imagePattern(GXPointMakeNull(), bounds.size, 0.0f/180.0f*M_PI, imgH, 1.f); //nvgImagePattern(context->_ctx, 0, 0, bounds.size.width , bounds.size.height, 0.0f/180.0f*NVG_PI, imgH, 1.f); context->addRoundedRect(GXRectMake(GXPointMakeNull(), bounds.size), 5); //nvgRoundedRect(context->_ctx, 0,0, bounds.size.width , bounds.size.height, 5); context->setFillPainter( imgPaint); //nvgFillPaint(context->_ctx, imgPaint); context->fill(); //nvgFill(context->_ctx); } const std::string file; int imgH; }; class CWin : public GXLayer { public: CWin() { str = "Test"; background = GXColors::DarkGray; } void paint( GXContext* context , const GXRect& bounds) override { context->beginPath(); //nvgBeginPath( context->_ctx ); context->addRoundedRect(bounds, 5); //nvgRoundedRect(context->_ctx, bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height , 5); //nvgFillColor(context->_ctx, background); context->setFillColor(background); context->fill(); //nvgFill( context->_ctx ); const std::string fontName = "Roboto-Regular.ttf"; int fontHandle = context->createFont(fontName); //nvgCreateFont( context->_ctx, fontName.c_str(), fontName.c_str()); assert( fontHandle != -1); context->setFontId( fontHandle); //nvgFontFaceId( context->_ctx, fontHandle); //nvgFontSize(context->_ctx, 20.f); context->setFontSize(20.f); context->setFillColor( GXColors::Red ); //nvgFillColor(context->_ctx, GXColors::Red); //const std::string &str = "Hello World"; //nvgTextBox(context->_ctx, bounds.origin.x, bounds.origin.y, bounds.size.width-20, str.c_str(), NULL); context->addTextBox(GXPointMake(20, 20), bounds.size.width-20, str); //nvgTextBox(context->_ctx, 20 , 20, bounds.size.width-20, str.c_str(), NULL); //nvgText(context->_ctx , bounds.origin.x, bounds.origin.y , str.c_str() , NULL); } std::string str; }; static CWin* mainWidget = nullptr; static CWin* imgWidget = nullptr; static GXContext* context = nullptr; static GXRenderer* renderer = nullptr; static void renderScreen( GXRenderer *render , Display* disp , GXContext *ctx) { //glClearColor(0.0, 0.0f, 0.0f, 1.0f); //glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT); render->draw( ctx ); DisplaySwap( disp ); //DisplayWaitEvents( disp ); DisplayPollEvents( disp ); } static void eventListener(void* d , const GXEvent *evt) { assert(d); assert(evt); Display* disp =(Display* ) d; assert(disp); switch (evt->type) { case GXEventTypeKey: { const GXEventKey* key = (const GXEventKey*) evt; assert(key); if( key->action == GXKeyAction_Press) { static std::string buf; const char* b = GXKeyGetChar(key); if( b) { if( key->code == GXKey_ENTER) { buf.clear(); } else { buf.push_back(b[0]); } } else if( key->code == GXKey_BACKSPACE) { buf.pop_back();// erase(buf.end()); } else { printf("Unkown char %i \n" , key->code); } printf("'%s'\n" , buf.c_str() ); assert(mainWidget); mainWidget->str = buf; mainWidget->setNeedsDisplay(); renderer->renderLayer( context, mainWidget, 1.f); /* assert(renderer); assert(context); widget->str = buf; renderer->renderLayer( context, widget, 1.f); */ } } break; case GXEventTypeMouse: { const GXEventMouse* mouse = (const GXEventMouse*) evt; printf("Mouse button %i state %i at (%f,%f) \n" , mouse->button , mouse->state , mouse->x , mouse->y); assert(imgWidget); imgWidget->bounds.origin = GXPointMake( mouse->x , mouse->y); break; } default: assert(false); break; } } int main() { GXRenderer render; Display disp; { /**/ if( DisplayInit(&disp) == 0) { printf("Display init error \n"); return -1; } int winWidth, winHeight; int fbWidth, fbHeight; float pxRatio; if (!disp._handle) { return -1; } DisplayMakeContextCurrent( &disp ); DisplayGetWindowSize( &disp, &winWidth, &winHeight); DisplayGetFramebufferSize( &disp , &fbWidth, &fbHeight); DisplaySetEventCallback(&disp, eventListener); // Calculate pixel ration for hi-dpi devices. pxRatio = (float)fbWidth / (float)winWidth; GXContext ctx; #ifdef USE_GLFW assert(DisplayGetType(&disp) == DisplayGLFW); #elif defined USE_DISPMAN assert(DisplayGetType(&disp) == DisplayDispman); #endif /**/ CWin mainLayer; CWin t1;//("images/image1.jpg"); C1 t2("images/image2.jpg"); mainWidget = &mainLayer; imgWidget = &t1; renderer = &render; context = &ctx; mainLayer.bounds = GXRectMake(0, 0, winWidth, winHeight); mainLayer.background = GXColors::LightGray; render.setRoot(&mainLayer); mainLayer.addChild(&t1); //mainLayer.addChild(&t2); t1.background = GXColorMake(0.5, 0.5, 0 , 0.5); t1.bounds.size = GXSizeMake(200, 200); t1.bounds.origin = GXPointMake(40, 10); t2.bounds.size = GXSizeMake(200, 200); t2.bounds.origin = GXPointMake(140, 160); t1.addChild(&t2); /* mainLayer.setNeedsDisplay(); t1.setNeedsDisplay(); t2.setNeedsDisplay(); */ /* GLint defaultFBO = -1; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); assert(defaultFBO == 0); */ render.renderLayer(&ctx, &mainLayer, pxRatio); render.renderLayer(&ctx, &t1, pxRatio); render.renderLayer(&ctx, &t2, pxRatio); /* //GLint defaultFBO = -1; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); assert(defaultFBO == 0); */ DisplayGetWindowSize( &disp, &winWidth, &winHeight); DisplayGetFramebufferSize(&disp, &fbWidth, &fbHeight); pxRatio = (float)fbWidth / (float)winWidth; glViewport(0, 0, fbWidth, fbHeight); GB::RunLoop runL; /**/ GB::Timer t; t.setInterval(40); t.setCallback([&](GB::Timer &timer) { /* GLint defaultFBO = -1; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); assert(defaultFBO == 0); */ renderScreen(&render , &disp , &ctx); if( DisplayShouldClose( &disp )) { runL.stop(); } }); runL.addSource(t); /**/ /* GB::Timer animTime; animTime.setInterval(50); animTime.setCallback([&t2](GB::Timer &timer) { t2.bounds.origin += GXPointMake(10, 10); if( t2.bounds.origin.y > 600) { t2.bounds.origin = GXPointMake(10, 10); } }); runL.addSource(animTime); */ /**/ /* GB::FDSource input(fileno(stdin)); input.notification = [&](GBRunLoopSourceNotification notif) { if( notif == GBRunLoopSourceCanRead) { static char buf[128]; if(input.read(buf, 128)) { printf("Read '%s' \n" , buf); } } }; runL.addSource(input); */ /**/ runL.run(); } DisplayRelease(&disp); return 0; } <|endoftext|>
<commit_before> /* * Copyright (c) 2012 Karl N. Redgate * * 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. */ /** \file UUID_Module.cc * \brief * */ #include <stdlib.h> #include <tcl.h> #include "tcl_util.h" #include "logger.h" #include "xuid.h" #include "UUID.h" #include "AppInit.h" namespace { int debug = 0; } /** */ static int UUID_obj( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { UUID *uuid = (UUID *)data; if ( objc == 1 ) { Tcl_SetObjResult( interp, Tcl_NewLongObj((long)(uuid)) ); return TCL_OK; } char *command = Tcl_GetStringFromObj( objv[1], NULL ); if ( Tcl_StringMatch(command, "type") ) { Svc_SetResult( interp, "UUID", TCL_STATIC ); return TCL_OK; } if ( Tcl_StringMatch(command, "data") ) { Tcl_Obj *obj = Tcl_NewByteArrayObj( uuid->raw(), 16 ); Tcl_SetObjResult( interp, obj ); return TCL_OK; } if ( Tcl_StringMatch(command, "string") ) { Tcl_Obj *obj = Tcl_NewStringObj( uuid->to_s(), -1 ); Tcl_SetObjResult( interp, obj ); return TCL_OK; } if ( Tcl_StringMatch(command, "set") ) { if ( objc < 3 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "set value" ); return TCL_ERROR; } char *uuid_string = Tcl_GetStringFromObj( objv[2], NULL ); uuid->set( uuid_string ); Tcl_Obj *obj = Tcl_NewStringObj( uuid->to_s(), -1 ); Tcl_SetObjResult( interp, obj ); return TCL_OK; } uint8_t *x = uuid->raw(); if ( Tcl_StringMatch(command, "dump") ) { printf( "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n", x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15] ); Tcl_ResetResult( interp ); return TCL_OK; } Svc_SetResult( interp, "Unknown command for UUID object", TCL_STATIC ); return TCL_ERROR; } /** */ static void UUID_delete( ClientData data ) { UUID *uuid = (UUID *)data; delete uuid; } /** */ static int UUID_cmd( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { if ( objc < 2 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "name [value]" ); return TCL_ERROR; } char *name = Tcl_GetStringFromObj( objv[1], NULL ); if ( objc == 2 ) { UUID *object = new UUID(); Tcl_CreateObjCommand( interp, name, UUID_obj, (ClientData)object, UUID_delete ); Svc_SetResult( interp, name, TCL_VOLATILE ); return TCL_OK; } if ( objc != 3 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "name value" ); return TCL_ERROR; } char *uuid_string = Tcl_GetStringFromObj( objv[2], NULL ); UUID *object = new UUID( uuid_string ); Tcl_CreateObjCommand( interp, name, UUID_obj, (ClientData)object, UUID_delete ); Svc_SetResult( interp, name, TCL_VOLATILE ); return TCL_OK; } /** */ static int guid_obj( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { guid_t *guid = (guid_t *)data; char buffer[36]; if ( objc == 1 ) { Tcl_SetObjResult( interp, Tcl_NewLongObj((long)(guid)) ); return TCL_OK; } char *command = Tcl_GetStringFromObj( objv[1], NULL ); if ( Tcl_StringMatch(command, "type") ) { Svc_SetResult( interp, "UUID", TCL_STATIC ); return TCL_OK; } #if 0 if ( Tcl_StringMatch(command, "data") ) { Tcl_Obj *obj = Tcl_NewByteArrayObj( uuid->raw(), 16 ); Tcl_SetObjResult( interp, obj ); return TCL_OK; } #endif if ( Tcl_StringMatch(command, "string") ) { format_guid( buffer, guid ); Tcl_Obj *obj = Tcl_NewStringObj( buffer, 36 ); Tcl_SetObjResult( interp, obj ); return TCL_OK; } if ( Tcl_StringMatch(command, "set") ) { if ( objc < 3 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "set value" ); return TCL_ERROR; } char *guid_string = Tcl_GetStringFromObj( objv[2], NULL ); parse_guid( guid_string, guid ); format_guid( buffer, guid ); Tcl_Obj *obj = Tcl_NewStringObj( buffer, 36 ); Tcl_SetObjResult( interp, obj ); return TCL_OK; } #if 0 uint8_t *x = uuid->raw(); if ( Tcl_StringMatch(command, "dump") ) { printf( "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n", x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15] ); Tcl_ResetResult( interp ); return TCL_OK; } #endif Svc_SetResult( interp, "Unknown command for UUID object", TCL_STATIC ); return TCL_ERROR; } /** */ static void guid_delete( ClientData data ) { guid_t *guid = (guid_t *)data; free( guid ); } /** */ static int guid_cmd( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { if ( objc < 2 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "name [value]" ); return TCL_ERROR; } char *name = Tcl_GetStringFromObj( objv[1], NULL ); if ( objc == 2 ) { guid_t *object = (guid_t *)malloc( sizeof(guid_t) ); Tcl_CreateObjCommand( interp, name, guid_obj, (ClientData)object, guid_delete ); Svc_SetResult( interp, name, TCL_VOLATILE ); return TCL_OK; } if ( objc != 3 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "name value" ); return TCL_ERROR; } char *guid_string = Tcl_GetStringFromObj( objv[2], NULL ); guid_t *object = (guid_t *)malloc( sizeof(guid_t) ); Tcl_CreateObjCommand( interp, name, guid_obj, (ClientData)object, guid_delete ); Svc_SetResult( interp, name, TCL_VOLATILE ); return TCL_OK; } /** */ static bool UUID_Module( Tcl_Interp *interp ) { Tcl_Command command; Tcl_Namespace *ns = Tcl_CreateNamespace(interp, "UUID", (ClientData)0, NULL); if ( ns == NULL ) { return false; } if ( Tcl_LinkVar(interp, "UUID::debug", (char *)&debug, TCL_LINK_INT) != TCL_OK ) { log_err( "failed to link ICMPv6::debug" ); exit( 1 ); } command = Tcl_CreateObjCommand(interp, "UUID", UUID_cmd, (ClientData)0, NULL); if ( command == NULL ) { return false; } return true; } app_init( UUID_Module ); /* vim: set autoindent expandtab sw=4 syntax=c : */ <commit_msg>connect guid cmds to interp<commit_after> /* * Copyright (c) 2012 Karl N. Redgate * * 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. */ /** \file UUID_Module.cc * \brief * */ #include <stdlib.h> #include <tcl.h> #include "tcl_util.h" #include "logger.h" #include "xuid.h" #include "UUID.h" #include "AppInit.h" namespace { int debug = 0; } /** */ static int UUID_obj( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { UUID *uuid = (UUID *)data; if ( objc == 1 ) { Tcl_SetObjResult( interp, Tcl_NewLongObj((long)(uuid)) ); return TCL_OK; } char *command = Tcl_GetStringFromObj( objv[1], NULL ); if ( Tcl_StringMatch(command, "type") ) { Svc_SetResult( interp, "UUID", TCL_STATIC ); return TCL_OK; } if ( Tcl_StringMatch(command, "data") ) { Tcl_Obj *obj = Tcl_NewByteArrayObj( uuid->raw(), 16 ); Tcl_SetObjResult( interp, obj ); return TCL_OK; } if ( Tcl_StringMatch(command, "string") ) { Tcl_Obj *obj = Tcl_NewStringObj( uuid->to_s(), -1 ); Tcl_SetObjResult( interp, obj ); return TCL_OK; } if ( Tcl_StringMatch(command, "set") ) { if ( objc < 3 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "set value" ); return TCL_ERROR; } char *uuid_string = Tcl_GetStringFromObj( objv[2], NULL ); uuid->set( uuid_string ); Tcl_Obj *obj = Tcl_NewStringObj( uuid->to_s(), -1 ); Tcl_SetObjResult( interp, obj ); return TCL_OK; } uint8_t *x = uuid->raw(); if ( Tcl_StringMatch(command, "dump") ) { printf( "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n", x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15] ); Tcl_ResetResult( interp ); return TCL_OK; } Svc_SetResult( interp, "Unknown command for UUID object", TCL_STATIC ); return TCL_ERROR; } /** */ static void UUID_delete( ClientData data ) { UUID *uuid = (UUID *)data; delete uuid; } /** */ static int UUID_cmd( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { if ( objc < 2 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "name [value]" ); return TCL_ERROR; } char *name = Tcl_GetStringFromObj( objv[1], NULL ); if ( objc == 2 ) { UUID *object = new UUID(); Tcl_CreateObjCommand( interp, name, UUID_obj, (ClientData)object, UUID_delete ); Svc_SetResult( interp, name, TCL_VOLATILE ); return TCL_OK; } if ( objc != 3 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "name value" ); return TCL_ERROR; } char *uuid_string = Tcl_GetStringFromObj( objv[2], NULL ); UUID *object = new UUID( uuid_string ); Tcl_CreateObjCommand( interp, name, UUID_obj, (ClientData)object, UUID_delete ); Svc_SetResult( interp, name, TCL_VOLATILE ); return TCL_OK; } /** */ static int guid_obj( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { guid_t *guid = (guid_t *)data; char buffer[36]; if ( objc == 1 ) { Tcl_SetObjResult( interp, Tcl_NewLongObj((long)(guid)) ); return TCL_OK; } char *command = Tcl_GetStringFromObj( objv[1], NULL ); if ( Tcl_StringMatch(command, "type") ) { Svc_SetResult( interp, "UUID", TCL_STATIC ); return TCL_OK; } #if 0 if ( Tcl_StringMatch(command, "data") ) { Tcl_Obj *obj = Tcl_NewByteArrayObj( uuid->raw(), 16 ); Tcl_SetObjResult( interp, obj ); return TCL_OK; } #endif if ( Tcl_StringMatch(command, "string") ) { format_guid( buffer, guid ); Tcl_Obj *obj = Tcl_NewStringObj( buffer, 36 ); Tcl_SetObjResult( interp, obj ); return TCL_OK; } if ( Tcl_StringMatch(command, "set") ) { if ( objc < 3 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "set value" ); return TCL_ERROR; } char *guid_string = Tcl_GetStringFromObj( objv[2], NULL ); parse_guid( guid_string, guid ); format_guid( buffer, guid ); Tcl_Obj *obj = Tcl_NewStringObj( buffer, 36 ); Tcl_SetObjResult( interp, obj ); return TCL_OK; } #if 0 uint8_t *x = uuid->raw(); if ( Tcl_StringMatch(command, "dump") ) { printf( "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n", x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15] ); Tcl_ResetResult( interp ); return TCL_OK; } #endif Svc_SetResult( interp, "Unknown command for UUID object", TCL_STATIC ); return TCL_ERROR; } /** */ static void guid_delete( ClientData data ) { guid_t *guid = (guid_t *)data; free( guid ); } /** */ static int guid_cmd( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { if ( objc < 2 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "name [value]" ); return TCL_ERROR; } char *name = Tcl_GetStringFromObj( objv[1], NULL ); if ( objc == 2 ) { guid_t *object = (guid_t *)malloc( sizeof(guid_t) ); Tcl_CreateObjCommand( interp, name, guid_obj, (ClientData)object, guid_delete ); Svc_SetResult( interp, name, TCL_VOLATILE ); return TCL_OK; } if ( objc != 3 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "name value" ); return TCL_ERROR; } char *guid_string = Tcl_GetStringFromObj( objv[2], NULL ); guid_t *object = (guid_t *)malloc( sizeof(guid_t) ); Tcl_CreateObjCommand( interp, name, guid_obj, (ClientData)object, guid_delete ); Svc_SetResult( interp, name, TCL_VOLATILE ); return TCL_OK; } /** */ static bool UUID_Module( Tcl_Interp *interp ) { Tcl_Command command; Tcl_Namespace *ns = Tcl_CreateNamespace(interp, "UUID", (ClientData)0, NULL); if ( ns == NULL ) { return false; } if ( Tcl_LinkVar(interp, "UUID::debug", (char *)&debug, TCL_LINK_INT) != TCL_OK ) { log_err( "failed to link ICMPv6::debug" ); exit( 1 ); } command = Tcl_CreateObjCommand(interp, "UUID::UUID", UUID_cmd, (ClientData)0, NULL); if ( command == NULL ) { return false; } command = Tcl_CreateObjCommand(interp, "UUID::guid", guid_cmd, (ClientData)0, NULL); if ( command == NULL ) { // logger ?? want to report TCL Error return false; } return true; } app_init( UUID_Module ); /* vim: set autoindent expandtab sw=4 syntax=c : */ <|endoftext|>
<commit_before>/**@file Module for managing Linux signals and allowing multiple handlers per signal. */ /* * Copyright 2014 Range Networks, Inc. * * This software is distributed under the terms of the GNU Affero Public License. * See the COPYING file in the main directory for details. * * This use of this software may be subject to additional restrictions. * See the LEGAL file in the main directory for details. 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 <cstdio> #include <cstring> #include <cerrno> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "coredumper.h" #include "UnixSignal.h" #include "Logger.h" //UnixSignal gSigVec; static void _sigHandler(int sig) { signal(sig, SIG_IGN); if (sig <= 0 || sig >= UnixSignal::C_NSIG) { LOG(ERR) << "Signal Handler for signal " << sig << " (out of range)"; return; } // work around C++ issue with function pointers and class based function pointers gSigVec.Handler(sig); signal(sig, SIG_DFL); printf("Rethrowing signal %d\n", sig); kill(getpid(), sig); } void UnixSignal::Handler(int sig) { // Only write core files for the signals that need core switch(sig) { case SIGQUIT: case SIGILL: case SIGABRT: case SIGFPE: case SIGSEGV: case SIGBUS: case SIGSYS: case SIGTRAP: case SIGXCPU: case SIGXFSZ: { char buf[BUFSIZ]; if (mAddPid) snprintf(buf, sizeof(buf)-1, "%s.%d", mCoreFile.c_str(), getpid()); else snprintf(buf, sizeof(buf)-1, "%s", mCoreFile.c_str()); WriteCoreDump(buf); // and save the files if needed if (mSaveFiles) { char buf[BUFSIZ]; std::string s; std::string p; sprintf(buf, "%d", getpid()); p = buf; s = "rm -rf /tmp/staging." ; s += p; s += "/ ; "; s += "mkdir /tmp/staging." ; s += p; s += "/ ; "; s += "cp --parents /etc/issue /tmp/staging." ; s += p; s += "/ ; "; s += "cp --parents /proc/cpuinfo /proc/interrupts /proc/iomem /proc/ioports /proc/diskstats /proc/loadavg /proc/locks /proc/meminfo /proc/softirqs /proc/stat /proc/uptime /proc/version /proc/version_signature /proc/vmstat /tmp/staging." ; s += p; s += "/ ; "; s += "for i in cmdline cpuset environ io limits maps net/tcp net/udp net/tcp6 net/udp6 net/unix net/netstat sched schedstat smaps stat statm status ; "; s += "do cp --parents /proc/" ; s += p; s += "/$i /tmp/staging." ; s += p; s += "/ ; "; s += "cp --parents /proc/"; s += p; s += "/task/*/stat* /tmp/staging."; s += p; s += "/ ; "; s += "done ; "; s += "tar --create --verbose --file=- --directory=/proc/"; s += p; s += " fd | ( cd /tmp/staging."; s += p; s += "/proc/"; s += p; s += "/ ; tar xpvf - ) ; "; s += "tar --create --verbose --file=- --directory=/tmp/staging."; s += p; s += "/ . | gzip > "; s += mTarFile; s += " ; "; s += "rm -rf /tmp/staging." ; s += p; printf("Running '%s'\n", s.c_str()); system(s.c_str()); } } break; default: break; } printf("Processing signal vector for sig %d\n", sig); mLock[sig].lock(); for (std::list<sighandler_t>::iterator i = mListHandlers[sig].begin(); i != mListHandlers[sig].end(); i++) { (*i)(sig); } mLock[sig].unlock(); printf("Done processing signal vector for sig %d\n", sig); } UnixSignal::UnixSignal(void) { for (int i = 0; i < C_NSIG; i++) { mListHandlers[i].clear(); //signal(i, _sigHandler); } mAddPid = false; mCoreFile = "core"; } UnixSignal::~UnixSignal(void) { for (int i = 0; i < C_NSIG; i++) { mListHandlers[i].clear(); signal(i, SIG_DFL); } } void UnixSignal::Register(sighandler_t handler, int sig) // register the handler to the signal { if (sig <= 0 || sig >= C_NSIG) { LOG(ERR) << "Unable to register callback for UnixSignal " << sig << " (out of range)"; return; } mLock[sig].lock(); signal(sig, _sigHandler); // only catch signals that have been registered mListHandlers[sig].insert(mListHandlers[sig].end(), handler); mLock[sig].unlock(); } void UnixSignal::Dump(void) { for (int sig = 0; sig < C_NSIG; sig++) { mLock[sig].lock(); if (mListHandlers[sig].size() != 0) { printf("Signal vectors for signal %d: ", sig); for (std::list<sighandler_t>::iterator i = mListHandlers[sig].begin(); i != mListHandlers[sig].end(); i++) { printf("%s0x%p", i == mListHandlers[sig].begin() ? "" : ", ", *i); } printf("\n"); } mLock[sig].unlock(); } } <commit_msg>- remove need for 3rdParty include reference, libcoredump now can be built-from-scratch and installed as lib and -dev headers<commit_after>/**@file Module for managing Linux signals and allowing multiple handlers per signal. */ /* * Copyright 2014 Range Networks, Inc. * * This software is distributed under the terms of the GNU Affero Public License. * See the COPYING file in the main directory for details. * * This use of this software may be subject to additional restrictions. * See the LEGAL file in the main directory for details. 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 <cstdio> #include <cstring> #include <cerrno> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <google/coredumper.h> #include "UnixSignal.h" #include "Logger.h" //UnixSignal gSigVec; static void _sigHandler(int sig) { signal(sig, SIG_IGN); if (sig <= 0 || sig >= UnixSignal::C_NSIG) { LOG(ERR) << "Signal Handler for signal " << sig << " (out of range)"; return; } // work around C++ issue with function pointers and class based function pointers gSigVec.Handler(sig); signal(sig, SIG_DFL); printf("Rethrowing signal %d\n", sig); kill(getpid(), sig); } void UnixSignal::Handler(int sig) { // Only write core files for the signals that need core switch(sig) { case SIGQUIT: case SIGILL: case SIGABRT: case SIGFPE: case SIGSEGV: case SIGBUS: case SIGSYS: case SIGTRAP: case SIGXCPU: case SIGXFSZ: { char buf[BUFSIZ]; if (mAddPid) snprintf(buf, sizeof(buf)-1, "%s.%d", mCoreFile.c_str(), getpid()); else snprintf(buf, sizeof(buf)-1, "%s", mCoreFile.c_str()); WriteCoreDump(buf); // and save the files if needed if (mSaveFiles) { char buf[BUFSIZ]; std::string s; std::string p; sprintf(buf, "%d", getpid()); p = buf; s = "rm -rf /tmp/staging." ; s += p; s += "/ ; "; s += "mkdir /tmp/staging." ; s += p; s += "/ ; "; s += "cp --parents /etc/issue /tmp/staging." ; s += p; s += "/ ; "; s += "cp --parents /proc/cpuinfo /proc/interrupts /proc/iomem /proc/ioports /proc/diskstats /proc/loadavg /proc/locks /proc/meminfo /proc/softirqs /proc/stat /proc/uptime /proc/version /proc/version_signature /proc/vmstat /tmp/staging." ; s += p; s += "/ ; "; s += "for i in cmdline cpuset environ io limits maps net/tcp net/udp net/tcp6 net/udp6 net/unix net/netstat sched schedstat smaps stat statm status ; "; s += "do cp --parents /proc/" ; s += p; s += "/$i /tmp/staging." ; s += p; s += "/ ; "; s += "cp --parents /proc/"; s += p; s += "/task/*/stat* /tmp/staging."; s += p; s += "/ ; "; s += "done ; "; s += "tar --create --verbose --file=- --directory=/proc/"; s += p; s += " fd | ( cd /tmp/staging."; s += p; s += "/proc/"; s += p; s += "/ ; tar xpvf - ) ; "; s += "tar --create --verbose --file=- --directory=/tmp/staging."; s += p; s += "/ . | gzip > "; s += mTarFile; s += " ; "; s += "rm -rf /tmp/staging." ; s += p; printf("Running '%s'\n", s.c_str()); system(s.c_str()); } } break; default: break; } printf("Processing signal vector for sig %d\n", sig); mLock[sig].lock(); for (std::list<sighandler_t>::iterator i = mListHandlers[sig].begin(); i != mListHandlers[sig].end(); i++) { (*i)(sig); } mLock[sig].unlock(); printf("Done processing signal vector for sig %d\n", sig); } UnixSignal::UnixSignal(void) { for (int i = 0; i < C_NSIG; i++) { mListHandlers[i].clear(); //signal(i, _sigHandler); } mAddPid = false; mCoreFile = "core"; } UnixSignal::~UnixSignal(void) { for (int i = 0; i < C_NSIG; i++) { mListHandlers[i].clear(); signal(i, SIG_DFL); } } void UnixSignal::Register(sighandler_t handler, int sig) // register the handler to the signal { if (sig <= 0 || sig >= C_NSIG) { LOG(ERR) << "Unable to register callback for UnixSignal " << sig << " (out of range)"; return; } mLock[sig].lock(); signal(sig, _sigHandler); // only catch signals that have been registered mListHandlers[sig].insert(mListHandlers[sig].end(), handler); mLock[sig].unlock(); } void UnixSignal::Dump(void) { for (int sig = 0; sig < C_NSIG; sig++) { mLock[sig].lock(); if (mListHandlers[sig].size() != 0) { printf("Signal vectors for signal %d: ", sig); for (std::list<sighandler_t>::iterator i = mListHandlers[sig].begin(); i != mListHandlers[sig].end(); i++) { printf("%s0x%p", i == mListHandlers[sig].begin() ? "" : ", ", *i); } printf("\n"); } mLock[sig].unlock(); } } <|endoftext|>
<commit_before>#include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include "Plane.h" #include "Shader.h" #include "Texture.h" #include "GameTime.h" #pragma region Variables GLFWwindow* window; GameTime gameTime; GLuint shader; GLuint shader2; GLuint waterTex; GLuint tex; Plane* plane; Plane* plane2; Camera cam; glm::vec2 mousePosLast; #pragma endregion #pragma region Function Headers void setupWindowAndContext(); void update(); void render(); #pragma endregion int main() { setupWindowAndContext(); glClearColor(100/255.0f, 149/255.0f, 237/255.0f, 1.0f); shader = loadShader("vertex.glsl", "fragment.phong.glsl"); shader2 = loadShader("vertex.glsl", "fragment.glsl"); plane = new Plane(); plane2 = new Plane(); cam.position = glm::vec3(3, 5, 3); //cam.direction = glm::vec3(1, 1, 0); cam.light = glm::vec3(0.0f, 0.0f, 0.0f); waterTex = loadTexture("water3.jpg"); //waterTex = loadTexture("18_vertex_texture_02.jpg"); plane->texture=waterTex; tex = loadTexture("rubber_duck-1331px.png"); tex = loadTexture("pebbles2.jpg"); //tex = loadTexture("magic.jpg"); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, tex); glActiveTexture(GL_TEXTURE0); plane2->texture = tex; while(!glfwWindowShouldClose(window)) { update(); render(); } return 0; } void setupWindowAndContext() { if(!glfwInit()) { std::cout << "GLFW Failed to Initialize!" << std::endl; exit(EXIT_FAILURE); } glfwWindowHint(GLFW_DECORATED, GL_FALSE); glfwWindowHint(GLFW_VISIBLE, GL_FALSE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow(WIN_WIDTH, WIN_HEIGHT, "OpenGL Water Demo", NULL, NULL); glfwShowWindow(window); glfwMakeContextCurrent(window); glewExperimental = true; if(glewInit() != GLEW_OK) { std::cout << "Glew Failed to Initialize!" << std::endl; exit(EXIT_FAILURE); } glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } void update() { gameTime.Update(); //cam.position -= glm::vec3(0.5f,1.0f,0) * gameTime.GetDeltaTimeSecondsF(); cam.light -= glm::vec3(0.1f,0.2f,0) * gameTime.GetDeltaTimeSecondsF(); cam.UpdateRotation(window, 20.0f * gameTime.GetDeltaTimeSecondsF()); //Camera Rotations double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); //cam.Rotation(-(xpos-mousePosLast.x), glm::vec3(0, 1, 0)); //cam.Rotation((ypos-mousePosLast.y), glm::vec3(1, 0, 0)); mousePosLast = glm::vec2(xpos, ypos); //Camera Translations glm::vec3 vel; if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { vel += glm::vec3(-1, 0, 0); } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { vel += glm::vec3(1, 0, 0); } if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { vel += glm::vec3(0, 0, 1); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { vel += glm::vec3(0, 0, -1); } if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) { shader = loadShader("vertex.glsl", "fragment.phong.glsl"); } vel *= gameTime.GetDeltaTimeSecondsF(); cam.Translate(vel); glfwPollEvents(); } void render() { glClear(GL_COLOR_BUFFER_BIT); //plane2->Draw(shader2, cam); plane->Draw(shader, cam); glfwSwapBuffers(window); } <commit_msg>Set default camera rotation<commit_after>#include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include "Plane.h" #include "Shader.h" #include "Texture.h" #include "GameTime.h" #pragma region Variables GLFWwindow* window; GameTime gameTime; GLuint shader; GLuint shader2; GLuint waterTex; GLuint tex; Plane* plane; Plane* plane2; Camera cam; glm::vec2 mousePosLast; #pragma endregion #pragma region Function Headers void setupWindowAndContext(); void update(); void render(); #pragma endregion int main() { setupWindowAndContext(); glClearColor(100/255.0f, 149/255.0f, 237/255.0f, 1.0f); shader = loadShader("vertex.glsl", "fragment.phong.glsl"); shader2 = loadShader("vertex.glsl", "fragment.glsl"); plane = new Plane(); plane2 = new Plane(); cam.position = glm::vec3(3, 5, 3); //cam.direction = glm::vec3(1, 1, 0); cam.light = glm::vec3(0.0f, 0.0f, 0.0f); waterTex = loadTexture("water3.jpg"); //waterTex = loadTexture("18_vertex_texture_02.jpg"); plane->texture=waterTex; tex = loadTexture("rubber_duck-1331px.png"); tex = loadTexture("pebbles2.jpg"); //tex = loadTexture("magic.jpg"); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, tex); glActiveTexture(GL_TEXTURE0); plane2->texture = tex; cam.rotation = glm::vec3(-173, -142, 0); while(!glfwWindowShouldClose(window)) { update(); render(); } return 0; } void setupWindowAndContext() { if(!glfwInit()) { std::cout << "GLFW Failed to Initialize!" << std::endl; exit(EXIT_FAILURE); } glfwWindowHint(GLFW_DECORATED, GL_FALSE); glfwWindowHint(GLFW_VISIBLE, GL_FALSE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow(WIN_WIDTH, WIN_HEIGHT, "OpenGL Water Demo", NULL, NULL); glfwShowWindow(window); glfwMakeContextCurrent(window); glewExperimental = true; if(glewInit() != GLEW_OK) { std::cout << "Glew Failed to Initialize!" << std::endl; exit(EXIT_FAILURE); } glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } void update() { gameTime.Update(); //cam.position -= glm::vec3(0.5f,1.0f,0) * gameTime.GetDeltaTimeSecondsF(); cam.light -= glm::vec3(0.1f,0.2f,0) * gameTime.GetDeltaTimeSecondsF(); cam.UpdateRotation(window, 20.0f * gameTime.GetDeltaTimeSecondsF()); //Camera Rotations double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); //cam.Rotation(-(xpos-mousePosLast.x), glm::vec3(0, 1, 0)); //cam.Rotation((ypos-mousePosLast.y), glm::vec3(1, 0, 0)); mousePosLast = glm::vec2(xpos, ypos); //Camera Translations glm::vec3 vel; if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { vel += glm::vec3(-1, 0, 0); } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { vel += glm::vec3(1, 0, 0); } if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { vel += glm::vec3(0, 0, 1); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { vel += glm::vec3(0, 0, -1); } if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) { shader = loadShader("vertex.glsl", "fragment.phong.glsl"); } vel *= gameTime.GetDeltaTimeSecondsF(); cam.Translate(vel); glfwPollEvents(); } void render() { glClear(GL_COLOR_BUFFER_BIT); //plane2->Draw(shader2, cam); plane->Draw(shader, cam); glfwSwapBuffers(window); } <|endoftext|>
<commit_before>// The MIT License (MIT) // // Copyright (c) 2015 Sergey Makeev, Vadim Slyusarev // // 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 <MTScheduler.h> namespace MT { FiberContext::FiberContext() : threadContext(nullptr) , taskStatus(FiberTaskStatus::UNKNOWN) , childrenFibersCount(0) , parentFiber(nullptr) , stackRequirements(StackRequirements::INVALID) { } void FiberContext::SetStatus(FiberTaskStatus::Type _taskStatus) { MT_ASSERT(threadContext, "Sanity check failed"); MT_ASSERT(threadContext->thread.IsCurrentThread(), "You can change task status only from owner thread"); taskStatus = _taskStatus; } FiberTaskStatus::Type FiberContext::GetStatus() const { return taskStatus; } void FiberContext::SetThreadContext(internal::ThreadContext * _threadContext) { if (_threadContext) { _threadContext->lastActiveFiberContext = this; } threadContext = _threadContext; } internal::ThreadContext* FiberContext::GetThreadContext() { return threadContext; } void FiberContext::Reset() { MT_ASSERT(childrenFibersCount.Load() == 0, "Can't release fiber with active children fibers"); currentTask = internal::TaskDesc(); parentFiber = nullptr; threadContext = nullptr; stackRequirements = StackRequirements::INVALID; } void FiberContext::WaitGroupAndYield(TaskGroup group) { MT_ASSERT(threadContext, "Sanity check failed!"); MT_ASSERT(threadContext->taskScheduler, "Sanity check failed!"); MT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), "Can't use WaitGroupAndYield outside Task. Use TaskScheduler.WaitGroup() instead."); MT_ASSERT(threadContext->thread.IsCurrentThread(), "Thread context sanity check failed"); MT_VERIFY(group != currentGroup, "Can't wait the same group. Deadlock detected!", return); MT_VERIFY(group.IsValid(), "Invalid group!", return); TaskScheduler::TaskGroupDescription & groupDesc = threadContext->taskScheduler->GetGroupDesc(group); ConcurrentQueueLIFO<FiberContext*> & groupQueue = groupDesc.GetWaitQueue(); // Change status taskStatus = FiberTaskStatus::AWAITING_GROUP; // Add current fiber to awaiting queue groupQueue.Push(this); Fiber & schedulerFiber = threadContext->schedulerFiber; #ifdef MT_INSTRUMENTED_BUILD threadContext->NotifyTaskYielded(currentTask); #endif // Yielding, so reset thread context threadContext = nullptr; //switch to scheduler Fiber::SwitchTo(fiber, schedulerFiber); } void FiberContext::RunSubtasksAndYieldImpl(ArrayView<internal::TaskBucket>& buckets) { MT_ASSERT(threadContext, "Sanity check failed!"); MT_ASSERT(threadContext->taskScheduler, "Sanity check failed!"); MT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), "Can't use RunSubtasksAndYield outside Task. Use TaskScheduler.WaitGroup() instead."); MT_ASSERT(threadContext->thread.IsCurrentThread(), "Thread context sanity check failed"); // add to scheduler threadContext->taskScheduler->RunTasksImpl(buckets, this, false); // MT_ASSERT(threadContext->thread.IsCurrentThread(), "Thread context sanity check failed"); // Change status taskStatus = FiberTaskStatus::AWAITING_CHILD; Fiber & schedulerFiber = threadContext->schedulerFiber; #ifdef MT_INSTRUMENTED_BUILD threadContext->NotifyTaskYielded(currentTask); #endif // Yielding, so reset thread context threadContext = nullptr; //switch to scheduler Fiber::SwitchTo(fiber, schedulerFiber); } void FiberContext::RunAsync(TaskGroup taskGroup, const TaskHandle* taskHandleArray, uint32 taskHandleCount) { MT_ASSERT(threadContext, "ThreadContext is nullptr"); MT_ASSERT(threadContext->taskScheduler, "Sanity check failed!"); MT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), "Can't use RunAsync outside Task. Use TaskScheduler.RunAsync() instead."); TaskScheduler& scheduler = *(threadContext->taskScheduler); ArrayView<internal::GroupedTask> buffer(threadContext->descBuffer, taskHandleCount); uint32 bucketCount = MT::Min((uint32)scheduler.GetWorkersCount(), taskHandleCount); ArrayView<internal::TaskBucket> buckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount); internal::DistibuteDescriptions(taskGroup, taskHandleArray, buffer, buckets); scheduler.RunTasksImpl(buckets, nullptr, false); } void FiberContext::RunSubtasksAndYield(TaskGroup taskGroup, const TaskHandle* taskHandleArray, uint32 taskHandleCount) { MT_ASSERT(threadContext, "ThreadContext is nullptr"); MT_ASSERT(threadContext->taskScheduler, "TaskScheduler is nullptr"); MT_ASSERT(taskHandleCount < internal::TASK_BUFFER_CAPACITY, "Buffer overrun!"); TaskScheduler& scheduler = *(threadContext->taskScheduler); ArrayView<internal::GroupedTask> buffer(threadContext->descBuffer, taskHandleCount); uint32 bucketCount = MT::Min((uint32)scheduler.GetWorkersCount(), taskHandleCount); ArrayView<internal::TaskBucket> buckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount); internal::DistibuteDescriptions(taskGroup, taskHandleArray, buffer, buckets); RunSubtasksAndYieldImpl(buckets); } } <commit_msg>fixed field initialization warning<commit_after>// The MIT License (MIT) // // Copyright (c) 2015 Sergey Makeev, Vadim Slyusarev // // 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 <MTScheduler.h> namespace MT { FiberContext::FiberContext() : threadContext(nullptr) , taskStatus(FiberTaskStatus::UNKNOWN) , stackRequirements(StackRequirements::INVALID) , childrenFibersCount(0) , parentFiber(nullptr) { } void FiberContext::SetStatus(FiberTaskStatus::Type _taskStatus) { MT_ASSERT(threadContext, "Sanity check failed"); MT_ASSERT(threadContext->thread.IsCurrentThread(), "You can change task status only from owner thread"); taskStatus = _taskStatus; } FiberTaskStatus::Type FiberContext::GetStatus() const { return taskStatus; } void FiberContext::SetThreadContext(internal::ThreadContext * _threadContext) { if (_threadContext) { _threadContext->lastActiveFiberContext = this; } threadContext = _threadContext; } internal::ThreadContext* FiberContext::GetThreadContext() { return threadContext; } void FiberContext::Reset() { MT_ASSERT(childrenFibersCount.Load() == 0, "Can't release fiber with active children fibers"); currentTask = internal::TaskDesc(); parentFiber = nullptr; threadContext = nullptr; stackRequirements = StackRequirements::INVALID; } void FiberContext::WaitGroupAndYield(TaskGroup group) { MT_ASSERT(threadContext, "Sanity check failed!"); MT_ASSERT(threadContext->taskScheduler, "Sanity check failed!"); MT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), "Can't use WaitGroupAndYield outside Task. Use TaskScheduler.WaitGroup() instead."); MT_ASSERT(threadContext->thread.IsCurrentThread(), "Thread context sanity check failed"); MT_VERIFY(group != currentGroup, "Can't wait the same group. Deadlock detected!", return); MT_VERIFY(group.IsValid(), "Invalid group!", return); TaskScheduler::TaskGroupDescription & groupDesc = threadContext->taskScheduler->GetGroupDesc(group); ConcurrentQueueLIFO<FiberContext*> & groupQueue = groupDesc.GetWaitQueue(); // Change status taskStatus = FiberTaskStatus::AWAITING_GROUP; // Add current fiber to awaiting queue groupQueue.Push(this); Fiber & schedulerFiber = threadContext->schedulerFiber; #ifdef MT_INSTRUMENTED_BUILD threadContext->NotifyTaskYielded(currentTask); #endif // Yielding, so reset thread context threadContext = nullptr; //switch to scheduler Fiber::SwitchTo(fiber, schedulerFiber); } void FiberContext::RunSubtasksAndYieldImpl(ArrayView<internal::TaskBucket>& buckets) { MT_ASSERT(threadContext, "Sanity check failed!"); MT_ASSERT(threadContext->taskScheduler, "Sanity check failed!"); MT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), "Can't use RunSubtasksAndYield outside Task. Use TaskScheduler.WaitGroup() instead."); MT_ASSERT(threadContext->thread.IsCurrentThread(), "Thread context sanity check failed"); // add to scheduler threadContext->taskScheduler->RunTasksImpl(buckets, this, false); // MT_ASSERT(threadContext->thread.IsCurrentThread(), "Thread context sanity check failed"); // Change status taskStatus = FiberTaskStatus::AWAITING_CHILD; Fiber & schedulerFiber = threadContext->schedulerFiber; #ifdef MT_INSTRUMENTED_BUILD threadContext->NotifyTaskYielded(currentTask); #endif // Yielding, so reset thread context threadContext = nullptr; //switch to scheduler Fiber::SwitchTo(fiber, schedulerFiber); } void FiberContext::RunAsync(TaskGroup taskGroup, const TaskHandle* taskHandleArray, uint32 taskHandleCount) { MT_ASSERT(threadContext, "ThreadContext is nullptr"); MT_ASSERT(threadContext->taskScheduler, "Sanity check failed!"); MT_ASSERT(threadContext->taskScheduler->IsWorkerThread(), "Can't use RunAsync outside Task. Use TaskScheduler.RunAsync() instead."); TaskScheduler& scheduler = *(threadContext->taskScheduler); ArrayView<internal::GroupedTask> buffer(threadContext->descBuffer, taskHandleCount); uint32 bucketCount = MT::Min((uint32)scheduler.GetWorkersCount(), taskHandleCount); ArrayView<internal::TaskBucket> buckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount); internal::DistibuteDescriptions(taskGroup, taskHandleArray, buffer, buckets); scheduler.RunTasksImpl(buckets, nullptr, false); } void FiberContext::RunSubtasksAndYield(TaskGroup taskGroup, const TaskHandle* taskHandleArray, uint32 taskHandleCount) { MT_ASSERT(threadContext, "ThreadContext is nullptr"); MT_ASSERT(threadContext->taskScheduler, "TaskScheduler is nullptr"); MT_ASSERT(taskHandleCount < internal::TASK_BUFFER_CAPACITY, "Buffer overrun!"); TaskScheduler& scheduler = *(threadContext->taskScheduler); ArrayView<internal::GroupedTask> buffer(threadContext->descBuffer, taskHandleCount); uint32 bucketCount = MT::Min((uint32)scheduler.GetWorkersCount(), taskHandleCount); ArrayView<internal::TaskBucket> buckets(MT_ALLOCATE_ON_STACK(sizeof(internal::TaskBucket) * bucketCount), bucketCount); internal::DistibuteDescriptions(taskGroup, taskHandleArray, buffer, buckets); RunSubtasksAndYieldImpl(buckets); } } <|endoftext|>
<commit_before>/** \brief Tool to adjust validation rules for journal set to selective * evaluation to avoid failing QS checks for field not eligible * in this context * \author Johannes Riedl * * \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 <iostream> #include "Compiler.h" #include "DbConnection.h" #include "DbResultSet.h" #include "DbRow.h" #include "StringUtil.h" #include "UBTools.h" #include "util.h" #include "ZoteroHarvesterConfig.h" namespace { using namespace ZoteroHarvester; [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " zotero_harvester.conf\n"; std::exit(EXIT_FAILURE); } std::string AssembleValaditionRulesIfNotExist(const std::string journal_id) { const auto tag("084"); const std::vector<char> subfield_codes({ 'a', '2' }); const std::vector<std::string> record_types({"regular_article", "review"}); std::vector<std::string> values; const auto field_presence("ignore"); // The following is the logic for "Insert if not exists beforehand" // The SELECTs in the for loop generate anonymous tuples that are merged in an multi row table by UNION ALL for (const auto &subfield_code : subfield_codes) for (const auto &record_type : record_types) values.emplace_back("(SELECT " + journal_id + ", \'" + tag + "\', \'" + subfield_code + "\', NULL, \'" + record_type + "\', \'" + field_presence + "\')"); return std::string("INSERT INTO metadata_presence_tracer ") + "SELECT * FROM (" + StringUtil::Join(values, " UNION ALL ") + ") AS tmp " + "WHERE NOT EXISTS(SELECT 1 FROM metadata_presence_tracer WHERE journal_id=" + journal_id + " AND marc_field_tag=" + tag + " LIMIT 1);"; } void LoadHarvesterConfig(const std::string &config_path, std::vector<std::unique_ptr<Config::JournalParams>> * const journal_params) { std::unique_ptr<Config::GlobalParams> global_params; std::vector<std::unique_ptr<Config::GroupParams>> group_params; Config::LoadHarvesterConfigFile(config_path, &global_params, &group_params, journal_params); } std::string GetJournalId(DbConnection * const db_connection, const std::string &zeder_id, const std::string &group) { db_connection->queryOrDie("SELECT id FROM zeder_journals WHERE zeder_id=\'" + zeder_id + "\' AND zeder_instance=\'" + group + "\'"); DbResultSet result_set(db_connection->getLastResultSet()); if (result_set.size() != 1) LOG_ERROR("Unable to uniquely determine journal_id for zeder_id " + zeder_id + " and group " + group); return result_set.getNextRow()["id"]; } void UpdateRules(DbConnection * const db_connection, const std::vector<std::unique_ptr<Config::JournalParams>> &journal_params) { for (const auto &journal : journal_params) if (journal->selective_evaluation_) { const std::string journal_id(GetJournalId(db_connection, std::to_string(journal->zeder_id_), StringUtil::ASCIIToLower(journal->group_))); db_connection->queryOrDie(AssembleValaditionRulesIfNotExist(journal_id)); } } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 2) Usage(); const std::string config_path(argv[1]); std::vector<std::unique_ptr<Config::JournalParams>> journal_params; LoadHarvesterConfig(config_path, &journal_params); DbConnection db_connection; UpdateRules(&db_connection, journal_params); return EXIT_SUCCESS; } <commit_msg>Workaround<commit_after>/** \brief Tool to adjust validation rules for journal set to selective * evaluation to avoid failing QS checks for field not eligible * in this context * \author Johannes Riedl * * \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 <iostream> #include "Compiler.h" #include "DbConnection.h" #include "DbResultSet.h" #include "DbRow.h" #include "StringUtil.h" #include "UBTools.h" #include "util.h" #include "ZoteroHarvesterConfig.h" namespace { using namespace ZoteroHarvester; [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " zotero_harvester.conf\n"; std::exit(EXIT_FAILURE); } std::string AssembleValaditionRulesIfNotExist(const std::string journal_id) { const auto tag("084"); const std::vector<char> subfield_codes({ 'a', '2' }); const std::vector<std::string> record_types({"regular_article", "review"}); std::vector<std::string> values; const auto field_presence("ignore"); // The following is the logic for "Insert if not exists beforehand" // The SELECTs in the for loop generate anonymous tuples that are merged in an multi row table by UNION ALL for (const auto &subfield_code : subfield_codes) for (const auto &record_type : record_types) values.emplace_back("(SELECT " + journal_id + ", \'" + tag + "\', \'" + subfield_code + "\', NULL, \'" + record_type + "\', \'" + field_presence + "\')"); return std::string("INSERT INTO metadata_presence_tracer ") + "SELECT * FROM (" + StringUtil::Join(values, " UNION ALL ") + ") AS tmp " + "WHERE NOT EXISTS(SELECT 1 FROM metadata_presence_tracer WHERE journal_id=" + journal_id + " AND marc_field_tag=" + tag + " LIMIT 1);"; } void LoadHarvesterConfig(const std::string &config_path, std::vector<std::unique_ptr<Config::JournalParams>> * const journal_params) { std::unique_ptr<Config::GlobalParams> global_params; std::vector<std::unique_ptr<Config::GroupParams>> group_params; Config::LoadHarvesterConfigFile(config_path, &global_params, &group_params, journal_params); } std::string GetJournalId(DbConnection * const db_connection, const std::string &zeder_id, const std::string &group) { db_connection->queryOrDie("SELECT id FROM zeder_journals WHERE zeder_id=\'" + zeder_id + "\' AND zeder_instance=\'" + group + "\'"); DbResultSet result_set(db_connection->getLastResultSet()); if (not result_set.size()) { return ""; } if (result_set.size() != 1) LOG_ERROR("Unable to uniquely determine journal_id for zeder_id " + zeder_id + " and group " + group); return result_set.getNextRow()["id"]; } void UpdateRules(DbConnection * const db_connection, const std::vector<std::unique_ptr<Config::JournalParams>> &journal_params) { for (const auto &journal : journal_params) if (journal->selective_evaluation_) { const std::string journal_id(GetJournalId(db_connection, std::to_string(journal->zeder_id_), StringUtil::ASCIIToLower(journal->group_))); if (journal_id.empty()) { LOG_WARNING("No journal_id result for zeder_id " + std::to_string(journal->zeder_id_) + " in group " + journal->group_ + " - Skipping journal"); continue; } db_connection->queryOrDie(AssembleValaditionRulesIfNotExist(journal_id)); } } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 2) Usage(); const std::string config_path(argv[1]); std::vector<std::unique_ptr<Config::JournalParams>> journal_params; LoadHarvesterConfig(config_path, &journal_params); DbConnection db_connection; UpdateRules(&db_connection, journal_params); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// // Copyright (c) 2008-2015 the Urho3D project. // // 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 "../Precompiled.h" #include "../Core/ProcessUtils.h" #include <cstdio> #include <fcntl.h> #ifdef __APPLE__ #include "TargetConditionals.h" #endif #if defined(IOS) #include "../Math/MathDefs.h" #include <mach/mach_host.h> #elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN) #include <LibCpuId/src/libcpuid.h> #endif #ifdef WIN32 #include <windows.h> #include <io.h> #else #include <unistd.h> #endif #if defined(_MSC_VER) #include <float.h> #elif !defined(ANDROID) && !defined(IOS) && !defined(RPI) && !defined(EMSCRIPTEN) // From http://stereopsis.com/FPU.html #define FPU_CW_PREC_MASK 0x0300 #define FPU_CW_PREC_SINGLE 0x0000 #define FPU_CW_PREC_DOUBLE 0x0200 #define FPU_CW_PREC_EXTENDED 0x0300 #define FPU_CW_ROUND_MASK 0x0c00 #define FPU_CW_ROUND_NEAR 0x0000 #define FPU_CW_ROUND_DOWN 0x0400 #define FPU_CW_ROUND_UP 0x0800 #define FPU_CW_ROUND_CHOP 0x0c00 inline unsigned GetFPUState() { unsigned control = 0; __asm__ __volatile__ ("fnstcw %0" : "=m" (control)); return control; } inline void SetFPUState(unsigned control) { __asm__ __volatile__ ("fldcw %0" : : "m" (control)); } #endif #include "../DebugNew.h" namespace Atomic { #ifdef WIN32 static bool consoleOpened = false; #endif static String currentLine; static Vector<String> arguments; #if defined(IOS) static void GetCPUData(host_basic_info_data_t* data) { mach_msg_type_number_t infoCount; infoCount = HOST_BASIC_INFO_COUNT; host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)data, &infoCount); } #elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN) static void GetCPUData(struct cpu_id_t* data) { if (cpu_identify(0, data) < 0) { data->num_logical_cpus = 1; data->num_cores = 1; } } #endif void InitFPU() { #if !defined(ATOMIC_LUAJIT) && !defined(ANDROID) && !defined(IOS) && !defined(RPI) && !defined(__x86_64__) && !defined(_M_AMD64) && !defined(EMSCRIPTEN) // Make sure FPU is in round-to-nearest, single precision mode // This ensures Direct3D and OpenGL behave similarly, and all threads behave similarly #ifdef _MSC_VER _controlfp(_RC_NEAR | _PC_24, _MCW_RC | _MCW_PC); #else unsigned control = GetFPUState(); control &= ~(FPU_CW_PREC_MASK | FPU_CW_ROUND_MASK); control |= (FPU_CW_PREC_SINGLE | FPU_CW_ROUND_NEAR); SetFPUState(control); #endif #endif } void ErrorDialog(const String& title, const String& message) { #ifdef WIN32 MessageBoxW(0, WString(message).CString(), WString(title).CString(), 0); #else PrintLine(message, true); #endif } void ErrorExit(const String& message, int exitCode) { if (!message.Empty()) PrintLine(message, true); exit(exitCode); } void OpenConsoleWindow() { #ifdef WIN32 if (consoleOpened) return; AllocConsole(); HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); int hCrt = _open_osfhandle((size_t)hOut, _O_TEXT); FILE* outFile = _fdopen(hCrt, "w"); setvbuf(outFile, NULL, _IONBF, 1); *stdout = *outFile; HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE); hCrt = _open_osfhandle((size_t)hIn, _O_TEXT); FILE* inFile = _fdopen(hCrt, "r"); setvbuf(inFile, NULL, _IONBF, 128); *stdin = *inFile; consoleOpened = true; #endif } void PrintUnicode(const String& str, bool error) { #if !defined(ANDROID) && !defined(IOS) #ifdef WIN32 // If the output stream has been redirected, use fprintf instead of WriteConsoleW, // though it means that proper Unicode output will not work FILE* out = error ? stderr : stdout; if (!_isatty(_fileno(out))) fprintf(out, "%s", str.CString()); else { HANDLE stream = GetStdHandle(error ? STD_ERROR_HANDLE : STD_OUTPUT_HANDLE); if (stream == INVALID_HANDLE_VALUE) return; WString strW(str); DWORD charsWritten; WriteConsoleW(stream, strW.CString(), strW.Length(), &charsWritten, 0); } #else fprintf(error ? stderr : stdout, "%s", str.CString()); #endif #endif } void PrintUnicodeLine(const String& str, bool error) { PrintUnicode(str + '\n', error); } void PrintLine(const String& str, bool error) { #if !defined(ANDROID) && !defined(IOS) fprintf(error ? stderr : stdout, "%s\n", str.CString()); #endif } const Vector<String>& ParseArguments(const String& cmdLine, bool skipFirstArgument) { arguments.Clear(); unsigned cmdStart = 0, cmdEnd = 0; bool inCmd = false; bool inQuote = false; for (unsigned i = 0; i < cmdLine.Length(); ++i) { if (cmdLine[i] == '\"') inQuote = !inQuote; if (cmdLine[i] == ' ' && !inQuote) { if (inCmd) { inCmd = false; cmdEnd = i; // Do not store the first argument (executable name) if (!skipFirstArgument) arguments.Push(cmdLine.Substring(cmdStart, cmdEnd - cmdStart)); skipFirstArgument = false; } } else { if (!inCmd) { inCmd = true; cmdStart = i; } } } if (inCmd) { cmdEnd = cmdLine.Length(); if (!skipFirstArgument) arguments.Push(cmdLine.Substring(cmdStart, cmdEnd - cmdStart)); } // Strip double quotes from the arguments for (unsigned i = 0; i < arguments.Size(); ++i) arguments[i].Replace("\"", ""); return arguments; } const Vector<String>& ParseArguments(const char* cmdLine) { return ParseArguments(String(cmdLine)); } const Vector<String>& ParseArguments(const WString& cmdLine) { return ParseArguments(String(cmdLine)); } const Vector<String>& ParseArguments(const wchar_t* cmdLine) { return ParseArguments(String(cmdLine)); } const Vector<String>& ParseArguments(int argc, char** argv) { String cmdLine; for (int i = 0; i < argc; ++i) cmdLine.AppendWithFormat("\"%s\" ", (const char*)argv[i]); return ParseArguments(cmdLine); } const Vector<String>& GetArguments() { return arguments; } String GetConsoleInput() { String ret; #ifdef ATOMIC_TESTING // When we are running automated tests, reading the console may block. Just return empty in that case return ret; #endif #ifdef WIN32 HANDLE input = GetStdHandle(STD_INPUT_HANDLE); HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE); if (input == INVALID_HANDLE_VALUE || output == INVALID_HANDLE_VALUE) return ret; // Use char-based input SetConsoleMode(input, ENABLE_PROCESSED_INPUT); INPUT_RECORD record; DWORD events = 0; DWORD readEvents = 0; if (!GetNumberOfConsoleInputEvents(input, &events)) return ret; while (events--) { ReadConsoleInputW(input, &record, 1, &readEvents); if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown) { unsigned c = record.Event.KeyEvent.uChar.UnicodeChar; if (c) { if (c == '\b') { PrintUnicode("\b \b"); int length = currentLine.LengthUTF8(); if (length) currentLine = currentLine.SubstringUTF8(0, length - 1); } else if (c == '\r') { PrintUnicode("\n"); ret = currentLine; currentLine.Clear(); return ret; } else { // We have disabled echo, so echo manually wchar_t out = c; DWORD charsWritten; WriteConsoleW(output, &out, 1, &charsWritten, 0); currentLine.AppendUTF8(c); } } } } #elif !defined(ANDROID) && !defined(IOS) int flags = fcntl(STDIN_FILENO, F_GETFL); fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK); for (;;) { int ch = fgetc(stdin); if (ch >= 0 && ch != '\n') ret += (char)ch; else break; } #endif return ret; } String GetPlatform() { #if defined(ANDROID) return "Android"; #elif defined(IOS) return "iOS"; #elif defined(WIN32) return "Windows"; #elif defined(__APPLE__) return "Mac OS X"; #elif defined(RPI) return "Raspberry Pi"; #elif defined(EMSCRIPTEN) return "HTML5"; #elif defined(__linux__) return "Linux"; #else return String::EMPTY; #endif } #if defined(ANDROID) || defined(RPI) static unsigned GetArmCPUCount() { FILE* fp; int res, i = -1, j = -1; fp = fopen("/sys/devices/system/cpu/present", "r"); // If failed, return at least 1 if (fp == 0) return 1; res = fscanf(fp, "%d-%d", &i, &j); fclose(fp); if (res == 1 && i == 0) return 1; else if (res == 2 && i == 0) return j + 1; // If failed, return at least 1 return 1; } #endif unsigned GetNumPhysicalCPUs() { #if defined(IOS) host_basic_info_data_t data; GetCPUData(&data); #if defined(TARGET_IPHONE_SIMULATOR) // Hardcoded to dual-core on simulator mode even if the host has more return Min(2, data.physical_cpu); #else return data.physical_cpu; #endif #elif defined(ANDROID) || defined(RPI) return GetArmCPUCount(); #elif !defined(EMSCRIPTEN) struct cpu_id_t data; GetCPUData(&data); return (unsigned)data.num_cores; #else /// \todo Implement properly return 1; #endif } unsigned GetNumLogicalCPUs() { #if defined(IOS) host_basic_info_data_t data; GetCPUData(&data); #if defined(TARGET_IPHONE_SIMULATOR) return Min(2, data.logical_cpu); #else return data.logical_cpu; #endif #elif defined(ANDROID) || defined (RPI) return GetArmCPUCount(); #elif !defined(EMSCRIPTEN) struct cpu_id_t data; GetCPUData(&data); return (unsigned)data.num_logical_cpus; #else /// \todo Implement properly return 1; #endif } } <commit_msg>--log-std now logs to debugging Visual Studio's output pane while editor is running<commit_after>// // Copyright (c) 2008-2015 the Urho3D project. // // 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 "../Precompiled.h" #include "../Core/ProcessUtils.h" #include <cstdio> #include <fcntl.h> #ifdef __APPLE__ #include "TargetConditionals.h" #endif #if defined(IOS) #include "../Math/MathDefs.h" #include <mach/mach_host.h> #elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN) #include <LibCpuId/src/libcpuid.h> #endif #ifdef WIN32 #include <windows.h> #include <io.h> #else #include <unistd.h> #endif #if defined(_MSC_VER) #include <float.h> #elif !defined(ANDROID) && !defined(IOS) && !defined(RPI) && !defined(EMSCRIPTEN) // From http://stereopsis.com/FPU.html #define FPU_CW_PREC_MASK 0x0300 #define FPU_CW_PREC_SINGLE 0x0000 #define FPU_CW_PREC_DOUBLE 0x0200 #define FPU_CW_PREC_EXTENDED 0x0300 #define FPU_CW_ROUND_MASK 0x0c00 #define FPU_CW_ROUND_NEAR 0x0000 #define FPU_CW_ROUND_DOWN 0x0400 #define FPU_CW_ROUND_UP 0x0800 #define FPU_CW_ROUND_CHOP 0x0c00 inline unsigned GetFPUState() { unsigned control = 0; __asm__ __volatile__ ("fnstcw %0" : "=m" (control)); return control; } inline void SetFPUState(unsigned control) { __asm__ __volatile__ ("fldcw %0" : : "m" (control)); } #endif #include "../DebugNew.h" namespace Atomic { #ifdef WIN32 static bool consoleOpened = false; #endif static String currentLine; static Vector<String> arguments; #if defined(IOS) static void GetCPUData(host_basic_info_data_t* data) { mach_msg_type_number_t infoCount; infoCount = HOST_BASIC_INFO_COUNT; host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)data, &infoCount); } #elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN) static void GetCPUData(struct cpu_id_t* data) { if (cpu_identify(0, data) < 0) { data->num_logical_cpus = 1; data->num_cores = 1; } } #endif void InitFPU() { #if !defined(ATOMIC_LUAJIT) && !defined(ANDROID) && !defined(IOS) && !defined(RPI) && !defined(__x86_64__) && !defined(_M_AMD64) && !defined(EMSCRIPTEN) // Make sure FPU is in round-to-nearest, single precision mode // This ensures Direct3D and OpenGL behave similarly, and all threads behave similarly #ifdef _MSC_VER _controlfp(_RC_NEAR | _PC_24, _MCW_RC | _MCW_PC); #else unsigned control = GetFPUState(); control &= ~(FPU_CW_PREC_MASK | FPU_CW_ROUND_MASK); control |= (FPU_CW_PREC_SINGLE | FPU_CW_ROUND_NEAR); SetFPUState(control); #endif #endif } void ErrorDialog(const String& title, const String& message) { #ifdef WIN32 MessageBoxW(0, WString(message).CString(), WString(title).CString(), 0); #else PrintLine(message, true); #endif } void ErrorExit(const String& message, int exitCode) { if (!message.Empty()) PrintLine(message, true); exit(exitCode); } void OpenConsoleWindow() { #ifdef WIN32 if (consoleOpened) return; AllocConsole(); HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); int hCrt = _open_osfhandle((size_t)hOut, _O_TEXT); FILE* outFile = _fdopen(hCrt, "w"); setvbuf(outFile, NULL, _IONBF, 1); *stdout = *outFile; HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE); hCrt = _open_osfhandle((size_t)hIn, _O_TEXT); FILE* inFile = _fdopen(hCrt, "r"); setvbuf(inFile, NULL, _IONBF, 128); *stdin = *inFile; consoleOpened = true; #endif } void PrintUnicode(const String& str, bool error) { #if !defined(ANDROID) && !defined(IOS) #ifdef WIN32 // If the output stream has been redirected, use fprintf instead of WriteConsoleW, // though it means that proper Unicode output will not work FILE* out = error ? stderr : stdout; if (!_isatty(_fileno(out))) fprintf(out, "%s", str.CString()); else { HANDLE stream = GetStdHandle(error ? STD_ERROR_HANDLE : STD_OUTPUT_HANDLE); if (stream == INVALID_HANDLE_VALUE) return; WString strW(str); DWORD charsWritten; WriteConsoleW(stream, strW.CString(), strW.Length(), &charsWritten, 0); if (IsDebuggerPresent()) { OutputDebugString(str.CString()); } } #else fprintf(error ? stderr : stdout, "%s", str.CString()); #endif #endif } void PrintUnicodeLine(const String& str, bool error) { PrintUnicode(str + '\n', error); } void PrintLine(const String& str, bool error) { #if !defined(ANDROID) && !defined(IOS) fprintf(error ? stderr : stdout, "%s\n", str.CString()); #endif } const Vector<String>& ParseArguments(const String& cmdLine, bool skipFirstArgument) { arguments.Clear(); unsigned cmdStart = 0, cmdEnd = 0; bool inCmd = false; bool inQuote = false; for (unsigned i = 0; i < cmdLine.Length(); ++i) { if (cmdLine[i] == '\"') inQuote = !inQuote; if (cmdLine[i] == ' ' && !inQuote) { if (inCmd) { inCmd = false; cmdEnd = i; // Do not store the first argument (executable name) if (!skipFirstArgument) arguments.Push(cmdLine.Substring(cmdStart, cmdEnd - cmdStart)); skipFirstArgument = false; } } else { if (!inCmd) { inCmd = true; cmdStart = i; } } } if (inCmd) { cmdEnd = cmdLine.Length(); if (!skipFirstArgument) arguments.Push(cmdLine.Substring(cmdStart, cmdEnd - cmdStart)); } // Strip double quotes from the arguments for (unsigned i = 0; i < arguments.Size(); ++i) arguments[i].Replace("\"", ""); return arguments; } const Vector<String>& ParseArguments(const char* cmdLine) { return ParseArguments(String(cmdLine)); } const Vector<String>& ParseArguments(const WString& cmdLine) { return ParseArguments(String(cmdLine)); } const Vector<String>& ParseArguments(const wchar_t* cmdLine) { return ParseArguments(String(cmdLine)); } const Vector<String>& ParseArguments(int argc, char** argv) { String cmdLine; for (int i = 0; i < argc; ++i) cmdLine.AppendWithFormat("\"%s\" ", (const char*)argv[i]); return ParseArguments(cmdLine); } const Vector<String>& GetArguments() { return arguments; } String GetConsoleInput() { String ret; #ifdef ATOMIC_TESTING // When we are running automated tests, reading the console may block. Just return empty in that case return ret; #endif #ifdef WIN32 HANDLE input = GetStdHandle(STD_INPUT_HANDLE); HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE); if (input == INVALID_HANDLE_VALUE || output == INVALID_HANDLE_VALUE) return ret; // Use char-based input SetConsoleMode(input, ENABLE_PROCESSED_INPUT); INPUT_RECORD record; DWORD events = 0; DWORD readEvents = 0; if (!GetNumberOfConsoleInputEvents(input, &events)) return ret; while (events--) { ReadConsoleInputW(input, &record, 1, &readEvents); if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown) { unsigned c = record.Event.KeyEvent.uChar.UnicodeChar; if (c) { if (c == '\b') { PrintUnicode("\b \b"); int length = currentLine.LengthUTF8(); if (length) currentLine = currentLine.SubstringUTF8(0, length - 1); } else if (c == '\r') { PrintUnicode("\n"); ret = currentLine; currentLine.Clear(); return ret; } else { // We have disabled echo, so echo manually wchar_t out = c; DWORD charsWritten; WriteConsoleW(output, &out, 1, &charsWritten, 0); currentLine.AppendUTF8(c); } } } } #elif !defined(ANDROID) && !defined(IOS) int flags = fcntl(STDIN_FILENO, F_GETFL); fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK); for (;;) { int ch = fgetc(stdin); if (ch >= 0 && ch != '\n') ret += (char)ch; else break; } #endif return ret; } String GetPlatform() { #if defined(ANDROID) return "Android"; #elif defined(IOS) return "iOS"; #elif defined(WIN32) return "Windows"; #elif defined(__APPLE__) return "Mac OS X"; #elif defined(RPI) return "Raspberry Pi"; #elif defined(EMSCRIPTEN) return "HTML5"; #elif defined(__linux__) return "Linux"; #else return String::EMPTY; #endif } #if defined(ANDROID) || defined(RPI) static unsigned GetArmCPUCount() { FILE* fp; int res, i = -1, j = -1; fp = fopen("/sys/devices/system/cpu/present", "r"); // If failed, return at least 1 if (fp == 0) return 1; res = fscanf(fp, "%d-%d", &i, &j); fclose(fp); if (res == 1 && i == 0) return 1; else if (res == 2 && i == 0) return j + 1; // If failed, return at least 1 return 1; } #endif unsigned GetNumPhysicalCPUs() { #if defined(IOS) host_basic_info_data_t data; GetCPUData(&data); #if defined(TARGET_IPHONE_SIMULATOR) // Hardcoded to dual-core on simulator mode even if the host has more return Min(2, data.physical_cpu); #else return data.physical_cpu; #endif #elif defined(ANDROID) || defined(RPI) return GetArmCPUCount(); #elif !defined(EMSCRIPTEN) struct cpu_id_t data; GetCPUData(&data); return (unsigned)data.num_cores; #else /// \todo Implement properly return 1; #endif } unsigned GetNumLogicalCPUs() { #if defined(IOS) host_basic_info_data_t data; GetCPUData(&data); #if defined(TARGET_IPHONE_SIMULATOR) return Min(2, data.logical_cpu); #else return data.logical_cpu; #endif #elif defined(ANDROID) || defined (RPI) return GetArmCPUCount(); #elif !defined(EMSCRIPTEN) struct cpu_id_t data; GetCPUData(&data); return (unsigned)data.num_logical_cpus; #else /// \todo Implement properly return 1; #endif } } <|endoftext|>
<commit_before>#include "QMLPlugin.hpp" #include <cutehmi/gui/CuteApplication.hpp> #include <cutehmi/gui/ColorSet.hpp> #include <cutehmi/gui/Palette.hpp> #include <cutehmi/gui/Fonts.hpp> #include <cutehmi/gui/Units.hpp> #include <cutehmi/gui/Theme.hpp> #include <QtQml> //<Doxygen-3.workaround target="Doxygen" cause="missing"> #ifdef DOXYGEN_WORKAROUND namespace CuteHMI { namespace GUI { /** * Exposes cutehmi::gui::CuteApplication to QML. */ class CuteApplication: public cutehmi::gui::CuteApplication {}; /** * Exposes cutehmi::gui::ColorSet to QML. */ class ColorSet: public cutehmi::gui::ColorSet {}; /** * Exposes cutehmi::gui::Palette to QML. */ class Palette: public cutehmi::gui::Palette {}; /** * Exposes cutehmi::gui::Fonts to QML. */ class Fonts: public cutehmi::gui::Fonts {}; /** * Exposes cutehmi::gui::Units to QML. */ class Units: public cutehmi::gui::Units {}; /** * Exposes cutehmi::gui::Theme to QML. */ class Theme: public cutehmi::gui::Theme {}; } } #endif //</Doxygen-3.workaround> namespace cutehmi { namespace gui { namespace internal { /** * Register QML types. * @param uri URI. */ void QMLPlugin::registerTypes(const char * uri) { Q_ASSERT(uri == QLatin1String("CuteHMI.GUI")); // @uri CuteHMI.GUI qmlRegisterType<cutehmi::gui::ColorSet>(uri, CUTEHMI_GUI_MAJOR, 0, "ColorSet"); qmlRegisterType<cutehmi::gui::Palette>(uri, CUTEHMI_GUI_MAJOR, 0, "Palette"); qmlRegisterType<cutehmi::gui::Fonts>(uri, CUTEHMI_GUI_MAJOR, 0, "Fonts"); qmlRegisterType<cutehmi::gui::Units>(uri, CUTEHMI_GUI_MAJOR, 0, "Units"); qmlRegisterSingletonType<cutehmi::gui::Theme>(uri, CUTEHMI_GUI_MAJOR, 0, "Theme", ThemeProvider); if (qEnvironmentVariableIsSet("QML_PUPPET_MODE")) { //<CuteHMI.LockScreen-1.workaround target="Qt" cause="design"> // @uri CuteHMI.GUI qmlRegisterSingletonType<cutehmi::gui::CuteApplication>(uri, CUTEHMI_GUI_MAJOR, 0, "CuteApplication", CuteApplicationProvider); //</CuteHMI.LockScreen-1.workaround> } } QObject * QMLPlugin::CuteApplicationProvider(QQmlEngine * engine, QJSEngine * scriptEngine) { Q_UNUSED(scriptEngine) QObject * app = cutehmi::gui::CuteApplication::instance(); engine->setObjectOwnership(app, QQmlEngine::CppOwnership); return app; } QObject * QMLPlugin::ThemeProvider(QQmlEngine * engine, QJSEngine * scriptEngine) { Q_UNUSED(scriptEngine) QObject * theme = & cutehmi::gui::Theme::Instance(); engine->setObjectOwnership(theme, QQmlEngine::CppOwnership); return theme; } } } } //(c)C: Copyright © 2020, Michał Policht <[email protected]>. All rights reserved. //(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT //(c)C: This file is a part of CuteHMI. //(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. //(c)C: CuteHMI 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. //(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>. //(c)C: Additionally, this file is licensed under terms of MIT license as expressed below. //(c)C: 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: //(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. //(c)C: 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. <commit_msg>Fix condition<commit_after>#include "QMLPlugin.hpp" #include <cutehmi/gui/CuteApplication.hpp> #include <cutehmi/gui/ColorSet.hpp> #include <cutehmi/gui/Palette.hpp> #include <cutehmi/gui/Fonts.hpp> #include <cutehmi/gui/Units.hpp> #include <cutehmi/gui/Theme.hpp> #include <QtQml> //<Doxygen-3.workaround target="Doxygen" cause="missing"> #ifdef DOXYGEN_WORKAROUND namespace CuteHMI { namespace GUI { /** * Exposes cutehmi::gui::CuteApplication to QML. */ class CuteApplication: public cutehmi::gui::CuteApplication {}; /** * Exposes cutehmi::gui::ColorSet to QML. */ class ColorSet: public cutehmi::gui::ColorSet {}; /** * Exposes cutehmi::gui::Palette to QML. */ class Palette: public cutehmi::gui::Palette {}; /** * Exposes cutehmi::gui::Fonts to QML. */ class Fonts: public cutehmi::gui::Fonts {}; /** * Exposes cutehmi::gui::Units to QML. */ class Units: public cutehmi::gui::Units {}; /** * Exposes cutehmi::gui::Theme to QML. */ class Theme: public cutehmi::gui::Theme {}; } } #endif //</Doxygen-3.workaround> namespace cutehmi { namespace gui { namespace internal { /** * Register QML types. * @param uri URI. */ void QMLPlugin::registerTypes(const char * uri) { Q_ASSERT(uri == QLatin1String("CuteHMI.GUI")); // @uri CuteHMI.GUI qmlRegisterType<cutehmi::gui::ColorSet>(uri, CUTEHMI_GUI_MAJOR, 0, "ColorSet"); qmlRegisterType<cutehmi::gui::Palette>(uri, CUTEHMI_GUI_MAJOR, 0, "Palette"); qmlRegisterType<cutehmi::gui::Fonts>(uri, CUTEHMI_GUI_MAJOR, 0, "Fonts"); qmlRegisterType<cutehmi::gui::Units>(uri, CUTEHMI_GUI_MAJOR, 0, "Units"); qmlRegisterSingletonType<cutehmi::gui::Theme>(uri, CUTEHMI_GUI_MAJOR, 0, "Theme", ThemeProvider); if (!qEnvironmentVariableIsSet("QML_PUPPET_MODE")) { //<CuteHMI.LockScreen-1.workaround target="Qt" cause="design"> // @uri CuteHMI.GUI qmlRegisterSingletonType<cutehmi::gui::CuteApplication>(uri, CUTEHMI_GUI_MAJOR, 0, "CuteApplication", CuteApplicationProvider); //</CuteHMI.LockScreen-1.workaround> } } QObject * QMLPlugin::CuteApplicationProvider(QQmlEngine * engine, QJSEngine * scriptEngine) { Q_UNUSED(scriptEngine) QObject * app = cutehmi::gui::CuteApplication::instance(); engine->setObjectOwnership(app, QQmlEngine::CppOwnership); return app; } QObject * QMLPlugin::ThemeProvider(QQmlEngine * engine, QJSEngine * scriptEngine) { Q_UNUSED(scriptEngine) QObject * theme = & cutehmi::gui::Theme::Instance(); engine->setObjectOwnership(theme, QQmlEngine::CppOwnership); return theme; } } } } //(c)C: Copyright © 2020, Michał Policht <[email protected]>. All rights reserved. //(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT //(c)C: This file is a part of CuteHMI. //(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. //(c)C: CuteHMI 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. //(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>. //(c)C: Additionally, this file is licensed under terms of MIT license as expressed below. //(c)C: 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: //(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. //(c)C: 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. <|endoftext|>
<commit_before>#include "CellFeature.h" #include "GameEntity.h" #include "GamePlayer.h" #include "GameType.h" #include "RtsGame.h" #include "MetaData.h" #include <cmath> using namespace IStrategizer; CellFeature::CellFeature(const PlanStepParameters& p_parameters) { m_alliedBuildingDescription.m_numberOfBuildings = p_parameters.at(PARAM_AlliedBuildingsCount); m_alliedBuildingDescription.m_numberOfCriticalBuildings = p_parameters.at(PARAM_AlliedCriticalBuildingsCount); m_alliedForceDescription.m_numberOfUnits = p_parameters.at(PARAM_AlliedUnitsCount); m_alliedForceDescription.m_totalDamage = p_parameters.at(PARAM_AlliedUnitsTotalDamage); m_alliedForceDescription.m_totalHP = p_parameters.at(PARAM_AlliedUnitsTotalHP); m_enemyBuildingDescription.m_numberOfBuildings = p_parameters.at(PARAM_EnemyBuildingsCount); m_enemyBuildingDescription.m_numberOfCriticalBuildings = p_parameters.at(PARAM_EnemyCriticalBuildingsCount); m_enemyForceDescription.m_numberOfUnits = p_parameters.at(PARAM_EnemyUnitsCount); m_enemyForceDescription.m_totalDamage = p_parameters.at(PARAM_EnemyUnitsTotalDamage); m_enemyForceDescription.m_totalHP = p_parameters.at(PARAM_EnemyUnitsTotalHP); m_resourceDescription.m_numberOfPrimary = p_parameters.at(PARAM_NumberOfPrimaryResources); m_resourceDescription.m_numberOfSecondary = p_parameters.at(PARAM_NumberOfSecondaryResources); m_resourceDescription.m_numberOfSupply = p_parameters.at(PARAM_NumberOfSupplyResources); m_distanceFromBase = p_parameters.at(PARAM_DistanceToBase); m_distanceFromEnemyBase = p_parameters.at(PARAM_DistanceToEnemyBase); } //---------------------------------------------------------------------------------------------- void CellFeature::To(PlanStepParameters& p_parameters) const { p_parameters[PARAM_AlliedBuildingsCount] = m_alliedBuildingDescription.m_numberOfBuildings; p_parameters[PARAM_AlliedCriticalBuildingsCount] = m_alliedBuildingDescription.m_numberOfCriticalBuildings; p_parameters[PARAM_AlliedUnitsCount] = m_alliedForceDescription.m_numberOfUnits; p_parameters[PARAM_AlliedUnitsTotalDamage] = m_alliedForceDescription.m_totalDamage; p_parameters[PARAM_AlliedUnitsTotalHP] = m_alliedForceDescription.m_totalHP; p_parameters[PARAM_EnemyBuildingsCount] = m_enemyBuildingDescription.m_numberOfBuildings; p_parameters[PARAM_EnemyCriticalBuildingsCount] = m_enemyBuildingDescription.m_numberOfCriticalBuildings; p_parameters[PARAM_EnemyUnitsCount] = m_enemyForceDescription.m_numberOfUnits; p_parameters[PARAM_EnemyUnitsTotalDamage] = m_enemyForceDescription.m_totalDamage; p_parameters[PARAM_EnemyUnitsTotalHP] = m_enemyForceDescription.m_totalHP; p_parameters[PARAM_NumberOfPrimaryResources] = m_resourceDescription.m_numberOfPrimary; p_parameters[PARAM_NumberOfSecondaryResources] = m_resourceDescription.m_numberOfSecondary; p_parameters[PARAM_NumberOfSupplyResources] = m_resourceDescription.m_numberOfSupply; p_parameters[PARAM_DistanceToBase] = m_distanceFromBase; p_parameters[PARAM_DistanceToEnemyBase] = m_distanceFromEnemyBase; } //---------------------------------------------------------------------------------------------- void CellFeature::AddEntity(GameEntity *p_entity, bool p_isAllied) { if(g_Game->GetEntityType(p_entity->Type())->Attr(ECATTR_IsBuilding)) { if(p_isAllied) m_alliedBuildingDescription.AddEntity(p_entity); else m_enemyBuildingDescription.AddEntity(p_entity); } else if(g_Game->GetEntityType(p_entity->Type())->Attr(ECATTR_CanAttack)) { if(p_isAllied) m_alliedForceDescription.AddEntity(p_entity); else m_enemyForceDescription.AddEntity(p_entity); } else { m_resourceDescription.AddEntity(p_entity); } } //---------------------------------------------------------------------------------------------- void CellFeature::RemoveEntity(GameEntity *p_entity, bool p_isAllied) { if(g_Game->GetEntityType(p_entity->Type())->Attr(ECATTR_IsBuilding)) { if(p_isAllied) m_alliedBuildingDescription.RemoveEntity(p_entity); else m_enemyBuildingDescription.RemoveEntity(p_entity); } else if(g_Game->GetEntityType(p_entity->Type())->Attr(ECATTR_CanAttack)) { if(p_isAllied) m_alliedForceDescription.RemoveEntity(p_entity); else m_enemyForceDescription.RemoveEntity(p_entity); } else { m_resourceDescription.RemoveEntity(p_entity); } } //---------------------------------------------------------------------------------------------- void CellFeature::Clear() { m_alliedBuildingDescription.Clear(); m_enemyBuildingDescription.Clear(); m_alliedForceDescription.Clear(); m_enemyForceDescription.Clear(); m_resourceDescription.Clear(); m_distanceFromBase = 0; m_distanceFromEnemyBase = 0; } //---------------------------------------------------------------------------------------------- float CellFeature::GetDistance(CellFeature *p_other) { float res = 0.0; float alliedBuildingDistance = m_alliedBuildingDescription.GetDistance(&(p_other->m_alliedBuildingDescription)); float enemyBuildingDistance = m_enemyBuildingDescription.GetDistance(&(p_other->m_enemyBuildingDescription)); float alliedForceDistance = m_alliedForceDescription.GetDistance(&(p_other->m_alliedForceDescription)); float enemyForceDistance = m_enemyForceDescription.GetDistance(&(p_other->m_enemyForceDescription)); float resourceDistance = m_resourceDescription.GetDistance(&(p_other->m_resourceDescription)); float distanceFromBase = GetBaseDistance(this->m_distanceFromBase, p_other->m_distanceFromBase); float distanceFromEnemyBase = GetBaseDistance(this->m_distanceFromEnemyBase, p_other->m_distanceFromEnemyBase); res += alliedBuildingDistance; res += enemyBuildingDistance; res += alliedForceDistance; res += enemyForceDistance; res += resourceDistance; res += distanceFromBase; res += distanceFromEnemyBase; return sqrt(res); } //---------------------------------------------------------------------------------------------- void CellFeature::CalculateDistanceToBases(Vector2 cellWorldPosition) { vector<TID> bases; g_Game->Enemy()->GetBases(bases); CalculateDistanceToBasesAux(cellWorldPosition, bases, m_distanceFromEnemyBase); g_Game->Self()->GetBases(bases); CalculateDistanceToBasesAux(cellWorldPosition, bases, m_distanceFromBase); } void CellFeature::CalculateDistanceToBasesAux(Vector2 cellWorldPosition, vector<TID> bases, double& distance) { assert(bases.size() > 0); TID baseId = bases[0]; GameEntity* pBase = g_Game->Self()->GetEntity(baseId); if (pBase == nullptr) pBase = g_Game->Enemy()->GetEntity(baseId); assert(pBase); distance = cellWorldPosition.Distance(pBase->GetPosition()); } //---------------------------------------------------------------------------------------------- float CellFeature::GetBaseDistance(double firstBase, double secondBase) const { return pow((float)(firstBase - secondBase), 2); }<commit_msg>Add line separator<commit_after>#include "CellFeature.h" #include "GameEntity.h" #include "GamePlayer.h" #include "GameType.h" #include "RtsGame.h" #include "MetaData.h" #include <cmath> using namespace IStrategizer; CellFeature::CellFeature(const PlanStepParameters& p_parameters) { m_alliedBuildingDescription.m_numberOfBuildings = p_parameters.at(PARAM_AlliedBuildingsCount); m_alliedBuildingDescription.m_numberOfCriticalBuildings = p_parameters.at(PARAM_AlliedCriticalBuildingsCount); m_alliedForceDescription.m_numberOfUnits = p_parameters.at(PARAM_AlliedUnitsCount); m_alliedForceDescription.m_totalDamage = p_parameters.at(PARAM_AlliedUnitsTotalDamage); m_alliedForceDescription.m_totalHP = p_parameters.at(PARAM_AlliedUnitsTotalHP); m_enemyBuildingDescription.m_numberOfBuildings = p_parameters.at(PARAM_EnemyBuildingsCount); m_enemyBuildingDescription.m_numberOfCriticalBuildings = p_parameters.at(PARAM_EnemyCriticalBuildingsCount); m_enemyForceDescription.m_numberOfUnits = p_parameters.at(PARAM_EnemyUnitsCount); m_enemyForceDescription.m_totalDamage = p_parameters.at(PARAM_EnemyUnitsTotalDamage); m_enemyForceDescription.m_totalHP = p_parameters.at(PARAM_EnemyUnitsTotalHP); m_resourceDescription.m_numberOfPrimary = p_parameters.at(PARAM_NumberOfPrimaryResources); m_resourceDescription.m_numberOfSecondary = p_parameters.at(PARAM_NumberOfSecondaryResources); m_resourceDescription.m_numberOfSupply = p_parameters.at(PARAM_NumberOfSupplyResources); m_distanceFromBase = p_parameters.at(PARAM_DistanceToBase); m_distanceFromEnemyBase = p_parameters.at(PARAM_DistanceToEnemyBase); } //---------------------------------------------------------------------------------------------- void CellFeature::To(PlanStepParameters& p_parameters) const { p_parameters[PARAM_AlliedBuildingsCount] = m_alliedBuildingDescription.m_numberOfBuildings; p_parameters[PARAM_AlliedCriticalBuildingsCount] = m_alliedBuildingDescription.m_numberOfCriticalBuildings; p_parameters[PARAM_AlliedUnitsCount] = m_alliedForceDescription.m_numberOfUnits; p_parameters[PARAM_AlliedUnitsTotalDamage] = m_alliedForceDescription.m_totalDamage; p_parameters[PARAM_AlliedUnitsTotalHP] = m_alliedForceDescription.m_totalHP; p_parameters[PARAM_EnemyBuildingsCount] = m_enemyBuildingDescription.m_numberOfBuildings; p_parameters[PARAM_EnemyCriticalBuildingsCount] = m_enemyBuildingDescription.m_numberOfCriticalBuildings; p_parameters[PARAM_EnemyUnitsCount] = m_enemyForceDescription.m_numberOfUnits; p_parameters[PARAM_EnemyUnitsTotalDamage] = m_enemyForceDescription.m_totalDamage; p_parameters[PARAM_EnemyUnitsTotalHP] = m_enemyForceDescription.m_totalHP; p_parameters[PARAM_NumberOfPrimaryResources] = m_resourceDescription.m_numberOfPrimary; p_parameters[PARAM_NumberOfSecondaryResources] = m_resourceDescription.m_numberOfSecondary; p_parameters[PARAM_NumberOfSupplyResources] = m_resourceDescription.m_numberOfSupply; p_parameters[PARAM_DistanceToBase] = m_distanceFromBase; p_parameters[PARAM_DistanceToEnemyBase] = m_distanceFromEnemyBase; } //---------------------------------------------------------------------------------------------- void CellFeature::AddEntity(GameEntity *p_entity, bool p_isAllied) { if(g_Game->GetEntityType(p_entity->Type())->Attr(ECATTR_IsBuilding)) { if(p_isAllied) m_alliedBuildingDescription.AddEntity(p_entity); else m_enemyBuildingDescription.AddEntity(p_entity); } else if(g_Game->GetEntityType(p_entity->Type())->Attr(ECATTR_CanAttack)) { if(p_isAllied) m_alliedForceDescription.AddEntity(p_entity); else m_enemyForceDescription.AddEntity(p_entity); } else { m_resourceDescription.AddEntity(p_entity); } } //---------------------------------------------------------------------------------------------- void CellFeature::RemoveEntity(GameEntity *p_entity, bool p_isAllied) { if(g_Game->GetEntityType(p_entity->Type())->Attr(ECATTR_IsBuilding)) { if(p_isAllied) m_alliedBuildingDescription.RemoveEntity(p_entity); else m_enemyBuildingDescription.RemoveEntity(p_entity); } else if(g_Game->GetEntityType(p_entity->Type())->Attr(ECATTR_CanAttack)) { if(p_isAllied) m_alliedForceDescription.RemoveEntity(p_entity); else m_enemyForceDescription.RemoveEntity(p_entity); } else { m_resourceDescription.RemoveEntity(p_entity); } } //---------------------------------------------------------------------------------------------- void CellFeature::Clear() { m_alliedBuildingDescription.Clear(); m_enemyBuildingDescription.Clear(); m_alliedForceDescription.Clear(); m_enemyForceDescription.Clear(); m_resourceDescription.Clear(); m_distanceFromBase = 0; m_distanceFromEnemyBase = 0; } //---------------------------------------------------------------------------------------------- float CellFeature::GetDistance(CellFeature *p_other) { float res = 0.0; float alliedBuildingDistance = m_alliedBuildingDescription.GetDistance(&(p_other->m_alliedBuildingDescription)); float enemyBuildingDistance = m_enemyBuildingDescription.GetDistance(&(p_other->m_enemyBuildingDescription)); float alliedForceDistance = m_alliedForceDescription.GetDistance(&(p_other->m_alliedForceDescription)); float enemyForceDistance = m_enemyForceDescription.GetDistance(&(p_other->m_enemyForceDescription)); float resourceDistance = m_resourceDescription.GetDistance(&(p_other->m_resourceDescription)); float distanceFromBase = GetBaseDistance(this->m_distanceFromBase, p_other->m_distanceFromBase); float distanceFromEnemyBase = GetBaseDistance(this->m_distanceFromEnemyBase, p_other->m_distanceFromEnemyBase); res += alliedBuildingDistance; res += enemyBuildingDistance; res += alliedForceDistance; res += enemyForceDistance; res += resourceDistance; res += distanceFromBase; res += distanceFromEnemyBase; return sqrt(res); } //---------------------------------------------------------------------------------------------- void CellFeature::CalculateDistanceToBases(Vector2 cellWorldPosition) { vector<TID> bases; g_Game->Enemy()->GetBases(bases); CalculateDistanceToBasesAux(cellWorldPosition, bases, m_distanceFromEnemyBase); g_Game->Self()->GetBases(bases); CalculateDistanceToBasesAux(cellWorldPosition, bases, m_distanceFromBase); } //---------------------------------------------------------------------------------------------- void CellFeature::CalculateDistanceToBasesAux(Vector2 cellWorldPosition, vector<TID> bases, double& distance) { assert(bases.size() > 0); TID baseId = bases[0]; GameEntity* pBase = g_Game->Self()->GetEntity(baseId); if (pBase == nullptr) pBase = g_Game->Enemy()->GetEntity(baseId); assert(pBase); distance = cellWorldPosition.Distance(pBase->GetPosition()); } //---------------------------------------------------------------------------------------------- float CellFeature::GetBaseDistance(double firstBase, double secondBase) const { return pow((float)(firstBase - secondBase), 2); }<|endoftext|>
<commit_before>#include "stdafx.h" #include "CppUnitTest.h" #include "..\ProjectEuler\Problem1.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace ProjectEulerTests { TEST_CLASS(Problem1Tests) { public: TEST_METHOD(SumMultiplesOf3And5Below_Input0_Returns0) { auto result = Problem1::SumMultiplesOf3And5Below(0); Assert::AreEqual(0, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input1_Returns0) { auto result = Problem1::SumMultiplesOf3And5Below(1); Assert::AreEqual(0, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input2_Returns0) { auto result = Problem1::SumMultiplesOf3And5Below(2); Assert::AreEqual(0, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input3_Returns0) { auto result = Problem1::SumMultiplesOf3And5Below(3); Assert::AreEqual(0, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input4_Returns3) { auto result = Problem1::SumMultiplesOf3And5Below(4); Assert::AreEqual(3, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input5_Returns3) { auto result = Problem1::SumMultiplesOf3And5Below(5); Assert::AreEqual(3, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input6_Returns8) { auto result = Problem1::SumMultiplesOf3And5Below(6); Assert::AreEqual(8, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input7_Returns14) { auto result = Problem1::SumMultiplesOf3And5Below(7); Assert::AreEqual(14, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input8_Returns14) { auto result = Problem1::SumMultiplesOf3And5Below(8); Assert::AreEqual(14, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input9_Returns14) { auto result = Problem1::SumMultiplesOf3And5Below(9); Assert::AreEqual(14, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input10_Returns23) { auto result = Problem1::SumMultiplesOf3And5Below(10); Assert::AreEqual(23, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input100_Returns2318) { auto result = Problem1::SumMultiplesOf3And5Below(100); Assert::AreEqual(2318, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input1000_Returns233168) { auto result = Problem1::SumMultiplesOf3And5Below(1000); Assert::AreEqual(233168, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input10000_Returns23331668) { auto result = Problem1::SumMultiplesOf3And5Below(10000); Assert::AreEqual(23331668, result); } TEST_METHOD(SumBelow_Input0_Returns0) { auto result = Problem1::SumBelow(0); Assert::AreEqual(0L, result); } TEST_METHOD(SumBelow_Input1_Returns0) { auto result = Problem1::SumBelow(1); Assert::AreEqual(0L, result); } TEST_METHOD(SumBelow_Input2_Returns1) { auto result = Problem1::SumBelow(2); Assert::AreEqual(1L, result); } TEST_METHOD(SumBelow_Input3_Returns3) { auto result = Problem1::SumBelow(3); Assert::AreEqual(3L, result); } TEST_METHOD(SumBelow_Input4_Returns6) { auto result = Problem1::SumBelow(4); Assert::AreEqual(6L, result); } TEST_METHOD(SumBelow_Input5_Returns10) { auto result = Problem1::SumBelow(5); Assert::AreEqual(10L, result); } TEST_METHOD(SumBelow_Input6_Returns15) { auto result = Problem1::SumBelow(6); Assert::AreEqual(15L, result); } TEST_METHOD(SumBelow_Input7_Returns21) { auto result = Problem1::SumBelow(7); Assert::AreEqual(21L, result); } TEST_METHOD(SumBelow_Input8_Returns28) { auto result = Problem1::SumBelow(8); Assert::AreEqual(28L, result); } TEST_METHOD(SumBelow_Input9_Returns36) { auto result = Problem1::SumBelow(9); Assert::AreEqual(36L, result); } TEST_METHOD(SumBelow_Input10_Returns45) { auto result = Problem1::SumBelow(10); Assert::AreEqual(45L, result); } TEST_METHOD(SumBelow_Input100_Returns4950) { auto result = Problem1::SumBelow(100); Assert::AreEqual(4950L, result); } TEST_METHOD(SumBelow_Input100000_Returns704982704) { auto result = Problem1::SumBelow(100000); Assert::AreEqual(704982704L, result); } TEST_METHOD(SumDivisibleBy_Input3and0_Returns0) { auto result = Problem1::SumDivisibleBy(3, 0L); Assert::AreEqual(0L, result); } TEST_METHOD(SumDivisibleBy_Input3and1_Returns0) { auto result = Problem1::SumDivisibleBy(3, 1L); Assert::AreEqual(0L, result); } TEST_METHOD(SumDivisibleBy_Input3and2_Returns0) { auto result = Problem1::SumDivisibleBy(3, 2L); Assert::AreEqual(0L, result); } TEST_METHOD(SumDivisibleBy_Input3and3_Returns0) { auto result = Problem1::SumDivisibleBy(3, 3L); Assert::AreEqual(0L, result); } TEST_METHOD(SumDivisibleBy_Input3and4_Returns3) { auto result = Problem1::SumDivisibleBy(3, 4L); Assert::AreEqual(3L, result); } TEST_METHOD(SumDivisibleBy_Input5and0_Returns0) { auto result = Problem1::SumDivisibleBy(5, 0L); Assert::AreEqual(0L, result); } TEST_METHOD(SumDivisibleBy_Input5and1_Returns0) { auto result = Problem1::SumDivisibleBy(5, 1L); Assert::AreEqual(0L, result); } TEST_METHOD(SumDivisibleBy_Input5and2_Returns0) { auto result = Problem1::SumDivisibleBy(5, 2L); Assert::AreEqual(0L, result); } TEST_METHOD(SumDivisibleBy_Input5and3_Returns0) { auto result = Problem1::SumDivisibleBy(5, 3L); Assert::AreEqual(0L, result); } }; }<commit_msg>red-commit - SumDivisibleBy_Input5and4_Returns0<commit_after>#include "stdafx.h" #include "CppUnitTest.h" #include "..\ProjectEuler\Problem1.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace ProjectEulerTests { TEST_CLASS(Problem1Tests) { public: TEST_METHOD(SumMultiplesOf3And5Below_Input0_Returns0) { auto result = Problem1::SumMultiplesOf3And5Below(0); Assert::AreEqual(0, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input1_Returns0) { auto result = Problem1::SumMultiplesOf3And5Below(1); Assert::AreEqual(0, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input2_Returns0) { auto result = Problem1::SumMultiplesOf3And5Below(2); Assert::AreEqual(0, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input3_Returns0) { auto result = Problem1::SumMultiplesOf3And5Below(3); Assert::AreEqual(0, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input4_Returns3) { auto result = Problem1::SumMultiplesOf3And5Below(4); Assert::AreEqual(3, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input5_Returns3) { auto result = Problem1::SumMultiplesOf3And5Below(5); Assert::AreEqual(3, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input6_Returns8) { auto result = Problem1::SumMultiplesOf3And5Below(6); Assert::AreEqual(8, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input7_Returns14) { auto result = Problem1::SumMultiplesOf3And5Below(7); Assert::AreEqual(14, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input8_Returns14) { auto result = Problem1::SumMultiplesOf3And5Below(8); Assert::AreEqual(14, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input9_Returns14) { auto result = Problem1::SumMultiplesOf3And5Below(9); Assert::AreEqual(14, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input10_Returns23) { auto result = Problem1::SumMultiplesOf3And5Below(10); Assert::AreEqual(23, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input100_Returns2318) { auto result = Problem1::SumMultiplesOf3And5Below(100); Assert::AreEqual(2318, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input1000_Returns233168) { auto result = Problem1::SumMultiplesOf3And5Below(1000); Assert::AreEqual(233168, result); } TEST_METHOD(SumMultiplesOf3And5Below_Input10000_Returns23331668) { auto result = Problem1::SumMultiplesOf3And5Below(10000); Assert::AreEqual(23331668, result); } TEST_METHOD(SumBelow_Input0_Returns0) { auto result = Problem1::SumBelow(0); Assert::AreEqual(0L, result); } TEST_METHOD(SumBelow_Input1_Returns0) { auto result = Problem1::SumBelow(1); Assert::AreEqual(0L, result); } TEST_METHOD(SumBelow_Input2_Returns1) { auto result = Problem1::SumBelow(2); Assert::AreEqual(1L, result); } TEST_METHOD(SumBelow_Input3_Returns3) { auto result = Problem1::SumBelow(3); Assert::AreEqual(3L, result); } TEST_METHOD(SumBelow_Input4_Returns6) { auto result = Problem1::SumBelow(4); Assert::AreEqual(6L, result); } TEST_METHOD(SumBelow_Input5_Returns10) { auto result = Problem1::SumBelow(5); Assert::AreEqual(10L, result); } TEST_METHOD(SumBelow_Input6_Returns15) { auto result = Problem1::SumBelow(6); Assert::AreEqual(15L, result); } TEST_METHOD(SumBelow_Input7_Returns21) { auto result = Problem1::SumBelow(7); Assert::AreEqual(21L, result); } TEST_METHOD(SumBelow_Input8_Returns28) { auto result = Problem1::SumBelow(8); Assert::AreEqual(28L, result); } TEST_METHOD(SumBelow_Input9_Returns36) { auto result = Problem1::SumBelow(9); Assert::AreEqual(36L, result); } TEST_METHOD(SumBelow_Input10_Returns45) { auto result = Problem1::SumBelow(10); Assert::AreEqual(45L, result); } TEST_METHOD(SumBelow_Input100_Returns4950) { auto result = Problem1::SumBelow(100); Assert::AreEqual(4950L, result); } TEST_METHOD(SumBelow_Input100000_Returns704982704) { auto result = Problem1::SumBelow(100000); Assert::AreEqual(704982704L, result); } TEST_METHOD(SumDivisibleBy_Input3and0_Returns0) { auto result = Problem1::SumDivisibleBy(3, 0L); Assert::AreEqual(0L, result); } TEST_METHOD(SumDivisibleBy_Input3and1_Returns0) { auto result = Problem1::SumDivisibleBy(3, 1L); Assert::AreEqual(0L, result); } TEST_METHOD(SumDivisibleBy_Input3and2_Returns0) { auto result = Problem1::SumDivisibleBy(3, 2L); Assert::AreEqual(0L, result); } TEST_METHOD(SumDivisibleBy_Input3and3_Returns0) { auto result = Problem1::SumDivisibleBy(3, 3L); Assert::AreEqual(0L, result); } TEST_METHOD(SumDivisibleBy_Input3and4_Returns3) { auto result = Problem1::SumDivisibleBy(3, 4L); Assert::AreEqual(3L, result); } TEST_METHOD(SumDivisibleBy_Input5and0_Returns0) { auto result = Problem1::SumDivisibleBy(5, 0L); Assert::AreEqual(0L, result); } TEST_METHOD(SumDivisibleBy_Input5and1_Returns0) { auto result = Problem1::SumDivisibleBy(5, 1L); Assert::AreEqual(0L, result); } TEST_METHOD(SumDivisibleBy_Input5and2_Returns0) { auto result = Problem1::SumDivisibleBy(5, 2L); Assert::AreEqual(0L, result); } TEST_METHOD(SumDivisibleBy_Input5and3_Returns0) { auto result = Problem1::SumDivisibleBy(5, 3L); Assert::AreEqual(0L, result); } TEST_METHOD(SumDivisibleBy_Input5and4_Returns0) { auto result = Problem1::SumDivisibleBy(5, 4L); Assert::AreEqual(0L, result); } }; }<|endoftext|>
<commit_before>/* * This file is part of TelepathyQt4 * * Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright (C) 2010 Nokia Corporation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <TelepathyQt4/DBusProxyFactory> #include "TelepathyQt4/dbus-proxy-factory-internal.h" #include "TelepathyQt4/_gen/dbus-proxy-factory-internal.moc.hpp" #include "TelepathyQt4/debug-internal.h" #include <TelepathyQt4/DBusProxy> #include <TelepathyQt4/ReadyObject> #include <TelepathyQt4/PendingReady> #include <QDBusConnection> namespace Tp { struct DBusProxyFactory::Private { Private(const QDBusConnection &bus) : bus(bus), cache(new Cache) {} ~Private() { delete cache; } QDBusConnection bus; Cache *cache; }; /** * \class DBusProxyFactory * \ingroup clientreadiness * \headerfile TelepathyQt4/dbus-proxy-factory.h <TelepathyQt4/DBusProxyFactory> * * Base class for all D-Bus proxy factory classes. Handles proxy caching and making them ready as * appropriate. */ /** * Class constructor. * * The intention for storing the bus here is that it generally doesn't make sense to construct * proxies for multiple buses in the same context. Allowing that would lead to more complex keying * needs in the cache, as well. * * \param bus The D-Bus bus connection for the objects constructed using this factory. */ DBusProxyFactory::DBusProxyFactory(const QDBusConnection &bus) : mPriv(new Private(bus)) { } /** * Class destructor. */ DBusProxyFactory::~DBusProxyFactory() { delete mPriv; } /** * Returns the D-Bus connection all of the proxies from this factory communicate with. * * \return The connection. */ const QDBusConnection &DBusProxyFactory::dbusConnection() const { return mPriv->bus; } /** * Returns a cached proxy with the given \a busName and \a objectPath. * * If a proxy has not been previously put into the cache by nowHaveProxy for those identifying * attributes, or a previously cached proxy has since been invalidated and/or destroyed, a \c Null * shared pointer is returned instead. * * \param busName Bus name of the proxy to return. * \param objectPath Object path of the proxy to return. * \return The proxy, if any. */ SharedPtr<RefCounted> DBusProxyFactory::cachedProxy(const QString &busName, const QString &objectPath) const { QString finalName = finalBusNameFrom(busName); return mPriv->cache->get(Cache::Key(finalName, objectPath)); } /** * Should be called by subclasses when they have a proxy, be it a newly-constructed one or one from * the cache. * * This function will then do the rest of the factory work, including caching the proxy if it's not * cached already, doing any prepare() work if appropriate, and making the features from * featuresFor() ready if they aren't already. * * The returned PendingReady only finishes when the prepare() operation for the proxy has completed, * and the requested features have all been made ready (or found unable to be made ready). Note that * this might have happened already before calling this function, if the proxy was not a newly * created one, but was looked up from the cache. DBusProxyFactory handles the necessary subleties * for this to work. * * Access to the proxy instance is allowed as soon as this method returns through * PendingReady::proxy(), if the proxy is needed in a context where it's not required to be ready. * * \param proxy The proxy which the factory should now make sure is prepared and made ready. * \return Readifying operation, which finishes when the proxy is usable. */ PendingReady *DBusProxyFactory::nowHaveProxy(const SharedPtr<RefCounted> &proxy) const { Q_ASSERT(!proxy.isNull()); // I really hate the casts needed in this function - we must really do something about the // DBusProxy class hierarchy so that every DBusProxy(Something) is always a ReadyObject and a // RefCounted, in the API/ABI break - then most of these proxyMisc-> things become just proxy-> ReadyObject *proxyReady = dynamic_cast<ReadyObject *>(proxy.data()); Q_ASSERT(proxyReady != NULL); Features specificFeatures = featuresFor(proxy); // FIXME: prepare currently doesn't work PendingOperation *prepareOp = NULL; mPriv->cache->put(proxy); if (prepareOp || (!specificFeatures.isEmpty() && !proxyReady->isReady(specificFeatures))) { return new PendingReady(prepareOp, specificFeatures, proxy, 0); } // No features requested or they are all ready - optimize a bit by not calling ReadinessHelper PendingReady *readyOp = new PendingReady(0, specificFeatures, proxy, 0); readyOp->setFinished(); return readyOp; } /** * Allows subclasses to do arbitrary manipulation on the object before it is attempted to be made * ready. * * If a non-\c NULL operation is returned, the completion of that operation is waited for before * starting to make the object ready whenever nowHaveProxy() is called the first time around for a * given proxy. * * \return \c NULL ie. nothing to do. */ PendingOperation *DBusProxyFactory::prepare(const SharedPtr<RefCounted> &object) const { // Nothing we could think about needs doing return NULL; } DBusProxyFactory::Cache::Cache() { } DBusProxyFactory::Cache::~Cache() { } SharedPtr<RefCounted> DBusProxyFactory::Cache::get(const Key &key) const { SharedPtr<RefCounted> counted(proxies.value(key)); // We already assert for it being a DBusProxy in put() if (!counted || !dynamic_cast<DBusProxy *>(counted.data())->isValid()) { // Weak pointer invalidated or proxy invalidated during this mainloop iteration and we still // haven't got the invalidated() signal for it return SharedPtr<RefCounted>(); } return counted; } void DBusProxyFactory::Cache::put(const SharedPtr<RefCounted> &obj) { DBusProxy *proxyProxy = dynamic_cast<DBusProxy *>(obj.data()); Q_ASSERT(proxyProxy != NULL); Key key(proxyProxy->busName(), proxyProxy->objectPath()); SharedPtr<RefCounted> existingProxy = SharedPtr<RefCounted>(proxies.value(key)); if (!existingProxy || existingProxy != obj) { connect(proxyProxy, SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)), SLOT(onProxyInvalidated(Tp::DBusProxy*))); debug() << "Inserting to factory cache proxy for" << key; proxies.insert(key, obj); } } void DBusProxyFactory::Cache::onProxyInvalidated(Tp::DBusProxy *proxy) { Key key(proxy->busName(), proxy->objectPath()); // Not having it would indicate invalidated() signaled twice for the same proxy, or us having // connected to two proxies with the same key, neither of which should happen Q_ASSERT(proxies.contains(key)); debug() << "Removing from factory cache invalidated proxy for" << key; proxies.remove(key); } } <commit_msg>Warn in DBusProxyFactory docs that prepare() is not currently really used<commit_after>/* * This file is part of TelepathyQt4 * * Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright (C) 2010 Nokia Corporation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <TelepathyQt4/DBusProxyFactory> #include "TelepathyQt4/dbus-proxy-factory-internal.h" #include "TelepathyQt4/_gen/dbus-proxy-factory-internal.moc.hpp" #include "TelepathyQt4/debug-internal.h" #include <TelepathyQt4/DBusProxy> #include <TelepathyQt4/ReadyObject> #include <TelepathyQt4/PendingReady> #include <QDBusConnection> namespace Tp { struct DBusProxyFactory::Private { Private(const QDBusConnection &bus) : bus(bus), cache(new Cache) {} ~Private() { delete cache; } QDBusConnection bus; Cache *cache; }; /** * \class DBusProxyFactory * \ingroup clientreadiness * \headerfile TelepathyQt4/dbus-proxy-factory.h <TelepathyQt4/DBusProxyFactory> * * Base class for all D-Bus proxy factory classes. Handles proxy caching and making them ready as * appropriate. */ /** * Class constructor. * * The intention for storing the bus here is that it generally doesn't make sense to construct * proxies for multiple buses in the same context. Allowing that would lead to more complex keying * needs in the cache, as well. * * \param bus The D-Bus bus connection for the objects constructed using this factory. */ DBusProxyFactory::DBusProxyFactory(const QDBusConnection &bus) : mPriv(new Private(bus)) { } /** * Class destructor. */ DBusProxyFactory::~DBusProxyFactory() { delete mPriv; } /** * Returns the D-Bus connection all of the proxies from this factory communicate with. * * \return The connection. */ const QDBusConnection &DBusProxyFactory::dbusConnection() const { return mPriv->bus; } /** * Returns a cached proxy with the given \a busName and \a objectPath. * * If a proxy has not been previously put into the cache by nowHaveProxy for those identifying * attributes, or a previously cached proxy has since been invalidated and/or destroyed, a \c Null * shared pointer is returned instead. * * \param busName Bus name of the proxy to return. * \param objectPath Object path of the proxy to return. * \return The proxy, if any. */ SharedPtr<RefCounted> DBusProxyFactory::cachedProxy(const QString &busName, const QString &objectPath) const { QString finalName = finalBusNameFrom(busName); return mPriv->cache->get(Cache::Key(finalName, objectPath)); } /** * Should be called by subclasses when they have a proxy, be it a newly-constructed one or one from * the cache. * * This function will then do the rest of the factory work, including caching the proxy if it's not * cached already, doing any prepare() work if appropriate, and making the features from * featuresFor() ready if they aren't already. * * The returned PendingReady only finishes when the prepare() operation for the proxy has completed, * and the requested features have all been made ready (or found unable to be made ready). Note that * this might have happened already before calling this function, if the proxy was not a newly * created one, but was looked up from the cache. DBusProxyFactory handles the necessary subleties * for this to work. * * Access to the proxy instance is allowed as soon as this method returns through * PendingReady::proxy(), if the proxy is needed in a context where it's not required to be ready. * * \param proxy The proxy which the factory should now make sure is prepared and made ready. * \return Readifying operation, which finishes when the proxy is usable. */ PendingReady *DBusProxyFactory::nowHaveProxy(const SharedPtr<RefCounted> &proxy) const { Q_ASSERT(!proxy.isNull()); // I really hate the casts needed in this function - we must really do something about the // DBusProxy class hierarchy so that every DBusProxy(Something) is always a ReadyObject and a // RefCounted, in the API/ABI break - then most of these proxyMisc-> things become just proxy-> ReadyObject *proxyReady = dynamic_cast<ReadyObject *>(proxy.data()); Q_ASSERT(proxyReady != NULL); Features specificFeatures = featuresFor(proxy); // FIXME: prepare currently doesn't work PendingOperation *prepareOp = NULL; mPriv->cache->put(proxy); if (prepareOp || (!specificFeatures.isEmpty() && !proxyReady->isReady(specificFeatures))) { return new PendingReady(prepareOp, specificFeatures, proxy, 0); } // No features requested or they are all ready - optimize a bit by not calling ReadinessHelper PendingReady *readyOp = new PendingReady(0, specificFeatures, proxy, 0); readyOp->setFinished(); return readyOp; } /** * Allows subclasses to do arbitrary manipulation on the object before it is attempted to be made * ready. * * If a non-\c NULL operation is returned, the completion of that operation is waited for before * starting to make the object ready whenever nowHaveProxy() is called the first time around for a * given proxy. * * \todo FIXME actually implement this... :) * \return \c NULL ie. nothing to do. */ PendingOperation *DBusProxyFactory::prepare(const SharedPtr<RefCounted> &object) const { // Nothing we could think about needs doing return NULL; } DBusProxyFactory::Cache::Cache() { } DBusProxyFactory::Cache::~Cache() { } SharedPtr<RefCounted> DBusProxyFactory::Cache::get(const Key &key) const { SharedPtr<RefCounted> counted(proxies.value(key)); // We already assert for it being a DBusProxy in put() if (!counted || !dynamic_cast<DBusProxy *>(counted.data())->isValid()) { // Weak pointer invalidated or proxy invalidated during this mainloop iteration and we still // haven't got the invalidated() signal for it return SharedPtr<RefCounted>(); } return counted; } void DBusProxyFactory::Cache::put(const SharedPtr<RefCounted> &obj) { DBusProxy *proxyProxy = dynamic_cast<DBusProxy *>(obj.data()); Q_ASSERT(proxyProxy != NULL); Key key(proxyProxy->busName(), proxyProxy->objectPath()); SharedPtr<RefCounted> existingProxy = SharedPtr<RefCounted>(proxies.value(key)); if (!existingProxy || existingProxy != obj) { connect(proxyProxy, SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)), SLOT(onProxyInvalidated(Tp::DBusProxy*))); debug() << "Inserting to factory cache proxy for" << key; proxies.insert(key, obj); } } void DBusProxyFactory::Cache::onProxyInvalidated(Tp::DBusProxy *proxy) { Key key(proxy->busName(), proxy->objectPath()); // Not having it would indicate invalidated() signaled twice for the same proxy, or us having // connected to two proxies with the same key, neither of which should happen Q_ASSERT(proxies.contains(key)); debug() << "Removing from factory cache invalidated proxy for" << key; proxies.remove(key); } } <|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <string> #include <vector> #include <list> using namespace std; char proc_char(char c) { if (c == -127) c = -111; else if (c <= -81) c += 32; if (c >= -74) c++; if (c == -111) c = -74; return c; } bool cmp(char c1, char c2) { if ((c1 == -48 || c1 == -47) && (c2 == -48 || c2 == -47)) return false; return proc_char(c1) < proc_char(c2); } int main() { int n; string s; cin >> n; list<string> lst; for (int i = 0; i< n; i++) { cin >> s; lst.push_back(s); } lst.sort(); lst.reverse(); cout << "\nSorted + reversed:\n"; for (auto i = lst.begin(); i != lst.end(); i++) cout << *i << endl; cout << "\nRemoved strings with digits in first place:\n"; lst.remove_if([](string& s){return isdigit(s[0]);}); for (auto i = lst.begin(); i != lst.end(); i++) cout << *i << endl; cout << "\nRussian strings sorted properly:\n"; lst.sort([](string& s1, string& s2){return lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), cmp);}); for (auto i = lst.begin(); i != lst.end(); i++) cout << *i << endl; return 0; } <commit_msg>Added copyright<commit_after>/* Copyright (c) 2017 Maxim Teryokhin This code is licensed under MIT. See LICENSE file for more details. */ #include <iostream> #include <algorithm> #include <string> #include <vector> #include <list> using namespace std; char proc_char(char c) { if (c == -127) c = -111; else if (c <= -81) c += 32; if (c >= -74) c++; if (c == -111) c = -74; return c; } bool cmp(char c1, char c2) { if ((c1 == -48 || c1 == -47) && (c2 == -48 || c2 == -47)) return false; return proc_char(c1) < proc_char(c2); } int main() { int n; string s; cin >> n; list<string> lst; for (int i = 0; i< n; i++) { cin >> s; lst.push_back(s); } lst.sort(); lst.reverse(); cout << "\nSorted + reversed:\n"; for (auto i = lst.begin(); i != lst.end(); i++) cout << *i << endl; cout << "\nRemoved strings with digits in first place:\n"; lst.remove_if([](string& s){return isdigit(s[0]);}); for (auto i = lst.begin(); i != lst.end(); i++) cout << *i << endl; cout << "\nRussian strings sorted properly:\n"; lst.sort([](string& s1, string& s2){return lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), cmp);}); for (auto i = lst.begin(); i != lst.end(); i++) cout << *i << endl; return 0; } <|endoftext|>
<commit_before>// // SRTerrain class : a subclass of vtDynTerrainGeom which encapsulates // Stefan Roettger's CLOD algorithm. // // utilizes: Roettger's MINI library implementation // http://wwwvis.informatik.uni-stuttgart.de/~roettger // // Copyright (c) 2002-2004 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "vtlib/vtlib.h" #include "SRTerrain.h" #include "vtdata/vtLog.h" #if VTLIB_NI // stub SRTerrain::SRTerrain() {} SRTerrain::~SRTerrain() {} float SRTerrain::GetElevation(int iX, int iZ, bool bTrue) const { return 0; } void SRTerrain::GetWorldLocation(int i, int j, FPoint3 &p, bool bTrue) const {} void SRTerrain::DoCulling(const vtCamera *pCam) {} void SRTerrain::DoRender() {} void SRTerrain::SetVerticalExag(float fExag) {} DTErr SRTerrain::Init(const vtElevationGrid *pGrid, float fZScale) { return DTErr_NOMEM; } #else #include "mini.h" #include "ministub.hpp" using namespace mini; #ifdef _MSC_VER #pragma comment( lib, "libMini.lib" ) #endif ///////////////////////////////////////////////////////////////////////////// // // Constructor/destructor // SRTerrain::SRTerrain() : vtDynTerrainGeom() { m_fResolution = 10000.0f; m_fHResolution = 20000.0f; m_fLResolution = 0.0f; m_pMini = NULL; } SRTerrain::~SRTerrain() { if (m_pMini) { delete m_pMini; m_pMini = NULL; } } ///////////////////////////////////////////////////////////////////////////// // // Unfortunately the following statics are required because libMini only // supports some functionality by callback, and the callback is only a // simple C function which has no context to tell us which terrain. // static const vtElevationGrid *s_pGrid; static SRTerrain *s_pSRTerrain; static int myfancnt, myvtxcnt; void beginfan_vtp() { if (myfancnt++>0) glEnd(); glBegin(GL_TRIANGLE_FAN); myvtxcnt-=2; // 2 vertices are needed to start each fan } void fanvertex_vtp(float x, float y, float z) { glVertex3f(x,y,z); myvtxcnt++; } void notify_vtp(int i, int j, int size) { // check to see if we need to switch texture if (s_pSRTerrain->m_iTPatchDim > 1 && size == s_pSRTerrain->m_iBlockSize) { int a = i / size; int b = j / size; s_pSRTerrain->LoadBlockMaterial(a, b); } } short int getelevation_vtp1(int i, int j, int size) { return s_pGrid->GetValue(i, j); } float getelevation_vtp2(int i, int j, int size) { return s_pGrid->GetFValue(i, j); } // // Initialize the terrain data // fZScale converts from height values (meters) to world coordinates // DTErr SRTerrain::Init(const vtElevationGrid *pGrid, float fZScale) { // Initializes necessary field of the parent class DTErr err = BasicInit(pGrid); if (err != DTErr_OK) return err; if (m_iColumns != m_iRows) return DTErr_NOTSQUARE; // compute n (log2 of grid size) // ensure that the grid is size (1 << n) + 1 int n = vt_log2(m_iColumns - 1); int required_size = (1<<n) + 1; if (m_iColumns != required_size || m_iRows != required_size) return DTErr_NOTPOWER2; int size = m_iColumns; float dim = m_fXStep; float cellaspect = m_fZStep / m_fXStep; s_pGrid = pGrid; #if 0 // NOTE: the following workaround is no longer needed with libMini 5.02 // // Totally strange but repeatable behavior: runtime exit in Release-mode // libMini with values over a certain level. Workaround here! // Exit happens if (scale * maximum_height / dim > 967) // // scale * maximum_height / dim > 967 // scale > dim * 967 / maximum_height // float fMin, fMax; pGrid->GetHeightExtents(fMin, fMax); // Avoid trouble with fMax small or zero if (fMax < 10) fMax = 10; // compute the largest supported value for MaxScale float fMaxMax = dim * 960 / fMax; // values greater than 10 are unnecessarily large if (fMaxMax > 10) fMaxMax = 10; m_fMaximumScale = fMaxMax; #else // This maxiumum scale is a reasonable tradeoff between the exaggeration // that the user is likely to need, and numerical precision issues. m_fMaximumScale = 10; #endif m_fHeightScale = fZScale; m_fDrawScale = m_fHeightScale / m_fMaximumScale; if (pGrid->IsFloatMode()) { float *image = NULL; m_pMini = new ministub(image, &size, &dim, m_fMaximumScale, cellaspect, beginfan_vtp, fanvertex_vtp, notify_vtp, getelevation_vtp2); } else { short *image = NULL; m_pMini = new ministub(image, &size, &dim, m_fMaximumScale, cellaspect, beginfan_vtp, fanvertex_vtp, notify_vtp, getelevation_vtp1); } m_iDrawnTriangles = -1; m_iBlockSize = m_iColumns / 4; return DTErr_OK; } void SRTerrain::SetVerticalExag(float fExag) { m_fHeightScale = fExag; // safety check if (m_fHeightScale > m_fMaximumScale) m_fHeightScale = m_fMaximumScale; m_fDrawScale = m_fHeightScale / m_fMaximumScale; } // // This will be called once per frame, during the culling pass. // // However, libMini does not allow you to call the culling pass // independently of the rendering pass, so we cannot do culling here. // Instead, just store the values for later use. // void SRTerrain::DoCulling(const vtCamera *pCam) { // Grab necessary values from the VTP Scene framework, store for later m_eyepos_ogl = pCam->GetTrans(); m_window_size = vtGetScene()->GetWindowSize(); m_fAspect = (float)m_window_size.x / m_window_size.y; m_fNear = pCam->GetHither(); m_fFar = pCam->GetYon(); // Get up vector and direction vector from camera matrix FMatrix4 mat; pCam->GetTransform1(mat); FPoint3 up(0.0f, 1.0f, 0.0f); mat.TransformVector(up, eye_up); FPoint3 forward(0.0f, 0.0f, -1.0f); mat.TransformVector(forward, eye_forward); if (pCam->IsOrtho()) { // libMini supports orthographic viewing as of libMini 5.0. // A negative FOV value indicates to the library that the FOV is // actually the orthographic height of the camera. m_fFOVY = pCam->GetWidth() / m_fAspect; m_fFOVY = -m_fFOVY; } else { float fov = pCam->GetFOV(); float fov_y2 = atan(tan (fov/2) / m_fAspect); m_fFOVY = fov_y2 * 2.0f * 180 / PIf; } } void SRTerrain::DoRender() { // Prepare the render state for our OpenGL usage PreRender(); // Render the triangles RenderSurface(); // Clean up PostRender(); } void SRTerrain::LoadSingleMaterial() { // single texture for the whole terrain vtMaterial *pMat = GetMaterial(0); if (pMat) { pMat->Apply(); SetupTexGen(1.0f); } } void SRTerrain::LoadBlockMaterial(int a, int b) { // we can't change the texture between glBegin/glEnd if (myfancnt++>0) glEnd(); // each block has it's own texture map int matidx = a*m_iTPatchDim + (m_iTPatchDim-1-b); vtMaterial *pMat = GetMaterial(matidx); if (pMat) { pMat->Apply(); SetupBlockTexGen(a, b); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } glBegin(GL_TRIANGLE_FAN); } void SRTerrain::RenderSurface() { s_pSRTerrain = this; if (m_iTPatchDim == 1) LoadSingleMaterial(); RenderPass(); // how to do a second rendering pass if (m_bDetailTexture) { // once again, with the detail texture material m_pDetailMat->Apply(); // the uv tiling is different (usually highly repetitive) SetupTexGen(m_fDetailTiling); // draw the second pass glPolygonOffset(-1.0f, -1.0f); glEnable(GL_POLYGON_OFFSET_FILL); RenderPass(); glDisable(GL_POLYGON_OFFSET_FILL); } DisableTexGen(); } void SRTerrain::RenderPass() { float ex = m_eyepos_ogl.x; float ey = m_eyepos_ogl.y; float ez = m_eyepos_ogl.z; float fov = m_fFOVY; float ux = eye_up.x; float uy = eye_up.y; float uz = eye_up.z; float dx = eye_forward.x; float dy = eye_forward.y; float dz = eye_forward.z; myfancnt = myvtxcnt = 0; // Convert the eye location to the unusual coordinate scheme of libMini. ex -= (m_iColumns/2)*m_fXStep; ez += (m_iRows/2)*m_fZStep; m_pMini->draw(m_fResolution, ex, ey, ez, dx, dy, dz, ux, uy, uz, fov, m_fAspect, m_fNear, m_fFar, m_fDrawScale); if (myfancnt>0) glEnd(); // We are drawing fans, so the number of triangles is roughly equal to // number of vertices m_iDrawnTriangles = myvtxcnt; // adaptively adjust resolution threshold up or down to attain // the desired polygon (vertex) count target int diff = m_iDrawnTriangles - m_iPolygonTarget; int iRange = m_iPolygonTarget / 10; // ensure within 10% // If we aren't within the triangle count range adjust the input resolution // like a binary search if (diff < -iRange || diff > iRange) { // VTLOG("diff %d, ", diff); if (diff < -iRange) { m_fLResolution = m_fResolution; // if the high end isn't high enough, double it if (m_fLResolution + 5 >= m_fHResolution) { // VTLOG("increase HRes, "); m_fHResolution *= 10; } } else { m_fHResolution = m_fResolution; if (m_fLResolution + 5 >= m_fHResolution) { // VTLOG("decrease LRes, "); m_fLResolution = 0; } } m_fResolution = m_fLResolution + (m_fHResolution - m_fLResolution) / 2; // VTLOG("rez: [%.1f, %.1f, %.1f] (%d/%d)\n", m_fLResolution, m_fResolution, m_fHResolution, m_iDrawnTriangles, m_iPolygonTarget); // keep the error within reasonable bounds if (m_fResolution < 5.0f) m_fResolution = 5.0f; if (m_fResolution > 4E7) m_fResolution = 4E7; } } // // These methods are called when the framework needs to know the surface // position of the terrain at a given grid point. Supply the height // value from our own data structures. // float SRTerrain::GetElevation(int iX, int iZ, bool bTrue) const { float height = m_pMini->getheight(iX, iZ); if (iX<0 || iX>m_iColumns-1 || iZ<0 || iZ>m_iRows-1) return 0.0f; if (bTrue) // convert stored value to true value return height / m_fMaximumScale; else // convert stored value to drawn value return height * m_fDrawScale; } void SRTerrain::GetWorldLocation(int i, int j, FPoint3 &p, bool bTrue) const { float height = m_pMini->getheight(i, j); if (bTrue) // convert stored value to true value height /= m_fMaximumScale; else // convert stored value to drawn value height *= m_fDrawScale; p.Set(m_fXLookup[i], height, m_fZLookup[j]); } void SRTerrain::SetPolygonCount(int iPolygonCount) { vtDynTerrainGeom::SetPolygonCount(iPolygonCount); m_fResolution = iPolygonCount * 5; m_fHResolution = 2 * m_fResolution; m_fLResolution = 0; } #endif // VTLIB_NI <commit_msg>updated for libMini 5.4<commit_after>// // SRTerrain class : a subclass of vtDynTerrainGeom which encapsulates // Stefan Roettger's CLOD algorithm. // // utilizes: Roettger's MINI library implementation // http://wwwvis.informatik.uni-stuttgart.de/~roettger // // Copyright (c) 2002-2004 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "vtlib/vtlib.h" #include "SRTerrain.h" #include "vtdata/vtLog.h" #if VTLIB_NI // stub SRTerrain::SRTerrain() {} SRTerrain::~SRTerrain() {} float SRTerrain::GetElevation(int iX, int iZ, bool bTrue) const { return 0; } void SRTerrain::GetWorldLocation(int i, int j, FPoint3 &p, bool bTrue) const {} void SRTerrain::DoCulling(const vtCamera *pCam) {} void SRTerrain::DoRender() {} void SRTerrain::SetVerticalExag(float fExag) {} DTErr SRTerrain::Init(const vtElevationGrid *pGrid, float fZScale) { return DTErr_NOMEM; } #else #include "mini.h" #include "ministub.hpp" using namespace mini; #ifdef _MSC_VER #pragma comment( lib, "libMini.lib" ) #endif ///////////////////////////////////////////////////////////////////////////// // // Constructor/destructor // SRTerrain::SRTerrain() : vtDynTerrainGeom() { m_fResolution = 10000.0f; m_fHResolution = 20000.0f; m_fLResolution = 0.0f; m_pMini = NULL; } SRTerrain::~SRTerrain() { if (m_pMini) { delete m_pMini; m_pMini = NULL; } } ///////////////////////////////////////////////////////////////////////////// // // Unfortunately the following statics are required because libMini only // supports some functionality by callback, and the callback is only a // simple C function which has no context to tell us which terrain. // static const vtElevationGrid *s_pGrid; static SRTerrain *s_pSRTerrain; static int myfancnt, myvtxcnt; static int s_iRows; void beginfan_vtp() { if (myfancnt++>0) glEnd(); glBegin(GL_TRIANGLE_FAN); myvtxcnt-=2; // 2 vertices are needed to start each fan } void fanvertex_vtp(float x, float y, float z) { glVertex3f(x,y,z); myvtxcnt++; } void notify_vtp(int i, int j, int size) { // check to see if we need to switch texture if (s_pSRTerrain->m_iTPatchDim > 1 && size == s_pSRTerrain->m_iBlockSize) { int a = i / size; int b = j / size; s_pSRTerrain->LoadBlockMaterial(a, b); } } short int getelevation_vtp1(int i, int j, int size, void *data_unused) { return s_pGrid->GetValue(i, s_iRows-1-j); } float getelevation_vtp2(int i, int j, int size, void *data_unused) { return s_pGrid->GetFValue(i, s_iRows-1-j); } // // Initialize the terrain data // fZScale converts from height values (meters) to world coordinates // DTErr SRTerrain::Init(const vtElevationGrid *pGrid, float fZScale) { // Initializes necessary field of the parent class DTErr err = BasicInit(pGrid); if (err != DTErr_OK) return err; if (m_iColumns != m_iRows) return DTErr_NOTSQUARE; // compute n (log2 of grid size) // ensure that the grid is size (1 << n) + 1 int n = vt_log2(m_iColumns - 1); int required_size = (1<<n) + 1; if (m_iColumns != required_size || m_iRows != required_size) return DTErr_NOTPOWER2; int size = m_iColumns; float dim = m_fXStep; float cellaspect = m_fZStep / m_fXStep; s_pGrid = pGrid; s_iRows = m_iRows; #if 0 // NOTE: the following workaround is no longer needed with libMini 5.02 // // Totally strange but repeatable behavior: runtime exit in Release-mode // libMini with values over a certain level. Workaround here! // Exit happens if (scale * maximum_height / dim > 967) // // scale * maximum_height / dim > 967 // scale > dim * 967 / maximum_height // float fMin, fMax; pGrid->GetHeightExtents(fMin, fMax); // Avoid trouble with fMax small or zero if (fMax < 10) fMax = 10; // compute the largest supported value for MaxScale float fMaxMax = dim * 960 / fMax; // values greater than 10 are unnecessarily large if (fMaxMax > 10) fMaxMax = 10; m_fMaximumScale = fMaxMax; #else // This maxiumum scale is a reasonable tradeoff between the exaggeration // that the user is likely to need, and numerical precision issues. m_fMaximumScale = 10; #endif m_fHeightScale = fZScale; m_fDrawScale = m_fHeightScale / m_fMaximumScale; if (pGrid->IsFloatMode()) { float *image = NULL; m_pMini = new ministub(image, &size, &dim, m_fMaximumScale, cellaspect, 0.0f, 0.0f, 0.0f, // grid center beginfan_vtp, fanvertex_vtp, notify_vtp, getelevation_vtp2); } else { short *image = NULL; m_pMini = new ministub(image, &size, &dim, m_fMaximumScale, cellaspect, 0.0f, 0.0f, 0.0f, // grid center beginfan_vtp, fanvertex_vtp, notify_vtp, getelevation_vtp1); } m_iDrawnTriangles = -1; m_iBlockSize = m_iColumns / 4; return DTErr_OK; } void SRTerrain::SetVerticalExag(float fExag) { m_fHeightScale = fExag; // safety check if (m_fHeightScale > m_fMaximumScale) m_fHeightScale = m_fMaximumScale; m_fDrawScale = m_fHeightScale / m_fMaximumScale; } // // This will be called once per frame, during the culling pass. // // However, libMini does not allow you to call the culling pass // independently of the rendering pass, so we cannot do culling here. // Instead, just store the values for later use. // void SRTerrain::DoCulling(const vtCamera *pCam) { // Grab necessary values from the VTP Scene framework, store for later m_eyepos_ogl = pCam->GetTrans(); m_window_size = vtGetScene()->GetWindowSize(); m_fAspect = (float)m_window_size.x / m_window_size.y; m_fNear = pCam->GetHither(); m_fFar = pCam->GetYon(); // Get up vector and direction vector from camera matrix FMatrix4 mat; pCam->GetTransform1(mat); FPoint3 up(0.0f, 1.0f, 0.0f); mat.TransformVector(up, eye_up); FPoint3 forward(0.0f, 0.0f, -1.0f); mat.TransformVector(forward, eye_forward); if (pCam->IsOrtho()) { // libMini supports orthographic viewing as of libMini 5.0. // A negative FOV value indicates to the library that the FOV is // actually the orthographic height of the camera. m_fFOVY = pCam->GetWidth() / m_fAspect; m_fFOVY = -m_fFOVY; } else { float fov = pCam->GetFOV(); float fov_y2 = atan(tan (fov/2) / m_fAspect); m_fFOVY = fov_y2 * 2.0f * 180 / PIf; } } void SRTerrain::DoRender() { // Prepare the render state for our OpenGL usage PreRender(); // Render the triangles RenderSurface(); // Clean up PostRender(); } void SRTerrain::LoadSingleMaterial() { // single texture for the whole terrain vtMaterial *pMat = GetMaterial(0); if (pMat) { pMat->Apply(); SetupTexGen(1.0f); } } void SRTerrain::LoadBlockMaterial(int a, int b) { // we can't change the texture between glBegin/glEnd if (myfancnt++>0) glEnd(); // each block has it's own texture map int matidx = a*m_iTPatchDim + (m_iTPatchDim-1-b); vtMaterial *pMat = GetMaterial(matidx); if (pMat) { pMat->Apply(); SetupBlockTexGen(a, b); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } glBegin(GL_TRIANGLE_FAN); } void SRTerrain::RenderSurface() { s_pSRTerrain = this; if (m_iTPatchDim == 1) LoadSingleMaterial(); RenderPass(); // how to do a second rendering pass if (m_bDetailTexture) { // once again, with the detail texture material m_pDetailMat->Apply(); // the uv tiling is different (usually highly repetitive) SetupTexGen(m_fDetailTiling); // draw the second pass glPolygonOffset(-1.0f, -1.0f); glEnable(GL_POLYGON_OFFSET_FILL); RenderPass(); glDisable(GL_POLYGON_OFFSET_FILL); } DisableTexGen(); } void SRTerrain::RenderPass() { float ex = m_eyepos_ogl.x; float ey = m_eyepos_ogl.y; float ez = m_eyepos_ogl.z; float fov = m_fFOVY; float ux = eye_up.x; float uy = eye_up.y; float uz = eye_up.z; float dx = eye_forward.x; float dy = eye_forward.y; float dz = eye_forward.z; myfancnt = myvtxcnt = 0; // Convert the eye location to the unusual coordinate scheme of libMini. ex -= (m_iColumns/2)*m_fXStep; ez += (m_iRows/2)*m_fZStep; m_pMini->draw(m_fResolution, ex, ey, ez, dx, dy, dz, ux, uy, uz, fov, m_fAspect, m_fNear, m_fFar, m_fDrawScale); if (myfancnt>0) glEnd(); // We are drawing fans, so the number of triangles is roughly equal to // number of vertices m_iDrawnTriangles = myvtxcnt; // adaptively adjust resolution threshold up or down to attain // the desired polygon (vertex) count target int diff = m_iDrawnTriangles - m_iPolygonTarget; int iRange = m_iPolygonTarget / 10; // ensure within 10% // If we aren't within the triangle count range adjust the input resolution // like a binary search if (diff < -iRange || diff > iRange) { // VTLOG("diff %d, ", diff); if (diff < -iRange) { m_fLResolution = m_fResolution; // if the high end isn't high enough, double it if (m_fLResolution + 5 >= m_fHResolution) { // VTLOG("increase HRes, "); m_fHResolution *= 10; } } else { m_fHResolution = m_fResolution; if (m_fLResolution + 5 >= m_fHResolution) { // VTLOG("decrease LRes, "); m_fLResolution = 0; } } m_fResolution = m_fLResolution + (m_fHResolution - m_fLResolution) / 2; // VTLOG("rez: [%.1f, %.1f, %.1f] (%d/%d)\n", m_fLResolution, m_fResolution, m_fHResolution, m_iDrawnTriangles, m_iPolygonTarget); // keep the error within reasonable bounds if (m_fResolution < 5.0f) m_fResolution = 5.0f; if (m_fResolution > 4E7) m_fResolution = 4E7; } } // // These methods are called when the framework needs to know the surface // position of the terrain at a given grid point. Supply the height // value from our own data structures. // float SRTerrain::GetElevation(int iX, int iZ, bool bTrue) const { float height = m_pMini->getheight(iX, iZ); if (iX<0 || iX>m_iColumns-1 || iZ<0 || iZ>m_iRows-1) return 0.0f; if (bTrue) // convert stored value to true value return height / m_fMaximumScale; else // convert stored value to drawn value return height * m_fDrawScale; } void SRTerrain::GetWorldLocation(int i, int j, FPoint3 &p, bool bTrue) const { float height = m_pMini->getheight(i, j); if (bTrue) // convert stored value to true value height /= m_fMaximumScale; else // convert stored value to drawn value height *= m_fDrawScale; p.Set(m_fXLookup[i], height, m_fZLookup[j]); } void SRTerrain::SetPolygonCount(int iPolygonCount) { vtDynTerrainGeom::SetPolygonCount(iPolygonCount); m_fResolution = iPolygonCount * 5; m_fHResolution = 2 * m_fResolution; m_fLResolution = 0; } #endif // VTLIB_NI <|endoftext|>
<commit_before>#pragma once #include <optional> #include <string_view> #include "Runtime/GCNTypes.hpp" #include "Runtime/Character/CharacterCommon.hpp" #include "Runtime/World/CActor.hpp" #include <zeus/CAABox.hpp> namespace urde { class CScriptCoverPoint : public CActor { bool xe8_26_landHere : 1; bool xe8_27_wallHang : 1; bool xe8_28_stay : 1; bool xe8_29_ : 1; bool xe8_30_attackDirection : 1; float xec_cosHorizontalAngle; float xf0_sinVerticalAngle; float xf4_coverTime; bool xf8_24_crouch : 1; bool xf8_25_inUse : 1; TUniqueId xfa_occupant = kInvalidUniqueId; TUniqueId xfc_retreating = kInvalidUniqueId; std::optional<zeus::CAABox> x100_touchBounds; float x11c_timeLeft = 0.f; public: CScriptCoverPoint(TUniqueId uid, std::string_view name, const CEntityInfo& info, zeus::CTransform xf, bool active, u32 flags, bool crouch, float horizontalAngle, float verticalAngle, float coverTime); void Accept(IVisitor& visitor) override; void Think(float, CStateManager&) override; void AddToRenderer(const zeus::CFrustum&, CStateManager&) override {} void AcceptScriptMsg(EScriptObjectMessage, TUniqueId, CStateManager&) override; void Render(CStateManager&) override {} std::optional<zeus::CAABox> GetTouchBounds() const override; void SetInUse(bool inUse); bool GetInUse(TUniqueId uid) const; bool ShouldLandHere() const { return xe8_26_landHere; } bool ShouldWallHang() const { return xe8_27_wallHang; } bool ShouldStay() const { return xe8_28_stay; } bool ShouldCrouch() const { return xf8_24_crouch; } bool Blown(const zeus::CVector3f& pos) const; float GetSinSqVerticalAngle() const; float GetCosHorizontalAngle() const { return xec_cosHorizontalAngle; } pas::ECoverDirection GetAttackDirection() const { return xe8_30_attackDirection ? pas::ECoverDirection::Left : pas::ECoverDirection::Right; } void Reserve(TUniqueId id) { xfa_occupant = id; } }; } // namespace urde <commit_msg>CScriptCoverPoint: Fix GetAttackDirection return value<commit_after>#pragma once #include <optional> #include <string_view> #include "Runtime/GCNTypes.hpp" #include "Runtime/Character/CharacterCommon.hpp" #include "Runtime/World/CActor.hpp" #include <zeus/CAABox.hpp> namespace urde { class CScriptCoverPoint : public CActor { bool xe8_26_landHere : 1; bool xe8_27_wallHang : 1; bool xe8_28_stay : 1; bool xe8_29_ : 1; bool xe8_30_attackDirection : 1; float xec_cosHorizontalAngle; float xf0_sinVerticalAngle; float xf4_coverTime; bool xf8_24_crouch : 1; bool xf8_25_inUse : 1; TUniqueId xfa_occupant = kInvalidUniqueId; TUniqueId xfc_retreating = kInvalidUniqueId; std::optional<zeus::CAABox> x100_touchBounds; float x11c_timeLeft = 0.f; public: CScriptCoverPoint(TUniqueId uid, std::string_view name, const CEntityInfo& info, zeus::CTransform xf, bool active, u32 flags, bool crouch, float horizontalAngle, float verticalAngle, float coverTime); void Accept(IVisitor& visitor) override; void Think(float, CStateManager&) override; void AddToRenderer(const zeus::CFrustum&, CStateManager&) override {} void AcceptScriptMsg(EScriptObjectMessage, TUniqueId, CStateManager&) override; void Render(CStateManager&) override {} std::optional<zeus::CAABox> GetTouchBounds() const override; void SetInUse(bool inUse); bool GetInUse(TUniqueId uid) const; bool ShouldLandHere() const { return xe8_26_landHere; } bool ShouldWallHang() const { return xe8_27_wallHang; } bool ShouldStay() const { return xe8_28_stay; } bool ShouldCrouch() const { return xf8_24_crouch; } bool Blown(const zeus::CVector3f& pos) const; float GetSinSqVerticalAngle() const; float GetCosHorizontalAngle() const { return xec_cosHorizontalAngle; } pas::ECoverDirection GetAttackDirection() const { return xe8_30_attackDirection ? pas::ECoverDirection::Right : pas::ECoverDirection::Left; } void Reserve(TUniqueId id) { xfa_occupant = id; } }; } // namespace urde <|endoftext|>
<commit_before>/* * Copyright 2008-2013 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <agency/detail/config.hpp> #include <agency/cuda/detail/feature_test.hpp> #include <agency/cuda/detail/terminate.hpp> #include <agency/cuda/detail/unique_ptr.hpp> #include <utility> namespace agency { namespace cuda { template<typename T> class future; template<> class future<void> { public: // XXX stream_ should default to per-thread default stream __host__ __device__ future() : stream_{0}, event_{0} {} // XXX this should be private // XXX stream_ should default to per-thread default stream __host__ __device__ future(cudaEvent_t e) : stream_{0}, event_{e} { } // end future() __host__ __device__ future(cudaStream_t s) : stream_{s} { #if __cuda_lib_has_cudart detail::throw_on_error(cudaEventCreateWithFlags(&event_, event_create_flags), "cudaEventCreateWithFlags in agency::cuda::future<void> ctor"); detail::throw_on_error(cudaEventRecord(event_, stream_), "cudaEventRecord in agency::cuda::future<void> ctor"); #else detail::terminate_with_message("agency::cuda::future<void> ctor requires CUDART"); #endif // __cuda_lib_has_cudart } // end future() __host__ __device__ future(future&& other) : stream_{0}, event_{0} { future::swap(stream_, other.stream_); future::swap(event_, other.event_); } // end future() __host__ __device__ future &operator=(future&& other) { future::swap(stream_, other.stream_); future::swap(event_, other.event_); return *this; } // end operator=() __host__ __device__ ~future() { if(valid()) { #if __cuda_lib_has_cudart // swallow errors cudaError_t e = cudaEventDestroy(event_); #if __cuda_lib_has_printf if(e) { printf("CUDA error after cudaEventDestroy in agency::cuda::future<void> dtor: %s", cudaGetErrorString(e)); } // end if #endif // __cuda_lib_has_printf #endif // __cuda_lib_has_cudart } // end if } // end ~future() __host__ __device__ void wait() const { // XXX should probably check for valid() here #if __cuda_lib_has_cudart #ifndef __CUDA_ARCH__ // XXX need to capture the error as an exception and then throw it in .get() detail::throw_on_error(cudaEventSynchronize(event_), "cudaEventSynchronize in agency::cuda<void>::future::wait"); #else // XXX need to capture the error as an exception and then throw it in .get() detail::throw_on_error(cudaDeviceSynchronize(), "cudaDeviceSynchronize in agency::cuda<void>::future::wait"); #endif // __CUDA_ARCH__ #else detail::terminate_with_message("agency::cuda::future<void>::wait() requires CUDART"); #endif // __cuda_lib_has_cudart } // end wait() __host__ __device__ void get() const { wait(); } // end get() __host__ __device__ bool valid() const { return event_ != 0; } // end valid() __host__ __device__ cudaEvent_t event() const { return event_; } // end event() __host__ __device__ cudaStream_t stream() const { return stream_; } // end stream() __host__ __device__ static future<void> make_ready() { cudaEvent_t ready_event = 0; #if __cuda_lib_has_cudart detail::throw_on_error(cudaEventCreateWithFlags(&ready_event, event_create_flags), "cudaEventCreateWithFlags in agency::cuda::future<void>::make_ready"); #else detail::terminate_with_message("agency::cuda::future<void>::make_ready() requires CUDART"); #endif return future<void>{ready_event}; } // XXX this is only used by grid_executor::then_execute() __host__ __device__ std::nullptr_t ptr() { return nullptr; } private: // implement swap to avoid depending on thrust::swap template<class T> __host__ __device__ static void swap(T& a, T& b) { T tmp{a}; a = b; b = tmp; } static const int event_create_flags = cudaEventDisableTiming; cudaStream_t stream_; cudaEvent_t event_; }; // end future<void> template<class T> class future { public: __host__ __device__ future() : event_() {} // XXX this should be private template<class U> __host__ __device__ future(U&& value, future<void>& e) : event_(std::move(e)), value_(detail::make_unique<T>(event_.stream(), std::forward<U>(value))) { } // end future() __host__ __device__ future(cudaStream_t s) : event_(s) { } // end future() __host__ __device__ future(future&& other) : event_(std::move(other.event_)), value_(std::move(other.value_)) { } // end future() __host__ __device__ future &operator=(future&& other) { event_ = std::move(other.event_); value_ = std::move(other.value_); return *this; } // end operator=() __host__ __device__ void wait() const { event_.wait(); } // end wait() __host__ __device__ T get() const { wait(); return *value_; } // end get() __host__ __device__ bool valid() const { return event_.valid(); } // end valid() // XXX only used by grid_executor // think of a better way to expose this __host__ __device__ future<void>& void_future() { return event_; } // end void_future() template<class U> __host__ __device__ static future<T> make_ready(U&& value) { auto event = future<void>::make_ready(); return future<T>{std::forward<U>(value), event}; } // XXX this is only used by grid_executor::then_execute() __host__ __device__ T* ptr() { return value_.get(); } private: future<void> event_; detail::unique_ptr<T> value_; }; // end future<T> inline __host__ __device__ future<void> make_ready_future() { return future<void>::make_ready(); } // end make_ready_future() template<class T> inline __host__ __device__ future<typename std::decay<T>::type> make_ready_future(T&& value) { return future<typename std::decay<T>::type>::make_ready(std::forward<T>(value)); } // end make_ready_future() } // end namespace cuda } // end namespace agency <commit_msg>Implement cuda::future::discard_value()<commit_after>/* * Copyright 2008-2013 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <agency/detail/config.hpp> #include <agency/cuda/detail/feature_test.hpp> #include <agency/cuda/detail/terminate.hpp> #include <agency/cuda/detail/unique_ptr.hpp> #include <utility> namespace agency { namespace cuda { template<typename T> class future; template<> class future<void> { public: // XXX stream_ should default to per-thread default stream __host__ __device__ future() : stream_{0}, event_{0} {} // XXX this should be private // XXX stream_ should default to per-thread default stream __host__ __device__ future(cudaEvent_t e) : stream_{0}, event_{e} { } // end future() __host__ __device__ future(cudaStream_t s) : stream_{s} { #if __cuda_lib_has_cudart detail::throw_on_error(cudaEventCreateWithFlags(&event_, event_create_flags), "cudaEventCreateWithFlags in agency::cuda::future<void> ctor"); detail::throw_on_error(cudaEventRecord(event_, stream_), "cudaEventRecord in agency::cuda::future<void> ctor"); #else detail::terminate_with_message("agency::cuda::future<void> ctor requires CUDART"); #endif // __cuda_lib_has_cudart } // end future() __host__ __device__ future(future&& other) : stream_{0}, event_{0} { future::swap(stream_, other.stream_); future::swap(event_, other.event_); } // end future() __host__ __device__ future &operator=(future&& other) { future::swap(stream_, other.stream_); future::swap(event_, other.event_); return *this; } // end operator=() __host__ __device__ ~future() { if(valid()) { #if __cuda_lib_has_cudart // swallow errors cudaError_t e = cudaEventDestroy(event_); #if __cuda_lib_has_printf if(e) { printf("CUDA error after cudaEventDestroy in agency::cuda::future<void> dtor: %s", cudaGetErrorString(e)); } // end if #endif // __cuda_lib_has_printf #endif // __cuda_lib_has_cudart } // end if } // end ~future() __host__ __device__ void wait() const { // XXX should probably check for valid() here #if __cuda_lib_has_cudart #ifndef __CUDA_ARCH__ // XXX need to capture the error as an exception and then throw it in .get() detail::throw_on_error(cudaEventSynchronize(event_), "cudaEventSynchronize in agency::cuda<void>::future::wait"); #else // XXX need to capture the error as an exception and then throw it in .get() detail::throw_on_error(cudaDeviceSynchronize(), "cudaDeviceSynchronize in agency::cuda<void>::future::wait"); #endif // __CUDA_ARCH__ #else detail::terminate_with_message("agency::cuda::future<void>::wait() requires CUDART"); #endif // __cuda_lib_has_cudart } // end wait() __host__ __device__ void get() const { wait(); } // end get() __host__ __device__ future<void> discard_value() { return std::move(*this); } // end discard_value() __host__ __device__ bool valid() const { return event_ != 0; } // end valid() __host__ __device__ cudaEvent_t event() const { return event_; } // end event() __host__ __device__ cudaStream_t stream() const { return stream_; } // end stream() __host__ __device__ static future<void> make_ready() { cudaEvent_t ready_event = 0; #if __cuda_lib_has_cudart detail::throw_on_error(cudaEventCreateWithFlags(&ready_event, event_create_flags), "cudaEventCreateWithFlags in agency::cuda::future<void>::make_ready"); #else detail::terminate_with_message("agency::cuda::future<void>::make_ready() requires CUDART"); #endif return future<void>{ready_event}; } // XXX this is only used by grid_executor::then_execute() __host__ __device__ std::nullptr_t ptr() { return nullptr; } private: // implement swap to avoid depending on thrust::swap template<class T> __host__ __device__ static void swap(T& a, T& b) { T tmp{a}; a = b; b = tmp; } static const int event_create_flags = cudaEventDisableTiming; cudaStream_t stream_; cudaEvent_t event_; }; // end future<void> template<class T> class future { public: __host__ __device__ future() : event_() {} // XXX this should be private template<class U> __host__ __device__ future(U&& value, future<void>& e) : event_(std::move(e)), value_(detail::make_unique<T>(event_.stream(), std::forward<U>(value))) { } // end future() __host__ __device__ future(cudaStream_t s) : event_(s) { } // end future() __host__ __device__ future(future&& other) : event_(std::move(other.event_)), value_(std::move(other.value_)) { } // end future() __host__ __device__ future &operator=(future&& other) { event_ = std::move(other.event_); value_ = std::move(other.value_); return *this; } // end operator=() __host__ __device__ void wait() const { event_.wait(); } // end wait() __host__ __device__ T get() const { wait(); return *value_; } // end get() __host__ __device__ future<void> discard_value() { return std::move(event_); } // end discard_value() __host__ __device__ bool valid() const { return event_.valid(); } // end valid() // XXX only used by grid_executor // think of a better way to expose this __host__ __device__ future<void>& void_future() { return event_; } // end void_future() template<class U> __host__ __device__ static future<T> make_ready(U&& value) { auto event = future<void>::make_ready(); return future<T>{std::forward<U>(value), event}; } // XXX this is only used by grid_executor::then_execute() __host__ __device__ T* ptr() { return value_.get(); } private: future<void> event_; detail::unique_ptr<T> value_; }; // end future<T> inline __host__ __device__ future<void> make_ready_future() { return future<void>::make_ready(); } // end make_ready_future() template<class T> inline __host__ __device__ future<typename std::decay<T>::type> make_ready_future(T&& value) { return future<typename std::decay<T>::type>::make_ready(std::forward<T>(value)); } // end make_ready_future() } // end namespace cuda } // end namespace agency <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2012 Torus Knot Software Ltd 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 "SamplePlugin.h" #include "VolumeCSG.h" #include "OgreVolumeCSGSource.h" #include "OgreVolumeCacheSource.h" #include "OgreVolumeTextureSource.h" #include "OgreVolumeMeshBuilder.h" #include "OgreMath.h" using namespace Ogre; using namespace OgreBites; using namespace Ogre::Volume; void Sample_VolumeCSG::setupContent(void) { setupControls(); setupShaderGenerator(); Real size = (Real)31.0; Vector3 to(size); // Light Light* directionalLight0 = mSceneMgr->createLight("directionalLight0"); directionalLight0->setType(Light::LT_DIRECTIONAL); directionalLight0->setDirection(Vector3((Real)1, (Real)-1, (Real)1)); directionalLight0->setDiffuseColour((Real)1, (Real)0.98, (Real)0.73); directionalLight0->setSpecularColour((Real)0.1, (Real)0.1, (Real)0.1); // Spheres CSGSphereSource sphere1((Real)5.0, Vector3((Real)5.5)); CSGSphereSource sphere2((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)5.5)); CSGSphereSource sphere3((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)25.5)); CSGSphereSource sphere4((Real)5.0, Vector3((Real)5.5, (Real)5.5, (Real)25.5)); // Cubes Real halfWidth = (Real)(2.5 / 2.0); CSGCubeSource cube1(Vector3((Real)5.5 - halfWidth), Vector3((Real)25.5 + halfWidth, (Real)5.5 + halfWidth, (Real)25.5 + halfWidth)); CSGCubeSource cube2(Vector3((Real)5.5 + halfWidth, (Real)0.0, (Real)5.5 + halfWidth), Vector3((Real)25.5 - halfWidth, to.y, (Real)25.5 - halfWidth)); CSGDifferenceSource difference1(&cube1, &cube2); // Inner rounded cube Real innerHalfWidth = (Real)(7.0 / 2.0); Vector3 center((Real)15.5, (Real)5.5, (Real)15.5); CSGCubeSource cube3(center - innerHalfWidth, center + innerHalfWidth); CSGSphereSource sphere5(innerHalfWidth + (Real)0.75, center); CSGIntersectionSource intersection1(&cube3, &sphere5); // A plane with noise CSGPlaneSource plane1((Real)1.0, Vector3::UNIT_Y); Real frequencies[] = {(Real)1.01, (Real)0.48}; Real amplitudes[] = {(Real)0.25, (Real)0.5}; CSGNoiseSource noise1(&plane1, frequencies, amplitudes, 2, 100); // Combine everything CSGUnionSource union1(&sphere1, &sphere2); CSGUnionSource union2(&union1, &sphere3); CSGUnionSource union3(&union2, &sphere4); CSGUnionSource union4(&union3, &difference1); CSGUnionSource union5(&union4, &intersection1); CSGUnionSource union6(&union5, &noise1); Source *src = &union6; mVolumeRoot = OGRE_NEW Chunk(); SceneNode *volumeRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("VolumeParent"); ChunkParameters parameters; parameters.sceneManager = mSceneMgr; parameters.src = src; parameters.baseError = (Real)0.25; mVolumeRoot->load(volumeRootNode, Vector3::ZERO, to, 1, &parameters); mVolumeRoot->setMaterial("Ogre/RTShader/TriplanarTexturing"); // Camera mCamera->setPosition(to + (Real)7.5); mCamera->lookAt(center + (Real)11.0); mCamera->setNearClipDistance((Real)0.5); mRotation = (Real)0.0; } //----------------------------------------------------------------------- void Sample_VolumeCSG::setupControls(void) { mTrayMgr->showCursor(); #if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS setDragLook(true); #endif mCameraMan->setStyle(OgreBites::CS_MANUAL); mCameraMan->setTopSpeed((Real)25.0); // make room for the volume mTrayMgr->showLogo(TL_TOPRIGHT); mTrayMgr->showFrameStats(TL_TOPRIGHT); mTrayMgr->toggleAdvancedFrameStats(); } //----------------------------------------------------------------------- void Sample_VolumeCSG::setupShaderGenerator() { RTShader::ShaderGenerator* mGen = RTShader::ShaderGenerator::getSingletonPtr(); mGen->setTargetLanguage("cg"); RTShader::RenderState* pMainRenderState = mGen->createOrRetrieveRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first; pMainRenderState->reset(); mGen->invalidateScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); // Make this viewport work with shader generator scheme. mViewport->setMaterialScheme(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); } //----------------------------------------------------------------------- void Sample_VolumeCSG::cleanupContent(void) { OGRE_DELETE mVolumeRoot; mVolumeRoot = 0; } //----------------------------------------------------------------------- Sample_VolumeCSG::Sample_VolumeCSG(void) : mVolumeRoot(0), mHideAll(false) { mInfo["Title"] = "Volume CSG and RTSS triplanar texturing"; mInfo["Description"] = "Demonstrates a volumetric CSG scene, showing sphere, cube, plane, union, difference and intersection. The triplanar texturing is generated by the RTSS."; mInfo["Thumbnail"] = "thumb_volumecsg.png"; mInfo["Category"] = "Geometry"; } //----------------------------------------------------------------------- bool Sample_VolumeCSG::keyPressed(const OIS::KeyEvent& evt) { if (evt.key == OIS::KC_H) { if (mHideAll) { mTrayMgr->showAll(); } else { mTrayMgr->hideAll(); } mHideAll = !mHideAll; } return SdkSample::keyPressed(evt); } bool Sample_VolumeCSG::frameRenderingQueued(const Ogre::FrameEvent& evt) { Vector3 center((Real)15.5, (Real)5.5, (Real)15.5); mRotation += Radian(evt.timeSinceLastFrame * (Real)0.5); Real r = (Real)35.0; mCamera->setPosition( Math::Sin(mRotation) * r + center.x, (Real)15.0 + center.y, Math::Cos(mRotation) * r + center.z ); mCamera->lookAt(center); return SdkSample::frameRenderingQueued(evt); } //----------------------------------------------------------------------- void Sample_VolumeCSG::_shutdown() { RTShader::RenderState* pMainRenderState = RTShader::ShaderGenerator::getSingleton().createOrRetrieveRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first; pMainRenderState->reset(); SdkSample::_shutdown(); } //----------------------------------------------------------------------- #ifndef OGRE_STATIC_LIB SamplePlugin* sp; Sample* s; //----------------------------------------------------------------------- extern "C" _OgreSampleExport void dllStartPlugin() { s = new Sample_VolumeCSG(); sp = OGRE_NEW SamplePlugin(s->getInfo()["Title"] + " Sample"); sp->addSample(s); Root::getSingleton().installPlugin(sp); } //----------------------------------------------------------------------- extern "C" _OgreSampleExport void dllStopPlugin() { Root::getSingleton().uninstallPlugin(sp); OGRE_DELETE sp; delete s; } #endif <commit_msg>Backout changeset 91b796f879aba6fc030b36895769ae1ef5d7c856<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2012 Torus Knot Software Ltd 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 "SamplePlugin.h" #include "VolumeCSG.h" #include "OgreVolumeCSGSource.h" #include "OgreVolumeCacheSource.h" #include "OgreVolumeTextureSource.h" #include "OgreVolumeMeshBuilder.h" #include "OgreMath.h" using namespace Ogre; using namespace OgreBites; using namespace Ogre::Volume; void Sample_VolumeCSG::setupContent(void) { setupControls(); setupShaderGenerator(); Real size = (Real)31.0; Vector3 to(size); // Light Light* directionalLight0 = mSceneMgr->createLight("directionalLight0"); directionalLight0->setType(Light::LT_DIRECTIONAL); directionalLight0->setDirection(Vector3((Real)1, (Real)-1, (Real)1)); directionalLight0->setDiffuseColour((Real)1, (Real)0.98, (Real)0.73); directionalLight0->setSpecularColour((Real)0.1, (Real)0.1, (Real)0.1); // Spheres CSGSphereSource sphere1((Real)5.0, Vector3((Real)5.5)); CSGSphereSource sphere2((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)5.5)); CSGSphereSource sphere3((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)25.5)); CSGSphereSource sphere4((Real)5.0, Vector3((Real)5.5, (Real)5.5, (Real)25.5)); // Cubes Real halfWidth = (Real)(2.5 / 2.0); CSGCubeSource cube1(Vector3((Real)5.5 - halfWidth), Vector3((Real)25.5 + halfWidth, (Real)5.5 + halfWidth, (Real)25.5 + halfWidth)); CSGCubeSource cube2(Vector3((Real)5.5 + halfWidth, (Real)0.0, (Real)5.5 + halfWidth), Vector3((Real)25.5 - halfWidth, to.y, (Real)25.5 - halfWidth)); CSGDifferenceSource difference1(&cube1, &cube2); // Inner rounded cube Real innerHalfWidth = (Real)(7.0 / 2.0); Vector3 center((Real)15.5, (Real)5.5, (Real)15.5); CSGCubeSource cube3(center - innerHalfWidth, center + innerHalfWidth); CSGSphereSource sphere5(innerHalfWidth + (Real)0.75, center); CSGIntersectionSource intersection1(&cube3, &sphere5); // A plane with noise CSGPlaneSource plane1((Real)1.0, Vector3::UNIT_Y); Real frequencies[] = {(Real)1.01, (Real)0.48}; Real amplitudes[] = {(Real)0.25, (Real)0.5}; CSGNoiseSource noise1(&plane1, frequencies, amplitudes, 2, 100); // Combine everything CSGUnionSource union1(&sphere1, &sphere2); CSGUnionSource union2(&union1, &sphere3); CSGUnionSource union3(&union2, &sphere4); CSGUnionSource union4(&union3, &difference1); CSGUnionSource union5(&union4, &intersection1); CSGUnionSource union6(&union5, &noise1); Source *src = &union6; src->serialize(Vector3::ZERO, to, (Real)0.12109375, "volume.dat"); mVolumeRoot = OGRE_NEW Chunk(); SceneNode *volumeRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("VolumeParent"); ChunkParameters parameters; parameters.sceneManager = mSceneMgr; parameters.src = src; parameters.baseError = (Real)0.25; mVolumeRoot->load(volumeRootNode, Vector3::ZERO, to, 1, &parameters); mVolumeRoot->setMaterial("Ogre/RTShader/TriplanarTexturing"); // Camera mCamera->setPosition(to + (Real)7.5); mCamera->lookAt(center + (Real)11.0); mCamera->setNearClipDistance((Real)0.5); mRotation = (Real)0.0; } //----------------------------------------------------------------------- void Sample_VolumeCSG::setupControls(void) { mTrayMgr->showCursor(); #if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS setDragLook(true); #endif mCameraMan->setStyle(OgreBites::CS_MANUAL); mCameraMan->setTopSpeed((Real)25.0); // make room for the volume mTrayMgr->showLogo(TL_TOPRIGHT); mTrayMgr->showFrameStats(TL_TOPRIGHT); mTrayMgr->toggleAdvancedFrameStats(); } //----------------------------------------------------------------------- void Sample_VolumeCSG::setupShaderGenerator() { RTShader::ShaderGenerator* mGen = RTShader::ShaderGenerator::getSingletonPtr(); mGen->setTargetLanguage("cg"); RTShader::RenderState* pMainRenderState = mGen->createOrRetrieveRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first; pMainRenderState->reset(); mGen->invalidateScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); // Make this viewport work with shader generator scheme. mViewport->setMaterialScheme(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); } //----------------------------------------------------------------------- void Sample_VolumeCSG::cleanupContent(void) { OGRE_DELETE mVolumeRoot; mVolumeRoot = 0; } //----------------------------------------------------------------------- Sample_VolumeCSG::Sample_VolumeCSG(void) : mVolumeRoot(0), mHideAll(false) { mInfo["Title"] = "Volume CSG and RTSS triplanar texturing"; mInfo["Description"] = "Demonstrates a volumetric CSG scene, showing sphere, cube, plane, union, difference and intersection. The triplanar texturing is generated by the RTSS."; mInfo["Thumbnail"] = "thumb_volumecsg.png"; mInfo["Category"] = "Geometry"; } //----------------------------------------------------------------------- bool Sample_VolumeCSG::keyPressed(const OIS::KeyEvent& evt) { if (evt.key == OIS::KC_H) { if (mHideAll) { mTrayMgr->showAll(); } else { mTrayMgr->hideAll(); } mHideAll = !mHideAll; } return SdkSample::keyPressed(evt); } bool Sample_VolumeCSG::frameRenderingQueued(const Ogre::FrameEvent& evt) { Vector3 center((Real)15.5, (Real)5.5, (Real)15.5); mRotation += Radian(evt.timeSinceLastFrame * (Real)0.5); Real r = (Real)35.0; mCamera->setPosition( Math::Sin(mRotation) * r + center.x, (Real)15.0 + center.y, Math::Cos(mRotation) * r + center.z ); mCamera->lookAt(center); return SdkSample::frameRenderingQueued(evt); } //----------------------------------------------------------------------- void Sample_VolumeCSG::_shutdown() { RTShader::RenderState* pMainRenderState = RTShader::ShaderGenerator::getSingleton().createOrRetrieveRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first; pMainRenderState->reset(); SdkSample::_shutdown(); } //----------------------------------------------------------------------- #ifndef OGRE_STATIC_LIB SamplePlugin* sp; Sample* s; //----------------------------------------------------------------------- extern "C" _OgreSampleExport void dllStartPlugin() { s = new Sample_VolumeCSG(); sp = OGRE_NEW SamplePlugin(s->getInfo()["Title"] + " Sample"); sp->addSample(s); Root::getSingleton().installPlugin(sp); } //----------------------------------------------------------------------- extern "C" _OgreSampleExport void dllStopPlugin() { Root::getSingleton().uninstallPlugin(sp); OGRE_DELETE sp; delete s; } #endif <|endoftext|>
<commit_before>/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //--------------------------------------------------------------------------- // Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Setup.h" //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #if defined(MEDIAINFO_TTML_YES) //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Text/File_Ttml.h" #if MEDIAINFO_EVENTS #include "MediaInfo/MediaInfo_Config_MediaInfo.h" #include "MediaInfo/MediaInfo_Events_Internal.h" #endif //MEDIAINFO_EVENTS #include "tinyxml2.h" #include <cstring> using namespace tinyxml2; using namespace std; //--------------------------------------------------------------------------- namespace MediaInfoLib { //*************************************************************************** // Utils //*************************************************************************** int64u Ttml_str2timecode(const char* Value) { size_t Length=strlen(Value); if (Length>=8 && Value[0]>='0' && Value[0]<='9' && Value[1]>='0' && Value[1]<='9' && Value[2]==':' && Value[3]>='0' && Value[3]<='9' && Value[4]>='0' && Value[4]<='9' && Value[5]==':' && Value[6]>='0' && Value[6]<='9' && Value[7]>='0' && Value[7]<='9') { int64u ToReturn=(int64u)(Value[0]-'0')*10*60*60*1000000000 +(int64u)(Value[1]-'0') *60*60*1000000000 +(int64u)(Value[3]-'0') *10*60*1000000000 +(int64u)(Value[4]-'0') *60*1000000000 +(int64u)(Value[6]-'0') *10*1000000000 +(int64u)(Value[7]-'0') *1000000000; if (Length>=9 && (Value[8]=='.' || Value[8]==',')) { if (Length>9+9) Length=9+9; //Nanoseconds max const char* Value_End=Value+Length; Value+=9; int64u Multiplier=100000000; while (Value<Value_End) { ToReturn+=(int64u)(*Value-'0')*Multiplier; Multiplier/=10; Value++; } } return ToReturn; } else if (Length>=2 && Value[Length-1]=='s') { return (int64u)(atof(Value)*1000000000); } else return (int64u)-1; } //*************************************************************************** // Constructor/Destructor //*************************************************************************** //--------------------------------------------------------------------------- File_Ttml::File_Ttml() :File__Analyze() { //Configuration #if MEDIAINFO_EVENTS ParserIDs[0]=MediaInfo_Parser_Ttml; StreamIDs_Width[0]=0; #endif //MEDIAINFO_EVENTS //Init Frame_Count=0; } //*************************************************************************** // Streams management //*************************************************************************** //--------------------------------------------------------------------------- void File_Ttml::Streams_Accept() { Fill(Stream_General, 0, General_Format, "TTML"); Stream_Prepare(Stream_Text); Fill(Stream_Text, 0, "Format", "TTML"); } //*************************************************************************** // Buffer - Global //*************************************************************************** //--------------------------------------------------------------------------- void File_Ttml::Read_Buffer_Unsynched() { GoTo(0); } //--------------------------------------------------------------------------- #if MEDIAINFO_SEEK size_t File_Ttml::Read_Buffer_Seek (size_t Method, int64u Value, int64u ID) { Open_Buffer_Unsynch(); return 1; } #endif //MEDIAINFO_SEEK //*************************************************************************** // Buffer - File header //*************************************************************************** //--------------------------------------------------------------------------- bool File_Ttml::FileHeader_Begin() { //All should be OK... return true; } //--------------------------------------------------------------------------- void File_Ttml::Read_Buffer_Continue() { tinyxml2::XMLDocument document; if (!FileHeader_Begin_XML(document)) return; XMLElement* Root=document.FirstChildElement("tt"); if (!Root) { Reject(); return; } if (!Status[IsAccepted]) { Accept(); #if MEDIAINFO_EVENTS MuxingMode=(int8u)-1; if (StreamIDs_Size>=2 && ParserIDs[StreamIDs_Size-2]==MediaInfo_Parser_Mpeg4) MuxingMode=11; //MPEG-4 if (StreamIDs_Size>2 && ParserIDs[StreamIDs_Size-2]==MediaInfo_Parser_Mxf) //Only if referenced MXF MuxingMode=13; //MXF #endif MEDIAINFO_EVENTS } tinyxml2::XMLElement* div=NULL; #if MEDIAINFO_EVENTS tinyxml2::XMLElement* p=NULL; #endif //MEDIAINFO_EVENTS for (XMLElement* tt_element=Root->FirstChildElement(); tt_element; tt_element=tt_element->NextSiblingElement()) { //body if (!strcmp(tt_element->Value(), "body")) { for (XMLElement* body_element=tt_element->FirstChildElement(); body_element; body_element=body_element->NextSiblingElement()) { //div if (!strcmp(body_element->Value(), "div")) { for (XMLElement* div_element=body_element->FirstChildElement(); div_element; div_element=div_element->NextSiblingElement()) { //p if (!strcmp(div_element->Value(), "p")) { div=body_element; #if MEDIAINFO_EVENTS p=div_element; #endif //MEDIAINFO_EVENTS break; } } if (div) break; } } if (div) break; } } #if MEDIAINFO_DEMUX Demux(Buffer, Buffer_Size, ContentType_MainStream); #endif //MEDIAINFO_DEMUX // Output #if MEDIAINFO_EVENTS for (; p; p=p->NextSiblingElement()) { //p if (!strcmp(p->Value(), "p")) { const char* Attribute; int64u DTS_Begin=(int64u)-1; Attribute=p->Attribute("begin"); if (Attribute) DTS_Begin=Ttml_str2timecode(Attribute); int64u DTS_End=(int64u)-1; Attribute=p->Attribute("end"); if (Attribute) DTS_End=Ttml_str2timecode(Attribute); string ContentUtf8; XMLPrinter printer; p->Accept(&printer); ContentUtf8+=printer.CStr(); while (!ContentUtf8.empty() && (ContentUtf8[ContentUtf8.size()-1]=='\r' || ContentUtf8[ContentUtf8.size()-1]=='\n')) ContentUtf8.resize(ContentUtf8.size()-1); Ztring Content; if (p->FirstChild()) Content.From_UTF8(p->FirstChild()->Value()); Frame_Count++; } } #endif MEDIAINFO_EVENTS Buffer_Offset=Buffer_Size; } } //NameSpace #endif //MEDIAINFO_TTML_YES <commit_msg>x TTML demux was done too early with NextPacket interface<commit_after>/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //--------------------------------------------------------------------------- // Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Setup.h" //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #if defined(MEDIAINFO_TTML_YES) //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Text/File_Ttml.h" #if MEDIAINFO_EVENTS #include "MediaInfo/MediaInfo_Config_MediaInfo.h" #include "MediaInfo/MediaInfo_Events_Internal.h" #endif //MEDIAINFO_EVENTS #include "tinyxml2.h" #include <cstring> using namespace tinyxml2; using namespace std; //--------------------------------------------------------------------------- namespace MediaInfoLib { //*************************************************************************** // Utils //*************************************************************************** int64u Ttml_str2timecode(const char* Value) { size_t Length=strlen(Value); if (Length>=8 && Value[0]>='0' && Value[0]<='9' && Value[1]>='0' && Value[1]<='9' && Value[2]==':' && Value[3]>='0' && Value[3]<='9' && Value[4]>='0' && Value[4]<='9' && Value[5]==':' && Value[6]>='0' && Value[6]<='9' && Value[7]>='0' && Value[7]<='9') { int64u ToReturn=(int64u)(Value[0]-'0')*10*60*60*1000000000 +(int64u)(Value[1]-'0') *60*60*1000000000 +(int64u)(Value[3]-'0') *10*60*1000000000 +(int64u)(Value[4]-'0') *60*1000000000 +(int64u)(Value[6]-'0') *10*1000000000 +(int64u)(Value[7]-'0') *1000000000; if (Length>=9 && (Value[8]=='.' || Value[8]==',')) { if (Length>9+9) Length=9+9; //Nanoseconds max const char* Value_End=Value+Length; Value+=9; int64u Multiplier=100000000; while (Value<Value_End) { ToReturn+=(int64u)(*Value-'0')*Multiplier; Multiplier/=10; Value++; } } return ToReturn; } else if (Length>=2 && Value[Length-1]=='s') { return (int64u)(atof(Value)*1000000000); } else return (int64u)-1; } //*************************************************************************** // Constructor/Destructor //*************************************************************************** //--------------------------------------------------------------------------- File_Ttml::File_Ttml() :File__Analyze() { //Configuration #if MEDIAINFO_EVENTS ParserIDs[0]=MediaInfo_Parser_Ttml; StreamIDs_Width[0]=0; #endif //MEDIAINFO_EVENTS //Init Frame_Count=0; } //*************************************************************************** // Streams management //*************************************************************************** //--------------------------------------------------------------------------- void File_Ttml::Streams_Accept() { Fill(Stream_General, 0, General_Format, "TTML"); Stream_Prepare(Stream_Text); Fill(Stream_Text, 0, "Format", "TTML"); } //*************************************************************************** // Buffer - Global //*************************************************************************** //--------------------------------------------------------------------------- void File_Ttml::Read_Buffer_Unsynched() { GoTo(0); } //--------------------------------------------------------------------------- #if MEDIAINFO_SEEK size_t File_Ttml::Read_Buffer_Seek (size_t Method, int64u Value, int64u ID) { Open_Buffer_Unsynch(); return 1; } #endif //MEDIAINFO_SEEK //*************************************************************************** // Buffer - File header //*************************************************************************** //--------------------------------------------------------------------------- bool File_Ttml::FileHeader_Begin() { //All should be OK... return true; } //--------------------------------------------------------------------------- void File_Ttml::Read_Buffer_Continue() { tinyxml2::XMLDocument document; if (!FileHeader_Begin_XML(document)) return; XMLElement* Root=document.FirstChildElement("tt"); if (!Root) { Reject(); return; } if (!Status[IsAccepted]) { Accept(); #if MEDIAINFO_EVENTS MuxingMode=(int8u)-1; if (StreamIDs_Size>=2 && ParserIDs[StreamIDs_Size-2]==MediaInfo_Parser_Mpeg4) MuxingMode=11; //MPEG-4 if (StreamIDs_Size>2 && ParserIDs[StreamIDs_Size-2]==MediaInfo_Parser_Mxf) //Only if referenced MXF MuxingMode=13; //MXF #endif MEDIAINFO_EVENTS #if MEDIAINFO_DEMUX && MEDIAINFO_NEXTPACKET if (Config->NextPacket_Get() && Config->Event_CallBackFunction_IsSet()) return; // Waiting for NextPacket #endif //MEDIAINFO_DEMUX && MEDIAINFO_NEXTPACKET } tinyxml2::XMLElement* div=NULL; #if MEDIAINFO_EVENTS tinyxml2::XMLElement* p=NULL; #endif //MEDIAINFO_EVENTS for (XMLElement* tt_element=Root->FirstChildElement(); tt_element; tt_element=tt_element->NextSiblingElement()) { //body if (!strcmp(tt_element->Value(), "body")) { for (XMLElement* body_element=tt_element->FirstChildElement(); body_element; body_element=body_element->NextSiblingElement()) { //div if (!strcmp(body_element->Value(), "div")) { for (XMLElement* div_element=body_element->FirstChildElement(); div_element; div_element=div_element->NextSiblingElement()) { //p if (!strcmp(div_element->Value(), "p")) { div=body_element; #if MEDIAINFO_EVENTS p=div_element; #endif //MEDIAINFO_EVENTS break; } } if (div) break; } } if (div) break; } } #if MEDIAINFO_DEMUX Demux(Buffer, Buffer_Size, ContentType_MainStream); #endif //MEDIAINFO_DEMUX // Output #if MEDIAINFO_EVENTS for (; p; p=p->NextSiblingElement()) { //p if (!strcmp(p->Value(), "p")) { const char* Attribute; int64u DTS_Begin=(int64u)-1; Attribute=p->Attribute("begin"); if (Attribute) DTS_Begin=Ttml_str2timecode(Attribute); int64u DTS_End=(int64u)-1; Attribute=p->Attribute("end"); if (Attribute) DTS_End=Ttml_str2timecode(Attribute); string ContentUtf8; XMLPrinter printer; p->Accept(&printer); ContentUtf8+=printer.CStr(); while (!ContentUtf8.empty() && (ContentUtf8[ContentUtf8.size()-1]=='\r' || ContentUtf8[ContentUtf8.size()-1]=='\n')) ContentUtf8.resize(ContentUtf8.size()-1); Ztring Content; if (p->FirstChild()) Content.From_UTF8(p->FirstChild()->Value()); Frame_Count++; } } #endif MEDIAINFO_EVENTS Buffer_Offset=Buffer_Size; } } //NameSpace #endif //MEDIAINFO_TTML_YES <|endoftext|>
<commit_before>#include <event/event_callback.h> #include <event/event_main.h> #include <event/event_system.h> #define TIMER_MS 1000 static uint8_t zbuf[8192]; class BufferSpeed { uintmax_t bytes_; Action *callback_action_; Action *timeout_action_; public: BufferSpeed(void) : callback_action_(NULL), timeout_action_(NULL) { callback_action_ = callback(this, &BufferSpeed::callback_complete)->schedule(); INFO("/example/buffer/append/speed1") << "Arming timer."; timeout_action_ = EventSystem::instance()->timeout(TIMER_MS, callback(this, &BufferSpeed::timer)); } ~BufferSpeed() { ASSERT(timeout_action_ == NULL); } private: void callback_complete(void) { callback_action_->cancel(); callback_action_ = NULL; Buffer tmp; tmp.append(zbuf, sizeof zbuf); bytes_ += tmp.length(); callback_action_ = callback(this, &BufferSpeed::callback_complete)->schedule(); } void timer(void) { timeout_action_->cancel(); timeout_action_ = NULL; ASSERT(callback_action_ != NULL); callback_action_->cancel(); callback_action_ = NULL; INFO("/example/buffer/append/speed1") << "Timer expired; " << bytes_ << " bytes appended."; } }; int main(void) { INFO("/example/buffer/append/speed1") << "Timer delay: " << TIMER_MS << "ms"; memset(zbuf, 0, sizeof zbuf); BufferSpeed *cs = new BufferSpeed(); event_main(); delete cs; } <commit_msg>Initialize the byte counter.<commit_after>#include <event/event_callback.h> #include <event/event_main.h> #include <event/event_system.h> #define TIMER_MS 1000 static uint8_t zbuf[8192]; class BufferSpeed { uintmax_t bytes_; Action *callback_action_; Action *timeout_action_; public: BufferSpeed(void) : bytes_(0), callback_action_(NULL), timeout_action_(NULL) { callback_action_ = callback(this, &BufferSpeed::callback_complete)->schedule(); INFO("/example/buffer/append/speed1") << "Arming timer."; timeout_action_ = EventSystem::instance()->timeout(TIMER_MS, callback(this, &BufferSpeed::timer)); } ~BufferSpeed() { ASSERT(timeout_action_ == NULL); } private: void callback_complete(void) { callback_action_->cancel(); callback_action_ = NULL; Buffer tmp; tmp.append(zbuf, sizeof zbuf); bytes_ += tmp.length(); callback_action_ = callback(this, &BufferSpeed::callback_complete)->schedule(); } void timer(void) { timeout_action_->cancel(); timeout_action_ = NULL; ASSERT(callback_action_ != NULL); callback_action_->cancel(); callback_action_ = NULL; INFO("/example/buffer/append/speed1") << "Timer expired; " << bytes_ << " bytes appended."; } }; int main(void) { INFO("/example/buffer/append/speed1") << "Timer delay: " << TIMER_MS << "ms"; memset(zbuf, 0, sizeof zbuf); BufferSpeed *cs = new BufferSpeed(); event_main(); delete cs; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: antsCommandLineParser.cxx,v $ Language: C++ Date: $Date: 2009/01/22 22:43:11 $ Version: $Revision: 1.1 $ 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. =========================================================================*/ #include "antsCommandLineParser.h" #include <algorithm> namespace itk { namespace ants { CommandLineParser ::CommandLineParser() { this->m_Options.clear(); this->m_Command.clear(); this->m_CommandDescription.clear(); this->m_UnknownOptions.clear(); this->m_LeftDelimiter = '['; this->m_RightDelimiter = ']'; } void CommandLineParser ::AddOption( OptionType::Pointer option ) { if( ( option->GetShortName() != '\0' || !this->GetOption( option->GetShortName() ) ) || ( !option->GetLongName().empty() || !this->GetOption( option->GetLongName() ) ) ) { this->m_Options.push_back( option ); } else { if( option->GetShortName() != '\0' && this->GetOption( option->GetShortName() ) ) { itkWarningMacro( "Duplicate short option '-" << option->GetShortName() << "'" ); } if( !( option->GetLongName().empty() ) && this->GetOption( option->GetLongName() ) ) { itkWarningMacro( "Duplicate long option '--" << option->GetLongName() << "'" ); } } } void CommandLineParser ::Parse( unsigned int argc, char * *argv ) { std::vector<std::string> arguments = this->RegroupCommandLineArguments( argc, argv ); unsigned int n = 0; this->m_Command = arguments[n++]; while( n < arguments.size() ) { std::string argument = arguments[n++]; std::string name; name.clear(); if( argument.find( "--" ) == 0 ) { name = argument.substr( 2, argument.length() - 1 ); } else if( argument.find( "-" ) == 0 && argument.find( "--" ) > 0 ) { name = argument.substr( 1, 2 ); } if( !( name.empty() ) ) { OptionType::Pointer option = this->GetOption( name ); if( !option ) { OptionType::Pointer unknownOption = OptionType::New(); if( name.length() > 1 ) { unknownOption->SetLongName( name ); } else { unknownOption->SetShortName( name.at( 0 ) ); } if( n == arguments.size() ) { unknownOption->AddValue( "1", this->m_LeftDelimiter, this->m_RightDelimiter ); } else { for( unsigned int m = n; m < arguments.size(); m++ ) { std::string value = arguments[m]; if( value.find( "-" ) != 0 ) { unknownOption->AddValue( value, this->m_LeftDelimiter, this->m_RightDelimiter ); } else { if( m == n ) { unknownOption->AddValue( "1", this->m_LeftDelimiter, this->m_RightDelimiter ); } n = m; break; } } } this->m_UnknownOptions.push_back( unknownOption ); } else // the option exists { if( n == arguments.size() ) { option->AddValue( "1", this->m_LeftDelimiter, this->m_RightDelimiter ); } else { for( unsigned int m = n; m < arguments.size(); m++ ) { std::string value = arguments[m]; if( value.find( "-" ) != 0 ) { option->AddValue( value, this->m_LeftDelimiter, this->m_RightDelimiter ); } else { if( m == n ) { option->AddValue( "1", this->m_LeftDelimiter, this->m_RightDelimiter ); } n = m; break; } } } } } } } std::vector<std::string> CommandLineParser ::RegroupCommandLineArguments( unsigned int argc, char * *argv ) { /** * Inclusion of this function allows the user to use spaces inside * the left and right delimiters. Also replace other left and right * delimiters. */ std::vector<std::string> arguments; std::string currentArg( "" ); bool isArgOpen = false; for( unsigned int n = 0; n < argc; n++ ) { std::string a( argv[n] ); // replace left delimiters std::replace( a.begin(), a.end(), '{', '[' ); std::replace( a.begin(), a.end(), '(', '[' ); std::replace( a.begin(), a.end(), '<', '[' ); // replace right delimiters std::replace( a.begin(), a.end(), '}', ']' ); std::replace( a.begin(), a.end(), ')', ']' ); std::replace( a.begin(), a.end(), '>', ']' ); if( isArgOpen ) { std::size_t leftDelimiterPosition = a.find( this->m_LeftDelimiter ); if( leftDelimiterPosition != std::string::npos ) { itkExceptionMacro( "Incorrect command line specification." ); } std::size_t rightDelimiterPosition = a.find( this->m_RightDelimiter ); if( rightDelimiterPosition != std::string::npos ) { if( rightDelimiterPosition < a.length() - 1 ) { itkExceptionMacro( "Incorrect command line specification." ); } else { currentArg += a; arguments.push_back( currentArg ); currentArg.clear(); isArgOpen = false; } } else { currentArg += a; } } else { std::size_t leftDelimiterPosition = a.find( this->m_LeftDelimiter ); std::size_t rightDelimiterPosition = a.find( this->m_RightDelimiter ); if( leftDelimiterPosition == std::string::npos ) { if( rightDelimiterPosition == std::string::npos ) { currentArg += a; arguments.push_back( currentArg ); currentArg.clear(); } else { itkExceptionMacro( "Incorrect command line specification." ); } } else if( leftDelimiterPosition != std::string::npos && rightDelimiterPosition != std::string::npos && leftDelimiterPosition < rightDelimiterPosition ) { if( rightDelimiterPosition < a.length() - 1 ) { itkExceptionMacro( "Incorrect command line specification." ); } currentArg += a; arguments.push_back( currentArg ); currentArg.clear(); isArgOpen = false; } else if( rightDelimiterPosition == std::string::npos && leftDelimiterPosition != std::string::npos ) { currentArg += a; isArgOpen = true; } } } return arguments; } CommandLineParser::OptionType::Pointer CommandLineParser ::GetOption( std::string name ) { if( name.length() == 1 ) { return this->GetOption( name.at( 0 ) ); } OptionListType::iterator it; for( it = this->m_Options.begin(); it != this->m_Options.end(); it++ ) { if( name.compare( (*it)->GetLongName() ) == 0 ) { return *it; } } return NULL; } CommandLineParser::OptionType::Pointer CommandLineParser ::GetOption( char name ) { OptionListType::iterator it; for( it = this->m_Options.begin(); it != this->m_Options.end(); it++ ) { if( name == (*it)->GetShortName() ) { return *it; } } return NULL; } void CommandLineParser ::PrintMenu( std::ostream& os, Indent indent, bool printShortVersion ) const { os << std::endl; os << "COMMAND: " << std::endl; os << indent << this->m_Command << std::endl; if( !this->m_CommandDescription.empty() && !printShortVersion ) { std::stringstream ss1; ss1 << indent << indent; std::stringstream ss2; ss2 << this->m_CommandDescription; std::string description = this->BreakUpStringIntoNewLines( ss2.str(), ss1.str(), 80 ); os << indent << indent << description << std::endl; } os << std::endl; os << "OPTIONS: " << std::endl; OptionListType::const_iterator it; for( it = this->m_Options.begin(); it != this->m_Options.end(); it++ ) { os << indent; std::stringstream ss; ss << indent; if( (*it)->GetShortName() != '\0' ) { os << "-" << (*it)->GetShortName(); ss << Indent( 2 ); if( !( (*it)->GetLongName() ).empty() ) { os << ", " << "--" << (*it)->GetLongName() << " " << std::flush; ss << Indent( 5 + ( (*it)->GetLongName() ).length() ); } else { os << " " << std::flush; ss << Indent( 1 ); } } else { os << "--" << (*it)->GetLongName() << " " << std::flush; ss << Indent( 3 + ( (*it)->GetLongName() ).length() ); } if( (*it)->GetNumberOfUsageOptions() > 0 ) { os << (*it)->GetUsageOption( 0 ) << std::endl; for( unsigned int i = 1; i < (*it)->GetNumberOfUsageOptions(); i++ ) { os << ss.str() << (*it)->GetUsageOption( i ) << std::endl; } } else { os << std::endl; } if( !( (*it)->GetDescription().empty() ) && !printShortVersion ) { std::stringstream ss1; ss1 << indent << indent; std::stringstream ss2; ss2 << (*it)->GetDescription(); std::string description = this->BreakUpStringIntoNewLines( ss2.str(), ss1.str(), 80 ); os << indent << indent << description << std::endl; } if( !printShortVersion ) { if( (*it)->GetValues().size() == 1 ) { os << indent << indent << "<VALUES>: " << (*it)->GetValue( 0 ); if( (*it)->GetParameters( 0 ).size() > 0 ) { os << "["; if( (*it)->GetParameters( 0 ).size() == 1 ) { os << (*it)->GetParameter( 0, 0 ); } else { for( unsigned int i = 0; i < (*it)->GetParameters( 0 ).size() - 1; i++ ) { os << (*it)->GetParameter( 0, i ) << ","; } os << (*it)->GetParameter( 0, (*it)->GetParameters( 0 ).size() - 1 ); } os << "]"; } os << std::endl; } else if( (*it)->GetValues().size() > 1 ) { os << indent << indent << "<VALUES>: "; for( unsigned int n = 0; n < (*it)->GetValues().size() - 1; n++ ) { os << (*it)->GetValue( n ); if( (*it)->GetParameters( n ).size() > 0 ) { os << "["; if( (*it)->GetParameters( n ).size() == 1 ) { os << (*it)->GetParameter( n, 0 ) << "], "; } else { for( unsigned int i = 0; i < (*it)->GetParameters( n ).size() - 1; i++ ) { os << (*it)->GetParameter( n, i ) << ","; } os << (*it)->GetParameter( n, (*it)->GetParameters( n ).size() - 1 ) << "], "; } } else { os << ", "; } } unsigned int nn = (*it)->GetValues().size() - 1; os << (*it)->GetValue( nn ); if( (*it)->GetParameters( nn ).size() > 0 ) { os << "["; if( (*it)->GetParameters( nn ).size() == 1 ) { os << (*it)->GetParameter( nn, 0 ) << "]"; } else { for( unsigned int i = 0; i < (*it)->GetParameters( nn ).size() - 1; i++ ) { os << (*it)->GetParameter( nn, i ) << ","; } os << (*it)->GetParameter( nn, (*it)->GetParameters( nn ).size() - 1 ) << "]"; } } } os << std::endl; } } } std::string CommandLineParser ::BreakUpStringIntoNewLines( std::string longString, std::string indentString, unsigned int numberOfCharactersPerLine ) const { std::vector<std::string> tokens; this->TokenizeString( longString, tokens, " " ); std::string newString( "" ); unsigned int currentTokenId = 0; unsigned int currentLineLength = 0; while( currentTokenId < tokens.size() ) { if( tokens[currentTokenId].length() >= numberOfCharactersPerLine ) { newString += ( std::string( "\n" ) + tokens[currentTokenId] + std::string( "\n" ) ); currentTokenId++; currentLineLength = 0; } else if( currentTokenId < tokens.size() && currentLineLength + tokens[currentTokenId].length() > numberOfCharactersPerLine ) { newString += ( std::string( "\n" ) + indentString ); currentLineLength = 0; } else { newString += ( tokens[currentTokenId] + std::string( " " ) ); currentLineLength += ( tokens[currentTokenId].length() + 1 ); currentTokenId++; } } return newString; } void CommandLineParser ::TokenizeString( std::string str, std::vector<std::string> & tokens, std::string delimiters ) const { // Skip delimiters at beginning. std::string::size_type lastPos = str.find_first_not_of( delimiters, 0 ); // Find first "non-delimiter". std::string::size_type pos = str.find_first_of( delimiters, lastPos ); while( std::string::npos != pos || std::string::npos != lastPos ) { // Found a token, add it to the vector. tokens.push_back( str.substr( lastPos, pos - lastPos ) ); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of( delimiters, pos ); // Find next "non-delimiter" pos = str.find_first_of( delimiters, lastPos ); } } /** * Standard "PrintSelf" method */ void CommandLineParser ::PrintSelf( std::ostream& os, Indent indent) const { Superclass::PrintSelf( os, indent ); os << indent << "Command: " << this->m_Command << std::endl; os << indent << "Options: " << std::endl; OptionListType::const_iterator it; for( it = this->m_Options.begin(); it != this->m_Options.end(); it++ ) { (*it)->Print( os, indent ); } if( this->m_UnknownOptions.size() ) { os << indent << "Unknown Options: " << std::endl; OptionListType::const_iterator its; for( its = this->m_UnknownOptions.begin(); its != this->m_UnknownOptions.end(); its++ ) { (*its)->Print( os, indent ); } } } } // end namespace ants } // end namespace itk <commit_msg>BUG: Negative volues weren't being processed on the command line correctly.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: antsCommandLineParser.cxx,v $ Language: C++ Date: $Date: 2009/01/22 22:43:11 $ Version: $Revision: 1.1 $ 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. =========================================================================*/ #include "antsCommandLineParser.h" #include <algorithm> namespace itk { namespace ants { CommandLineParser ::CommandLineParser() { this->m_Options.clear(); this->m_Command.clear(); this->m_CommandDescription.clear(); this->m_UnknownOptions.clear(); this->m_LeftDelimiter = '['; this->m_RightDelimiter = ']'; } void CommandLineParser ::AddOption( OptionType::Pointer option ) { if( ( option->GetShortName() != '\0' || !this->GetOption( option->GetShortName() ) ) || ( !option->GetLongName().empty() || !this->GetOption( option->GetLongName() ) ) ) { this->m_Options.push_back( option ); } else { if( option->GetShortName() != '\0' && this->GetOption( option->GetShortName() ) ) { itkWarningMacro( "Duplicate short option '-" << option->GetShortName() << "'" ); } if( !( option->GetLongName().empty() ) && this->GetOption( option->GetLongName() ) ) { itkWarningMacro( "Duplicate long option '--" << option->GetLongName() << "'" ); } } } void CommandLineParser ::Parse( unsigned int argc, char * *argv ) { std::vector<std::string> arguments = this->RegroupCommandLineArguments( argc, argv ); unsigned int n = 0; this->m_Command = arguments[n++]; while( n < arguments.size() ) { std::string argument = arguments[n++]; std::string name; name.clear(); if( argument.find( "--" ) == 0 ) { name = argument.substr( 2, argument.length() - 1 ); } else if( argument.find( "-" ) == 0 && argument.find( "--" ) > 0 ) { name = argument.substr( 1, 2 ); } if( !( name.empty() ) && !atof( name.c_str() ) ) { OptionType::Pointer option = this->GetOption( name ); if( !option ) { OptionType::Pointer unknownOption = OptionType::New(); if( name.length() > 1 ) { unknownOption->SetLongName( name ); } else { unknownOption->SetShortName( name.at( 0 ) ); } if( n == arguments.size() ) { unknownOption->AddValue( "1", this->m_LeftDelimiter, this->m_RightDelimiter ); } else { for( unsigned int m = n; m < arguments.size(); m++ ) { std::string value = arguments[m]; if( value.find( "-" ) != 0 ) { unknownOption->AddValue( value, this->m_LeftDelimiter, this->m_RightDelimiter ); } else { if( m == n ) { unknownOption->AddValue( "1", this->m_LeftDelimiter, this->m_RightDelimiter ); } n = m; break; } } } this->m_UnknownOptions.push_back( unknownOption ); } else // the option exists { if( n == arguments.size() ) { option->AddValue( "1", this->m_LeftDelimiter, this->m_RightDelimiter ); } else { for( unsigned int m = n; m < arguments.size(); m++ ) { std::string value = arguments[m]; if( value.find( "-" ) != 0 || atof( value.c_str() ) ) { option->AddValue( value, this->m_LeftDelimiter, this->m_RightDelimiter ); } else { if( m == n ) { option->AddValue( "1", this->m_LeftDelimiter, this->m_RightDelimiter ); } n = m; break; } } } } } } } std::vector<std::string> CommandLineParser ::RegroupCommandLineArguments( unsigned int argc, char * *argv ) { /** * Inclusion of this function allows the user to use spaces inside * the left and right delimiters. Also replace other left and right * delimiters. */ std::vector<std::string> arguments; std::string currentArg( "" ); bool isArgOpen = false; for( unsigned int n = 0; n < argc; n++ ) { std::string a( argv[n] ); // replace left delimiters std::replace( a.begin(), a.end(), '{', '[' ); std::replace( a.begin(), a.end(), '(', '[' ); std::replace( a.begin(), a.end(), '<', '[' ); // replace right delimiters std::replace( a.begin(), a.end(), '}', ']' ); std::replace( a.begin(), a.end(), ')', ']' ); std::replace( a.begin(), a.end(), '>', ']' ); if( isArgOpen ) { std::size_t leftDelimiterPosition = a.find( this->m_LeftDelimiter ); if( leftDelimiterPosition != std::string::npos ) { itkExceptionMacro( "Incorrect command line specification." ); } std::size_t rightDelimiterPosition = a.find( this->m_RightDelimiter ); if( rightDelimiterPosition != std::string::npos ) { if( rightDelimiterPosition < a.length() - 1 ) { itkExceptionMacro( "Incorrect command line specification." ); } else { currentArg += a; arguments.push_back( currentArg ); currentArg.clear(); isArgOpen = false; } } else { currentArg += a; } } else { std::size_t leftDelimiterPosition = a.find( this->m_LeftDelimiter ); std::size_t rightDelimiterPosition = a.find( this->m_RightDelimiter ); if( leftDelimiterPosition == std::string::npos ) { if( rightDelimiterPosition == std::string::npos ) { currentArg += a; arguments.push_back( currentArg ); currentArg.clear(); } else { itkExceptionMacro( "Incorrect command line specification." ); } } else if( leftDelimiterPosition != std::string::npos && rightDelimiterPosition != std::string::npos && leftDelimiterPosition < rightDelimiterPosition ) { if( rightDelimiterPosition < a.length() - 1 ) { itkExceptionMacro( "Incorrect command line specification." ); } currentArg += a; arguments.push_back( currentArg ); currentArg.clear(); isArgOpen = false; } else if( rightDelimiterPosition == std::string::npos && leftDelimiterPosition != std::string::npos ) { currentArg += a; isArgOpen = true; } } } return arguments; } CommandLineParser::OptionType::Pointer CommandLineParser ::GetOption( std::string name ) { if( name.length() == 1 ) { return this->GetOption( name.at( 0 ) ); } OptionListType::iterator it; for( it = this->m_Options.begin(); it != this->m_Options.end(); it++ ) { if( name.compare( (*it)->GetLongName() ) == 0 ) { return *it; } } return NULL; } CommandLineParser::OptionType::Pointer CommandLineParser ::GetOption( char name ) { OptionListType::iterator it; for( it = this->m_Options.begin(); it != this->m_Options.end(); it++ ) { if( name == (*it)->GetShortName() ) { return *it; } } return NULL; } void CommandLineParser ::PrintMenu( std::ostream& os, Indent indent, bool printShortVersion ) const { os << std::endl; os << "COMMAND: " << std::endl; os << indent << this->m_Command << std::endl; if( !this->m_CommandDescription.empty() && !printShortVersion ) { std::stringstream ss1; ss1 << indent << indent; std::stringstream ss2; ss2 << this->m_CommandDescription; std::string description = this->BreakUpStringIntoNewLines( ss2.str(), ss1.str(), 80 ); os << indent << indent << description << std::endl; } os << std::endl; os << "OPTIONS: " << std::endl; OptionListType::const_iterator it; for( it = this->m_Options.begin(); it != this->m_Options.end(); it++ ) { os << indent; std::stringstream ss; ss << indent; if( (*it)->GetShortName() != '\0' ) { os << "-" << (*it)->GetShortName(); ss << Indent( 2 ); if( !( (*it)->GetLongName() ).empty() ) { os << ", " << "--" << (*it)->GetLongName() << " " << std::flush; ss << Indent( 5 + ( (*it)->GetLongName() ).length() ); } else { os << " " << std::flush; ss << Indent( 1 ); } } else { os << "--" << (*it)->GetLongName() << " " << std::flush; ss << Indent( 3 + ( (*it)->GetLongName() ).length() ); } if( (*it)->GetNumberOfUsageOptions() > 0 ) { os << (*it)->GetUsageOption( 0 ) << std::endl; for( unsigned int i = 1; i < (*it)->GetNumberOfUsageOptions(); i++ ) { os << ss.str() << (*it)->GetUsageOption( i ) << std::endl; } } else { os << std::endl; } if( !( (*it)->GetDescription().empty() ) && !printShortVersion ) { std::stringstream ss1; ss1 << indent << indent; std::stringstream ss2; ss2 << (*it)->GetDescription(); std::string description = this->BreakUpStringIntoNewLines( ss2.str(), ss1.str(), 80 ); os << indent << indent << description << std::endl; } if( !printShortVersion ) { if( (*it)->GetValues().size() == 1 ) { os << indent << indent << "<VALUES>: " << (*it)->GetValue( 0 ); if( (*it)->GetParameters( 0 ).size() > 0 ) { os << "["; if( (*it)->GetParameters( 0 ).size() == 1 ) { os << (*it)->GetParameter( 0, 0 ); } else { for( unsigned int i = 0; i < (*it)->GetParameters( 0 ).size() - 1; i++ ) { os << (*it)->GetParameter( 0, i ) << ","; } os << (*it)->GetParameter( 0, (*it)->GetParameters( 0 ).size() - 1 ); } os << "]"; } os << std::endl; } else if( (*it)->GetValues().size() > 1 ) { os << indent << indent << "<VALUES>: "; for( unsigned int n = 0; n < (*it)->GetValues().size() - 1; n++ ) { os << (*it)->GetValue( n ); if( (*it)->GetParameters( n ).size() > 0 ) { os << "["; if( (*it)->GetParameters( n ).size() == 1 ) { os << (*it)->GetParameter( n, 0 ) << "], "; } else { for( unsigned int i = 0; i < (*it)->GetParameters( n ).size() - 1; i++ ) { os << (*it)->GetParameter( n, i ) << ","; } os << (*it)->GetParameter( n, (*it)->GetParameters( n ).size() - 1 ) << "], "; } } else { os << ", "; } } unsigned int nn = (*it)->GetValues().size() - 1; os << (*it)->GetValue( nn ); if( (*it)->GetParameters( nn ).size() > 0 ) { os << "["; if( (*it)->GetParameters( nn ).size() == 1 ) { os << (*it)->GetParameter( nn, 0 ) << "]"; } else { for( unsigned int i = 0; i < (*it)->GetParameters( nn ).size() - 1; i++ ) { os << (*it)->GetParameter( nn, i ) << ","; } os << (*it)->GetParameter( nn, (*it)->GetParameters( nn ).size() - 1 ) << "]"; } } } os << std::endl; } } } std::string CommandLineParser ::BreakUpStringIntoNewLines( std::string longString, std::string indentString, unsigned int numberOfCharactersPerLine ) const { std::vector<std::string> tokens; this->TokenizeString( longString, tokens, " " ); std::string newString( "" ); unsigned int currentTokenId = 0; unsigned int currentLineLength = 0; while( currentTokenId < tokens.size() ) { if( tokens[currentTokenId].length() >= numberOfCharactersPerLine ) { newString += ( std::string( "\n" ) + tokens[currentTokenId] + std::string( "\n" ) ); currentTokenId++; currentLineLength = 0; } else if( currentTokenId < tokens.size() && currentLineLength + tokens[currentTokenId].length() > numberOfCharactersPerLine ) { newString += ( std::string( "\n" ) + indentString ); currentLineLength = 0; } else { newString += ( tokens[currentTokenId] + std::string( " " ) ); currentLineLength += ( tokens[currentTokenId].length() + 1 ); currentTokenId++; } } return newString; } void CommandLineParser ::TokenizeString( std::string str, std::vector<std::string> & tokens, std::string delimiters ) const { // Skip delimiters at beginning. std::string::size_type lastPos = str.find_first_not_of( delimiters, 0 ); // Find first "non-delimiter". std::string::size_type pos = str.find_first_of( delimiters, lastPos ); while( std::string::npos != pos || std::string::npos != lastPos ) { // Found a token, add it to the vector. tokens.push_back( str.substr( lastPos, pos - lastPos ) ); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of( delimiters, pos ); // Find next "non-delimiter" pos = str.find_first_of( delimiters, lastPos ); } } /** * Standard "PrintSelf" method */ void CommandLineParser ::PrintSelf( std::ostream& os, Indent indent) const { Superclass::PrintSelf( os, indent ); os << indent << "Command: " << this->m_Command << std::endl; os << indent << "Options: " << std::endl; OptionListType::const_iterator it; for( it = this->m_Options.begin(); it != this->m_Options.end(); it++ ) { (*it)->Print( os, indent ); } if( this->m_UnknownOptions.size() ) { os << indent << "Unknown Options: " << std::endl; OptionListType::const_iterator its; for( its = this->m_UnknownOptions.begin(); its != this->m_UnknownOptions.end(); its++ ) { (*its)->Print( os, indent ); } } } } // end namespace ants } // end namespace itk <|endoftext|>
<commit_before>/* * ElevationChangeDetection.cpp * * Created on: Mar 26, 2015 * Author: Martin Wermelinger * Institute: ETH Zurich, Autonomous Systems Lab */ #include "elevation_change_detection/ElevationChangeDetection.hpp" #include <grid_map_msgs/GetGridMap.h> // Eigenvalues #include <Eigen/Dense> using namespace Eigen; using namespace grid_map; namespace elevation_change_detection { ElevationChangeDetection::ElevationChangeDetection(ros::NodeHandle& nodeHandle) : nodeHandle_(nodeHandle), type_("elevation") { ROS_INFO("Elevation change detection node started."); readParameters(); submapClient_ = nodeHandle_.serviceClient<grid_map_msgs::GetGridMap>(submapServiceName_); elevationChangePublisher_ = nodeHandle_.advertise<grid_map_msgs::GridMap>("elevation_change_map", 1, true); groundTruthPublisher_ = nodeHandle_.advertise<grid_map_msgs::GridMap>("ground_truth_map", 1, true); updateTimer_ = nodeHandle_.createTimer(updateDuration_, &ElevationChangeDetection::updateTimerCallback, this); requestedMapTypes_.push_back(type_); } ElevationChangeDetection::~ElevationChangeDetection() { updateTimer_.stop(); nodeHandle_.shutdown(); } bool ElevationChangeDetection::readParameters() { nodeHandle_.param("submap_service", submapServiceName_, std::string("/get_grid_map")); double updateRate; nodeHandle_.param("update_rate", updateRate, 1.0); updateDuration_.fromSec(1.0 / updateRate); nodeHandle_.param("map_frame_id", mapFrameId_, std::string("map")); std::string robotFrameId; nodeHandle_.param("robot_frame_id", robotFrameId, std::string("base")); double mapCenterX, mapCenterY; nodeHandle_.param("map_center_x", mapCenterX, 0.0); nodeHandle_.param("map_center_y", mapCenterY, 0.0); submapPoint_.header.frame_id = robotFrameId; submapPoint_.point.x = mapCenterX; submapPoint_.point.y = mapCenterY; submapPoint_.point.z = 0.0; nodeHandle_.param("map_length_x", mapLength_.x(), 5.0); nodeHandle_.param("map_length_y", mapLength_.y(), 5.0); nodeHandle_.param("threshold", threshold_, 0.0); return true; } bool ElevationChangeDetection::loadElevationMap(const std::string& pathToBag, const std::string& topicName) { return grid_map::GridMapRosConverter::loadFromBag(pathToBag, topicName, groundTruthMap_); } void ElevationChangeDetection::updateTimerCallback(const ros::TimerEvent& timerEvent) { grid_map_msgs::GridMap mapMessage; ROS_DEBUG("Sending request to %s.", submapServiceName_.c_str()); submapClient_.waitForExistence(); ROS_DEBUG("Sending request to %s.", submapServiceName_.c_str()); if (getGridMap(mapMessage)) { grid_map::GridMap elevationMap; grid_map::GridMapRosConverter::fromMessage(mapMessage, elevationMap); computeElevationChange(elevationMap); // Publish elevation change map. if (!publishElevationChangeMap(elevationMap)) ROS_DEBUG("Elevation change map has not been broadcasted."); if (!publishGroundTruthMap(groundTruthMap_)) ROS_DEBUG("Ground truth map has not been broadcasted."); } else { ROS_WARN("Failed to retrieve elevation grid map."); } } bool ElevationChangeDetection::getGridMap(grid_map_msgs::GridMap& map) { submapPoint_.header.stamp = ros::Time(0); geometry_msgs::PointStamped submapPointTransformed; try { transformListener_.transformPoint(mapFrameId_, submapPoint_, submapPointTransformed); } catch (tf::TransformException &ex) { ROS_ERROR("%s", ex.what()); } grid_map_msgs::GetGridMap submapService; submapService.request.position_x = submapPointTransformed.point.x; submapService.request.position_y = submapPointTransformed.point.y; submapService.request.length_x = mapLength_.x(); submapService.request.length_y = mapLength_.y(); submapService.request.layers.resize(requestedMapTypes_.size()); for (unsigned int i = 0; i < requestedMapTypes_.size(); ++i) { submapService.request.layers[i] = requestedMapTypes_[i]; } if (!submapClient_.call(submapService)) return false; map = submapService.response.map; return true; } void ElevationChangeDetection::computeElevationChange(grid_map::GridMap& elevationMap) { elevationMap.add("elevation_change", elevationMap.get(type_)); std::vector<std::string> validTypes; std::vector<std::string> basicLayers; validTypes.push_back(type_); basicLayers.push_back("elevation_change"); elevationMap.setBasicLayers(basicLayers); elevationMap.clear(); for (GridMapIterator iterator(elevationMap); !iterator.isPassedEnd(); ++iterator) { // Check if elevation map has valid value if (!elevationMap.isValid(*iterator, validTypes)) continue; double height = elevationMap.at(type_, *iterator); // Get the ground truth height Vector2d position, groundTruthPosition; Array2i groundTruthIndex; elevationMap.getPosition(*iterator, position); groundTruthMap_.getIndex(position, groundTruthIndex); if (!groundTruthMap_.isValid(groundTruthIndex, validTypes)) continue; double groundTruthHeight = groundTruthMap_.at(type_, groundTruthIndex); // Add to elevation change map double diffElevation = std::abs(height - groundTruthHeight); if (diffElevation <= threshold_) continue; elevationMap.at("elevation_change", *iterator) = diffElevation; } } bool ElevationChangeDetection::publishElevationChangeMap(const grid_map::GridMap& map) { if (elevationChangePublisher_.getNumSubscribers() < 1) return false; grid_map_msgs::GridMap message; GridMapRosConverter::toMessage(map, message); elevationChangePublisher_.publish(message); ROS_DEBUG("Elevation map raw has been published."); return true; } bool ElevationChangeDetection::publishGroundTruthMap(const grid_map::GridMap& map) { if (groundTruthPublisher_.getNumSubscribers() < 1) return false; grid_map_msgs::GridMap message; GridMapRosConverter::toMessage(map, message); groundTruthPublisher_.publish(message); ROS_DEBUG("Ground truth map raw has been published."); return true; } } /* namespace elevation_change_detection */ <commit_msg>Added loading from rosbag.<commit_after>/* * ElevationChangeDetection.cpp * * Created on: Mar 26, 2015 * Author: Martin Wermelinger * Institute: ETH Zurich, Autonomous Systems Lab */ #include "elevation_change_detection/ElevationChangeDetection.hpp" #include <grid_map_msgs/GetGridMap.h> // Eigenvalues #include <Eigen/Dense> using namespace Eigen; using namespace grid_map; namespace elevation_change_detection { ElevationChangeDetection::ElevationChangeDetection(ros::NodeHandle& nodeHandle) : nodeHandle_(nodeHandle), type_("elevation") { ROS_INFO("Elevation change detection node started."); readParameters(); submapClient_ = nodeHandle_.serviceClient<grid_map_msgs::GetGridMap>(submapServiceName_); elevationChangePublisher_ = nodeHandle_.advertise<grid_map_msgs::GridMap>("elevation_change_map", 1, true); groundTruthPublisher_ = nodeHandle_.advertise<grid_map_msgs::GridMap>("ground_truth_map", 1, true); updateTimer_ = nodeHandle_.createTimer(updateDuration_, &ElevationChangeDetection::updateTimerCallback, this); requestedMapTypes_.push_back(type_); } ElevationChangeDetection::~ElevationChangeDetection() { updateTimer_.stop(); nodeHandle_.shutdown(); } bool ElevationChangeDetection::readParameters() { nodeHandle_.param("submap_service", submapServiceName_, std::string("/get_grid_map")); double updateRate; nodeHandle_.param("update_rate", updateRate, 1.0); updateDuration_.fromSec(1.0 / updateRate); nodeHandle_.param("map_frame_id", mapFrameId_, std::string("map")); std::string robotFrameId; nodeHandle_.param("robot_frame_id", robotFrameId, std::string("base")); double mapCenterX, mapCenterY; nodeHandle_.param("map_center_x", mapCenterX, 0.0); nodeHandle_.param("map_center_y", mapCenterY, 0.0); submapPoint_.header.frame_id = robotFrameId; submapPoint_.point.x = mapCenterX; submapPoint_.point.y = mapCenterY; submapPoint_.point.z = 0.0; nodeHandle_.param("map_length_x", mapLength_.x(), 5.0); nodeHandle_.param("map_length_y", mapLength_.y(), 5.0); nodeHandle_.param("threshold", threshold_, 0.0); std::string bagTopicName_, pathToBag_; nodeHandle_.param("bag_topic_name", bagTopicName_, std::string("grid_map")); nodeHandle_.param("path_to_bag", pathToBag_, std::string("lee_ground_truth.bag")); loadElevationMap(pathToBag_, bagTopicName_); if (!groundTruthMap_.exists(type_)) ROS_ERROR("Can't find bag or topic of the ground truth map!"); return true; } bool ElevationChangeDetection::loadElevationMap(const std::string& pathToBag, const std::string& topicName) { return grid_map::GridMapRosConverter::loadFromBag(pathToBag, topicName, groundTruthMap_); } void ElevationChangeDetection::updateTimerCallback(const ros::TimerEvent& timerEvent) { grid_map_msgs::GridMap mapMessage; ROS_DEBUG("Sending request to %s.", submapServiceName_.c_str()); submapClient_.waitForExistence(); ROS_DEBUG("Sending request to %s.", submapServiceName_.c_str()); if (getGridMap(mapMessage)) { grid_map::GridMap elevationMap; grid_map::GridMapRosConverter::fromMessage(mapMessage, elevationMap); computeElevationChange(elevationMap); // Publish elevation change map. if (!publishElevationChangeMap(elevationMap)) ROS_DEBUG("Elevation change map has not been broadcasted."); if (!publishGroundTruthMap(groundTruthMap_)) ROS_DEBUG("Ground truth map has not been broadcasted."); } else { ROS_WARN("Failed to retrieve elevation grid map."); } } bool ElevationChangeDetection::getGridMap(grid_map_msgs::GridMap& map) { submapPoint_.header.stamp = ros::Time(0); geometry_msgs::PointStamped submapPointTransformed; try { transformListener_.transformPoint(mapFrameId_, submapPoint_, submapPointTransformed); } catch (tf::TransformException &ex) { ROS_ERROR("%s", ex.what()); } grid_map_msgs::GetGridMap submapService; submapService.request.position_x = submapPointTransformed.point.x; submapService.request.position_y = submapPointTransformed.point.y; submapService.request.length_x = mapLength_.x(); submapService.request.length_y = mapLength_.y(); submapService.request.layers.resize(requestedMapTypes_.size()); for (unsigned int i = 0; i < requestedMapTypes_.size(); ++i) { submapService.request.layers[i] = requestedMapTypes_[i]; } if (!submapClient_.call(submapService)) return false; map = submapService.response.map; return true; } void ElevationChangeDetection::computeElevationChange(grid_map::GridMap& elevationMap) { elevationMap.add("elevation_change", elevationMap.get(type_)); std::vector<std::string> validTypes; std::vector<std::string> basicLayers; validTypes.push_back(type_); basicLayers.push_back("elevation_change"); elevationMap.setBasicLayers(basicLayers); elevationMap.clear(); for (GridMapIterator iterator(elevationMap); !iterator.isPassedEnd(); ++iterator) { // Check if elevation map has valid value if (!elevationMap.isValid(*iterator, validTypes)) continue; double height = elevationMap.at(type_, *iterator); // Get the ground truth height Vector2d position, groundTruthPosition; Array2i groundTruthIndex; elevationMap.getPosition(*iterator, position); groundTruthMap_.getIndex(position, groundTruthIndex); if (!groundTruthMap_.isValid(groundTruthIndex, validTypes)) continue; double groundTruthHeight = groundTruthMap_.at(type_, groundTruthIndex); // Add to elevation change map double diffElevation = std::abs(height - groundTruthHeight); if (diffElevation <= threshold_) continue; elevationMap.at("elevation_change", *iterator) = diffElevation; } } bool ElevationChangeDetection::publishElevationChangeMap(const grid_map::GridMap& map) { if (elevationChangePublisher_.getNumSubscribers() < 1) return false; grid_map_msgs::GridMap message; GridMapRosConverter::toMessage(map, message); elevationChangePublisher_.publish(message); ROS_DEBUG("Elevation map raw has been published."); return true; } bool ElevationChangeDetection::publishGroundTruthMap(const grid_map::GridMap& map) { if (groundTruthPublisher_.getNumSubscribers() < 1) return false; grid_map_msgs::GridMap message; GridMapRosConverter::toMessage(map, message); groundTruthPublisher_.publish(message); ROS_DEBUG("Ground truth map raw has been published."); return true; } } /* namespace elevation_change_detection */ <|endoftext|>
<commit_before>#include "stdafx.h" #include "GameManager.h" #include "FileStuff.h" #include "ConstVars.h" //̾ #include "GameLayer.h" #include "UILayer.h" // #include "StageInformation.h" #include "StageScene.h" #include "GameScene.h" //Ŵ #include "CollectionManager.h" #include "ColliderManager.h" #include "TargetManager.h" //ö̴ #include "Collider.h" #include "Bullet.h" #include "CrossBullet.h" #include "Explosion.h" //Ÿ #include "Target.h" // #include "Sling.h" GameManager* GameManager::m_instance = nullptr; GameManager* GameManager::GetInstance() { if (m_instance == nullptr) { m_instance = new GameManager(); } return m_instance; } GameManager::GameManager() { m_sling = nullptr; m_colliderManager = new ColliderManager(); m_targetManager = new TargetManager(); m_isJudged = false; m_lastTarget = nullptr; } void GameManager::Reset() { m_sling = nullptr; delete m_colliderManager; m_colliderManager = new ColliderManager(); delete m_targetManager; m_targetManager = new TargetManager(); m_isJudged = false; m_lastTarget = nullptr; } GameManager::~GameManager() {} void GameManager::SetStage(GameLayer* gameLayer, UILayer* uiLayer, int stageNum) { Reset(); StageInformation stageInfo(stageNum); m_targetManager->InitTargets(&stageInfo); AppendTargetsToLayer(gameLayer); m_colliderManager->InitBullets(&stageInfo); AppendBulletsToLayer(uiLayer); m_sling = InitSling(gameLayer); m_stage = stageNum; } Sling* GameManager::InitSling(GameLayer* gameLayer) { Sling* sling = Sling::create(); gameLayer->addChild(sling); sling->LoadBullet(); return sling; } void GameManager::AppendTargetsToLayer(GameLayer* gameLayer) { for (Target* target : m_targetManager->m_targets) { gameLayer->addChild(target); } } void GameManager::AppendBulletsToLayer(UILayer* uiLayer) { for (int i = 0; i < m_colliderManager->m_bulletNum; i++) { Bullet* bullet = static_cast<Bullet*>(m_colliderManager->m_colliders.at(i)); Sprite* bulletSpr = bullet->GetSprite(); uiLayer->addChild(bulletSpr); bulletSpr->setPosition(Vec2(45 + i*25, 50)); } } void GameManager::ShotBullet(Sling* sling) { Bullet* bullet = m_colliderManager->GetBulletToShot(sling); if (bullet) { Scene* currentScene = Director::getInstance()->getRunningScene(); GameScene* gameScene = static_cast<GameScene*>(currentScene->getChildByName("GameScene")); GameLayer* gameLayer = gameScene->GetGameLayer(); UILayer* uiLayer = gameScene->GetUILayer(); gameLayer->addChild(bullet); sling->ShotComplete(); if (m_colliderManager->HasBulletToShot()) { sling->LoadBullet(); } } } void GameManager::Play(GameLayer* gameLayer, UILayer* uiLayer) { Vector<Collider*>& colliders = m_colliderManager->m_colliders; Vector<Target*>& targets = m_targetManager->m_targets; Collider* collider = nullptr; for (int i = 0; i < colliders.size(); i++) { collider = colliders.at(i); if (collider->IsFlying()) { collider->Act(); CheckCollide(collider, targets); } if (collider->IsBullet()) { Bullet* bullet = static_cast<Bullet*>(collider); if (bullet->IsToExplode()) { Explosion* explosion = bullet->GetExplosion(); m_colliderManager->AddExplosion(explosion); gameLayer->addChild(explosion); } } } m_colliderManager->EraseDeadColliders(); m_targetManager->EraseDeadTargets(); ControlWinFailProgress(uiLayer); } void GameManager::CheckCollide(Collider* collider, Vector<Target*>& targets) { m_lastTarget = nullptr; // ѹ 浹 Ÿٿ 浹  浹üũ ʵ . bool collidingCheck = false; // 浹 Ÿ ִ üũ. --> lastTarget ʿ䰡 ִüũ for (Target* target : targets) { if (target == m_lastTarget) { break; collidingCheck = true; } if (target->IsEnemy()) { m_targetManager->SaveEnemyPosition(target->getPosition()); EnemyDyingEffect(); } if (collider->IsBullet()) { if (IsCollision(target, collider)) { m_lastTarget = target; target->ApplyCollisionEffect(collider); collidingCheck = true; } } else { Explosion* explosion = static_cast<Explosion*>(collider); const float explosionRadius = explosion->GetBoundingRadius(); const Vec2 explosionPosition = explosion->getPosition(); const Rect targetBoundingBox = target->GetBoundingArea(); if ( targetBoundingBox.intersectsCircle( explosionPosition, explosionRadius) ) { target->ApplyCollisionEffect(explosion); } } } if (!collidingCheck) { m_lastTarget = nullptr; } } void GameManager::EnemyDyingEffect() { /* ParticleSmoke* enemyDyingEffect = ParticleSmoke::create(); enemyDyingEffect->setPosition(enemyPos); gameLayer->addChild(enemyDyingEffect); */ } void GameManager::SetCollectionPos(const Vec2& pos) { const Vec2 compensateToParentPos = Vec2(160, 0); m_curCollection->setPosition(pos + compensateToParentPos); } void GameManager::EarnCollectionEvent(UILayer* uiLayer) { GameScene* gameScene = static_cast<GameScene*>(uiLayer->getParent()); const Point& enemyPos = m_targetManager->GetEnemyPosition(); const Vec2& aboveCharacterPos = gameScene->GetCharacterPos() + Vec2(0, 100); m_curCollection = m_collectionManager->GetCollectionSprOfStage(m_stage); m_curCollection->setPosition(enemyPos); uiLayer->addChild(m_curCollection); //part 1 MoveBy* moveBy_00 = MoveBy::create(1.50f, Point(0, -10)); MoveBy* moveBy_01 = MoveBy::create(1.00f, Point(0, -10)); Blink* blink_00 = Blink::create(1.50f, 5); Blink* blink_01 = Blink::create(1.00f, 5); FadeIn* fadeIn_00 = FadeIn::create(1.50f); FadeOut* fadeOut_00 = FadeOut::create(1.00f); Spawn* spawn_00 = Spawn::create(fadeIn_00, moveBy_00, blink_00, NULL); Spawn* spawn_01 = Spawn::create(fadeOut_00, moveBy_01, blink_01, NULL); //part 2 CallFuncN* callFuncN = CallFuncN::create(CC_CALLBACK_0 (GameManager::SetCollectionPos, this, aboveCharacterPos)); MoveBy* moveBy_02 = MoveBy::create(1.50f, Point(0, -30)); MoveBy* moveBy_03 = MoveBy::create(1.00f, Point(0, -20)); Blink* blink_02 = Blink::create(1.50f, 5); Blink* blink_03 = Blink::create(1.00f, 5); FadeIn* fadeIn_01 = FadeIn::create(0.01f); FadeOut* fadeOut_01 = FadeOut::create(2.50f); Spawn* spawn_02 = Spawn::create(fadeIn_01, moveBy_02, blink_02, NULL); Spawn* spawn_03 = Spawn::create(fadeOut_01, moveBy_03, blink_03, NULL); Sequence* sequence = Sequence::create( spawn_00, spawn_01, callFuncN, spawn_02, spawn_03, NULL); m_curCollection->runAction(sequence); } void GameManager::WinProgress(UILayer* uiLayer) { int lastStage = UserDefault::getInstance()->getIntegerForKey(ConstVars::LASTSTAGE); if (m_stage == lastStage && (m_stage == CollectionManager::SHOES || m_stage == CollectionManager::SCARF || m_stage == CollectionManager::BOTTLE || m_stage == CollectionManager::MONITOR || m_stage == CollectionManager::LETTER)) { //EarnCollectionEvent(uiLayer); //DelayTime* waitEventTime = DelayTime::create(4.50f); //CallFuncN* showWidget = CallFuncN::create(CC_CALLBACK_0( // UILayer::MakeSuccessWidget, uiLayer, m_stage)); //Sequence* waitAndshow = Sequence::create(waitEventTime, showWidget, NULL); //uiLayer->runAction(waitAndshow); uiLayer->MakeSuccessWidget(m_stage); } else { if (m_stage==0) { Director::getInstance()->popScene(); } else { uiLayer->MakeSuccessWidget(m_stage); } } if (lastStage == m_stage && m_stage + 1 <= StageInformation::GetMaxStageNum()) { UserDefault::getInstance()->setIntegerForKey(ConstVars::LASTSTAGE, m_stage + 1); } } void GameManager::FailProgress(UILayer* uiLayer) { if (m_stage == 0) { Director::getInstance()->popScene(); } else { uiLayer->MakeFailWidget(m_stage); } } void GameManager::ControlWinFailProgress(UILayer* uiLayer) { if (!m_isJudged) { if (!m_targetManager->HasEnemy()) { m_isJudged = true; m_sling->ShotComplete(); WinProgress(uiLayer); } else if (!m_colliderManager->HasCollider()){ m_isJudged = true; m_sling->ShotComplete(); FailProgress(uiLayer); } } } bool GameManager::IsCollision(Target* target, Collider* collider) { float rotation = target->getRotation(); const Rect colliderBoundingBox = static_cast<Bullet*>(collider)->GetBoundingArea(); const Rect targetBoundingBox = target->GetBoundingArea(); if (rotation < 1 && rotation > -1){ //ȸ // 簢 浹 if (targetBoundingBox.intersectsRect(colliderBoundingBox)) return true; return false; } float colliderX = collider->getPosition().x; float colliderY = collider->getPosition().y; float minX = targetBoundingBox.getMinX(); // left margin float maxX = targetBoundingBox.getMaxX(); // right margin float minY = targetBoundingBox.getMinY(); // lower margin float maxY = targetBoundingBox.getMaxY(); // upper margin Point LL(minX, minY); Point LU(minX, maxY); Point RL(maxX, minY); Point RU(maxX, maxY); //ȸ簢 LL.rotate(target->getPosition(), -CC_DEGREES_TO_RADIANS(target->getRotation())); LU.rotate(target->getPosition(), -CC_DEGREES_TO_RADIANS(target->getRotation())); RL.rotate(target->getPosition(), -CC_DEGREES_TO_RADIANS(target->getRotation())); RU.rotate(target->getPosition(), -CC_DEGREES_TO_RADIANS(target->getRotation())); // y = Ax + upperB // y = Ax + lowerB // y = -1/Ax + leftB // y = -1/Ax + rightB float a = (RU.y- LU.y) / (RU.x - LU.x); // // RU.y = a * RU.x + upperB float upperB = RU.y - a * (RU.x); float lowerB = LL.y - a * (LL.x); // LL.y = (-1/a) * LL.x + leftB float leftB = LL.y - (-1 / a) * LL.x; float rightB = RU.y - (-1 / a) * RU.x; // װ ȿ ִ üũ. // uppermargin lowermargin ̿ ִ X, Y (y-uppermargin) *(y-lowermargin) < 0 // left right . //׿ dot //makeDebugPoint(Point(colliderX, (colliderX * a + upperB)), target->getParent()); //makeDebugPoint(Point(colliderX, (colliderX * a + lowerB)), target->getParent()); //makeDebugPoint(Point(colliderX, (colliderX * (-1 / a) + rightB)), target->getParent()); //makeDebugPoint(Point(colliderX, (colliderX * (-1 / a) + leftB)), target->getParent()); if ( ((colliderX * a + upperB) - colliderY) * ((colliderX * a + lowerB) - colliderY) < 0 && ((colliderX * (-1 / a) + leftB) - colliderY) * ((colliderX * (-1 / a) + rightB) - colliderY) < 0 ) { return true; } else return false; } void GameManager::makeDebugPoint(Point p, Node* spr) { Sprite* dot = Sprite::create(FileStuff::DEBRIS); dot->setScale(2.); spr->addChild(dot); Point pos = spr->convertToWorldSpace(Point::ZERO); dot->setPosition(p - pos); Sequence* action = Sequence::create(DelayTime::create(0.1), RemoveSelf::create(),NULL); dot->runAction(action); }<commit_msg>add collision angle infinte bug<commit_after>#include "stdafx.h" #include "GameManager.h" #include "FileStuff.h" #include "ConstVars.h" //̾ #include "GameLayer.h" #include "UILayer.h" // #include "StageInformation.h" #include "StageScene.h" #include "GameScene.h" //Ŵ #include "CollectionManager.h" #include "ColliderManager.h" #include "TargetManager.h" //ö̴ #include "Collider.h" #include "Bullet.h" #include "CrossBullet.h" #include "Explosion.h" //Ÿ #include "Target.h" // #include "Sling.h" GameManager* GameManager::m_instance = nullptr; GameManager* GameManager::GetInstance() { if (m_instance == nullptr) { m_instance = new GameManager(); } return m_instance; } GameManager::GameManager() { m_sling = nullptr; m_colliderManager = new ColliderManager(); m_targetManager = new TargetManager(); m_isJudged = false; m_lastTarget = nullptr; } void GameManager::Reset() { m_sling = nullptr; delete m_colliderManager; m_colliderManager = new ColliderManager(); delete m_targetManager; m_targetManager = new TargetManager(); m_isJudged = false; m_lastTarget = nullptr; } GameManager::~GameManager() {} void GameManager::SetStage(GameLayer* gameLayer, UILayer* uiLayer, int stageNum) { Reset(); StageInformation stageInfo(stageNum); m_targetManager->InitTargets(&stageInfo); AppendTargetsToLayer(gameLayer); m_colliderManager->InitBullets(&stageInfo); AppendBulletsToLayer(uiLayer); m_sling = InitSling(gameLayer); m_stage = stageNum; } Sling* GameManager::InitSling(GameLayer* gameLayer) { Sling* sling = Sling::create(); gameLayer->addChild(sling); sling->LoadBullet(); return sling; } void GameManager::AppendTargetsToLayer(GameLayer* gameLayer) { for (Target* target : m_targetManager->m_targets) { gameLayer->addChild(target); } } void GameManager::AppendBulletsToLayer(UILayer* uiLayer) { for (int i = 0; i < m_colliderManager->m_bulletNum; i++) { Bullet* bullet = static_cast<Bullet*>(m_colliderManager->m_colliders.at(i)); Sprite* bulletSpr = bullet->GetSprite(); uiLayer->addChild(bulletSpr); bulletSpr->setPosition(Vec2(45 + i*25, 50)); } } void GameManager::ShotBullet(Sling* sling) { Bullet* bullet = m_colliderManager->GetBulletToShot(sling); if (bullet) { Scene* currentScene = Director::getInstance()->getRunningScene(); GameScene* gameScene = static_cast<GameScene*>(currentScene->getChildByName("GameScene")); GameLayer* gameLayer = gameScene->GetGameLayer(); UILayer* uiLayer = gameScene->GetUILayer(); gameLayer->addChild(bullet); sling->ShotComplete(); if (m_colliderManager->HasBulletToShot()) { sling->LoadBullet(); } } } void GameManager::Play(GameLayer* gameLayer, UILayer* uiLayer) { Vector<Collider*>& colliders = m_colliderManager->m_colliders; Vector<Target*>& targets = m_targetManager->m_targets; Collider* collider = nullptr; for (int i = 0; i < colliders.size(); i++) { collider = colliders.at(i); if (collider->IsFlying()) { collider->Act(); CheckCollide(collider, targets); } if (collider->IsBullet()) { Bullet* bullet = static_cast<Bullet*>(collider); if (bullet->IsToExplode()) { Explosion* explosion = bullet->GetExplosion(); m_colliderManager->AddExplosion(explosion); gameLayer->addChild(explosion); } } } m_colliderManager->EraseDeadColliders(); m_targetManager->EraseDeadTargets(); ControlWinFailProgress(uiLayer); } void GameManager::CheckCollide(Collider* collider, Vector<Target*>& targets) { m_lastTarget = nullptr; // ѹ 浹 Ÿٿ 浹  浹üũ ʵ . bool collidingCheck = false; // 浹 Ÿ ִ üũ. --> lastTarget ʿ䰡 ִüũ for (Target* target : targets) { if (target == m_lastTarget) { break; collidingCheck = true; } if (target->IsEnemy()) { m_targetManager->SaveEnemyPosition(target->getPosition()); EnemyDyingEffect(); } if (collider->IsBullet()) { if (IsCollision(target, collider)) { m_lastTarget = target; target->ApplyCollisionEffect(collider); collidingCheck = true; } } else { Explosion* explosion = static_cast<Explosion*>(collider); const float explosionRadius = explosion->GetBoundingRadius(); const Vec2 explosionPosition = explosion->getPosition(); const Rect targetBoundingBox = target->GetBoundingArea(); if ( targetBoundingBox.intersectsCircle( explosionPosition, explosionRadius) ) { target->ApplyCollisionEffect(explosion); } } } if (!collidingCheck) { m_lastTarget = nullptr; } } void GameManager::EnemyDyingEffect() { /* ParticleSmoke* enemyDyingEffect = ParticleSmoke::create(); enemyDyingEffect->setPosition(enemyPos); gameLayer->addChild(enemyDyingEffect); */ } void GameManager::SetCollectionPos(const Vec2& pos) { const Vec2 compensateToParentPos = Vec2(160, 0); m_curCollection->setPosition(pos + compensateToParentPos); } void GameManager::EarnCollectionEvent(UILayer* uiLayer) { GameScene* gameScene = static_cast<GameScene*>(uiLayer->getParent()); const Point& enemyPos = m_targetManager->GetEnemyPosition(); const Vec2& aboveCharacterPos = gameScene->GetCharacterPos() + Vec2(0, 100); m_curCollection = m_collectionManager->GetCollectionSprOfStage(m_stage); m_curCollection->setPosition(enemyPos); uiLayer->addChild(m_curCollection); //part 1 MoveBy* moveBy_00 = MoveBy::create(1.50f, Point(0, -10)); MoveBy* moveBy_01 = MoveBy::create(1.00f, Point(0, -10)); Blink* blink_00 = Blink::create(1.50f, 5); Blink* blink_01 = Blink::create(1.00f, 5); FadeIn* fadeIn_00 = FadeIn::create(1.50f); FadeOut* fadeOut_00 = FadeOut::create(1.00f); Spawn* spawn_00 = Spawn::create(fadeIn_00, moveBy_00, blink_00, NULL); Spawn* spawn_01 = Spawn::create(fadeOut_00, moveBy_01, blink_01, NULL); //part 2 CallFuncN* callFuncN = CallFuncN::create(CC_CALLBACK_0 (GameManager::SetCollectionPos, this, aboveCharacterPos)); MoveBy* moveBy_02 = MoveBy::create(1.50f, Point(0, -30)); MoveBy* moveBy_03 = MoveBy::create(1.00f, Point(0, -20)); Blink* blink_02 = Blink::create(1.50f, 5); Blink* blink_03 = Blink::create(1.00f, 5); FadeIn* fadeIn_01 = FadeIn::create(0.01f); FadeOut* fadeOut_01 = FadeOut::create(2.50f); Spawn* spawn_02 = Spawn::create(fadeIn_01, moveBy_02, blink_02, NULL); Spawn* spawn_03 = Spawn::create(fadeOut_01, moveBy_03, blink_03, NULL); Sequence* sequence = Sequence::create( spawn_00, spawn_01, callFuncN, spawn_02, spawn_03, NULL); m_curCollection->runAction(sequence); } void GameManager::WinProgress(UILayer* uiLayer) { int lastStage = UserDefault::getInstance()->getIntegerForKey(ConstVars::LASTSTAGE); if (m_stage == lastStage && (m_stage == CollectionManager::SHOES || m_stage == CollectionManager::SCARF || m_stage == CollectionManager::BOTTLE || m_stage == CollectionManager::MONITOR || m_stage == CollectionManager::LETTER)) { //EarnCollectionEvent(uiLayer); //DelayTime* waitEventTime = DelayTime::create(4.50f); //CallFuncN* showWidget = CallFuncN::create(CC_CALLBACK_0( // UILayer::MakeSuccessWidget, uiLayer, m_stage)); //Sequence* waitAndshow = Sequence::create(waitEventTime, showWidget, NULL); //uiLayer->runAction(waitAndshow); uiLayer->MakeSuccessWidget(m_stage); } else { if (m_stage==0) { Director::getInstance()->popScene(); } else { uiLayer->MakeSuccessWidget(m_stage); } } if (lastStage == m_stage && m_stage + 1 <= StageInformation::GetMaxStageNum()) { UserDefault::getInstance()->setIntegerForKey(ConstVars::LASTSTAGE, m_stage + 1); } } void GameManager::FailProgress(UILayer* uiLayer) { if (m_stage == 0) { Director::getInstance()->popScene(); } else { uiLayer->MakeFailWidget(m_stage); } } void GameManager::ControlWinFailProgress(UILayer* uiLayer) { if (!m_isJudged) { if (!m_targetManager->HasEnemy()) { m_isJudged = true; m_sling->ShotComplete(); WinProgress(uiLayer); } else if (!m_colliderManager->HasCollider()){ m_isJudged = true; m_sling->ShotComplete(); FailProgress(uiLayer); } } } bool GameManager::IsCollision(Target* target, Collider* collider) { float rotation = target->getRotation(); const Rect colliderBoundingBox = static_cast<Bullet*>(collider)->GetBoundingArea(); const Rect targetBoundingBox = target->GetBoundingArea(); if (rotation< 3 && rotation > -3 || rotation< 93 && rotation > 87 || rotation< 183 && rotation > 177 || rotation< 273 && rotation > 267){ //ȸ // 簢 浹 if (targetBoundingBox.intersectsRect(colliderBoundingBox)) return true; return false; } float colliderX = collider->getPosition().x; float colliderY = collider->getPosition().y; float minX = targetBoundingBox.getMinX(); // left margin float maxX = targetBoundingBox.getMaxX(); // right margin float minY = targetBoundingBox.getMinY(); // lower margin float maxY = targetBoundingBox.getMaxY(); // upper margin Point LL(minX, minY); Point LU(minX, maxY); Point RL(maxX, minY); Point RU(maxX, maxY); //ȸ簢 LL.rotate(target->getPosition(), -CC_DEGREES_TO_RADIANS(target->getRotation())); LU.rotate(target->getPosition(), -CC_DEGREES_TO_RADIANS(target->getRotation())); RL.rotate(target->getPosition(), -CC_DEGREES_TO_RADIANS(target->getRotation())); RU.rotate(target->getPosition(), -CC_DEGREES_TO_RADIANS(target->getRotation())); // y = Ax + upperB // y = Ax + lowerB // y = -1/Ax + leftB // y = -1/Ax + rightB float a = (RU.y- LU.y) / (RU.x - LU.x); // // RU.y = a * RU.x + upperB float upperB = RU.y - a * (RU.x); float lowerB = LL.y - a * (LL.x); // LL.y = (-1/a) * LL.x + leftB float leftB = LL.y - (-1 / a) * LL.x; float rightB = RU.y - (-1 / a) * RU.x; // װ ȿ ִ üũ. // uppermargin lowermargin ̿ ִ X, Y (y-uppermargin) *(y-lowermargin) < 0 // left right . //׿ dot //makeDebugPoint(Point(colliderX, (colliderX * a + upperB)), target->getParent()); //makeDebugPoint(Point(colliderX, (colliderX * a + lowerB)), target->getParent()); //makeDebugPoint(Point(colliderX, (colliderX * (-1 / a) + rightB)), target->getParent()); //makeDebugPoint(Point(colliderX, (colliderX * (-1 / a) + leftB)), target->getParent()); if ( ((colliderX * a + upperB) - colliderY) * ((colliderX * a + lowerB) - colliderY) < 0 && ((colliderX * (-1 / a) + leftB) - colliderY) * ((colliderX * (-1 / a) + rightB) - colliderY) < 0 ) { return true; } else return false; } void GameManager::makeDebugPoint(Point p, Node* spr) { Sprite* dot = Sprite::create(FileStuff::DEBRIS); dot->setScale(2.); spr->addChild(dot); Point pos = spr->convertToWorldSpace(Point::ZERO); dot->setPosition(p - pos); Sequence* action = Sequence::create(DelayTime::create(0.1), RemoveSelf::create(),NULL); dot->runAction(action); }<|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAnalyzeImageIO.h" #include "itkAnalyzeImageIOFactory.h" #include "itkConvertPixelBuffer.txx" #include "itkDICOMImageIO2.h" #include "itkDICOMImageIO2Factory.h" #include "itkDefaultConvertPixelTraits.h" #include "itkDicomImageIO.h" #include "itkDicomImageIOFactory.h" #include "itkFileIteratorBase.h" #include "itkGE4ImageIO.h" #include "itkGE4ImageIOFactory.h" #include "itkGE5ImageIO.h" #include "itkGE5ImageIOFactory.h" #include "itkGEAdwImageIO.h" #include "itkGEAdwImageIOFactory.h" #include "itkGEImageHeader.h" #include "itkGiplImageIO.h" #include "itkGiplImageIOFactory.h" #include "itkIOCommon.h" #include "itkIPLCommonImageIO.h" #include "itkImageFileReader.txx" #include "itkImageFileWriter.txx" #include "itkImageIOBase.h" #include "itkImageIOFactory.h" #include "itkImageIORegion.h" #include "itkImageSeriesReader.txx" #include "itkImageSeriesWriter.txx" #include "itkImageWriter.txx" #include "itkMetaImageIO.h" #include "itkMetaImageIOFactory.h" #include "itkMvtSunf.h" #include "itkNumericSeriesFileIterator.h" #include "itkPNGImageIO.h" #include "itkPNGImageIOFactory.h" #include "itkRawImageIO.txx" #include "itkRawImageWriter.txx" #include "itkSiemensVisionImageIO.h" #include "itkSiemensVisionImageIOFactory.h" #include "itkStimulateImageIO.h" #include "itkStimulateImageIOFactory.h" #include "itkVOLImageIO.h" #include "itkVOLImageIOFactory.h" #include "itkVTKImageIO.h" #include "itkVTKImageIOFactory.h" #include "itkWriter.h" #include "pixeldata.h" int main ( int , char* ) { return 0; } <commit_msg>ENH: Updated to latest headers<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAnalyzeDbh.h" #include "itkAnalyzeImageIO.h" #include "itkAnalyzeImageIOFactory.h" #include "itkConvertPixelBuffer.txx" #include "itkDICOMImageIO2.h" #include "itkDICOMImageIO2Factory.h" #include "itkDefaultConvertPixelTraits.h" #include "itkDicomImageIO.h" #include "itkDicomImageIOFactory.h" #include "itkFileIteratorBase.h" #include "itkGE4ImageIO.h" #include "itkGE4ImageIOFactory.h" #include "itkGE5ImageIO.h" #include "itkGE5ImageIOFactory.h" #include "itkGEAdwImageIO.h" #include "itkGEAdwImageIOFactory.h" #include "itkGEImageHeader.h" #include "itkGiplImageIO.h" #include "itkGiplImageIOFactory.h" #include "itkIOCommon.h" #include "itkIPLCommonImageIO.h" #include "itkImageFileReader.txx" #include "itkImageFileWriter.txx" #include "itkImageIOBase.h" #include "itkImageIOFactory.h" #include "itkImageIORegion.h" #include "itkImageSeriesReader.txx" #include "itkImageSeriesWriter.txx" #include "itkImageWriter.txx" #include "itkMetaImageIO.h" #include "itkMetaImageIOFactory.h" #include "itkMvtSunf.h" #include "itkNumericSeriesFileIterator.h" #include "itkPNGImageIO.h" #include "itkPNGImageIOFactory.h" #include "itkRawImageIO.txx" #include "itkRawImageWriter.txx" #include "itkSiemensVisionImageIO.h" #include "itkSiemensVisionImageIOFactory.h" #include "itkStimulateImageIO.h" #include "itkStimulateImageIOFactory.h" #include "itkVOLImageIO.h" #include "itkVOLImageIOFactory.h" #include "itkVTKImageIO.h" #include "itkVTKImageIOFactory.h" #include "itkWriter.h" #include "pixeldata.h" int main ( int , char* ) { return 0; } <|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 "otbMultiResolutionPyramid.h" #include "otbImage.h" #include "otbVectorImage.h" #include "otbPerBandVectorImageFilter.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkShrinkImageFilter.h" #include "otbImageFileReader.h" #include "otbObjectList.h" #include "otbStreamingImageFileWriter.h" #include "otbCommandLineArgumentParser.h" #include "otbStandardWriterWatcher.h" namespace otb { int MultiResolutionPyramid::Describe(ApplicationDescriptor* descriptor) { descriptor->SetName("Multi-resolution pyramid tool"); descriptor->SetDescription("Build a multi-resolution pyramid of the image."); descriptor->AddInputImage(); descriptor->AddOption("NumberOfLevels","Number of levels in the pyramid (default is 1)","level",1,false, ApplicationDescriptor::Integer); descriptor->AddOption("ShrinkFactor","Subsampling factor (default is 2)","sfactor",1,false, ApplicationDescriptor::Integer); descriptor->AddOption("VarianceFactor","Before subsampling, image is smoothed with a gaussian kernel of variance VarianceFactor*ShrinkFactor. Higher values will result in more blur, lower in more aliasing (default is 0.6)","vfactor",1,false,ApplicationDescriptor::Real); descriptor->AddOption("FastScheme","If used, this option allows to speed-up computation by iteratively subsampling previous level of pyramid instead of processing the full input image each time. Please note that this may result in extra blur or extra aliasing.","fast",0,false,ApplicationDescriptor::Integer); descriptor->AddOption("OutputPrefixAndExtextension","prefix for the output files, and extension","out",2,true,ApplicationDescriptor::String); descriptor->AddOption("AvailableMemory","Set the maximum of available memory for the pipeline execution in mega bytes (optional, 256 by default)","ram", 1, false, otb::ApplicationDescriptor::Integer); return EXIT_SUCCESS; } int MultiResolutionPyramid::Execute(otb::ApplicationOptionsResult* parseResult) { const unsigned int Dimension = 2; typedef otb::Image<unsigned short, Dimension> USImageType; typedef otb::VectorImage<unsigned short, Dimension> USVectorImageType; typedef otb::Image<short, Dimension> SImageType; typedef otb::VectorImage<short, Dimension> SVectorImageType; typedef otb::ImageFileReader<USVectorImageType> ReaderType; typedef itk::DiscreteGaussianImageFilter<USImageType,SImageType> SmoothingImageFilterType; typedef otb::PerBandVectorImageFilter<USVectorImageType,SVectorImageType, SmoothingImageFilterType> SmoothingVectorImageFilterType; typedef itk::ShrinkImageFilter<SVectorImageType,USVectorImageType> ShrinkFilterType; typedef otb::StreamingImageFileWriter<USVectorImageType> WriterType; unsigned int nbLevels = 1; if(parseResult->IsOptionPresent("NumberOfLevels")) { nbLevels = parseResult->GetParameterUInt("NumberOfLevels"); } unsigned int shrinkFactor = 2; if(parseResult->IsOptionPresent("ShrinkFactor")) { shrinkFactor = parseResult->GetParameterUInt("ShrinkFactor"); } double varianceFactor = 0.6; if(parseResult->IsOptionPresent("VarianceFactor")) { varianceFactor = parseResult->GetParameterDouble("VarianceFactor"); } bool fastScheme = parseResult->IsOptionPresent("FastScheme"); std::string prefix = parseResult->GetParameterString("OutputPrefixAndExtextension",0); std::string ext = parseResult->GetParameterString("OutputPrefixAndExtextension",1); ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(parseResult->GetInputImage()); unsigned int currentLevel = 1; unsigned int currentFactor = shrinkFactor; while(currentLevel <= nbLevels) { std::cout<<"Processing level "<<currentLevel<<" with shrink factor "<<currentFactor<<std::endl; if(fastScheme && currentLevel > 1) { itk::OStringStream oss; oss<<prefix<<"_"<<currentLevel-1<<"."<<ext; reader = ReaderType::New(); reader->SetFileName(oss.str().c_str()); } SmoothingVectorImageFilterType::Pointer smoothingFilter = SmoothingVectorImageFilterType::New(); smoothingFilter->SetInput(reader->GetOutput()); // According to // http://www.ipol.im/pub/algo/gjmr_line_segment_detector/ // This is a good balance between blur and aliasing double variance = varianceFactor * static_cast<double>(currentFactor); smoothingFilter->GetFilter()->SetVariance(variance); ShrinkFilterType::Pointer shrinkFilter = ShrinkFilterType::New(); shrinkFilter->SetInput(smoothingFilter->GetOutput()); shrinkFilter->SetShrinkFactors(currentFactor); itk::OStringStream oss; oss<<prefix<<"_"<<currentLevel<<"."<<ext; WriterType::Pointer writer = WriterType::New(); writer->SetInput(shrinkFilter->GetOutput()); writer->SetFileName(oss.str().c_str()); unsigned int ram = 256; if (parseResult->IsOptionPresent("AvailableMemory")) { ram = parseResult->GetParameterUInt("AvailableMemory"); } writer->SetAutomaticTiledStreaming(ram); oss.str(""); oss<<"Writing "<<prefix<<"_"<<currentLevel<<"."<<ext; otb::StandardWriterWatcher watcher(writer,shrinkFilter,oss.str().c_str()); writer->Update(); if(!fastScheme) { currentFactor*=shrinkFactor; } ++currentLevel; } return EXIT_SUCCESS; } } <commit_msg>STYLE<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 "otbMultiResolutionPyramid.h" #include "otbImage.h" #include "otbVectorImage.h" #include "otbPerBandVectorImageFilter.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkShrinkImageFilter.h" #include "otbImageFileReader.h" #include "otbObjectList.h" #include "otbStreamingImageFileWriter.h" #include "otbCommandLineArgumentParser.h" #include "otbStandardWriterWatcher.h" namespace otb { int MultiResolutionPyramid::Describe(ApplicationDescriptor* descriptor) { descriptor->SetName("Multi-resolution pyramid tool"); descriptor->SetDescription("Build a multi-resolution pyramid of the image."); descriptor->AddInputImage(); descriptor->AddOption("NumberOfLevels","Number of levels in the pyramid (default is 1)","level", 1, false, ApplicationDescriptor::Integer); descriptor->AddOption("ShrinkFactor","Subsampling factor (default is 2)","sfactor", 1, false, ApplicationDescriptor::Integer); descriptor->AddOption("VarianceFactor","Before subsampling, image is smoothed with a gaussian kernel of variance VarianceFactor*ShrinkFactor. Higher values will result in more blur, lower in more aliasing (default is 0.6)","vfactor", 1, false, ApplicationDescriptor::Real); descriptor->AddOption("FastScheme","If used, this option allows to speed-up computation by iteratively subsampling previous level of pyramid instead of processing the full input image each time. Please note that this may result in extra blur or extra aliasing.","fast", 0, false, ApplicationDescriptor::Integer); descriptor->AddOption("OutputPrefixAndExtextension","prefix for the output files, and extension","out", 2, true, ApplicationDescriptor::String); descriptor->AddOption("AvailableMemory","Set the maximum of available memory for the pipeline execution in mega bytes (optional, 256 by default)","ram", 1, false, otb::ApplicationDescriptor::Integer); return EXIT_SUCCESS; } int MultiResolutionPyramid::Execute(otb::ApplicationOptionsResult* parseResult) { const unsigned int Dimension = 2; typedef otb::Image<unsigned short, Dimension> USImageType; typedef otb::VectorImage<unsigned short, Dimension> USVectorImageType; typedef otb::Image<short, Dimension> SImageType; typedef otb::VectorImage<short, Dimension> SVectorImageType; typedef otb::ImageFileReader<USVectorImageType> ReaderType; typedef itk::DiscreteGaussianImageFilter<USImageType, SImageType> SmoothingImageFilterType; typedef otb::PerBandVectorImageFilter<USVectorImageType, SVectorImageType, SmoothingImageFilterType> SmoothingVectorImageFilterType; typedef itk::ShrinkImageFilter<SVectorImageType, USVectorImageType> ShrinkFilterType; typedef otb::StreamingImageFileWriter<USVectorImageType> WriterType; unsigned int nbLevels = 1; if(parseResult->IsOptionPresent("NumberOfLevels")) { nbLevels = parseResult->GetParameterUInt("NumberOfLevels"); } unsigned int shrinkFactor = 2; if(parseResult->IsOptionPresent("ShrinkFactor")) { shrinkFactor = parseResult->GetParameterUInt("ShrinkFactor"); } double varianceFactor = 0.6; if(parseResult->IsOptionPresent("VarianceFactor")) { varianceFactor = parseResult->GetParameterDouble("VarianceFactor"); } bool fastScheme = parseResult->IsOptionPresent("FastScheme"); std::string prefix = parseResult->GetParameterString("OutputPrefixAndExtextension", 0); std::string ext = parseResult->GetParameterString("OutputPrefixAndExtextension", 1); ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(parseResult->GetInputImage()); unsigned int currentLevel = 1; unsigned int currentFactor = shrinkFactor; while(currentLevel <= nbLevels) { std::cout<<"Processing level "<<currentLevel<<" with shrink factor "<<currentFactor<<std::endl; if(fastScheme && currentLevel > 1) { itk::OStringStream oss; oss<<prefix<<"_"<<currentLevel-1<<"."<<ext; reader = ReaderType::New(); reader->SetFileName(oss.str().c_str()); } SmoothingVectorImageFilterType::Pointer smoothingFilter = SmoothingVectorImageFilterType::New(); smoothingFilter->SetInput(reader->GetOutput()); // According to // http://www.ipol.im/pub/algo/gjmr_line_segment_detector/ // This is a good balance between blur and aliasing double variance = varianceFactor * static_cast<double>(currentFactor); smoothingFilter->GetFilter()->SetVariance(variance); ShrinkFilterType::Pointer shrinkFilter = ShrinkFilterType::New(); shrinkFilter->SetInput(smoothingFilter->GetOutput()); shrinkFilter->SetShrinkFactors(currentFactor); itk::OStringStream oss; oss<<prefix<<"_"<<currentLevel<<"."<<ext; WriterType::Pointer writer = WriterType::New(); writer->SetInput(shrinkFilter->GetOutput()); writer->SetFileName(oss.str().c_str()); unsigned int ram = 256; if (parseResult->IsOptionPresent("AvailableMemory")) { ram = parseResult->GetParameterUInt("AvailableMemory"); } writer->SetAutomaticTiledStreaming(ram); oss.str(""); oss<<"Writing "<<prefix<<"_"<<currentLevel<<"."<<ext; otb::StandardWriterWatcher watcher(writer, shrinkFilter, oss.str().c_str()); writer->Update(); if(!fastScheme) { currentFactor*=shrinkFactor; } ++currentLevel; } return EXIT_SUCCESS; } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkHandleRepresentation.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 "vtkHandleRepresentation.h" #include "vtkCoordinate.h" #include "vtkInteractorObserver.h" #include "vtkObjectFactory.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" vtkCxxRevisionMacro(vtkHandleRepresentation, "1.7"); //---------------------------------------------------------------------- vtkHandleRepresentation::vtkHandleRepresentation() { // Positions are maintained via a vtkCoordinate this->DisplayPosition = vtkCoordinate::New(); this->DisplayPosition->SetCoordinateSystemToDisplay(); this->WorldPosition = vtkCoordinate::New(); this->WorldPosition->SetCoordinateSystemToWorld(); this->InteractionState = vtkHandleRepresentation::Outside; this->Tolerance = 15; this->ActiveRepresentation = 0; this->Constrained = 0; this->DisplayPositionTime.Modified(); this->WorldPositionTime.Modified(); } //---------------------------------------------------------------------- vtkHandleRepresentation::~vtkHandleRepresentation() { this->DisplayPosition->Delete(); this->WorldPosition->Delete(); } //---------------------------------------------------------------------- void vtkHandleRepresentation::SetDisplayPosition(double pos[3]) { this->DisplayPosition->SetValue(pos); if ( this->Renderer ) { double *p = this->DisplayPosition->GetComputedWorldValue(this->Renderer); this->WorldPosition->SetValue(p[0], p[1], p[2]); } this->DisplayPositionTime.Modified(); } //---------------------------------------------------------------------- void vtkHandleRepresentation::GetDisplayPosition(double pos[3]) { // The world position maintains the position if ( this->Renderer && (this->WorldPositionTime > this->DisplayPositionTime) ) { int *p = this->WorldPosition->GetComputedDisplayValue(this->Renderer); this->DisplayPosition->SetValue(p[0],p[1],0.0); } this->DisplayPosition->GetValue(pos); } double* vtkHandleRepresentation::GetDisplayPosition() { return this->DisplayPosition->GetValue(); } //---------------------------------------------------------------------- void vtkHandleRepresentation::SetWorldPosition(double pos[3]) { this->WorldPosition->SetValue(pos); this->WorldPositionTime.Modified(); } //---------------------------------------------------------------------- void vtkHandleRepresentation::GetWorldPosition(double pos[3]) { this->WorldPosition->GetValue(pos); } double* vtkHandleRepresentation::GetWorldPosition() { return this->WorldPosition->GetValue(); } //---------------------------------------------------------------------- void vtkHandleRepresentation::SetRenderer(vtkRenderer *ren) { this->DisplayPosition->SetViewport(ren); this->WorldPosition->SetViewport(ren); this->Superclass::SetRenderer(ren); } //---------------------------------------------------------------------- void vtkHandleRepresentation::ShallowCopy(vtkProp *prop) { vtkHandleRepresentation *rep = vtkHandleRepresentation::SafeDownCast(prop); if ( rep ) { this->SetTolerance(rep->GetTolerance()); this->SetActiveRepresentation(rep->GetActiveRepresentation()); this->SetConstrained(rep->GetConstrained()); } this->Superclass::ShallowCopy(prop); } //---------------------------------------------------------------------- unsigned long vtkHandleRepresentation::GetMTime() { unsigned long mTime=this->Superclass::GetMTime(); unsigned long wMTime=this->WorldPosition->GetMTime(); mTime = ( wMTime > mTime ? wMTime : mTime ); unsigned long dMTime=this->DisplayPosition->GetMTime(); mTime = ( dMTime > mTime ? dMTime : mTime ); return mTime; } //---------------------------------------------------------------------- void vtkHandleRepresentation::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); double p[3]; this->GetDisplayPosition(p); os << indent << "Display Position: (" << p[0] << ", " << p[1] << ", " << p[2] << ")\n"; this->GetWorldPosition(p); os << indent << "World Position: (" << p[0] << ", " << p[1] << ", " << p[2] << ")\n"; os << indent << "Constrained: " << (this->Constrained ? "On" : "Off") << "\n"; os << indent << "Tolerance: " << this->Tolerance << "\n"; os << indent << "Active Representation: " << (this->ActiveRepresentation ? "On" : "Off") << "\n"; } <commit_msg>STYLE:Marked method<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkHandleRepresentation.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 "vtkHandleRepresentation.h" #include "vtkCoordinate.h" #include "vtkInteractorObserver.h" #include "vtkObjectFactory.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" vtkCxxRevisionMacro(vtkHandleRepresentation, "1.8"); //---------------------------------------------------------------------- vtkHandleRepresentation::vtkHandleRepresentation() { // Positions are maintained via a vtkCoordinate this->DisplayPosition = vtkCoordinate::New(); this->DisplayPosition->SetCoordinateSystemToDisplay(); this->WorldPosition = vtkCoordinate::New(); this->WorldPosition->SetCoordinateSystemToWorld(); this->InteractionState = vtkHandleRepresentation::Outside; this->Tolerance = 15; this->ActiveRepresentation = 0; this->Constrained = 0; this->DisplayPositionTime.Modified(); this->WorldPositionTime.Modified(); } //---------------------------------------------------------------------- vtkHandleRepresentation::~vtkHandleRepresentation() { this->DisplayPosition->Delete(); this->WorldPosition->Delete(); } //---------------------------------------------------------------------- void vtkHandleRepresentation::SetDisplayPosition(double pos[3]) { this->DisplayPosition->SetValue(pos); if ( this->Renderer ) { double *p = this->DisplayPosition->GetComputedWorldValue(this->Renderer); this->WorldPosition->SetValue(p[0], p[1], p[2]); } this->DisplayPositionTime.Modified(); } //---------------------------------------------------------------------- void vtkHandleRepresentation::GetDisplayPosition(double pos[3]) { // The world position maintains the position if ( this->Renderer && (this->WorldPositionTime > this->DisplayPositionTime) ) { int *p = this->WorldPosition->GetComputedDisplayValue(this->Renderer); this->DisplayPosition->SetValue(p[0],p[1],0.0); } this->DisplayPosition->GetValue(pos); } //---------------------------------------------------------------------- double* vtkHandleRepresentation::GetDisplayPosition() { return this->DisplayPosition->GetValue(); } //---------------------------------------------------------------------- void vtkHandleRepresentation::SetWorldPosition(double pos[3]) { this->WorldPosition->SetValue(pos); this->WorldPositionTime.Modified(); } //---------------------------------------------------------------------- void vtkHandleRepresentation::GetWorldPosition(double pos[3]) { this->WorldPosition->GetValue(pos); } double* vtkHandleRepresentation::GetWorldPosition() { return this->WorldPosition->GetValue(); } //---------------------------------------------------------------------- void vtkHandleRepresentation::SetRenderer(vtkRenderer *ren) { this->DisplayPosition->SetViewport(ren); this->WorldPosition->SetViewport(ren); this->Superclass::SetRenderer(ren); } //---------------------------------------------------------------------- void vtkHandleRepresentation::ShallowCopy(vtkProp *prop) { vtkHandleRepresentation *rep = vtkHandleRepresentation::SafeDownCast(prop); if ( rep ) { this->SetTolerance(rep->GetTolerance()); this->SetActiveRepresentation(rep->GetActiveRepresentation()); this->SetConstrained(rep->GetConstrained()); } this->Superclass::ShallowCopy(prop); } //---------------------------------------------------------------------- unsigned long vtkHandleRepresentation::GetMTime() { unsigned long mTime=this->Superclass::GetMTime(); unsigned long wMTime=this->WorldPosition->GetMTime(); mTime = ( wMTime > mTime ? wMTime : mTime ); unsigned long dMTime=this->DisplayPosition->GetMTime(); mTime = ( dMTime > mTime ? dMTime : mTime ); return mTime; } //---------------------------------------------------------------------- void vtkHandleRepresentation::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); double p[3]; this->GetDisplayPosition(p); os << indent << "Display Position: (" << p[0] << ", " << p[1] << ", " << p[2] << ")\n"; this->GetWorldPosition(p); os << indent << "World Position: (" << p[0] << ", " << p[1] << ", " << p[2] << ")\n"; os << indent << "Constrained: " << (this->Constrained ? "On" : "Off") << "\n"; os << indent << "Tolerance: " << this->Tolerance << "\n"; os << indent << "Active Representation: " << (this->ActiveRepresentation ? "On" : "Off") << "\n"; } <|endoftext|>
<commit_before>#include "Camera.h" #include "Utility.h" #include <GL\glew.h> #include <glm\gtc\matrix_transform.hpp> #include <glm\gtc\quaternion.hpp> #include <glm\gtx\transform.hpp> #include <glm\gtx\quaternion.hpp> Camera::Camera( glm::vec2 windowSize, ProjectionType type, glm::vec2 zLimits) : windowSize( windowSize ), projectionType( type ), projectionZLimit( zLimits ), position({ 0.0f, 5.0f, 0.0f }), forward({ 0.0f, 0.0f, -1.0f }), up({ 0.0f, 1.0f, 0.0f }), axis(glm::cross(forward, up)) { setupView(); refreshProjection(); refreshViewProjection(); } Camera::~Camera(void) { } // VIEW void Camera::setupView() { view = glm::lookAt(position, position + forward, -glm::cross(forward,axis)); refreshViewProjection(); } void Camera::applyOffset(glm::vec3 offset) { position += offset; setupView(); } void Camera::setMoveForward(bool movement) { moveForward = movement; } void Camera::setMoveBackward(bool movement) { moveBackward = movement; } void Camera::setMoveLeft(bool movement) { moveLeft = movement; } void Camera::setMoveRight(bool movement) { moveRight = movement; } void Camera::rotate(int idx, int idy) { float dx = -100.f * idx / windowSize.x; float dy = -100.f * idy / windowSize.y; auto pitch = glm::angleAxis(dy, axis); auto heading = glm::angleAxis(dx, up); glm::quat temp = glm::cross(pitch, heading); temp = glm::normalize(temp); //update the direction from the quaternion forward = glm::rotate(temp, forward); axis = glm::rotate(heading, axis); // if up changes, camera becomes too free //up = glm::rotate(pitch, up); setupView(); } void Camera::update(float dt) { int forwardMovement = (moveForward ? 1 : 0) + (moveBackward ? -1 : 0); if (forwardMovement != 0) { applyOffset( forward * (forwardMovement * dt * 10.0f) ); } int sideMovement = (moveLeft ? -1 : 0) + (moveRight ? 1 : 0); if (sideMovement != 0) { applyOffset( axis * (sideMovement * dt * 10.0f) ); } } const glm::mat4 & Camera::getView() const { return view; } // PROJECTION void Camera::refreshProjection() { if (projectionType == PERSPECTIVE) { setupPerspectiveProjection( 45.0f, windowSize.x/windowSize.y, projectionZLimit.x, projectionZLimit.y); } else { // TODO: projection start and size are dependant on the world and cameras relative eye offset // Ortho size could and should be open to outside interpretations, for now it is fixed setupOtrhographicProjection({ 0.0f,0.0f }, { windowSize.x,windowSize.y }, projectionZLimit.x, projectionZLimit.y); } } void Camera::setupOtrhographicProjection(glm::vec2 projectionStart, glm::vec2 projectionSize, float zNear, float zFar) { projectionType = ProjectionType::OTRHOGRAPHIC; this->projectionStart = projectionStart; this->projectionSize = projectionSize; projection = glm::ortho( projectionStart.x, projectionStart.x + projectionSize.x, projectionStart.y, projectionStart.y + projectionSize.y, zNear, zFar); refreshViewProjection(); } void Camera::setupPerspectiveProjection(float fovy, float aspectRatio, float zNear, float zFar) { projectionType = ProjectionType::PERSPECTIVE; projection = glm::perspective(fovy, aspectRatio, zNear, zFar); refreshViewProjection(); } const glm::mat4 & Camera::getProjection() const { return projection; } // VIEW PROJECTION void Camera::refreshViewProjection() { viewProjection = projection * view; } const glm::mat4& Camera::getViewProjection() const { return viewProjection; } void Camera::updateCamera() { // OLD: /*glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0, 0, -distance); glRotatef(angles.x, 1.0, 0.0, 0.0); glRotatef(angles.y, 0.0, 1.0, 0.0); glTranslatef(-center.x, -center.y, -center.z);*/ /*glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(FOVy, aspectRatio, NCP, FCP); */ frustum.setupGLProjection(); frustum.CalculateFrustum(); } // VIEWPORT void Camera::windowDidResize(float width, float height) { // TODO: viewport could stretch to fit, or it could be static windowSize.x = width; windowSize.y = height; setupViewport(0,0,width,height); refreshProjection(); } void Camera::setupViewport(float x, float y, float width, float height) { viewportPos.x = x; viewportPos.y = y; viewportSize.x = width; viewportSize.y = height; } void Camera::loadViewport() { glViewport(viewportPos.x, viewportPos.y, viewportSize.x, viewportSize.y); } const Frustum & Camera::getFrustum() const { return frustum; } <commit_msg>Speed up camera movement.<commit_after>#include "Camera.h" #include "Utility.h" #include <GL\glew.h> #include <glm\gtc\matrix_transform.hpp> #include <glm\gtc\quaternion.hpp> #include <glm\gtx\transform.hpp> #include <glm\gtx\quaternion.hpp> Camera::Camera( glm::vec2 windowSize, ProjectionType type, glm::vec2 zLimits) : windowSize( windowSize ), projectionType( type ), projectionZLimit( zLimits ), position({ 0.0f, 5.0f, 0.0f }), forward({ 0.0f, 0.0f, -1.0f }), up({ 0.0f, 1.0f, 0.0f }), axis(glm::cross(forward, up)) { setupView(); refreshProjection(); refreshViewProjection(); } Camera::~Camera(void) { } // VIEW void Camera::setupView() { view = glm::lookAt(position, position + forward, -glm::cross(forward,axis)); refreshViewProjection(); } void Camera::applyOffset(glm::vec3 offset) { position += offset; setupView(); } void Camera::setMoveForward(bool movement) { moveForward = movement; } void Camera::setMoveBackward(bool movement) { moveBackward = movement; } void Camera::setMoveLeft(bool movement) { moveLeft = movement; } void Camera::setMoveRight(bool movement) { moveRight = movement; } void Camera::rotate(int idx, int idy) { float dx = -100.f * idx / windowSize.x; float dy = -100.f * idy / windowSize.y; auto pitch = glm::angleAxis(dy, axis); auto heading = glm::angleAxis(dx, up); glm::quat temp = glm::cross(pitch, heading); temp = glm::normalize(temp); //update the direction from the quaternion forward = glm::rotate(temp, forward); axis = glm::rotate(heading, axis); // if up changes, camera becomes too free //up = glm::rotate(pitch, up); setupView(); } void Camera::update(float dt) { float speed = 30.0f; int forwardMovement = (moveForward ? 1 : 0) + (moveBackward ? -1 : 0); if (forwardMovement != 0) { applyOffset( forward * (forwardMovement * dt * speed) ); } int sideMovement = (moveLeft ? -1 : 0) + (moveRight ? 1 : 0); if (sideMovement != 0) { applyOffset( axis * (sideMovement * dt * speed) ); } } const glm::mat4 & Camera::getView() const { return view; } // PROJECTION void Camera::refreshProjection() { if (projectionType == PERSPECTIVE) { setupPerspectiveProjection( 45.0f, windowSize.x/windowSize.y, projectionZLimit.x, projectionZLimit.y); } else { // TODO: projection start and size are dependant on the world and cameras relative eye offset // Ortho size could and should be open to outside interpretations, for now it is fixed setupOtrhographicProjection({ 0.0f,0.0f }, { windowSize.x,windowSize.y }, projectionZLimit.x, projectionZLimit.y); } } void Camera::setupOtrhographicProjection(glm::vec2 projectionStart, glm::vec2 projectionSize, float zNear, float zFar) { projectionType = ProjectionType::OTRHOGRAPHIC; this->projectionStart = projectionStart; this->projectionSize = projectionSize; projection = glm::ortho( projectionStart.x, projectionStart.x + projectionSize.x, projectionStart.y, projectionStart.y + projectionSize.y, zNear, zFar); refreshViewProjection(); } void Camera::setupPerspectiveProjection(float fovy, float aspectRatio, float zNear, float zFar) { projectionType = ProjectionType::PERSPECTIVE; projection = glm::perspective(fovy, aspectRatio, zNear, zFar); refreshViewProjection(); } const glm::mat4 & Camera::getProjection() const { return projection; } // VIEW PROJECTION void Camera::refreshViewProjection() { viewProjection = projection * view; } const glm::mat4& Camera::getViewProjection() const { return viewProjection; } void Camera::updateCamera() { // OLD: /*glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0, 0, -distance); glRotatef(angles.x, 1.0, 0.0, 0.0); glRotatef(angles.y, 0.0, 1.0, 0.0); glTranslatef(-center.x, -center.y, -center.z);*/ /*glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(FOVy, aspectRatio, NCP, FCP); */ frustum.setupGLProjection(); frustum.CalculateFrustum(); } // VIEWPORT void Camera::windowDidResize(float width, float height) { // TODO: viewport could stretch to fit, or it could be static windowSize.x = width; windowSize.y = height; setupViewport(0,0,width,height); refreshProjection(); } void Camera::setupViewport(float x, float y, float width, float height) { viewportPos.x = x; viewportPos.y = y; viewportSize.x = width; viewportSize.y = height; } void Camera::loadViewport() { glViewport(viewportPos.x, viewportPos.y, viewportSize.x, viewportSize.y); } const Frustum & Camera::getFrustum() const { return frustum; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2014 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "ep_engine.h" #include "connmap.h" #include "dcp-backfill-manager.h" #include "dcp-backfill.h" #include "dcp-producer.h" static const size_t sleepTime = 1; class BackfillManagerTask : public GlobalTask { public: BackfillManagerTask(EventuallyPersistentEngine* e, connection_t c, const Priority &p, double sleeptime = 0, bool shutdown = false) : GlobalTask(e, p, sleeptime, shutdown), conn(c) {} bool run(); std::string getDescription(); private: connection_t conn; }; bool BackfillManagerTask::run() { DcpProducer* producer = static_cast<DcpProducer*>(conn.get()); if (producer->doDisconnect()) { return false; } backfill_status_t status = producer->getBackfillManager()->backfill(); if (status == backfill_finished) { return false; } else if (status == backfill_snooze) { snooze(sleepTime); } if (engine->getEpStats().isShutdown) { return false; } return true; } std::string BackfillManagerTask::getDescription() { std::stringstream ss; ss << "Backfilling items for " << conn->getName(); return ss.str(); } BackfillManager::BackfillManager(EventuallyPersistentEngine* e, connection_t c) : engine(e), conn(c), managerTask(NULL) { Configuration& config = e->getConfiguration(); scanBuffer.bytesRead = 0; scanBuffer.itemsRead = 0; scanBuffer.maxBytes = config.getDcpScanByteLimit(); scanBuffer.maxItems = config.getDcpScanItemLimit(); buffer.bytesRead = 0; buffer.maxBytes = config.getDcpBackfillByteLimit(); buffer.nextReadSize = 0; buffer.full = false; } BackfillManager::~BackfillManager() { LockHolder lh(lock); if (managerTask) { managerTask->cancel(); } while (!activeBackfills.empty()) { DCPBackfill* backfill = activeBackfills.front(); activeBackfills.pop(); backfill->cancel(); delete backfill; } while (!snoozingBackfills.empty()) { DCPBackfill* backfill = (snoozingBackfills.front()).second; snoozingBackfills.pop_front(); backfill->cancel(); delete backfill; } } void BackfillManager::schedule(stream_t stream, uint64_t start, uint64_t end) { LockHolder lh(lock); activeBackfills.push(new DCPBackfill(engine, stream, start, end)); if (managerTask) { managerTask->snooze(0); return; } managerTask = new BackfillManagerTask(engine, conn, Priority::BackfillTaskPriority); ExecutorPool::get()->schedule(managerTask, NONIO_TASK_IDX); } bool BackfillManager::bytesRead(uint32_t bytes) { LockHolder lh(lock); if (scanBuffer.itemsRead >= scanBuffer.maxItems) { return false; } // Always allow an item to be backfilled if the scan buffer is empty, // otherwise check to see if there is room for the item. if (scanBuffer.bytesRead + bytes <= scanBuffer.maxBytes || scanBuffer.bytesRead == 0) { scanBuffer.bytesRead += bytes; } if (buffer.bytesRead == 0 || buffer.bytesRead + bytes <= buffer.maxBytes) { buffer.bytesRead += bytes; } else { scanBuffer.bytesRead -= bytes; buffer.full = true; buffer.nextReadSize = bytes; return false; } scanBuffer.itemsRead++; return true; } void BackfillManager::bytesSent(uint32_t bytes) { LockHolder lh(lock); cb_assert(buffer.bytesRead >= bytes); buffer.bytesRead -= bytes; if (buffer.full) { uint32_t bufferSize = buffer.bytesRead; bool canFitNext = buffer.maxBytes - bufferSize >= buffer.nextReadSize; bool enoughCleared = bufferSize < (buffer.maxBytes * 3 / 4); if (canFitNext && enoughCleared) { buffer.nextReadSize = 0; buffer.full = false; if (managerTask) { managerTask->snooze(0); } } } } backfill_status_t BackfillManager::backfill() { LockHolder lh(lock); if (buffer.full) { return backfill_snooze; } if (activeBackfills.empty() && snoozingBackfills.empty()) { managerTask.reset(); return backfill_finished; } if (engine->getEpStore()->isMemoryUsageTooHigh()) { LOG(EXTENSION_LOG_WARNING, "DCP backfilling task for connection %s " "temporarily suspended because the current memory usage is too " "high", conn->getName().c_str()); return backfill_snooze; } while (!snoozingBackfills.empty()) { std::pair<rel_time_t, DCPBackfill*> snoozer = snoozingBackfills.front(); // If snoozing task is found to be sleeping for greater than // allowed snoozetime, push into active queue if (snoozer.first + sleepTime <= ep_current_time()) { DCPBackfill* bfill = snoozer.second; activeBackfills.push(bfill); snoozingBackfills.pop_front(); } else { break; } } if (activeBackfills.empty()) { return backfill_snooze; } DCPBackfill* backfill = activeBackfills.front(); lh.unlock(); backfill_status_t status = backfill->run(); lh.lock(); if (status == backfill_success && buffer.full) { // Snooze while the buffer is full return backfill_snooze; } scanBuffer.bytesRead = 0; scanBuffer.itemsRead = 0; activeBackfills.pop(); if (status == backfill_success) { activeBackfills.push(backfill); } else if (status == backfill_finished) { lh.unlock(); delete backfill; } else if (status == backfill_snooze) { uint16_t vbid = backfill->getVBucketId(); RCPtr<VBucket> vb = engine->getVBucket(vbid); if (vb) { snoozingBackfills.push_back( std::make_pair(ep_current_time(), backfill)); shared_ptr<Callback<uint64_t> > cb(new BackfillCallback(backfill->getEndSeqno(), vbid, conn)); vb->addPersistenceNotification(cb); } else { lh.unlock(); LOG(EXTENSION_LOG_WARNING, "Deleting the backfill, as vbucket %d " "seems to have been deleted!", vbid); backfill->cancel(); delete backfill; } } else { abort(); } return backfill_success; } void BackfillManager::wakeUpTask() { LockHolder lh(lock); if (managerTask) { managerTask->snooze(0); } } void BackfillManager::wakeUpSnoozingBackfills(uint16_t vbid) { LockHolder lh(lock); std::list<std::pair<rel_time_t, DCPBackfill*> >::iterator it; for (it = snoozingBackfills.begin(); it != snoozingBackfills.end(); ++it) { DCPBackfill *bfill = (*it).second; if (vbid == bfill->getVBucketId()) { activeBackfills.push(bfill); snoozingBackfills.erase(it); managerTask->snooze(0); return; } } } bool BackfillManager::addIfLessThanMax(AtomicValue<uint32_t>& val, uint32_t incr, uint32_t max) { do { uint32_t oldVal = val.load(); uint32_t newVal = oldVal + incr; if (newVal > max) { return false; } if (val.compare_exchange_strong(oldVal, newVal)) { return true; } } while (true); } <commit_msg>MB-13070: Check for a dead backfill task when scheduling backfill<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2014 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "ep_engine.h" #include "connmap.h" #include "dcp-backfill-manager.h" #include "dcp-backfill.h" #include "dcp-producer.h" static const size_t sleepTime = 1; class BackfillManagerTask : public GlobalTask { public: BackfillManagerTask(EventuallyPersistentEngine* e, connection_t c, const Priority &p, double sleeptime = 0, bool shutdown = false) : GlobalTask(e, p, sleeptime, shutdown), conn(c) {} bool run(); std::string getDescription(); private: connection_t conn; }; bool BackfillManagerTask::run() { DcpProducer* producer = static_cast<DcpProducer*>(conn.get()); if (producer->doDisconnect()) { return false; } backfill_status_t status = producer->getBackfillManager()->backfill(); if (status == backfill_finished) { return false; } else if (status == backfill_snooze) { snooze(sleepTime); } if (engine->getEpStats().isShutdown) { return false; } return true; } std::string BackfillManagerTask::getDescription() { std::stringstream ss; ss << "Backfilling items for " << conn->getName(); return ss.str(); } BackfillManager::BackfillManager(EventuallyPersistentEngine* e, connection_t c) : engine(e), conn(c), managerTask(NULL) { Configuration& config = e->getConfiguration(); scanBuffer.bytesRead = 0; scanBuffer.itemsRead = 0; scanBuffer.maxBytes = config.getDcpScanByteLimit(); scanBuffer.maxItems = config.getDcpScanItemLimit(); buffer.bytesRead = 0; buffer.maxBytes = config.getDcpBackfillByteLimit(); buffer.nextReadSize = 0; buffer.full = false; } BackfillManager::~BackfillManager() { LockHolder lh(lock); if (managerTask) { managerTask->cancel(); } while (!activeBackfills.empty()) { DCPBackfill* backfill = activeBackfills.front(); activeBackfills.pop(); backfill->cancel(); delete backfill; } while (!snoozingBackfills.empty()) { DCPBackfill* backfill = (snoozingBackfills.front()).second; snoozingBackfills.pop_front(); backfill->cancel(); delete backfill; } } void BackfillManager::schedule(stream_t stream, uint64_t start, uint64_t end) { LockHolder lh(lock); activeBackfills.push(new DCPBackfill(engine, stream, start, end)); if (managerTask && !managerTask->isdead()) { managerTask->snooze(0); return; } managerTask.reset(new BackfillManagerTask(engine, conn, Priority::BackfillTaskPriority)); ExecutorPool::get()->schedule(managerTask, NONIO_TASK_IDX); } bool BackfillManager::bytesRead(uint32_t bytes) { LockHolder lh(lock); if (scanBuffer.itemsRead >= scanBuffer.maxItems) { return false; } // Always allow an item to be backfilled if the scan buffer is empty, // otherwise check to see if there is room for the item. if (scanBuffer.bytesRead + bytes <= scanBuffer.maxBytes || scanBuffer.bytesRead == 0) { scanBuffer.bytesRead += bytes; } if (buffer.bytesRead == 0 || buffer.bytesRead + bytes <= buffer.maxBytes) { buffer.bytesRead += bytes; } else { scanBuffer.bytesRead -= bytes; buffer.full = true; buffer.nextReadSize = bytes; return false; } scanBuffer.itemsRead++; return true; } void BackfillManager::bytesSent(uint32_t bytes) { LockHolder lh(lock); cb_assert(buffer.bytesRead >= bytes); buffer.bytesRead -= bytes; if (buffer.full) { uint32_t bufferSize = buffer.bytesRead; bool canFitNext = buffer.maxBytes - bufferSize >= buffer.nextReadSize; bool enoughCleared = bufferSize < (buffer.maxBytes * 3 / 4); if (canFitNext && enoughCleared) { buffer.nextReadSize = 0; buffer.full = false; if (managerTask) { managerTask->snooze(0); } } } } backfill_status_t BackfillManager::backfill() { LockHolder lh(lock); if (buffer.full) { return backfill_snooze; } if (activeBackfills.empty() && snoozingBackfills.empty()) { managerTask.reset(); return backfill_finished; } if (engine->getEpStore()->isMemoryUsageTooHigh()) { LOG(EXTENSION_LOG_WARNING, "DCP backfilling task for connection %s " "temporarily suspended because the current memory usage is too " "high", conn->getName().c_str()); return backfill_snooze; } while (!snoozingBackfills.empty()) { std::pair<rel_time_t, DCPBackfill*> snoozer = snoozingBackfills.front(); // If snoozing task is found to be sleeping for greater than // allowed snoozetime, push into active queue if (snoozer.first + sleepTime <= ep_current_time()) { DCPBackfill* bfill = snoozer.second; activeBackfills.push(bfill); snoozingBackfills.pop_front(); } else { break; } } if (activeBackfills.empty()) { return backfill_snooze; } DCPBackfill* backfill = activeBackfills.front(); lh.unlock(); backfill_status_t status = backfill->run(); lh.lock(); if (status == backfill_success && buffer.full) { // Snooze while the buffer is full return backfill_snooze; } scanBuffer.bytesRead = 0; scanBuffer.itemsRead = 0; activeBackfills.pop(); if (status == backfill_success) { activeBackfills.push(backfill); } else if (status == backfill_finished) { lh.unlock(); delete backfill; } else if (status == backfill_snooze) { uint16_t vbid = backfill->getVBucketId(); RCPtr<VBucket> vb = engine->getVBucket(vbid); if (vb) { snoozingBackfills.push_back( std::make_pair(ep_current_time(), backfill)); shared_ptr<Callback<uint64_t> > cb(new BackfillCallback(backfill->getEndSeqno(), vbid, conn)); vb->addPersistenceNotification(cb); } else { lh.unlock(); LOG(EXTENSION_LOG_WARNING, "Deleting the backfill, as vbucket %d " "seems to have been deleted!", vbid); backfill->cancel(); delete backfill; } } else { abort(); } return backfill_success; } void BackfillManager::wakeUpTask() { LockHolder lh(lock); if (managerTask) { managerTask->snooze(0); } } void BackfillManager::wakeUpSnoozingBackfills(uint16_t vbid) { LockHolder lh(lock); std::list<std::pair<rel_time_t, DCPBackfill*> >::iterator it; for (it = snoozingBackfills.begin(); it != snoozingBackfills.end(); ++it) { DCPBackfill *bfill = (*it).second; if (vbid == bfill->getVBucketId()) { activeBackfills.push(bfill); snoozingBackfills.erase(it); managerTask->snooze(0); return; } } } bool BackfillManager::addIfLessThanMax(AtomicValue<uint32_t>& val, uint32_t incr, uint32_t max) { do { uint32_t oldVal = val.load(); uint32_t newVal = oldVal + incr; if (newVal > max) { return false; } if (val.compare_exchange_strong(oldVal, newVal)) { return true; } } while (true); } <|endoftext|>
<commit_before>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <unistd.h> #include <fnord/io/file.h> #include <fnord/io/fileutil.h> #include <fnord/io/mmappedfile.h> #include <fnord/logging.h> #include <fnord/io/fileutil.h> #include <fnord/util/binarymessagereader.h> #include <fnord/util/binarymessagewriter.h> #include <dproc/LocalScheduler.h> using namespace fnord; namespace dproc { LocalScheduler::LocalScheduler( const String& tempdir /* = "/tmp" */, size_t max_threads /* = 8 */, size_t max_requests /* = 32 */) : tempdir_(tempdir), tpool_(max_threads), req_tpool_(max_requests) {} void LocalScheduler::start() { req_tpool_.start(); tpool_.start(); } void LocalScheduler::stop() { req_tpool_.stop(); tpool_.stop(); } RefPtr<TaskResultFuture> LocalScheduler::run( RefPtr<Application> app, const TaskSpec& task) { RefPtr<TaskResultFuture> result(new TaskResultFuture()); try { auto instance = mkRef( new LocalTaskRef( app, task.task_name(), Buffer(task.params().data(), task.params().size()))); req_tpool_.run([this, app, result, instance] () { try { LocalTaskPipeline pipeline; pipeline.tasks.push_back(instance); runPipeline(app.get(), &pipeline, result); if (instance->failed) { RAISE(kRuntimeError, "task failed"); } result->returnResult(instance->task); } catch (const StandardException& e) { fnord::logError("dproc.scheduler", e, "task failed"); result->returnError(e); } }); } catch (const StandardException& e) { fnord::logError("dproc.scheduler", e, "task failed"); result->returnError(e); } return result; } void LocalScheduler::runPipeline( Application* app, LocalTaskPipeline* pipeline, RefPtr<TaskResultFuture> result) { fnord::logDebug( "fnord.dproc", "Starting local pipeline id=$0 tasks=$1", (void*) pipeline, pipeline->tasks.size()); std::unique_lock<std::mutex> lk(pipeline->mutex); result->updateStatus([&pipeline] (TaskStatus* status) { status->num_subtasks_total = pipeline->tasks.size(); }); while (pipeline->tasks.size() > 0) { bool waiting = true; size_t num_waiting = 0; size_t num_running = 0; size_t num_completed = 0; for (auto& taskref : pipeline->tasks) { if (taskref->finished) { ++num_completed; continue; } if (taskref->running) { ++num_running; continue; } if (!taskref->expanded) { taskref->expanded = true; auto rdd = dynamic_cast<dproc::RDD*>(taskref->task.get()); if (rdd != nullptr) { auto cache_key = rdd->cacheKeySHA1(); if (!cache_key.isEmpty()) { taskref->cache_filename = FileUtil::joinPaths( tempdir_, StringUtil::format("$0.rdd", cache_key.get())); } if (!taskref->cache_filename.empty() && FileUtil::exists(taskref->cache_filename)) { fnord::logDebug( "fnord.dproc", "Read RDD from cache: $0, key=$1", taskref->debug_name, cache_key.get()); taskref->readCache(); result->updateStatus([&pipeline] (TaskStatus* status) { ++status->num_subtasks_completed; }); taskref->finished = true; waiting = false; break; } } auto parent_task = taskref; size_t numdeps = 0; for (const auto& dep : taskref->task->dependencies()) { RefPtr<LocalTaskRef> depref(new LocalTaskRef(app, dep.task_name, dep.params)); parent_task->dependencies.emplace_back(depref); pipeline->tasks.emplace_back(depref); ++numdeps; } if (numdeps > 0) { result->updateStatus([numdeps] (TaskStatus* status) { status->num_subtasks_total += numdeps; }); } waiting = false; break; } bool deps_finished = true; for (const auto& dep : taskref->dependencies) { if (dep->failed) { taskref->failed = true; taskref->finished = true; waiting = false; } if (!dep->finished) { deps_finished = false; } } if (!taskref->finished) { if (!deps_finished) { ++num_waiting; continue; } fnord::logDebug( "fnord.dproc", "Computing RDD: $0", taskref->debug_name); taskref->running = true; tpool_.run(std::bind( &LocalScheduler::runTask, this, pipeline, taskref, result)); waiting = false; } } fnord::logDebug( "fnord.dproc", "Running local pipeline id=$0: $1", (void*) pipeline, result->status().toString()); if (waiting) { pipeline->wakeup.wait(lk); } while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) { pipeline->tasks.pop_back(); } } fnord::logDebug( "fnord.dproc", "Completed local pipeline id=$0", (void*) pipeline); } void LocalScheduler::runTask( LocalTaskPipeline* pipeline, RefPtr<LocalTaskRef> task, RefPtr<TaskResultFuture> result) { bool from_cache = false; auto rdd = dynamic_cast<dproc::RDD*>(task->task.get()); if (rdd != nullptr && !task->cache_filename.empty() && FileUtil::exists(task->cache_filename)) { fnord::logDebug( "fnord.dproc", "Read RDD from cache: $0, key=$1", task->debug_name, rdd->cacheKeySHA1().get()); task->readCache(); from_cache = true; } if (!from_cache) { try { task->task->compute(task.get()); if (rdd != nullptr && !task->cache_filename.empty()) { auto cache_file = task->cache_filename; auto cache = rdd->encode(); auto f = File::openFile( cache_file + "~", File::O_CREATEOROPEN | File::O_WRITE | File::O_TRUNCATE); f.write(cache->data(), cache->size()); FileUtil::mv(cache_file + "~", cache_file); } } catch (const std::exception& e) { task->failed = true; fnord::logError("fnord.dproc", e, "error"); } } result->updateStatus([&pipeline] (TaskStatus* status) { ++status->num_subtasks_completed; }); std::unique_lock<std::mutex> lk(pipeline->mutex); task->finished = true; lk.unlock(); pipeline->wakeup.notify_all(); } LocalScheduler::LocalTaskRef::LocalTaskRef( RefPtr<Application> app, const String& task_name, const Buffer& params) : task(app->getTaskInstance(task_name, params)), debug_name(StringUtil::format("$0#$1", app->name(), task_name)), running(false), expanded(false), finished(false), failed(false) {} void LocalScheduler::LocalTaskRef::readCache() { auto rdd = dynamic_cast<dproc::RDD*>(task.get()); if (rdd == nullptr) { RAISE(kRuntimeError, "can't cache actions"); } rdd->decode( new io::MmappedFile( File::openFile( cache_filename, File::O_READ))); } RefPtr<dproc::RDD> LocalScheduler::LocalTaskRef::getDependency(size_t index) { if (index >= dependencies.size()) { RAISEF(kIndexError, "invalid dependecy index: $0", index); } const auto& dep = dependencies[index]; return dynamic_cast<dproc::RDD*>(dep->task.get()); } size_t LocalScheduler::LocalTaskRef::numDependencies() const { return dependencies.size(); } } // namespace dproc <commit_msg>dproc log namespace<commit_after>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <unistd.h> #include <fnord/io/file.h> #include <fnord/io/fileutil.h> #include <fnord/io/mmappedfile.h> #include <fnord/logging.h> #include <fnord/io/fileutil.h> #include <fnord/util/binarymessagereader.h> #include <fnord/util/binarymessagewriter.h> #include <dproc/LocalScheduler.h> using namespace fnord; namespace dproc { LocalScheduler::LocalScheduler( const String& tempdir /* = "/tmp" */, size_t max_threads /* = 8 */, size_t max_requests /* = 32 */) : tempdir_(tempdir), tpool_(max_threads), req_tpool_(max_requests) {} void LocalScheduler::start() { req_tpool_.start(); tpool_.start(); } void LocalScheduler::stop() { req_tpool_.stop(); tpool_.stop(); } RefPtr<TaskResultFuture> LocalScheduler::run( RefPtr<Application> app, const TaskSpec& task) { RefPtr<TaskResultFuture> result(new TaskResultFuture()); try { auto instance = mkRef( new LocalTaskRef( app, task.task_name(), Buffer(task.params().data(), task.params().size()))); req_tpool_.run([this, app, result, instance] () { try { LocalTaskPipeline pipeline; pipeline.tasks.push_back(instance); runPipeline(app.get(), &pipeline, result); if (instance->failed) { RAISE(kRuntimeError, "task failed"); } result->returnResult(instance->task); } catch (const StandardException& e) { fnord::logError("dproc.scheduler", e, "task failed"); result->returnError(e); } }); } catch (const StandardException& e) { fnord::logError("dproc.scheduler", e, "task failed"); result->returnError(e); } return result; } void LocalScheduler::runPipeline( Application* app, LocalTaskPipeline* pipeline, RefPtr<TaskResultFuture> result) { fnord::logDebug( "dproc", "Starting local pipeline id=$0 tasks=$1", (void*) pipeline, pipeline->tasks.size()); std::unique_lock<std::mutex> lk(pipeline->mutex); result->updateStatus([&pipeline] (TaskStatus* status) { status->num_subtasks_total = pipeline->tasks.size(); }); while (pipeline->tasks.size() > 0) { bool waiting = true; size_t num_waiting = 0; size_t num_running = 0; size_t num_completed = 0; for (auto& taskref : pipeline->tasks) { if (taskref->finished) { ++num_completed; continue; } if (taskref->running) { ++num_running; continue; } if (!taskref->expanded) { taskref->expanded = true; auto rdd = dynamic_cast<dproc::RDD*>(taskref->task.get()); if (rdd != nullptr) { auto cache_key = rdd->cacheKeySHA1(); if (!cache_key.isEmpty()) { taskref->cache_filename = FileUtil::joinPaths( tempdir_, StringUtil::format("$0.rdd", cache_key.get())); } if (!taskref->cache_filename.empty() && FileUtil::exists(taskref->cache_filename)) { fnord::logDebug( "dproc", "Read RDD from cache: $0, key=$1", taskref->debug_name, cache_key.get()); taskref->readCache(); result->updateStatus([&pipeline] (TaskStatus* status) { ++status->num_subtasks_completed; }); taskref->finished = true; waiting = false; break; } } auto parent_task = taskref; size_t numdeps = 0; for (const auto& dep : taskref->task->dependencies()) { RefPtr<LocalTaskRef> depref(new LocalTaskRef(app, dep.task_name, dep.params)); parent_task->dependencies.emplace_back(depref); pipeline->tasks.emplace_back(depref); ++numdeps; } if (numdeps > 0) { result->updateStatus([numdeps] (TaskStatus* status) { status->num_subtasks_total += numdeps; }); } waiting = false; break; } bool deps_finished = true; for (const auto& dep : taskref->dependencies) { if (dep->failed) { taskref->failed = true; taskref->finished = true; waiting = false; } if (!dep->finished) { deps_finished = false; } } if (!taskref->finished) { if (!deps_finished) { ++num_waiting; continue; } fnord::logDebug( "dproc", "Computing RDD: $0", taskref->debug_name); taskref->running = true; tpool_.run(std::bind( &LocalScheduler::runTask, this, pipeline, taskref, result)); waiting = false; } } fnord::logDebug( "dproc", "Running local pipeline id=$0: $1", (void*) pipeline, result->status().toString()); if (waiting) { pipeline->wakeup.wait(lk); } while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) { pipeline->tasks.pop_back(); } } fnord::logDebug( "dproc", "Completed local pipeline id=$0", (void*) pipeline); } void LocalScheduler::runTask( LocalTaskPipeline* pipeline, RefPtr<LocalTaskRef> task, RefPtr<TaskResultFuture> result) { bool from_cache = false; auto rdd = dynamic_cast<dproc::RDD*>(task->task.get()); if (rdd != nullptr && !task->cache_filename.empty() && FileUtil::exists(task->cache_filename)) { fnord::logDebug( "dproc", "Read RDD from cache: $0, key=$1", task->debug_name, rdd->cacheKeySHA1().get()); task->readCache(); from_cache = true; } if (!from_cache) { try { task->task->compute(task.get()); if (rdd != nullptr && !task->cache_filename.empty()) { auto cache_file = task->cache_filename; auto cache = rdd->encode(); auto f = File::openFile( cache_file + "~", File::O_CREATEOROPEN | File::O_WRITE | File::O_TRUNCATE); f.write(cache->data(), cache->size()); FileUtil::mv(cache_file + "~", cache_file); } } catch (const std::exception& e) { task->failed = true; fnord::logError("dproc", e, "error"); } } result->updateStatus([&pipeline] (TaskStatus* status) { ++status->num_subtasks_completed; }); std::unique_lock<std::mutex> lk(pipeline->mutex); task->finished = true; lk.unlock(); pipeline->wakeup.notify_all(); } LocalScheduler::LocalTaskRef::LocalTaskRef( RefPtr<Application> app, const String& task_name, const Buffer& params) : task(app->getTaskInstance(task_name, params)), debug_name(StringUtil::format("$0#$1", app->name(), task_name)), running(false), expanded(false), finished(false), failed(false) {} void LocalScheduler::LocalTaskRef::readCache() { auto rdd = dynamic_cast<dproc::RDD*>(task.get()); if (rdd == nullptr) { RAISE(kRuntimeError, "can't cache actions"); } rdd->decode( new io::MmappedFile( File::openFile( cache_filename, File::O_READ))); } RefPtr<dproc::RDD> LocalScheduler::LocalTaskRef::getDependency(size_t index) { if (index >= dependencies.size()) { RAISEF(kIndexError, "invalid dependecy index: $0", index); } const auto& dep = dependencies[index]; return dynamic_cast<dproc::RDD*>(dep->task.get()); } size_t LocalScheduler::LocalTaskRef::numDependencies() const { return dependencies.size(); } } // namespace dproc <|endoftext|>
<commit_before>#include "QtWebSockets/QWebSocketServer" #include "QtWebSockets/QWebSocket" #include <QtCore/QDebug> #include "WebSocketServer.h" #include "Player.h" WebSocketServer::WebSocketServer(quint16 port, QObject *parent) : QObject(parent), m_pWebSocketServer(Q_NULLPTR), m_clients() { m_pWebSocketServer = new QWebSocketServer(QStringLiteral("Chat Server"), QWebSocketServer::NonSecureMode, this); if (m_pWebSocketServer->listen(QHostAddress::Any, port)) { qDebug() << "WebSocket server listening on port " << port; connect(m_pWebSocketServer, &QWebSocketServer::newConnection, this, &WebSocketServer::onNewConnection); connect(Player::instance(), &Player::statusChanged, this, &WebSocketServer::broadcastStatus); connect(Player::instance(), &Player::playlistChanged, this, &WebSocketServer::broadcastPlaylist); } } WebSocketServer::~WebSocketServer() { m_pWebSocketServer->close(); qDeleteAll(m_clients.begin(), m_clients.end()); } void WebSocketServer::onNewConnection() { QWebSocket *socket = m_pWebSocketServer->nextPendingConnection(); connect(socket, &QWebSocket::disconnected, this, &WebSocketServer::socketDisconnected); JsonApi *api = new JsonApi(socket); connect(socket, &QWebSocket::textMessageReceived, api, &JsonApi::processMessage); m_clients[socket] = api; } void WebSocketServer::broadcastStatus(EMSPlayerStatus newStatus) { foreach( JsonApi *api, m_clients.values() ) { if (api) { api->sendStatus(newStatus); } } } void WebSocketServer::broadcastPlaylist(EMSPlaylist newPlaylist) { foreach( JsonApi *api, m_clients.values() ) { if (api) { api->sendPlaylist(newPlaylist); } } } void WebSocketServer::sendAuthRequestToLocalUI(const EMSClient client) { QMapIterator<QWebSocket*, JsonApi*> client_it(m_clients); qDebug() << "WebSocketServer: nb clients = " << m_clients.size(); // Search the websocket for the local UI, while (client_it.hasNext()) { client_it.next(); if (client_it.key()->peerAddress() == QHostAddress::LocalHost) { // and send the authentication request message client_it.value()->sendAuthRequest(client); return; } } } void WebSocketServer::processMessage(QString message) { QWebSocket *client = qobject_cast<QWebSocket *>(sender()); m_clients[client]->processMessage(message); } void WebSocketServer::socketDisconnected() { QWebSocket *client = qobject_cast<QWebSocket *>(sender()); if (client) { delete m_clients[client]; m_clients.remove(client); } } <commit_msg>Accept client: add log for debug<commit_after>#include "QtWebSockets/QWebSocketServer" #include "QtWebSockets/QWebSocket" #include <QtCore/QDebug> #include "WebSocketServer.h" #include "Player.h" WebSocketServer::WebSocketServer(quint16 port, QObject *parent) : QObject(parent), m_pWebSocketServer(Q_NULLPTR), m_clients() { m_pWebSocketServer = new QWebSocketServer(QStringLiteral("Chat Server"), QWebSocketServer::NonSecureMode, this); if (m_pWebSocketServer->listen(QHostAddress::Any, port)) { qDebug() << "WebSocket server listening on port " << port; connect(m_pWebSocketServer, &QWebSocketServer::newConnection, this, &WebSocketServer::onNewConnection); connect(Player::instance(), &Player::statusChanged, this, &WebSocketServer::broadcastStatus); connect(Player::instance(), &Player::playlistChanged, this, &WebSocketServer::broadcastPlaylist); } } WebSocketServer::~WebSocketServer() { m_pWebSocketServer->close(); qDeleteAll(m_clients.begin(), m_clients.end()); } void WebSocketServer::onNewConnection() { QWebSocket *socket = m_pWebSocketServer->nextPendingConnection(); connect(socket, &QWebSocket::disconnected, this, &WebSocketServer::socketDisconnected); JsonApi *api = new JsonApi(socket); connect(socket, &QWebSocket::textMessageReceived, api, &JsonApi::processMessage); m_clients[socket] = api; } void WebSocketServer::broadcastStatus(EMSPlayerStatus newStatus) { foreach( JsonApi *api, m_clients.values() ) { if (api) { api->sendStatus(newStatus); } } } void WebSocketServer::broadcastPlaylist(EMSPlaylist newPlaylist) { foreach( JsonApi *api, m_clients.values() ) { if (api) { api->sendPlaylist(newPlaylist); } } } void WebSocketServer::sendAuthRequestToLocalUI(const EMSClient client) { QMapIterator<QWebSocket*, JsonApi*> client_it(m_clients); qDebug() << "WebSocketServer: sent the 'authentication' request for " << client.uuid; qDebug() << "WebSocketServer: nb connected clients = " << m_clients.size(); // Search the websocket for the local UI, while (client_it.hasNext()) { client_it.next(); if (client_it.key()->peerAddress() == QHostAddress::LocalHost) { // and send the authentication request message client_it.value()->sendAuthRequest(client); return; } } } void WebSocketServer::processMessage(QString message) { QWebSocket *client = qobject_cast<QWebSocket *>(sender()); m_clients[client]->processMessage(message); } void WebSocketServer::socketDisconnected() { QWebSocket *client = qobject_cast<QWebSocket *>(sender()); if (client) { delete m_clients[client]; m_clients.remove(client); } } <|endoftext|>
<commit_before>/* * 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 Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * e133-receiver.cpp * Copyright (C) 2011 Simon Newton * * This creates a E1.33 receiver with one (emulated) RDM responder. The node is * registered in slp and the RDM responder responds to E1.33 commands. */ #if HAVE_CONFIG_H # include <config.h> #endif #include <signal.h> #include <sysexits.h> #include <ola/acn/ACNPort.h> #include <ola/acn/CID.h> #include <ola/DmxBuffer.h> #include <ola/base/Flags.h> #include <ola/base/Init.h> #include <ola/BaseTypes.h> #include <ola/io/Descriptor.h> #include <ola/Logging.h> #include <ola/network/InterfacePicker.h> #include <ola/rdm/RDMControllerAdaptor.h> #include <ola/rdm/UIDAllocator.h> #include <ola/rdm/UID.h> #include <ola/stl/STLUtils.h> #include <memory> #include <string> #include <vector> #ifdef USE_SPI #include "plugins/spi/SPIBackend.h" using ola::plugin::spi::SPIBackend; DEFINE_string(spi_device, "", "Path to the SPI device to use."); #endif #include "plugins/e131/e131/E131Node.h" #include "plugins/usbpro/BaseUsbProWidget.h" #include "plugins/usbpro/DmxTriWidget.h" #include "tools/e133/SimpleE133Node.h" using ola::DmxBuffer; using ola::acn::CID; using ola::network::IPV4Address; using ola::rdm::UID; using std::auto_ptr; using std::string; using std::vector; using ola::plugin::usbpro::DmxTriWidget; DEFINE_bool(dummy, true, "Include a dummy responder endpoint"); DEFINE_bool(e131, true, "Include E1.31 support"); DEFINE_string(listen_ip, "", "The IP address to listen on."); DEFINE_string(uid, "7a70:00000001", "The UID of the responder."); DEFINE_s_uint16(lifetime, t, 300, "The value to use for the service lifetime"); DEFINE_s_uint32(universe, u, 1, "The E1.31 universe to listen on."); DEFINE_string(tri_device, "", "Path to the RDM-TRI device to use."); SimpleE133Node *simple_node; /* * Terminate cleanly on interrupt. */ static void InteruptSignal(int signo) { if (simple_node) simple_node->Stop(); (void) signo; } void HandleDMX(DmxBuffer *buffer, DmxTriWidget *widget) { widget->SendDMX(*buffer); } #ifdef USE_SPI void HandleDMX(DmxBuffer *buffer, SPIBackend *backend) { backend->WriteDMX(*buffer, 0); } #endif /* * Startup a node */ int main(int argc, char *argv[]) { ola::SetHelpString( "[options]", "Run a very simple E1.33 Responder."); ola::ParseFlags(&argc, argv); ola::InitLoggingFromFlags(); auto_ptr<UID> uid(UID::FromString(FLAGS_uid)); if (!uid.get()) { OLA_WARN << "Invalid UID: " << FLAGS_uid; ola::DisplayUsage(); exit(EX_USAGE); } CID cid = CID::Generate(); // Find a network interface to use ola::network::Interface interface; { auto_ptr<const ola::network::InterfacePicker> picker( ola::network::InterfacePicker::NewPicker()); if (!picker->ChooseInterface(&interface, FLAGS_listen_ip)) { OLA_INFO << "Failed to find an interface"; exit(EX_UNAVAILABLE); } } // Setup the Node. SimpleE133Node::Options opts(cid, interface.ip_address, *uid, FLAGS_lifetime); SimpleE133Node node(opts); // Optionally attach some other endpoints. vector<E133Endpoint*> endpoints; auto_ptr<ola::plugin::dummy::DummyResponder> dummy_responder; auto_ptr<ola::rdm::DiscoverableRDMControllerAdaptor> discoverable_dummy_responder; auto_ptr<DmxTriWidget> tri_widget; ola::rdm::UIDAllocator uid_allocator(*uid); // The first uid is used for the management endpoint so we burn a UID here. { auto_ptr<UID> dummy_uid(uid_allocator.AllocateNext()); } // Setup E1.31 if required. auto_ptr<ola::plugin::e131::E131Node> e131_node; if (FLAGS_e131) { e131_node.reset(new ola::plugin::e131::E131Node(FLAGS_listen_ip, cid)); if (!e131_node->Start()) { OLA_WARN << "Failed to start E1.31 node"; exit(EX_UNAVAILABLE); } OLA_INFO << "Started E1.31 node!"; node.SelectServer()->AddReadDescriptor(e131_node->GetSocket()); } if (FLAGS_dummy) { auto_ptr<UID> dummy_uid(uid_allocator.AllocateNext()); if (!dummy_uid.get()) { OLA_WARN << "Failed to allocate a UID for the DummyResponder."; exit(EX_USAGE); } dummy_responder.reset(new ola::plugin::dummy::DummyResponder(*dummy_uid)); discoverable_dummy_responder.reset( new ola::rdm::DiscoverableRDMControllerAdaptor( *dummy_uid, dummy_responder.get())); endpoints.push_back(new E133Endpoint(discoverable_dummy_responder.get(), E133Endpoint::EndpointProperties())); } // uber hack for now. // TODO(simon): fix this DmxBuffer tri_buffer; uint8_t unused_priority; if (!FLAGS_tri_device.str().empty()) { ola::io::ConnectedDescriptor *descriptor = ola::plugin::usbpro::BaseUsbProWidget::OpenDevice(FLAGS_tri_device); if (!descriptor) { OLA_WARN << "Failed to open " << FLAGS_tri_device; exit(EX_USAGE); } tri_widget.reset(new DmxTriWidget(node.SelectServer(), descriptor)); node.SelectServer()->AddReadDescriptor(descriptor); E133Endpoint::EndpointProperties properties; properties.is_physical = true; endpoints.push_back( new E133Endpoint(tri_widget.get(), properties)); if (e131_node.get()) { // Danger! e131_node->SetHandler( 1, &tri_buffer, &unused_priority, NewCallback(&HandleDMX, &tri_buffer, tri_widget.get())); } } // uber hack for now. // TODO(simon): fix this #ifdef USE_SPI auto_ptr<SPIBackend> spi_backend; DmxBuffer spi_buffer; if (!FLAGS_spi_device.str().empty()) { auto_ptr<UID> spi_uid(uid_allocator.AllocateNext()); if (!spi_uid.get()) { OLA_WARN << "Failed to allocate a UID for the SPI device."; exit(EX_USAGE); } spi_backend.reset( new SPIBackend(FLAGS_spi_device, *spi_uid, SPIBackend::Options())); E133Endpoint::EndpointProperties properties; properties.is_physical = true; endpoints.push_back(new E133Endpoint(spi_backend.get(), properties)); if (e131_node.get()) { // Danger! e131_node->SetHandler( 1, &spi_buffer, &unused_priority, NewCallback(&HandleDMX, &spi_buffer, spi_backend.get())); } } #endif for (unsigned int i = 0; i < endpoints.size(); i++) { node.AddEndpoint(i + 1, endpoints[i]); } simple_node = &node; if (!node.Init()) exit(EX_UNAVAILABLE); // signal handler if (!ola::InstallSignal(SIGINT, &InteruptSignal)) return false; node.Run(); if (e131_node.get()) { node.SelectServer()->RemoveReadDescriptor(e131_node->GetSocket()); } for (unsigned int i = 0; i < endpoints.size(); i++) { node.RemoveEndpoint(i + 1); } ola::STLDeleteElements(&endpoints); } <commit_msg>* make the function names unique<commit_after>/* * 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 Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * e133-receiver.cpp * Copyright (C) 2011 Simon Newton * * This creates a E1.33 receiver with one (emulated) RDM responder. The node is * registered in slp and the RDM responder responds to E1.33 commands. */ #if HAVE_CONFIG_H # include <config.h> #endif #include <signal.h> #include <sysexits.h> #include <ola/acn/ACNPort.h> #include <ola/acn/CID.h> #include <ola/DmxBuffer.h> #include <ola/base/Flags.h> #include <ola/base/Init.h> #include <ola/BaseTypes.h> #include <ola/io/Descriptor.h> #include <ola/Logging.h> #include <ola/network/InterfacePicker.h> #include <ola/rdm/RDMControllerAdaptor.h> #include <ola/rdm/UIDAllocator.h> #include <ola/rdm/UID.h> #include <ola/stl/STLUtils.h> #include <memory> #include <string> #include <vector> #ifdef USE_SPI #include "plugins/spi/SPIBackend.h" using ola::plugin::spi::SPIBackend; DEFINE_string(spi_device, "", "Path to the SPI device to use."); #endif #include "plugins/e131/e131/E131Node.h" #include "plugins/usbpro/BaseUsbProWidget.h" #include "plugins/usbpro/DmxTriWidget.h" #include "tools/e133/SimpleE133Node.h" using ola::DmxBuffer; using ola::acn::CID; using ola::network::IPV4Address; using ola::rdm::UID; using std::auto_ptr; using std::string; using std::vector; using ola::plugin::usbpro::DmxTriWidget; DEFINE_bool(dummy, true, "Include a dummy responder endpoint"); DEFINE_bool(e131, true, "Include E1.31 support"); DEFINE_string(listen_ip, "", "The IP address to listen on."); DEFINE_string(uid, "7a70:00000001", "The UID of the responder."); DEFINE_s_uint16(lifetime, t, 300, "The value to use for the service lifetime"); DEFINE_s_uint32(universe, u, 1, "The E1.31 universe to listen on."); DEFINE_string(tri_device, "", "Path to the RDM-TRI device to use."); SimpleE133Node *simple_node; /* * Terminate cleanly on interrupt. */ static void InteruptSignal(int signo) { if (simple_node) simple_node->Stop(); (void) signo; } void HandleTriDMX(DmxBuffer *buffer, DmxTriWidget *widget) { widget->SendDMX(*buffer); } #ifdef USE_SPI void HandleSpiDMX(DmxBuffer *buffer, SPIBackend *backend) { backend->WriteDMX(*buffer, 0); } #endif /* * Startup a node */ int main(int argc, char *argv[]) { ola::SetHelpString( "[options]", "Run a very simple E1.33 Responder."); ola::ParseFlags(&argc, argv); ola::InitLoggingFromFlags(); auto_ptr<UID> uid(UID::FromString(FLAGS_uid)); if (!uid.get()) { OLA_WARN << "Invalid UID: " << FLAGS_uid; ola::DisplayUsage(); exit(EX_USAGE); } CID cid = CID::Generate(); // Find a network interface to use ola::network::Interface interface; { auto_ptr<const ola::network::InterfacePicker> picker( ola::network::InterfacePicker::NewPicker()); if (!picker->ChooseInterface(&interface, FLAGS_listen_ip)) { OLA_INFO << "Failed to find an interface"; exit(EX_UNAVAILABLE); } } // Setup the Node. SimpleE133Node::Options opts(cid, interface.ip_address, *uid, FLAGS_lifetime); SimpleE133Node node(opts); // Optionally attach some other endpoints. vector<E133Endpoint*> endpoints; auto_ptr<ola::plugin::dummy::DummyResponder> dummy_responder; auto_ptr<ola::rdm::DiscoverableRDMControllerAdaptor> discoverable_dummy_responder; auto_ptr<DmxTriWidget> tri_widget; ola::rdm::UIDAllocator uid_allocator(*uid); // The first uid is used for the management endpoint so we burn a UID here. { auto_ptr<UID> dummy_uid(uid_allocator.AllocateNext()); } // Setup E1.31 if required. auto_ptr<ola::plugin::e131::E131Node> e131_node; if (FLAGS_e131) { e131_node.reset(new ola::plugin::e131::E131Node(FLAGS_listen_ip, cid)); if (!e131_node->Start()) { OLA_WARN << "Failed to start E1.31 node"; exit(EX_UNAVAILABLE); } OLA_INFO << "Started E1.31 node!"; node.SelectServer()->AddReadDescriptor(e131_node->GetSocket()); } if (FLAGS_dummy) { auto_ptr<UID> dummy_uid(uid_allocator.AllocateNext()); if (!dummy_uid.get()) { OLA_WARN << "Failed to allocate a UID for the DummyResponder."; exit(EX_USAGE); } dummy_responder.reset(new ola::plugin::dummy::DummyResponder(*dummy_uid)); discoverable_dummy_responder.reset( new ola::rdm::DiscoverableRDMControllerAdaptor( *dummy_uid, dummy_responder.get())); endpoints.push_back(new E133Endpoint(discoverable_dummy_responder.get(), E133Endpoint::EndpointProperties())); } // uber hack for now. // TODO(simon): fix this DmxBuffer tri_buffer; uint8_t unused_priority; if (!FLAGS_tri_device.str().empty()) { ola::io::ConnectedDescriptor *descriptor = ola::plugin::usbpro::BaseUsbProWidget::OpenDevice(FLAGS_tri_device); if (!descriptor) { OLA_WARN << "Failed to open " << FLAGS_tri_device; exit(EX_USAGE); } tri_widget.reset(new DmxTriWidget(node.SelectServer(), descriptor)); node.SelectServer()->AddReadDescriptor(descriptor); E133Endpoint::EndpointProperties properties; properties.is_physical = true; endpoints.push_back( new E133Endpoint(tri_widget.get(), properties)); if (e131_node.get()) { // Danger! e131_node->SetHandler( 1, &tri_buffer, &unused_priority, NewCallback(&HandleTriDMX, &tri_buffer, tri_widget.get())); } } // uber hack for now. // TODO(simon): fix this #ifdef USE_SPI auto_ptr<SPIBackend> spi_backend; DmxBuffer spi_buffer; if (!FLAGS_spi_device.str().empty()) { auto_ptr<UID> spi_uid(uid_allocator.AllocateNext()); if (!spi_uid.get()) { OLA_WARN << "Failed to allocate a UID for the SPI device."; exit(EX_USAGE); } spi_backend.reset( new SPIBackend(FLAGS_spi_device, *spi_uid, SPIBackend::Options())); E133Endpoint::EndpointProperties properties; properties.is_physical = true; endpoints.push_back(new E133Endpoint(spi_backend.get(), properties)); if (e131_node.get()) { // Danger! e131_node->SetHandler( 1, &spi_buffer, &unused_priority, NewCallback(&HandleSpiDMX, &spi_buffer, spi_backend.get())); } } #endif for (unsigned int i = 0; i < endpoints.size(); i++) { node.AddEndpoint(i + 1, endpoints[i]); } simple_node = &node; if (!node.Init()) exit(EX_UNAVAILABLE); // signal handler if (!ola::InstallSignal(SIGINT, &InteruptSignal)) return false; node.Run(); if (e131_node.get()) { node.SelectServer()->RemoveReadDescriptor(e131_node->GetSocket()); } for (unsigned int i = 0; i < endpoints.size(); i++) { node.RemoveEndpoint(i + 1); } ola::STLDeleteElements(&endpoints); } <|endoftext|>
<commit_before>#include "Spectrum2.h" Spectrum2::Spectrum2(uint16_t columns, uint16_t rows, uint16_t rowOffset, uint16_t length, uint8_t hue, uint8_t saturation, bool invert, CRGB * leds) : Visualization(columns, rows, hue, saturation, leds) { this->rowOffset = rowOffset; this->invert = invert; this->length = length; this->density = 0.06; this->threshold = 1000.0; this->peak = 2000.0; this->drift = 0; this->totalMagnitudeMovingAverage = 20000.0; } void Spectrum2::display(float* magnitudes) { uint_fast16_t peakCount = 0; bool overPeak = false; float sorted[this->length]; memcpy(sorted, magnitudes, sizeof(magnitudes[0]) * this->length); std::sort(sorted, sorted+sizeof(sorted)/sizeof(sorted[0])); const float alpha = 0.9; float cutoffMagnitude = sorted[(uint_fast16_t)((1 - this->density)*this->length)]; float peakMagnitude = sorted[this->length - 2]; this->threshold = (this->threshold * alpha) + (cutoffMagnitude* (1 - alpha)); this->peak = (this->peak * alpha) + (peakMagnitude * (1 - alpha)); float magnitude; float magnitudeSum = 0; for (uint8_t y=0; y<this->length; y++) { overPeak = false; magnitudeSum += magnitudes[y]; if (magnitudes[y] < this->threshold) { continue; } if (magnitudes[y] > this->peak * 1.2) { peakCount++; overPeak = true; } magnitude = ((magnitudes[y] - this->threshold) / (this->peak - this->threshold)); magnitude = min(magnitude, 1); magnitude = max(magnitude, 0.15); CRGB c = CHSV(this->hue, this->saturation, magnitude*255); CRGB c2 = CHSV(this->hue, this->saturation, magnitude*128); for (uint8_t x=0; x<this->columns; x++) { if (this->invert) { leds[this->xy2Pos(x, this->rowOffset - y)] = c; if (overPeak) { if (y > 0) { leds[this->xy2Pos(x, (this->rowOffset - (y - 1)))] = c2; } if (y < this->length - 1) { leds[this->xy2Pos(x, (this->rowOffset - (y + 1)))] = c2; } } } else { leds[this->xy2Pos(x, y + this->rowOffset)] = c; if (overPeak) { if (y > 0) { leds[this->xy2Pos(x, (y + this->rowOffset) - 1)] = c2; } if (y < this->length - 1) { leds[this->xy2Pos(x, y + this->rowOffset + 1)] = c2; } } } } if (overPeak) { y++; } } this->hue += this->drift; // Change hue to pink on big volume increases if (this->drift > 0 && magnitudeSum > this->totalMagnitudeMovingAverage * 1.75) { this->hue = 240; } this->totalMagnitudeMovingAverage = (this->totalMagnitudeMovingAverage * (0.9998)) + (magnitudeSum/5000.0); uint_fast32_t currentTime = millis(); // put things we want to log here if (currentTime > this->loggingTimestamp + 5000) { this->loggingTimestamp = currentTime; // Serial.print(peakCount); // Serial.print(cutoffMagnitude); // Serial.print("\t"); // Serial.print(peakMagnitude); // Serial.print("\t"); // Serial.print(this->threshold); // Serial.print("\t"); // Serial.print(this->peak); // Serial.print("\t"); // Serial.print(this->hue); // Serial.print("\t"); // Serial.print(magnitudeSum); // Serial.print("\t"); // Serial.print(this->totalMagnitudeMovingAverage); // Serial.println(""); } } void Spectrum2::setDrift(uint8_t drift) { this->drift = drift; } float Spectrum2::getDensity() { return this->density; } void Spectrum2::setDensity(float density) { this->density = density; } <commit_msg>make drift time based vs cycle based<commit_after>#include "Spectrum2.h" Spectrum2::Spectrum2(uint16_t columns, uint16_t rows, uint16_t rowOffset, uint16_t length, uint8_t hue, uint8_t saturation, bool invert, CRGB * leds) : Visualization(columns, rows, hue, saturation, leds) { this->rowOffset = rowOffset; this->invert = invert; this->length = length; this->density = 0.06; this->threshold = 1000.0; this->peak = 2000.0; this->drift = 0; this->totalMagnitudeMovingAverage = 20000.0; } void Spectrum2::display(float* magnitudes) { uint_fast16_t peakCount = 0; bool overPeak = false; float sorted[this->length]; memcpy(sorted, magnitudes, sizeof(magnitudes[0]) * this->length); std::sort(sorted, sorted+sizeof(sorted)/sizeof(sorted[0])); const float alpha = 0.9; float cutoffMagnitude = sorted[(uint_fast16_t)((1 - this->density)*this->length)]; float peakMagnitude = sorted[this->length - 2]; this->threshold = (this->threshold * alpha) + (cutoffMagnitude* (1 - alpha)); this->peak = (this->peak * alpha) + (peakMagnitude * (1 - alpha)); float magnitude; float magnitudeSum = 0; for (uint8_t y=0; y<this->length; y++) { overPeak = false; magnitudeSum += magnitudes[y]; if (magnitudes[y] < this->threshold) { continue; } if (magnitudes[y] > this->peak * 1.2) { peakCount++; overPeak = true; } magnitude = ((magnitudes[y] - this->threshold) / (this->peak - this->threshold)); magnitude = min(magnitude, 1); magnitude = max(magnitude, 0.15); CRGB c = CHSV(this->hue, this->saturation, magnitude*255); CRGB c2 = CHSV(this->hue, this->saturation, magnitude*128); for (uint8_t x=0; x<this->columns; x++) { if (this->invert) { leds[this->xy2Pos(x, this->rowOffset - y)] = c; if (overPeak) { if (y > 0) { leds[this->xy2Pos(x, (this->rowOffset - (y - 1)))] = c2; } if (y < this->length - 1) { leds[this->xy2Pos(x, (this->rowOffset - (y + 1)))] = c2; } } } else { leds[this->xy2Pos(x, y + this->rowOffset)] = c; if (overPeak) { if (y > 0) { leds[this->xy2Pos(x, (y + this->rowOffset) - 1)] = c2; } if (y < this->length - 1) { leds[this->xy2Pos(x, y + this->rowOffset + 1)] = c2; } } } } if (overPeak) { y++; } } uint_fast32_t currentTime = millis(); this->hue = (currentTime / this->drift) % 256; // Change hue to pink on big volume increases if (this->drift > 0 && magnitudeSum > this->totalMagnitudeMovingAverage * 1.75) { this->hue = 240; } this->totalMagnitudeMovingAverage = (this->totalMagnitudeMovingAverage * (0.9998)) + (magnitudeSum/5000.0); // put things we want to log here if (currentTime > this->loggingTimestamp + 5000) { this->loggingTimestamp = currentTime; // Serial.print(peakCount); // Serial.print(cutoffMagnitude); // Serial.print("\t"); // Serial.print(peakMagnitude); // Serial.print("\t"); // Serial.print(this->threshold); // Serial.print("\t"); // Serial.print(this->peak); // Serial.print("\t"); // Serial.print(this->hue); // Serial.print("\t"); // Serial.print(magnitudeSum); // Serial.print("\t"); // Serial.print(this->totalMagnitudeMovingAverage); // Serial.println(""); } } void Spectrum2::setDrift(uint8_t drift) { this->drift = drift; } float Spectrum2::getDensity() { return this->density; } void Spectrum2::setDensity(float density) { this->density = density; } <|endoftext|>
<commit_before>/* ** Copyright 2015 Centreon ** ** 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. ** ** For more information : [email protected] */ #include <sstream> #include "com/centreon/broker/database.hh" #include "com/centreon/broker/database_preparator.hh" #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/mapping/entry.hh" using namespace com::centreon::broker; /** * Constructor. * * @param[in] event_id Event ID. * @param[in] unique Event UNIQUE. * @param[in] excluded Fields excluded from the query. */ database_preparator::database_preparator( unsigned int event_id, database_preparator::event_unique const& unique, database_query::excluded_fields const& excluded) : _event_id(event_id), _excluded(excluded), _unique(unique) {} /** * Copy constructor. * * @param[in] other Object to copy. */ database_preparator::database_preparator( database_preparator const& other) { _event_id = other._event_id; _excluded = other._excluded; _unique = other._unique; } /** * Destructor. */ database_preparator::~database_preparator() {} /** * Assignment operator. * * @param[in] other Object to copy. * * @return This object. */ database_preparator& database_preparator::operator=( database_preparator const& other) { if (this != &other) { _event_id = other._event_id; _excluded = other._excluded; _unique = other._unique; } return (*this); } /** * Prepare insertion query for specified event. * * @param[out] q Database query, prepared and ready to run. */ void database_preparator::prepare_insert(database_query& q) { // Find event info. io::event_info const* info(io::events::instance().get_event_info(_event_id)); if (!info) throw (exceptions::msg() << "could not prepare insertion query for event of type " << _event_id << ": event is not registered"); // Database schema version. bool schema_v2(q.db_object().schema_version() == database::v2); // Build query string. std::string query; query = "INSERT INTO "; if (schema_v2) query.append(info->get_table_v2()); else query.append(info->get_table()); query.append(" ("); mapping::entry const* entries(info->get_mapping()); for (int i(0); !entries[i].is_null(); ++i) { char const* entry_name; if (schema_v2) entry_name = entries[i].get_name_v2(); else entry_name = entries[i].get_name(); if (!entry_name || !entry_name[0] || (_excluded.find(entry_name) != _excluded.end())) continue ; query.append(entry_name); query.append(", "); } query.resize(query.size() - 2); query.append(") VALUES("); for (int i(0); !entries[i].is_null(); ++i) { char const* entry_name; if (schema_v2) entry_name = entries[i].get_name_v2(); else entry_name = entries[i].get_name(); if (!entry_name || !entry_name[0] || (_excluded.find(entry_name) != _excluded.end())) continue ; query.append(":"); query.append(entry_name); query.append(", "); } query.resize(query.size() - 2); query.append(")"); // Prepare statement. try { q.prepare(query); } catch (std::exception const& e) { throw (exceptions::msg() << "could not prepare insertion query for event '" << info->get_name() << "' in table '" << info->get_table() << "': " << e.what()); } return ; } /** * Prepare update query for specified event. * * @param[out] q Database query, prepared and ready to run. */ void database_preparator::prepare_update(database_query& q) { // Find event info. io::event_info const* info(io::events::instance().get_event_info(_event_id)); if (!info) throw (exceptions::msg() << "could not prepare update query for event of type " << _event_id << ": event is not registered"); // Database schema version. bool schema_v2(q.db_object().schema_version() == database::v2); // Build query string. std::string query; std::string where; query = "UPDATE "; if (schema_v2) query.append(info->get_table_v2()); else query.append(info->get_table()); query.append(" SET "); where = " WHERE "; mapping::entry const* entries(info->get_mapping()); for (int i(0); !entries[i].is_null(); ++i) { char const* entry_name; if (schema_v2) entry_name = entries[i].get_name_v2(); else entry_name = entries[i].get_name(); if (!entry_name || !entry_name[0] || (_excluded.find(entry_name) != _excluded.end())) continue ; // Standard field. if (_unique.find(entry_name) == _unique.end()) { query.append(entry_name); query.append("=:"); query.append(entry_name); query.append(", "); } // Part of ID field. else { where.append("COALESCE("); where.append(entry_name); where.append(", -1)=COALESCE(:"); where.append(entry_name); where.append(", -1) AND "); } } query.resize(query.size() - 2); query.append(where, 0, where.size() - 5); // Prepare statement. try { q.prepare(query); } catch (std::exception const& e) { throw (exceptions::msg() << "could not prepare update query for event '" << info->get_name() << "' on table '" << info->get_table() << "': " << e.what()); } return ; } /** * Prepare deletion query for specified event. * * @param[out] q Database query, prepared and ready to run. */ void database_preparator::prepare_delete(database_query& q) { // Find event info. io::event_info const* info(io::events::instance().get_event_info(_event_id)); if (!info) throw (exceptions::msg() << "could not prepare deletion query for event of type " << _event_id << ": event is not registered"); // Database schema version. bool schema_v2(q.db_object().schema_version() == database::v2); // Prepare query. std::string query; query = "DELETE FROM "; if (schema_v2) query.append(info->get_table_v2()); else query.append(info->get_table()); query.append(" WHERE "); for (event_unique::const_iterator it(_unique.begin()), end(_unique.end()); it != end; ++it) { query.append("COALESCE("); query.append(*it); query.append(", -1)=COALESCE(:"); query.append(*it); query.append(", -1) AND "); } query.resize(query.size() - 5); // Prepare statement. try { q.prepare(query); } catch (std::exception const& e) { throw (exceptions::msg() << "could not prepare deletion query for event '" << info->get_name() << "' on table '" << info->get_table() << "': " << e.what()); } return ; } <commit_msg>Core: fix indexing in database preparator queries.<commit_after>/* ** Copyright 2015 Centreon ** ** 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. ** ** For more information : [email protected] */ #include <sstream> #include "com/centreon/broker/database.hh" #include "com/centreon/broker/database_preparator.hh" #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/mapping/entry.hh" using namespace com::centreon::broker; /** * Constructor. * * @param[in] event_id Event ID. * @param[in] unique Event UNIQUE. * @param[in] excluded Fields excluded from the query. */ database_preparator::database_preparator( unsigned int event_id, database_preparator::event_unique const& unique, database_query::excluded_fields const& excluded) : _event_id(event_id), _excluded(excluded), _unique(unique) {} /** * Copy constructor. * * @param[in] other Object to copy. */ database_preparator::database_preparator( database_preparator const& other) { _event_id = other._event_id; _excluded = other._excluded; _unique = other._unique; } /** * Destructor. */ database_preparator::~database_preparator() {} /** * Assignment operator. * * @param[in] other Object to copy. * * @return This object. */ database_preparator& database_preparator::operator=( database_preparator const& other) { if (this != &other) { _event_id = other._event_id; _excluded = other._excluded; _unique = other._unique; } return (*this); } /** * Prepare insertion query for specified event. * * @param[out] q Database query, prepared and ready to run. */ void database_preparator::prepare_insert(database_query& q) { // Find event info. io::event_info const* info(io::events::instance().get_event_info(_event_id)); if (!info) throw (exceptions::msg() << "could not prepare insertion query for event of type " << _event_id << ": event is not registered"); // Database schema version. bool schema_v2(q.db_object().schema_version() == database::v2); // Build query string. std::string query; query = "INSERT INTO "; if (schema_v2) query.append(info->get_table_v2()); else query.append(info->get_table()); query.append(" ("); mapping::entry const* entries(info->get_mapping()); for (int i(0); !entries[i].is_null(); ++i) { char const* entry_name; if (schema_v2) entry_name = entries[i].get_name_v2(); else entry_name = entries[i].get_name(); if (!entry_name || !entry_name[0] || (_excluded.find(entry_name) != _excluded.end())) continue ; query.append(entry_name); query.append(", "); } query.resize(query.size() - 2); query.append(") VALUES("); for (int i(0); !entries[i].is_null(); ++i) { char const* entry_name; if (schema_v2) entry_name = entries[i].get_name_v2(); else entry_name = entries[i].get_name(); if (!entry_name || !entry_name[0] || (_excluded.find(entry_name) != _excluded.end())) continue ; query.append(":"); query.append(entry_name); query.append(", "); } query.resize(query.size() - 2); query.append(")"); // Prepare statement. try { q.prepare(query); } catch (std::exception const& e) { throw (exceptions::msg() << "could not prepare insertion query for event '" << info->get_name() << "' in table '" << info->get_table() << "': " << e.what()); } return ; } /** * Prepare update query for specified event. * * @param[out] q Database query, prepared and ready to run. */ void database_preparator::prepare_update(database_query& q) { // Find event info. io::event_info const* info(io::events::instance().get_event_info(_event_id)); if (!info) throw (exceptions::msg() << "could not prepare update query for event of type " << _event_id << ": event is not registered"); // Database schema version. bool schema_v2(q.db_object().schema_version() == database::v2); // Build query string. std::string query; std::string where; query = "UPDATE "; if (schema_v2) query.append(info->get_table_v2()); else query.append(info->get_table()); query.append(" SET "); where = " WHERE "; mapping::entry const* entries(info->get_mapping()); for (int i(0); !entries[i].is_null(); ++i) { char const* entry_name; if (schema_v2) entry_name = entries[i].get_name_v2(); else entry_name = entries[i].get_name(); if (!entry_name || !entry_name[0] || (_excluded.find(entry_name) != _excluded.end())) continue ; // Standard field. if (_unique.find(entry_name) == _unique.end()) { query.append(entry_name); query.append("=:"); query.append(entry_name); query.append(", "); } // Part of ID field. else { where.append(entry_name); where.append("=COALESCE(:"); where.append(entry_name); where.append(", -1) AND "); } } query.resize(query.size() - 2); query.append(where, 0, where.size() - 5); // Prepare statement. try { q.prepare(query); } catch (std::exception const& e) { throw (exceptions::msg() << "could not prepare update query for event '" << info->get_name() << "' on table '" << info->get_table() << "': " << e.what()); } return ; } /** * Prepare deletion query for specified event. * * @param[out] q Database query, prepared and ready to run. */ void database_preparator::prepare_delete(database_query& q) { // Find event info. io::event_info const* info(io::events::instance().get_event_info(_event_id)); if (!info) throw (exceptions::msg() << "could not prepare deletion query for event of type " << _event_id << ": event is not registered"); // Database schema version. bool schema_v2(q.db_object().schema_version() == database::v2); // Prepare query. std::string query; query = "DELETE FROM "; if (schema_v2) query.append(info->get_table_v2()); else query.append(info->get_table()); query.append(" WHERE "); for (event_unique::const_iterator it(_unique.begin()), end(_unique.end()); it != end; ++it) { query.append(*it); query.append("=COALESCE(:"); query.append(*it); query.append(", -1) AND "); } query.resize(query.size() - 5); // Prepare statement. try { q.prepare(query); } catch (std::exception const& e) { throw (exceptions::msg() << "could not prepare deletion query for event '" << info->get_name() << "' on table '" << info->get_table() << "': " << e.what()); } return ; } <|endoftext|>
<commit_before>#include "styleContext.h" #include "platform.h" #include "builders.h" #include "scene/scene.h" #define DUMP(...) //do { logMsg(__VA_ARGS__); duk_dump_context_stderr(m_ctx); } while(0) namespace Tangram { const static char DATA_ID[] = "\xff""\xff""data"; const static char ATTR_ID[] = "\xff""\xff""attr"; const static char FUNC_ID[] = "\xff""\xff""fns"; StyleContext::StyleContext() { m_ctx = duk_create_heap_default(); // add empty feature_object duk_push_object(m_ctx); // assign instance to feature_object duk_push_pointer(m_ctx, this); if (!duk_put_prop_string(m_ctx, -2, DATA_ID)) { LOGE("Ctx not assigned"); } // put object in global scope if (!duk_put_global_string(m_ctx, "feature")) { LOGE("Feature not assigned"); } DUMP("init\n"); } StyleContext::~StyleContext() { duk_destroy_heap(m_ctx); } void StyleContext::initFunctions(const Scene& _scene) { if (_scene.id == m_sceneId) { return; } m_sceneId = _scene.id; auto arr_idx = duk_push_array(m_ctx); int id = 0; for (auto& function : _scene.functions()) { LOGD("compile '%s'", function.c_str()); duk_push_string(m_ctx, function.c_str()); duk_push_string(m_ctx, ""); if (duk_pcompile(m_ctx, DUK_COMPILE_FUNCTION) == 0) { duk_put_prop_index(m_ctx, arr_idx, id); } else { LOGE("Compile failed: %s", duk_safe_to_string(m_ctx, -1)); duk_pop(m_ctx); } id++; } if (!duk_put_global_string(m_ctx, FUNC_ID)) { LOGE("'fns' object not set"); } DUMP("setScene - %d functions\n", id); } void StyleContext::setFeature(const Feature& _feature) { m_feature = &_feature; for (auto& item : _feature.props.items()) { addAccessor(item.key); } } void StyleContext::setGlobalZoom(float _zoom) { static const std::string _key("$zoom"); if (_zoom != m_globalZoom) { setGlobal(_key, _zoom); } } void StyleContext::setGlobal(const std::string& _key, const Value& _val) { Value& entry = m_globals[_key]; if (entry == _val) { return; } entry = _val; if (_val.is<float>()) { duk_push_number(m_ctx, _val.get<float>()); duk_put_global_string(m_ctx, _key.c_str()); if (_key == "$zoom") { m_globalZoom = _val.get<float>(); } } else if (_val.is<std::string>()) { duk_push_string(m_ctx, _val.get<std::string>().c_str()); duk_put_global_string(m_ctx, _key.c_str()); } } const Value& StyleContext::getGlobal(const std::string& _key) const { const static Value NOT_FOUND(none_type{}); auto it = m_globals.find(_key); if (it != m_globals.end()) { return it->second; } return NOT_FOUND; } void StyleContext::clear() { m_feature = nullptr; } bool StyleContext::addFunction(const std::string& _name, const std::string& _func) { duk_push_string(m_ctx, _func.c_str()); duk_push_string(m_ctx, _name.c_str()); if (duk_pcompile(m_ctx, DUK_COMPILE_FUNCTION) != 0) { LOGE("Compile failed: %s", duk_safe_to_string(m_ctx, -1)); return false; } // Put function in global scope duk_put_global_string(m_ctx, _name.c_str()); DUMP("addFunction\n"); return true; } bool StyleContext::evalFilter(FunctionID _id) const { if (!duk_get_global_string(m_ctx, FUNC_ID)) { LOGE("EvalFilterFn - functions not initialized"); return false; } if (!duk_get_prop_index(m_ctx, -1, _id)) { LOGE("EvalFilterFn - function %d not set", _id); } if (duk_pcall(m_ctx, 0) != 0) { LOGE("EvalFilterFn: %s", duk_safe_to_string(m_ctx, -1)); } bool result = false; if (duk_is_boolean(m_ctx, -1)) { result = duk_get_boolean(m_ctx, -1); } // pop result duk_pop(m_ctx); // pop fns obj duk_pop(m_ctx); DUMP("evalFilterFn\n"); return result; } bool StyleContext::evalFilterFn(const std::string& _name) { if (!duk_get_global_string(m_ctx, _name.c_str())) { LOGE("EvalFilter %s", _name.c_str()); return false; } if (duk_pcall(m_ctx, 0) != 0) { LOGE("EvalFilterFn: %s", duk_safe_to_string(m_ctx, -1)); } bool result = false; if (duk_is_boolean(m_ctx, -1)) { result = duk_get_boolean(m_ctx, -1); } // pop result duk_pop(m_ctx); DUMP("evalFilterFn\n"); return result; } bool StyleContext::parseStyleResult(StyleParamKey _key, StyleParam::Value& _val) const { _val = none_type{}; if (duk_is_string(m_ctx, -1)) { std::string value(duk_get_string(m_ctx, -1)); _val = StyleParam::parseString(_key, value); } else if (duk_is_boolean(m_ctx, -1)) { bool value = duk_get_boolean(m_ctx, -1); switch (_key) { case StyleParamKey::visible: _val = value; break; case StyleParamKey::extrude: _val = value ? glm::vec2(NAN, NAN) : glm::vec2(0.0f, 0.0f); break; default: break; } } else if (duk_is_array(m_ctx, -1)) { duk_get_prop_string(m_ctx, -1, "length"); int len = duk_get_int(m_ctx, -1); duk_pop(m_ctx); switch (_key) { case StyleParamKey::extrude: { if (len != 2) { LOGW("Wrong array size for extrusion: '%d'.", len); break; } duk_get_prop_index(m_ctx, -1, 0); double v1 = duk_get_number(m_ctx, -1); duk_pop(m_ctx); duk_get_prop_index(m_ctx, -1, 1); double v2 = duk_get_number(m_ctx, -1); duk_pop(m_ctx); _val = glm::vec2(v1, v2); break; } case StyleParamKey::color: case StyleParamKey::outline_color: case StyleParamKey::font_fill: case StyleParamKey::font_stroke_color: { if (len < 3 || len > 4) { LOGW("Wrong array size for color: '%d'.", len); break; } duk_get_prop_index(m_ctx, -1, 0); double r = duk_get_number(m_ctx, -1); duk_pop(m_ctx); duk_get_prop_index(m_ctx, -1, 1); double g = duk_get_number(m_ctx, -1); duk_pop(m_ctx); duk_get_prop_index(m_ctx, -1, 2); double b = duk_get_number(m_ctx, -1); duk_pop(m_ctx); double a = 1.0; if (len == 4) { duk_get_prop_index(m_ctx, -1, 3); a = duk_get_number(m_ctx, -1); duk_pop(m_ctx); } _val = (((uint32_t)(255.0 * a) & 0xff) << 24) | (((uint32_t)(255.0 * r) & 0xff)<< 16) | (((uint32_t)(255.0 * g) & 0xff)<< 8) | (((uint32_t)(255.0 * b) & 0xff)); break; } default: break; } } else if (duk_is_number(m_ctx, -1)) { switch (_key) { case StyleParamKey::width: case StyleParamKey::outline_width: case StyleParamKey::font_stroke_width: { double v = duk_get_number(m_ctx, -1); _val = StyleParam::Width{static_cast<float>(v)}; break; } case StyleParamKey::order: case StyleParamKey::priority: case StyleParamKey::color: case StyleParamKey::outline_color: case StyleParamKey::font_fill: case StyleParamKey::font_stroke_color: { _val = static_cast<uint32_t>(duk_get_uint(m_ctx, -1)); break; } default: break; } } else { LOGW("Unhandled return type from Javascript function."); } duk_pop(m_ctx); DUMP("parseStyleResult\n"); return !_val.is<none_type>(); } bool StyleContext::evalStyle(FunctionID _id, StyleParamKey _key, StyleParam::Value& _val) const { if (!duk_get_global_string(m_ctx, FUNC_ID)) { LOGE("EvalFilterFn - functions array not initialized"); return false; } if (!duk_get_prop_index(m_ctx, -1, _id)) { LOGE("EvalFilterFn - function %d not set", _id); } // pop fns array duk_remove(m_ctx, -2); if (duk_pcall(m_ctx, 0) != 0) { LOGE("EvalFilterFn: %s", duk_safe_to_string(m_ctx, -1)); duk_pop(m_ctx); return false; } return parseStyleResult(_key, _val); } bool StyleContext::evalStyleFn(const std::string& name, StyleParamKey _key, StyleParam::Value& _val) { if (!duk_get_global_string(m_ctx, name.c_str())) { LOGE("EvalFilter %s", name.c_str()); return false; } if (duk_pcall(m_ctx, 0) != 0) { LOGE("EvalStyleFn: %s", duk_safe_to_string(m_ctx, -1)); duk_pop(m_ctx); return false; } return parseStyleResult(_key, _val); } void StyleContext::addAccessor(const std::string& _name) { auto it = m_accessors.find(_name); if (it != m_accessors.end()) { return; } auto entry = m_accessors.emplace(_name, Accessor{_name, this}); if (!entry.second) { return; // hmm, already added.. } Accessor& attr = (*entry.first).second; // push 'feature' obj onto stack if (!duk_get_global_string(m_ctx, "feature")) { LOGE("'feature' not in global scope"); return; } // push property name duk_push_string(m_ctx, _name.c_str()); // push getter function duk_push_c_function(m_ctx, jsPropertyGetter, 0 /*nargs*/); duk_push_pointer(m_ctx, (void*)&attr); duk_put_prop_string(m_ctx, -2, ATTR_ID); // push setter function // duk_push_c_function(m_ctx, jsPropertySetter, 1 /*nargs*/); // duk_push_pointer(m_ctx, (void*)&attr); // duk_put_prop_string(m_ctx, -2, ATTR_ID); // stack: [ feature_obj, name, getter, setter ] -> [ feature_obj.name ] duk_def_prop(m_ctx, -3, DUK_DEFPROP_HAVE_GETTER | // DUK_DEFPROP_HAVE_SETTER | // DUK_DEFPROP_WRITABLE | // DUK_DEFPROP_HAVE_ENUMERABLE | // DUK_DEFPROP_ENUMERABLE | // DUK_DEFPROP_HAVE_CONFIGURABLE | 0); // pop feature obj duk_pop(m_ctx); DUMP("addAccessor\n"); } duk_ret_t StyleContext::jsPropertyGetter(duk_context *_ctx) { // Storing state for a Duktape/C function: // http://duktape.org/guide.html#programming.9 duk_push_current_function(_ctx); duk_get_prop_string(_ctx, -1, ATTR_ID); auto* attr = static_cast<const Accessor*> (duk_to_pointer(_ctx, -1)); if (!attr || !attr->ctx || !attr->ctx->m_feature) { LOGE("Error: no context set %p %p", attr, attr ? attr->ctx : nullptr); duk_pop(_ctx); return 0; } auto it = attr->ctx->m_feature->props.get(attr->key); if (it.is<std::string>()) { duk_push_string(_ctx, it.get<std::string>().c_str()); } else if (it.is<float>()) { duk_push_number(_ctx, it.get<float>()); } else { duk_push_undefined(_ctx); } return 1; } duk_ret_t StyleContext::jsPropertySetter(duk_context *_ctx) { return 0; } } <commit_msg>fix: stroke width is still just a float<commit_after>#include "styleContext.h" #include "platform.h" #include "builders.h" #include "scene/scene.h" #define DUMP(...) //do { logMsg(__VA_ARGS__); duk_dump_context_stderr(m_ctx); } while(0) namespace Tangram { const static char DATA_ID[] = "\xff""\xff""data"; const static char ATTR_ID[] = "\xff""\xff""attr"; const static char FUNC_ID[] = "\xff""\xff""fns"; StyleContext::StyleContext() { m_ctx = duk_create_heap_default(); // add empty feature_object duk_push_object(m_ctx); // assign instance to feature_object duk_push_pointer(m_ctx, this); if (!duk_put_prop_string(m_ctx, -2, DATA_ID)) { LOGE("Ctx not assigned"); } // put object in global scope if (!duk_put_global_string(m_ctx, "feature")) { LOGE("Feature not assigned"); } DUMP("init\n"); } StyleContext::~StyleContext() { duk_destroy_heap(m_ctx); } void StyleContext::initFunctions(const Scene& _scene) { if (_scene.id == m_sceneId) { return; } m_sceneId = _scene.id; auto arr_idx = duk_push_array(m_ctx); int id = 0; for (auto& function : _scene.functions()) { LOGD("compile '%s'", function.c_str()); duk_push_string(m_ctx, function.c_str()); duk_push_string(m_ctx, ""); if (duk_pcompile(m_ctx, DUK_COMPILE_FUNCTION) == 0) { duk_put_prop_index(m_ctx, arr_idx, id); } else { LOGE("Compile failed: %s", duk_safe_to_string(m_ctx, -1)); duk_pop(m_ctx); } id++; } if (!duk_put_global_string(m_ctx, FUNC_ID)) { LOGE("'fns' object not set"); } DUMP("setScene - %d functions\n", id); } void StyleContext::setFeature(const Feature& _feature) { m_feature = &_feature; for (auto& item : _feature.props.items()) { addAccessor(item.key); } } void StyleContext::setGlobalZoom(float _zoom) { static const std::string _key("$zoom"); if (_zoom != m_globalZoom) { setGlobal(_key, _zoom); } } void StyleContext::setGlobal(const std::string& _key, const Value& _val) { Value& entry = m_globals[_key]; if (entry == _val) { return; } entry = _val; if (_val.is<float>()) { duk_push_number(m_ctx, _val.get<float>()); duk_put_global_string(m_ctx, _key.c_str()); if (_key == "$zoom") { m_globalZoom = _val.get<float>(); } } else if (_val.is<std::string>()) { duk_push_string(m_ctx, _val.get<std::string>().c_str()); duk_put_global_string(m_ctx, _key.c_str()); } } const Value& StyleContext::getGlobal(const std::string& _key) const { const static Value NOT_FOUND(none_type{}); auto it = m_globals.find(_key); if (it != m_globals.end()) { return it->second; } return NOT_FOUND; } void StyleContext::clear() { m_feature = nullptr; } bool StyleContext::addFunction(const std::string& _name, const std::string& _func) { duk_push_string(m_ctx, _func.c_str()); duk_push_string(m_ctx, _name.c_str()); if (duk_pcompile(m_ctx, DUK_COMPILE_FUNCTION) != 0) { LOGE("Compile failed: %s", duk_safe_to_string(m_ctx, -1)); return false; } // Put function in global scope duk_put_global_string(m_ctx, _name.c_str()); DUMP("addFunction\n"); return true; } bool StyleContext::evalFilter(FunctionID _id) const { if (!duk_get_global_string(m_ctx, FUNC_ID)) { LOGE("EvalFilterFn - functions not initialized"); return false; } if (!duk_get_prop_index(m_ctx, -1, _id)) { LOGE("EvalFilterFn - function %d not set", _id); } if (duk_pcall(m_ctx, 0) != 0) { LOGE("EvalFilterFn: %s", duk_safe_to_string(m_ctx, -1)); } bool result = false; if (duk_is_boolean(m_ctx, -1)) { result = duk_get_boolean(m_ctx, -1); } // pop result duk_pop(m_ctx); // pop fns obj duk_pop(m_ctx); DUMP("evalFilterFn\n"); return result; } bool StyleContext::evalFilterFn(const std::string& _name) { if (!duk_get_global_string(m_ctx, _name.c_str())) { LOGE("EvalFilter %s", _name.c_str()); return false; } if (duk_pcall(m_ctx, 0) != 0) { LOGE("EvalFilterFn: %s", duk_safe_to_string(m_ctx, -1)); } bool result = false; if (duk_is_boolean(m_ctx, -1)) { result = duk_get_boolean(m_ctx, -1); } // pop result duk_pop(m_ctx); DUMP("evalFilterFn\n"); return result; } bool StyleContext::parseStyleResult(StyleParamKey _key, StyleParam::Value& _val) const { _val = none_type{}; if (duk_is_string(m_ctx, -1)) { std::string value(duk_get_string(m_ctx, -1)); _val = StyleParam::parseString(_key, value); } else if (duk_is_boolean(m_ctx, -1)) { bool value = duk_get_boolean(m_ctx, -1); switch (_key) { case StyleParamKey::visible: _val = value; break; case StyleParamKey::extrude: _val = value ? glm::vec2(NAN, NAN) : glm::vec2(0.0f, 0.0f); break; default: break; } } else if (duk_is_array(m_ctx, -1)) { duk_get_prop_string(m_ctx, -1, "length"); int len = duk_get_int(m_ctx, -1); duk_pop(m_ctx); switch (_key) { case StyleParamKey::extrude: { if (len != 2) { LOGW("Wrong array size for extrusion: '%d'.", len); break; } duk_get_prop_index(m_ctx, -1, 0); double v1 = duk_get_number(m_ctx, -1); duk_pop(m_ctx); duk_get_prop_index(m_ctx, -1, 1); double v2 = duk_get_number(m_ctx, -1); duk_pop(m_ctx); _val = glm::vec2(v1, v2); break; } case StyleParamKey::color: case StyleParamKey::outline_color: case StyleParamKey::font_fill: case StyleParamKey::font_stroke_color: { if (len < 3 || len > 4) { LOGW("Wrong array size for color: '%d'.", len); break; } duk_get_prop_index(m_ctx, -1, 0); double r = duk_get_number(m_ctx, -1); duk_pop(m_ctx); duk_get_prop_index(m_ctx, -1, 1); double g = duk_get_number(m_ctx, -1); duk_pop(m_ctx); duk_get_prop_index(m_ctx, -1, 2); double b = duk_get_number(m_ctx, -1); duk_pop(m_ctx); double a = 1.0; if (len == 4) { duk_get_prop_index(m_ctx, -1, 3); a = duk_get_number(m_ctx, -1); duk_pop(m_ctx); } _val = (((uint32_t)(255.0 * a) & 0xff) << 24) | (((uint32_t)(255.0 * r) & 0xff)<< 16) | (((uint32_t)(255.0 * g) & 0xff)<< 8) | (((uint32_t)(255.0 * b) & 0xff)); break; } default: break; } } else if (duk_is_number(m_ctx, -1)) { switch (_key) { case StyleParamKey::width: case StyleParamKey::outline_width: { // TODO more efficient way to return pixels. // atm this only works by return value as string double v = duk_get_number(m_ctx, -1); _val = StyleParam::Width{static_cast<float>(v)}; break; } case StyleParamKey::font_stroke_width: { double v = duk_get_number(m_ctx, -1); _val = static_cast<float>(v); break; } case StyleParamKey::order: case StyleParamKey::priority: case StyleParamKey::color: case StyleParamKey::outline_color: case StyleParamKey::font_fill: case StyleParamKey::font_stroke_color: { _val = static_cast<uint32_t>(duk_get_uint(m_ctx, -1)); break; } default: break; } } else { LOGW("Unhandled return type from Javascript function."); } duk_pop(m_ctx); DUMP("parseStyleResult\n"); return !_val.is<none_type>(); } bool StyleContext::evalStyle(FunctionID _id, StyleParamKey _key, StyleParam::Value& _val) const { if (!duk_get_global_string(m_ctx, FUNC_ID)) { LOGE("EvalFilterFn - functions array not initialized"); return false; } if (!duk_get_prop_index(m_ctx, -1, _id)) { LOGE("EvalFilterFn - function %d not set", _id); } // pop fns array duk_remove(m_ctx, -2); if (duk_pcall(m_ctx, 0) != 0) { LOGE("EvalFilterFn: %s", duk_safe_to_string(m_ctx, -1)); duk_pop(m_ctx); return false; } return parseStyleResult(_key, _val); } bool StyleContext::evalStyleFn(const std::string& name, StyleParamKey _key, StyleParam::Value& _val) { if (!duk_get_global_string(m_ctx, name.c_str())) { LOGE("EvalFilter %s", name.c_str()); return false; } if (duk_pcall(m_ctx, 0) != 0) { LOGE("EvalStyleFn: %s", duk_safe_to_string(m_ctx, -1)); duk_pop(m_ctx); return false; } return parseStyleResult(_key, _val); } void StyleContext::addAccessor(const std::string& _name) { auto it = m_accessors.find(_name); if (it != m_accessors.end()) { return; } auto entry = m_accessors.emplace(_name, Accessor{_name, this}); if (!entry.second) { return; // hmm, already added.. } Accessor& attr = (*entry.first).second; // push 'feature' obj onto stack if (!duk_get_global_string(m_ctx, "feature")) { LOGE("'feature' not in global scope"); return; } // push property name duk_push_string(m_ctx, _name.c_str()); // push getter function duk_push_c_function(m_ctx, jsPropertyGetter, 0 /*nargs*/); duk_push_pointer(m_ctx, (void*)&attr); duk_put_prop_string(m_ctx, -2, ATTR_ID); // push setter function // duk_push_c_function(m_ctx, jsPropertySetter, 1 /*nargs*/); // duk_push_pointer(m_ctx, (void*)&attr); // duk_put_prop_string(m_ctx, -2, ATTR_ID); // stack: [ feature_obj, name, getter, setter ] -> [ feature_obj.name ] duk_def_prop(m_ctx, -3, DUK_DEFPROP_HAVE_GETTER | // DUK_DEFPROP_HAVE_SETTER | // DUK_DEFPROP_WRITABLE | // DUK_DEFPROP_HAVE_ENUMERABLE | // DUK_DEFPROP_ENUMERABLE | // DUK_DEFPROP_HAVE_CONFIGURABLE | 0); // pop feature obj duk_pop(m_ctx); DUMP("addAccessor\n"); } duk_ret_t StyleContext::jsPropertyGetter(duk_context *_ctx) { // Storing state for a Duktape/C function: // http://duktape.org/guide.html#programming.9 duk_push_current_function(_ctx); duk_get_prop_string(_ctx, -1, ATTR_ID); auto* attr = static_cast<const Accessor*> (duk_to_pointer(_ctx, -1)); if (!attr || !attr->ctx || !attr->ctx->m_feature) { LOGE("Error: no context set %p %p", attr, attr ? attr->ctx : nullptr); duk_pop(_ctx); return 0; } auto it = attr->ctx->m_feature->props.get(attr->key); if (it.is<std::string>()) { duk_push_string(_ctx, it.get<std::string>().c_str()); } else if (it.is<float>()) { duk_push_number(_ctx, it.get<float>()); } else { duk_push_undefined(_ctx); } return 1; } duk_ret_t StyleContext::jsPropertySetter(duk_context *_ctx) { return 0; } } <|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // This file implements logic for lowering MHLO general dot to a regular dot. #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringSwitch.h" #include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h" #include "mlir-hlo/Dialect/mhlo/transforms/passes.h" #include "mlir-hlo/Dialect/mhlo/transforms/rewriters.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/Function.h" #include "mlir/IR/Location.h" #include "mlir/IR/Operation.h" #include "mlir/IR/PatternMatch.h" #include "mlir/IR/StandardTypes.h" #include "mlir/IR/TypeUtilities.h" #include "mlir/Pass/Pass.h" using mlir::DenseIntElementsAttr; using mlir::ElementsAttr; using mlir::failure; using mlir::FunctionPass; using mlir::LogicalResult; using mlir::MLIRContext; using mlir::OpRewritePattern; using mlir::OwningRewritePatternList; using mlir::PassRegistration; using mlir::PassWrapper; using mlir::PatternRewriter; using mlir::RankedTensorType; using mlir::success; using mlir::Value; namespace { Value TransposeReshape(Value arg, mlir::Location loc, llvm::ArrayRef<int64_t> left_dims, llvm::ArrayRef<int64_t> right_dims, llvm::ArrayRef<int64_t> arg_shape, PatternRewriter *rewriter) { auto element_type = mlir::getElementTypeOrSelf(arg.getType()); int64_t left_size = 1; for (auto dim : left_dims) { left_size *= arg_shape[dim]; } int64_t right_size = 1; for (auto dim : right_dims) { right_size *= arg_shape[dim]; } // Generate the transpose permutation attribute. llvm::SmallVector<int64_t, 5> transpose_permutation(left_dims.begin(), left_dims.end()); transpose_permutation.append(right_dims.begin(), right_dims.end()); mlir::TensorType transpose_permutation_type = RankedTensorType::get( {static_cast<int64_t>(transpose_permutation.size())}, rewriter->getIntegerType(64)); auto transpose_permutation_attr = DenseIntElementsAttr::get(transpose_permutation_type, llvm::makeArrayRef(transpose_permutation)) .cast<DenseIntElementsAttr>(); // Compute the resulting shape. llvm::SmallVector<int64_t, 5> transposed_shape; for (auto val : transpose_permutation) { transposed_shape.push_back(arg_shape[val]); } auto transpose_type = RankedTensorType::get(transposed_shape, element_type); auto transpose_result = rewriter->create<mlir::mhlo::TransposeOp>( loc, transpose_type, arg, transpose_permutation_attr); // Return the final result. auto reshaped_type = RankedTensorType::get({left_size, right_size}, element_type); return rewriter->create<mlir::mhlo::ReshapeOp>(loc, reshaped_type, transpose_result); } Value ProcessDotArg(Value arg, mlir::Location loc, ElementsAttr contract_dims_attr, bool outer_dims_first, PatternRewriter *rewriter) { auto shape = arg.getType().cast<mlir::ShapedType>().getShape(); llvm::SmallVector<bool, 5> is_outer_dim; is_outer_dim.resize(shape.size(), true); // Compute the contract dimension ordering. llvm::SmallVector<int64_t, 5> contract_dims; for (auto dim : contract_dims_attr.getValues<int64_t>()) { contract_dims.push_back(dim); is_outer_dim[dim] = false; } // Compute the outer dimension orderings. llvm::SmallVector<int64_t, 5> outer_dims; for (auto it : llvm::enumerate(is_outer_dim)) { if (it.value()) { outer_dims.push_back(it.index()); } } if (outer_dims_first) { return TransposeReshape(arg, loc, outer_dims, contract_dims, shape, rewriter); } return TransposeReshape(arg, loc, contract_dims, outer_dims, shape, rewriter); } struct GeneralDotConvert : public OpRewritePattern<mlir::mhlo::DotGeneralOp> { // Attempts to lower a General Dot operator to a standard Dot operator. // General dots include batching dimensions and can have collapsing // dimensions along any axis. Inserting correctly arrange transpose and // reshape operators organizes the tensors and allows the General Dot to be // replaced with the standard Dot operator. // // Note: This requires an empty list of batch dimensions. explicit GeneralDotConvert(MLIRContext *context) : OpRewritePattern(context) {} LogicalResult matchAndRewrite(mlir::mhlo::DotGeneralOp op, PatternRewriter &rewriter) const override { auto dot_element_type = mlir::getElementTypeOrSelf(op); auto dot_numbers = op.dot_dimension_numbers(); if (dot_numbers.lhs_batching_dimensions().getNumElements() != 0 || dot_numbers.rhs_batching_dimensions().getNumElements() != 0) { return failure(); } auto lhs = ProcessDotArg(op.lhs(), op.getLoc(), dot_numbers.lhs_contracting_dimensions(), /*outer_dims_first=*/true, &rewriter); auto rhs = ProcessDotArg(op.rhs(), op.getLoc(), dot_numbers.rhs_contracting_dimensions(), /*outer_dims_first=*/false, &rewriter); // Dot resulting shape. auto lhs_shape = lhs.getType().cast<mlir::ShapedType>().getShape(); auto rhs_shape = rhs.getType().cast<mlir::ShapedType>().getShape(); auto new_dot_type = RankedTensorType::get({lhs_shape[0], rhs_shape[1]}, dot_element_type); auto new_dot_op = rewriter.create<mlir::mhlo::DotOp>( op.getLoc(), new_dot_type, lhs, rhs, *(op.precision_config())); rewriter.replaceOpWithNewOp<mlir::mhlo::ReshapeOp>(op, op.getType(), new_dot_op); return success(); } }; struct LegalizeGeneralDotPass : public PassWrapper<LegalizeGeneralDotPass, FunctionPass> { /// Lower all general dots that can be represented as a non-batched matmul. void runOnFunction() override { OwningRewritePatternList patterns; mlir::mhlo::PopulateGeneralDotOpLoweringPatterns(&patterns, &getContext()); applyPatternsAndFoldGreedily(getFunction(), patterns); } }; } // namespace void mlir::mhlo::PopulateGeneralDotOpLoweringPatterns( OwningRewritePatternList *patterns, MLIRContext *ctx) { patterns->insert<GeneralDotConvert>(ctx); } std::unique_ptr<::mlir::Pass> mlir::mhlo::createLegalizeGeneralDotPass() { return std::make_unique<LegalizeGeneralDotPass>(); } <commit_msg>Only apply GeneralDotOpLoweringPatterns for static shaped inputs<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // This file implements logic for lowering MHLO general dot to a regular dot. #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringSwitch.h" #include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h" #include "mlir-hlo/Dialect/mhlo/transforms/passes.h" #include "mlir-hlo/Dialect/mhlo/transforms/rewriters.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/Function.h" #include "mlir/IR/Location.h" #include "mlir/IR/Operation.h" #include "mlir/IR/PatternMatch.h" #include "mlir/IR/StandardTypes.h" #include "mlir/IR/TypeUtilities.h" #include "mlir/Pass/Pass.h" using mlir::DenseIntElementsAttr; using mlir::ElementsAttr; using mlir::failure; using mlir::FunctionPass; using mlir::LogicalResult; using mlir::MLIRContext; using mlir::OpRewritePattern; using mlir::OwningRewritePatternList; using mlir::PassRegistration; using mlir::PassWrapper; using mlir::PatternRewriter; using mlir::RankedTensorType; using mlir::success; using mlir::Value; namespace { Value TransposeReshape(Value arg, mlir::Location loc, llvm::ArrayRef<int64_t> left_dims, llvm::ArrayRef<int64_t> right_dims, llvm::ArrayRef<int64_t> arg_shape, PatternRewriter *rewriter) { auto element_type = mlir::getElementTypeOrSelf(arg.getType()); int64_t left_size = 1; for (auto dim : left_dims) { left_size *= arg_shape[dim]; } int64_t right_size = 1; for (auto dim : right_dims) { right_size *= arg_shape[dim]; } // Generate the transpose permutation attribute. llvm::SmallVector<int64_t, 5> transpose_permutation(left_dims.begin(), left_dims.end()); transpose_permutation.append(right_dims.begin(), right_dims.end()); mlir::TensorType transpose_permutation_type = RankedTensorType::get( {static_cast<int64_t>(transpose_permutation.size())}, rewriter->getIntegerType(64)); auto transpose_permutation_attr = DenseIntElementsAttr::get(transpose_permutation_type, llvm::makeArrayRef(transpose_permutation)) .cast<DenseIntElementsAttr>(); // Compute the resulting shape. llvm::SmallVector<int64_t, 5> transposed_shape; for (auto val : transpose_permutation) { transposed_shape.push_back(arg_shape[val]); } auto transpose_type = RankedTensorType::get(transposed_shape, element_type); auto transpose_result = rewriter->create<mlir::mhlo::TransposeOp>( loc, transpose_type, arg, transpose_permutation_attr); // Return the final result. auto reshaped_type = RankedTensorType::get({left_size, right_size}, element_type); return rewriter->create<mlir::mhlo::ReshapeOp>(loc, reshaped_type, transpose_result); } Value ProcessDotArg(Value arg, mlir::Location loc, ElementsAttr contract_dims_attr, bool outer_dims_first, PatternRewriter *rewriter) { auto shape = arg.getType().cast<mlir::ShapedType>().getShape(); llvm::SmallVector<bool, 5> is_outer_dim; is_outer_dim.resize(shape.size(), true); // Compute the contract dimension ordering. llvm::SmallVector<int64_t, 5> contract_dims; for (auto dim : contract_dims_attr.getValues<int64_t>()) { contract_dims.push_back(dim); is_outer_dim[dim] = false; } // Compute the outer dimension orderings. llvm::SmallVector<int64_t, 5> outer_dims; for (auto it : llvm::enumerate(is_outer_dim)) { if (it.value()) { outer_dims.push_back(it.index()); } } if (outer_dims_first) { return TransposeReshape(arg, loc, outer_dims, contract_dims, shape, rewriter); } return TransposeReshape(arg, loc, contract_dims, outer_dims, shape, rewriter); } struct GeneralDotConvert : public OpRewritePattern<mlir::mhlo::DotGeneralOp> { // Attempts to lower a General Dot operator to a standard Dot operator. // General dots include batching dimensions and can have collapsing // dimensions along any axis. Inserting correctly arrange transpose and // reshape operators organizes the tensors and allows the General Dot to be // replaced with the standard Dot operator. // // Note: This requires an empty list of batch dimensions. explicit GeneralDotConvert(MLIRContext *context) : OpRewritePattern(context) {} LogicalResult matchAndRewrite(mlir::mhlo::DotGeneralOp op, PatternRewriter &rewriter) const override { auto dot_element_type = mlir::getElementTypeOrSelf(op); auto dot_numbers = op.dot_dimension_numbers(); if (dot_numbers.lhs_batching_dimensions().getNumElements() != 0 || dot_numbers.rhs_batching_dimensions().getNumElements() != 0) { return failure(); } auto lhs = ProcessDotArg(op.lhs(), op.getLoc(), dot_numbers.lhs_contracting_dimensions(), /*outer_dims_first=*/true, &rewriter); auto rhs = ProcessDotArg(op.rhs(), op.getLoc(), dot_numbers.rhs_contracting_dimensions(), /*outer_dims_first=*/false, &rewriter); // Accept only static shaped types. auto lhs_shape_type = lhs.getType().dyn_cast_or_null<mlir::ShapedType>(); auto rhs_shape_type = rhs.getType().dyn_cast_or_null<mlir::ShapedType>(); if (!lhs_shape_type || !rhs_shape_type) return failure(); if (!lhs_shape_type.hasStaticShape() || !rhs_shape_type.hasStaticShape()) return failure(); // Dot resulting shape. auto lhs_shape = lhs_shape_type.getShape(); auto rhs_shape = rhs_shape_type.getShape(); auto new_dot_type = RankedTensorType::get({lhs_shape[0], rhs_shape[1]}, dot_element_type); auto new_dot_op = rewriter.create<mlir::mhlo::DotOp>( op.getLoc(), new_dot_type, lhs, rhs, *(op.precision_config())); rewriter.replaceOpWithNewOp<mlir::mhlo::ReshapeOp>(op, op.getType(), new_dot_op); return success(); } }; struct LegalizeGeneralDotPass : public PassWrapper<LegalizeGeneralDotPass, FunctionPass> { /// Lower all general dots that can be represented as a non-batched matmul. void runOnFunction() override { OwningRewritePatternList patterns; mlir::mhlo::PopulateGeneralDotOpLoweringPatterns(&patterns, &getContext()); applyPatternsAndFoldGreedily(getFunction(), patterns); } }; } // namespace void mlir::mhlo::PopulateGeneralDotOpLoweringPatterns( OwningRewritePatternList *patterns, MLIRContext *ctx) { patterns->insert<GeneralDotConvert>(ctx); } std::unique_ptr<::mlir::Pass> mlir::mhlo::createLegalizeGeneralDotPass() { return std::make_unique<LegalizeGeneralDotPass>(); } <|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 "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" class DownloadsApiTest : public ExtensionApiTest { public: void SetUpCommandLine(CommandLine* command_line) { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis); } }; // Disabled: see http://crbug.com/101170 IN_PROC_BROWSER_TEST_F(DownloadsApiTest, DISABLED_Downloads) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("downloads")) << message_; } <commit_msg>DownloadsApiTest uses a ScopedTempDir to clean up after itself. BUG=101162<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 "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" class DownloadsApiTest : public ExtensionApiTest { public: void SetUpCommandLine(CommandLine* command_line) { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis); } void SetUpTempDownloadsDir() { ASSERT_TRUE(tmpdir.CreateUniqueTempDir()); browser()->profile()->GetPrefs()->SetFilePath( prefs::kDownloadDefaultDirectory, tmpdir.path()); } private: ScopedTempDir tmpdir; }; IN_PROC_BROWSER_TEST_F(DownloadsApiTest, Downloads) { SetUpTempDownloadsDir(); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("downloads")) << message_; } <|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <algorithm> #include <iomanip> #include <boost/bind.hpp> #include "libtorrent/kademlia/node_id.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/assert.hpp" using boost::bind; namespace libtorrent { namespace dht { // returns the distance between the two nodes // using the kademlia XOR-metric node_id distance(node_id const& n1, node_id const& n2) { node_id ret; node_id::iterator k = ret.begin(); for (node_id::const_iterator i = n1.begin(), j = n2.begin() , end(n1.end()); i != end; ++i, ++j, ++k) { *k = *i ^ *j; } return ret; } // returns true if: distance(n1, ref) < distance(n2, ref) bool compare_ref(node_id const& n1, node_id const& n2, node_id const& ref) { for (node_id::const_iterator i = n1.begin(), j = n2.begin() , k = ref.begin(), end(n1.end()); i != end; ++i, ++j, ++k) { boost::uint8_t lhs = (*i ^ *k); boost::uint8_t rhs = (*j ^ *k); if (lhs < rhs) return true; if (lhs > rhs) return false; } return false; } // returns n in: 2^n <= distance(n1, n2) < 2^(n+1) // useful for finding out which bucket a node belongs to int distance_exp(node_id const& n1, node_id const& n2) { int byte = node_id::size - 1; for (node_id::const_iterator i = n1.begin(), j = n2.begin() , end(n1.end()); i != end; ++i, ++j, --byte) { TORRENT_ASSERT(byte >= 0); boost::uint8_t t = *i ^ *j; if (t == 0) continue; // we have found the first non-zero byte // return the bit-number of the first bit // that differs int bit = byte * 8; for (int b = 7; b >= 0; --b) if (t >= (1 << b)) return bit + b; return bit; } return 0; } struct static_ { static_() { std::srand(std::time(0)); } } static__; node_id generate_id() { char random[20]; #ifdef _MSC_VER std::generate(random, random + 20, &rand); #else std::generate(random, random + 20, &std::rand); #endif hasher h; h.update(random, 20); return h.final(); } } } // namespace libtorrent::dht <commit_msg>added missing include statement<commit_after>/* Copyright (c) 2006, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <algorithm> #include <iomanip> #include <ctime> #include <boost/bind.hpp> #include "libtorrent/kademlia/node_id.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/assert.hpp" using boost::bind; namespace libtorrent { namespace dht { // returns the distance between the two nodes // using the kademlia XOR-metric node_id distance(node_id const& n1, node_id const& n2) { node_id ret; node_id::iterator k = ret.begin(); for (node_id::const_iterator i = n1.begin(), j = n2.begin() , end(n1.end()); i != end; ++i, ++j, ++k) { *k = *i ^ *j; } return ret; } // returns true if: distance(n1, ref) < distance(n2, ref) bool compare_ref(node_id const& n1, node_id const& n2, node_id const& ref) { for (node_id::const_iterator i = n1.begin(), j = n2.begin() , k = ref.begin(), end(n1.end()); i != end; ++i, ++j, ++k) { boost::uint8_t lhs = (*i ^ *k); boost::uint8_t rhs = (*j ^ *k); if (lhs < rhs) return true; if (lhs > rhs) return false; } return false; } // returns n in: 2^n <= distance(n1, n2) < 2^(n+1) // useful for finding out which bucket a node belongs to int distance_exp(node_id const& n1, node_id const& n2) { int byte = node_id::size - 1; for (node_id::const_iterator i = n1.begin(), j = n2.begin() , end(n1.end()); i != end; ++i, ++j, --byte) { TORRENT_ASSERT(byte >= 0); boost::uint8_t t = *i ^ *j; if (t == 0) continue; // we have found the first non-zero byte // return the bit-number of the first bit // that differs int bit = byte * 8; for (int b = 7; b >= 0; --b) if (t >= (1 << b)) return bit + b; return bit; } return 0; } struct static_ { static_() { std::srand(std::time(0)); } } static__; node_id generate_id() { char random[20]; #ifdef _MSC_VER std::generate(random, random + 20, &rand); #else std::generate(random, random + 20, &std::rand); #endif hasher h; h.update(random, 20); return h.final(); } } } // namespace libtorrent::dht <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/browser.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/extensions/browser_action_test_util.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/user_script_master.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); // Loads a simple extension which attempts to change the title of every page // that loads to "modified". ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("incognito").AppendASCII("content_scripts"))); // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); Browser* otr_browser = BrowserList::FindBrowserWithType( browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL, false); TabContents* tab = otr_browser->GetSelectedTabContents(); // Verify the script didn't run. bool result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( tab->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'Unmodified')", &result); EXPECT_TRUE(result); } IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); // Load a dummy extension. This just tests that we don't regress a // crash fix when multiple incognito- and non-incognito-enabled extensions // are mixed. ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("content_scripts").AppendASCII("all_frames"))); // Loads a simple extension which attempts to change the title of every page // that loads to "modified". ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII("api_test") .AppendASCII("incognito").AppendASCII("content_scripts"))); // Dummy extension #2. ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("content_scripts").AppendASCII("isolated_world1"))); // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); Browser* otr_browser = BrowserList::FindBrowserWithType( browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL, false); TabContents* tab = otr_browser->GetSelectedTabContents(); // Verify the script ran. bool result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( tab->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'modified')", &result); EXPECT_TRUE(result); } // Tests that the APIs in an incognito-enabled extension work properly. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ResultCatcher catcher; // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_ .AppendASCII("incognito").AppendASCII("apis"))); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } // Tests that the APIs in an incognito-enabled split-mode extension work // properly. #if defined(OS_CHROMEOS) || defined(OS_LINUX) // Hanging on ChromeOS and linux: http://crbug.com/53991 #define MAYBE_IncognitoSplitMode DISABLED_IncognitoSplitMode #else #define MAYBE_IncognitoSplitMode IncognitoSplitMode #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_IncognitoSplitMode) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); // We need 2 ResultCatchers because we'll be running the same test in both // regular and incognito mode. ResultCatcher catcher; catcher.RestrictToProfile(browser()->profile()); ResultCatcher catcher_incognito; catcher_incognito.RestrictToProfile( browser()->profile()->GetOffTheRecordProfile()); // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_ .AppendASCII("incognito").AppendASCII("split"))); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message(); } // Tests that the APIs in an incognito-disabled extension don't see incognito // events or callbacks. // Hangy, http://crbug.com/53869. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoDisabled) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ResultCatcher catcher; // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); ASSERT_TRUE(LoadExtension(test_data_dir_ .AppendASCII("incognito").AppendASCII("apis_disabled"))); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } // Test that opening a popup from an incognito browser window works properly. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ResultCatcher catcher; ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_ .AppendASCII("incognito").AppendASCII("popup"))); // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); Browser* incognito_browser = BrowserList::FindBrowserWithType( browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL, false); // Simulate the incognito's browser action being clicked. BrowserActionTestUtil(incognito_browser).Press(0); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } <commit_msg>Disable IncognitoSplitMode everywhere, it's failing and hangy. Working on a fix.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/browser.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/extensions/browser_action_test_util.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/user_script_master.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); // Loads a simple extension which attempts to change the title of every page // that loads to "modified". ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("incognito").AppendASCII("content_scripts"))); // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); Browser* otr_browser = BrowserList::FindBrowserWithType( browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL, false); TabContents* tab = otr_browser->GetSelectedTabContents(); // Verify the script didn't run. bool result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( tab->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'Unmodified')", &result); EXPECT_TRUE(result); } IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); // Load a dummy extension. This just tests that we don't regress a // crash fix when multiple incognito- and non-incognito-enabled extensions // are mixed. ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("content_scripts").AppendASCII("all_frames"))); // Loads a simple extension which attempts to change the title of every page // that loads to "modified". ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII("api_test") .AppendASCII("incognito").AppendASCII("content_scripts"))); // Dummy extension #2. ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test") .AppendASCII("content_scripts").AppendASCII("isolated_world1"))); // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); Browser* otr_browser = BrowserList::FindBrowserWithType( browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL, false); TabContents* tab = otr_browser->GetSelectedTabContents(); // Verify the script ran. bool result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( tab->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'modified')", &result); EXPECT_TRUE(result); } // Tests that the APIs in an incognito-enabled extension work properly. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ResultCatcher catcher; // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_ .AppendASCII("incognito").AppendASCII("apis"))); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } // Tests that the APIs in an incognito-enabled split-mode extension work // properly. // Hanging/failing: http://crbug.com/53991 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoSplitMode) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); // We need 2 ResultCatchers because we'll be running the same test in both // regular and incognito mode. ResultCatcher catcher; catcher.RestrictToProfile(browser()->profile()); ResultCatcher catcher_incognito; catcher_incognito.RestrictToProfile( browser()->profile()->GetOffTheRecordProfile()); // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_ .AppendASCII("incognito").AppendASCII("split"))); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message(); } // Tests that the APIs in an incognito-disabled extension don't see incognito // events or callbacks. // Hangy, http://crbug.com/53869. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoDisabled) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ResultCatcher catcher; // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); ASSERT_TRUE(LoadExtension(test_data_dir_ .AppendASCII("incognito").AppendASCII("apis_disabled"))); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } // Test that opening a popup from an incognito browser window works properly. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) { host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ResultCatcher catcher; ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_ .AppendASCII("incognito").AppendASCII("popup"))); // Open incognito window and navigate to test page. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL("http://www.example.com:1337/files/extensions/test_file.html")); Browser* incognito_browser = BrowserList::FindBrowserWithType( browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL, false); // Simulate the incognito's browser action being clicked. BrowserActionTestUtil(incognito_browser).Press(0); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_message_service.h" #include "chrome/common/render_messages.h" #include "chrome/renderer/extensions/event_bindings.h" #include "chrome/renderer/extensions/renderer_extension_bindings.h" #include "chrome/test/render_view_test.h" #include "testing/gtest/include/gtest/gtest.h" static void DispatchOnConnect(int source_port_id, const std::string& name, const std::string& tab_json) { ListValue args; args.Set(0, Value::CreateIntegerValue(source_port_id)); args.Set(1, Value::CreateStringValue(name)); args.Set(2, Value::CreateStringValue(tab_json)); args.Set(3, Value::CreateStringValue("")); // extension ID is empty for tests args.Set(4, Value::CreateStringValue("")); // extension ID is empty for tests RendererExtensionBindings::Invoke( ExtensionMessageService::kDispatchOnConnect, args, NULL, false, GURL()); } static void DispatchOnDisconnect(int source_port_id) { ListValue args; args.Set(0, Value::CreateIntegerValue(source_port_id)); RendererExtensionBindings::Invoke( ExtensionMessageService::kDispatchOnDisconnect, args, NULL, false, GURL()); } static void DispatchOnMessage(const std::string& message, int source_port_id) { ListValue args; args.Set(0, Value::CreateStringValue(message)); args.Set(1, Value::CreateIntegerValue(source_port_id)); RendererExtensionBindings::Invoke( ExtensionMessageService::kDispatchOnMessage, args, NULL, false, GURL()); } // Tests that the bindings for opening a channel to an extension and sending // and receiving messages through that channel all works. TEST_F(RenderViewTest, DISABLED_ExtensionMessagesOpenChannel) { render_thread_.sink().ClearMessages(); LoadHTML("<body></body>"); ExecuteJavaScript( "var port = chrome.extension.connect({name:'testName'});" "port.onMessage.addListener(doOnMessage);" "port.postMessage({message: 'content ready'});" "function doOnMessage(msg, port) {" " alert('content got: ' + msg.val);" "}"); // Verify that we opened a channel and sent a message through it. const IPC::Message* open_channel_msg = render_thread_.sink().GetUniqueMessageMatching( ViewHostMsg_OpenChannelToExtension::ID); ASSERT_TRUE(open_channel_msg); void* iter = IPC::SyncMessage::GetDataIterator(open_channel_msg); ViewHostMsg_OpenChannelToExtension::SendParam open_params; ASSERT_TRUE(IPC::ReadParam(open_channel_msg, &iter, &open_params)); EXPECT_EQ("testName", open_params.d); const IPC::Message* post_msg = render_thread_.sink().GetUniqueMessageMatching( ViewHostMsg_ExtensionPostMessage::ID); ASSERT_TRUE(post_msg); ViewHostMsg_ExtensionPostMessage::Param post_params; ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params); EXPECT_EQ("{\"message\":\"content ready\"}", post_params.b); // Now simulate getting a message back from the other side. render_thread_.sink().ClearMessages(); const int kPortId = 0; DispatchOnMessage("{\"val\": 42}", kPortId); // Verify that we got it. const IPC::Message* alert_msg = render_thread_.sink().GetUniqueMessageMatching( ViewHostMsg_RunJavaScriptMessage::ID); ASSERT_TRUE(alert_msg); iter = IPC::SyncMessage::GetDataIterator(alert_msg); ViewHostMsg_RunJavaScriptMessage::SendParam alert_param; ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param)); EXPECT_EQ(L"content got: 42", alert_param.a); } // Tests that the bindings for handling a new channel connection and channel // closing all works. TEST_F(RenderViewTest, DISABLED_ExtensionMessagesOnConnect) { LoadHTML("<body></body>"); ExecuteJavaScript( "chrome.extension.onConnect.addListener(function (port) {" " port.test = 24;" " port.onMessage.addListener(doOnMessage);" " port.onDisconnect.addListener(doOnDisconnect);" " port.postMessage({message: 'onconnect from ' + port.tab.url + " " ' name ' + port.name});" "});" "function doOnMessage(msg, port) {" " alert('got: ' + msg.val);" "}" "function doOnDisconnect(port) {" " alert('disconnected: ' + port.test);" "}"); render_thread_.sink().ClearMessages(); // Simulate a new connection being opened. const int kPortId = 0; const std::string kPortName = "testName"; DispatchOnConnect(kPortId, kPortName, "{\"url\":\"foo://bar\"}"); // Verify that we handled the new connection by posting a message. const IPC::Message* post_msg = render_thread_.sink().GetUniqueMessageMatching( ViewHostMsg_ExtensionPostMessage::ID); ASSERT_TRUE(post_msg); ViewHostMsg_ExtensionPostMessage::Param post_params; ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params); std::string expected_msg = "{\"message\":\"onconnect from foo://bar name " + kPortName + "\"}"; EXPECT_EQ(expected_msg, post_params.b); // Now simulate getting a message back from the channel opener. render_thread_.sink().ClearMessages(); DispatchOnMessage("{\"val\": 42}", kPortId); // Verify that we got it. const IPC::Message* alert_msg = render_thread_.sink().GetUniqueMessageMatching( ViewHostMsg_RunJavaScriptMessage::ID); ASSERT_TRUE(alert_msg); void* iter = IPC::SyncMessage::GetDataIterator(alert_msg); ViewHostMsg_RunJavaScriptMessage::SendParam alert_param; ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param)); EXPECT_EQ(L"got: 42", alert_param.a); // Now simulate the channel closing. render_thread_.sink().ClearMessages(); DispatchOnDisconnect(kPortId); // Verify that we got it. alert_msg = render_thread_.sink().GetUniqueMessageMatching( ViewHostMsg_RunJavaScriptMessage::ID); ASSERT_TRUE(alert_msg); iter = IPC::SyncMessage::GetDataIterator(alert_msg); ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param)); EXPECT_EQ(L"disconnected: 24", alert_param.a); } <commit_msg>It seems all RenderView tests have issues. I'll try reverting last significant RenderView change and see if that helps.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_message_service.h" #include "chrome/common/render_messages.h" #include "chrome/renderer/extensions/event_bindings.h" #include "chrome/renderer/extensions/renderer_extension_bindings.h" #include "chrome/test/render_view_test.h" #include "testing/gtest/include/gtest/gtest.h" static void DispatchOnConnect(int source_port_id, const std::string& name, const std::string& tab_json) { ListValue args; args.Set(0, Value::CreateIntegerValue(source_port_id)); args.Set(1, Value::CreateStringValue(name)); args.Set(2, Value::CreateStringValue(tab_json)); args.Set(3, Value::CreateStringValue("")); // extension ID is empty for tests args.Set(4, Value::CreateStringValue("")); // extension ID is empty for tests RendererExtensionBindings::Invoke( ExtensionMessageService::kDispatchOnConnect, args, NULL, false, GURL()); } static void DispatchOnDisconnect(int source_port_id) { ListValue args; args.Set(0, Value::CreateIntegerValue(source_port_id)); RendererExtensionBindings::Invoke( ExtensionMessageService::kDispatchOnDisconnect, args, NULL, false, GURL()); } static void DispatchOnMessage(const std::string& message, int source_port_id) { ListValue args; args.Set(0, Value::CreateStringValue(message)); args.Set(1, Value::CreateIntegerValue(source_port_id)); RendererExtensionBindings::Invoke( ExtensionMessageService::kDispatchOnMessage, args, NULL, false, GURL()); } // Tests that the bindings for opening a channel to an extension and sending // and receiving messages through that channel all works. TEST_F(RenderViewTest, ExtensionMessagesOpenChannel) { render_thread_.sink().ClearMessages(); LoadHTML("<body></body>"); ExecuteJavaScript( "var port = chrome.extension.connect({name:'testName'});" "port.onMessage.addListener(doOnMessage);" "port.postMessage({message: 'content ready'});" "function doOnMessage(msg, port) {" " alert('content got: ' + msg.val);" "}"); // Verify that we opened a channel and sent a message through it. const IPC::Message* open_channel_msg = render_thread_.sink().GetUniqueMessageMatching( ViewHostMsg_OpenChannelToExtension::ID); ASSERT_TRUE(open_channel_msg); void* iter = IPC::SyncMessage::GetDataIterator(open_channel_msg); ViewHostMsg_OpenChannelToExtension::SendParam open_params; ASSERT_TRUE(IPC::ReadParam(open_channel_msg, &iter, &open_params)); EXPECT_EQ("testName", open_params.d); const IPC::Message* post_msg = render_thread_.sink().GetUniqueMessageMatching( ViewHostMsg_ExtensionPostMessage::ID); ASSERT_TRUE(post_msg); ViewHostMsg_ExtensionPostMessage::Param post_params; ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params); EXPECT_EQ("{\"message\":\"content ready\"}", post_params.b); // Now simulate getting a message back from the other side. render_thread_.sink().ClearMessages(); const int kPortId = 0; DispatchOnMessage("{\"val\": 42}", kPortId); // Verify that we got it. const IPC::Message* alert_msg = render_thread_.sink().GetUniqueMessageMatching( ViewHostMsg_RunJavaScriptMessage::ID); ASSERT_TRUE(alert_msg); iter = IPC::SyncMessage::GetDataIterator(alert_msg); ViewHostMsg_RunJavaScriptMessage::SendParam alert_param; ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param)); EXPECT_EQ(L"content got: 42", alert_param.a); } // Tests that the bindings for handling a new channel connection and channel // closing all works. TEST_F(RenderViewTest, ExtensionMessagesOnConnect) { LoadHTML("<body></body>"); ExecuteJavaScript( "chrome.extension.onConnect.addListener(function (port) {" " port.test = 24;" " port.onMessage.addListener(doOnMessage);" " port.onDisconnect.addListener(doOnDisconnect);" " port.postMessage({message: 'onconnect from ' + port.tab.url + " " ' name ' + port.name});" "});" "function doOnMessage(msg, port) {" " alert('got: ' + msg.val);" "}" "function doOnDisconnect(port) {" " alert('disconnected: ' + port.test);" "}"); render_thread_.sink().ClearMessages(); // Simulate a new connection being opened. const int kPortId = 0; const std::string kPortName = "testName"; DispatchOnConnect(kPortId, kPortName, "{\"url\":\"foo://bar\"}"); // Verify that we handled the new connection by posting a message. const IPC::Message* post_msg = render_thread_.sink().GetUniqueMessageMatching( ViewHostMsg_ExtensionPostMessage::ID); ASSERT_TRUE(post_msg); ViewHostMsg_ExtensionPostMessage::Param post_params; ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params); std::string expected_msg = "{\"message\":\"onconnect from foo://bar name " + kPortName + "\"}"; EXPECT_EQ(expected_msg, post_params.b); // Now simulate getting a message back from the channel opener. render_thread_.sink().ClearMessages(); DispatchOnMessage("{\"val\": 42}", kPortId); // Verify that we got it. const IPC::Message* alert_msg = render_thread_.sink().GetUniqueMessageMatching( ViewHostMsg_RunJavaScriptMessage::ID); ASSERT_TRUE(alert_msg); void* iter = IPC::SyncMessage::GetDataIterator(alert_msg); ViewHostMsg_RunJavaScriptMessage::SendParam alert_param; ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param)); EXPECT_EQ(L"got: 42", alert_param.a); // Now simulate the channel closing. render_thread_.sink().ClearMessages(); DispatchOnDisconnect(kPortId); // Verify that we got it. alert_msg = render_thread_.sink().GetUniqueMessageMatching( ViewHostMsg_RunJavaScriptMessage::ID); ASSERT_TRUE(alert_msg); iter = IPC::SyncMessage::GetDataIterator(alert_msg); ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param)); EXPECT_EQ(L"disconnected: 24", alert_param.a); } <|endoftext|>
<commit_before>// Copyright 2020 The Google Research 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 "test_util.h" #include <functional> #include <iostream> #include "definitions.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace automl_zero { using ::std::function; // NOLINT; using ::std::pair; // NOLINT; using ::std::unordered_set; // NOLINT; using ::testing::Pair; using ::testing::UnorderedElementsAre; IntegerT cycle_up_to_five() { static IntegerT x = 0; return x++ % 5; } TEST(IsEventuallyTest, CorrectAnswer) { EXPECT_TRUE(IsEventually( function<IntegerT()>(cycle_up_to_five), {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4})); } TEST(IsEventuallyTest, DisallowedNumber) { EXPECT_FALSE(IsEventually( function<IntegerT()>(cycle_up_to_five), {0, 1, 2, 4}, {0, 1, 2, 3, 4})); } TEST(IsEventuallyTest, MissingRequiredNumber) { EXPECT_FALSE(IsEventually( function<IntegerT()>(cycle_up_to_five), {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4, 5})); } TEST(IsEventuallyTest, NotRequiredNumber) { EXPECT_TRUE(IsEventually( function<IntegerT()>(cycle_up_to_five), {0, 1, 2, 3, 4}, {0, 1, 2, 4})); } TEST(IsEventuallyTest, MissingAllowedNumber) { EXPECT_TRUE(IsEventually( function<IntegerT()>(cycle_up_to_five), {0, 1, 2, 3, 4, 5}, {0, 1, 2, 3, 4})); } TEST(IsNeverTest, ExcludedValue) { EXPECT_FALSE(IsNever( function<IntegerT()>(cycle_up_to_five), {3}, 3.0)); } TEST(IsNeverTest, NotExcludedValue) { EXPECT_TRUE(IsNever( function<IntegerT()>(cycle_up_to_five), {6}, 3.0)); } TEST(RangeTest, WorksCorrectly) { EXPECT_THAT(Range<IntegerT>(0, 5), UnorderedElementsAre(0, 1, 2, 3, 4)); } TEST(CartesianProductTest, WorksCorrectly) { EXPECT_THAT(CartesianProduct(Range<IntegerT>(0, 3), Range<IntegerT>(3, 5)), UnorderedElementsAre(Pair(0, 3), Pair(0, 4), Pair(1, 3), Pair(1, 4), Pair(2, 3), Pair(2, 4))); } } // namespace automl_zero <commit_msg>Internal change<commit_after>// Copyright 2020 The Google Research 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 "test_util.h" #include <functional> #include <iostream> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/node_hash_set.h" #include "definitions.h" namespace automl_zero { using ::std::function; // NOLINT; using ::std::pair; // NOLINT; // NOLINT; using ::testing::Pair; using ::testing::UnorderedElementsAre; IntegerT cycle_up_to_five() { static IntegerT x = 0; return x++ % 5; } TEST(IsEventuallyTest, CorrectAnswer) { EXPECT_TRUE(IsEventually( function<IntegerT()>(cycle_up_to_five), {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4})); } TEST(IsEventuallyTest, DisallowedNumber) { EXPECT_FALSE(IsEventually( function<IntegerT()>(cycle_up_to_five), {0, 1, 2, 4}, {0, 1, 2, 3, 4})); } TEST(IsEventuallyTest, MissingRequiredNumber) { EXPECT_FALSE(IsEventually( function<IntegerT()>(cycle_up_to_five), {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4, 5})); } TEST(IsEventuallyTest, NotRequiredNumber) { EXPECT_TRUE(IsEventually( function<IntegerT()>(cycle_up_to_five), {0, 1, 2, 3, 4}, {0, 1, 2, 4})); } TEST(IsEventuallyTest, MissingAllowedNumber) { EXPECT_TRUE(IsEventually( function<IntegerT()>(cycle_up_to_five), {0, 1, 2, 3, 4, 5}, {0, 1, 2, 3, 4})); } TEST(IsNeverTest, ExcludedValue) { EXPECT_FALSE(IsNever( function<IntegerT()>(cycle_up_to_five), {3}, 3.0)); } TEST(IsNeverTest, NotExcludedValue) { EXPECT_TRUE(IsNever( function<IntegerT()>(cycle_up_to_five), {6}, 3.0)); } TEST(RangeTest, WorksCorrectly) { EXPECT_THAT(Range<IntegerT>(0, 5), UnorderedElementsAre(0, 1, 2, 3, 4)); } TEST(CartesianProductTest, WorksCorrectly) { EXPECT_THAT(CartesianProduct(Range<IntegerT>(0, 3), Range<IntegerT>(3, 5)), UnorderedElementsAre(Pair(0, 3), Pair(0, 4), Pair(1, 3), Pair(1, 4), Pair(2, 3), Pair(2, 4))); } } // namespace automl_zero <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Toolstrip) { ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_; } <commit_msg>TBR: rafaelw,leiz disable a ExtensionApiTest.Toolstrip which is flaky on linux<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" // TODO(rafaelw,erikkay) disabled due to flakiness // BUG=22668 (probably the same bug) IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Toolstrip) { ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_; } <|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 "base/command_line.h" #include "base/path_service.h" #include "base/process/launch.h" #include "base/rand_util.h" #include "base/strings/stringprintf.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/media/webrtc_browsertest_base.h" #include "chrome/browser/media/webrtc_browsertest_common.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/ui_test_utils.h" #include "chrome/test/ui/ui_test.h" #include "content/public/test/browser_test_utils.h" #include "net/test/python_utils.h" // You need this solution to run this test. The solution will download appengine // and the apprtc code for you. const char kAdviseOnGclientSolution[] = "You need to add this solution to your .gclient to run this test:\n" "{\n" " \"name\" : \"webrtc.DEPS\",\n" " \"url\" : \"svn://svn.chromium.org/chrome/trunk/deps/" "third_party/webrtc/webrtc.DEPS\",\n" "}"; const char kTitlePageOfAppEngineAdminPage[] = "Instances"; // WebRTC-AppRTC integration test. Requires a real webcam and microphone // on the running system. This test is not meant to run in the main browser // test suite since normal tester machines do not have webcams. // // This test will bring up a AppRTC instance on localhost and verify that the // call gets up when connecting to the same room from two tabs in a browser. class WebrtcApprtcBrowserTest : public WebRtcTestBase { public: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { EXPECT_FALSE(command_line->HasSwitch( switches::kUseFakeDeviceForMediaStream)); EXPECT_FALSE(command_line->HasSwitch( switches::kUseFakeUIForMediaStream)); // The video playback will not work without a GPU, so force its use here. command_line->AppendSwitch(switches::kUseGpuInTests); } protected: bool LaunchApprtcInstanceOnLocalhost() { base::FilePath appengine_dev_appserver = GetSourceDir().Append( FILE_PATH_LITERAL("../google_appengine/dev_appserver.py")); if (!base::PathExists(appengine_dev_appserver)) { LOG(ERROR) << "Missing appengine sdk at " << appengine_dev_appserver.value() << ". " << kAdviseOnGclientSolution; return false; } base::FilePath apprtc_dir = GetSourceDir().Append( FILE_PATH_LITERAL("third_party/webrtc_apprtc/apprtc")); if (!base::PathExists(apprtc_dir)) { LOG(ERROR) << "Missing AppRTC code at " << apprtc_dir.value() << ". " << kAdviseOnGclientSolution; return false; } CommandLine command_line(CommandLine::NO_PROGRAM); EXPECT_TRUE(GetPythonCommand(&command_line)); command_line.AppendArgPath(appengine_dev_appserver); command_line.AppendArgPath(apprtc_dir); command_line.AppendArg("--port=9999"); command_line.AppendArg("--admin_port=9998"); command_line.AppendArg("--skip_sdk_update_check"); LOG(INFO) << "Running " << command_line.GetCommandLineString(); return base::LaunchProcess(command_line, base::LaunchOptions(), &dev_appserver_); } bool LocalApprtcInstanceIsUp() { // Load the admin page and see if we manage to load it right. ui_test_utils::NavigateToURL(browser(), GURL("localhost:9998")); content::WebContents* tab_contents = browser()->tab_strip_model()->GetActiveWebContents(); std::string javascript = "window.domAutomationController.send(document.title)"; std::string result; if (!content::ExecuteScriptAndExtractString(tab_contents, javascript, &result)) return false; return result == kTitlePageOfAppEngineAdminPage; } bool StopApprtcInstance() { return base::KillProcess(dev_appserver_, 0, false); } bool WaitForCallToComeUp(content::WebContents* tab_contents) { // Apprtc will set remoteVideo.style.opacity to 1 when the call comes up. std::string javascript = "window.domAutomationController.send(remoteVideo.style.opacity)"; return PollingWaitUntil(javascript, "1", tab_contents); } base::FilePath GetSourceDir() { base::FilePath source_dir; PathService::Get(base::DIR_SOURCE_ROOT, &source_dir); return source_dir; } private: base::ProcessHandle dev_appserver_; }; #if defined (OS_WIN) || defined(OS_MACOSX) #define MAYBE_MANUAL_WorksOnApprtc DISABLED_MANUAL_WorksOnApprtc #else #define MAYBE_MANUAL_WorksOnApprtc MANUAL_WorksOnApprtc #endif IN_PROC_BROWSER_TEST_F(WebrtcApprtcBrowserTest, MAYBE_MANUAL_WorksOnApprtc) { if (!LaunchApprtcInstanceOnLocalhost()) { // TODO(phoglund): assert on this once everything is in place on the bots. return; } while (!LocalApprtcInstanceIsUp()) LOG(INFO) << "Waiting for AppRTC to come up..."; GURL room_url = GURL(base::StringPrintf("localhost:9999?r=room_%d", base::RandInt(0, 65536))); chrome::AddBlankTabAt(browser(), -1, true); content::WebContents* left_tab = OpenPageAndAcceptUserMedia(room_url); chrome::AddBlankTabAt(browser(), -1, true); content::WebContents* right_tab = OpenPageAndAcceptUserMedia(room_url); ASSERT_TRUE(WaitForCallToComeUp(left_tab)); ASSERT_TRUE(WaitForCallToComeUp(right_tab)); ASSERT_TRUE(StopApprtcInstance()); } <commit_msg>Now looking at AppRTC from the out/ directory.<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 "base/command_line.h" #include "base/path_service.h" #include "base/process/launch.h" #include "base/rand_util.h" #include "base/strings/stringprintf.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/media/webrtc_browsertest_base.h" #include "chrome/browser/media/webrtc_browsertest_common.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/ui_test_utils.h" #include "chrome/test/ui/ui_test.h" #include "content/public/test/browser_test_utils.h" #include "net/test/python_utils.h" // You need this solution to run this test. The solution will download appengine // and the apprtc code for you. const char kAdviseOnGclientSolution[] = "You need to add this solution to your .gclient to run this test:\n" "{\n" " \"name\" : \"webrtc.DEPS\",\n" " \"url\" : \"svn://svn.chromium.org/chrome/trunk/deps/" "third_party/webrtc/webrtc.DEPS\",\n" "}"; const char kTitlePageOfAppEngineAdminPage[] = "Instances"; // WebRTC-AppRTC integration test. Requires a real webcam and microphone // on the running system. This test is not meant to run in the main browser // test suite since normal tester machines do not have webcams. // // This test will bring up a AppRTC instance on localhost and verify that the // call gets up when connecting to the same room from two tabs in a browser. class WebrtcApprtcBrowserTest : public WebRtcTestBase { public: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { EXPECT_FALSE(command_line->HasSwitch( switches::kUseFakeDeviceForMediaStream)); EXPECT_FALSE(command_line->HasSwitch( switches::kUseFakeUIForMediaStream)); // The video playback will not work without a GPU, so force its use here. command_line->AppendSwitch(switches::kUseGpuInTests); } protected: bool LaunchApprtcInstanceOnLocalhost() { base::FilePath appengine_dev_appserver = GetSourceDir().Append( FILE_PATH_LITERAL("../google_appengine/dev_appserver.py")); if (!base::PathExists(appengine_dev_appserver)) { LOG(ERROR) << "Missing appengine sdk at " << appengine_dev_appserver.value() << ". " << kAdviseOnGclientSolution; return false; } base::FilePath apprtc_dir = GetSourceDir().Append(FILE_PATH_LITERAL("out/apprtc")); if (!base::PathExists(apprtc_dir)) { LOG(ERROR) << "Missing AppRTC code at " << apprtc_dir.value() << ". " << kAdviseOnGclientSolution; return false; } CommandLine command_line(CommandLine::NO_PROGRAM); EXPECT_TRUE(GetPythonCommand(&command_line)); command_line.AppendArgPath(appengine_dev_appserver); command_line.AppendArgPath(apprtc_dir); command_line.AppendArg("--port=9999"); command_line.AppendArg("--admin_port=9998"); command_line.AppendArg("--skip_sdk_update_check"); LOG(INFO) << "Running " << command_line.GetCommandLineString(); return base::LaunchProcess(command_line, base::LaunchOptions(), &dev_appserver_); } bool LocalApprtcInstanceIsUp() { // Load the admin page and see if we manage to load it right. ui_test_utils::NavigateToURL(browser(), GURL("localhost:9998")); content::WebContents* tab_contents = browser()->tab_strip_model()->GetActiveWebContents(); std::string javascript = "window.domAutomationController.send(document.title)"; std::string result; if (!content::ExecuteScriptAndExtractString(tab_contents, javascript, &result)) return false; return result == kTitlePageOfAppEngineAdminPage; } bool StopApprtcInstance() { return base::KillProcess(dev_appserver_, 0, false); } bool WaitForCallToComeUp(content::WebContents* tab_contents) { // Apprtc will set remoteVideo.style.opacity to 1 when the call comes up. std::string javascript = "window.domAutomationController.send(remoteVideo.style.opacity)"; return PollingWaitUntil(javascript, "1", tab_contents); } base::FilePath GetSourceDir() { base::FilePath source_dir; PathService::Get(base::DIR_SOURCE_ROOT, &source_dir); return source_dir; } private: base::ProcessHandle dev_appserver_; }; #if defined (OS_WIN) || defined(OS_MACOSX) #define MAYBE_MANUAL_WorksOnApprtc DISABLED_MANUAL_WorksOnApprtc #else #define MAYBE_MANUAL_WorksOnApprtc MANUAL_WorksOnApprtc #endif IN_PROC_BROWSER_TEST_F(WebrtcApprtcBrowserTest, MAYBE_MANUAL_WorksOnApprtc) { ASSERT_TRUE(LaunchApprtcInstanceOnLocalhost()); while (!LocalApprtcInstanceIsUp()) LOG(INFO) << "Waiting for AppRTC to come up..."; GURL room_url = GURL(base::StringPrintf("localhost:9999?r=room_%d", base::RandInt(0, 65536))); chrome::AddBlankTabAt(browser(), -1, true); content::WebContents* left_tab = OpenPageAndAcceptUserMedia(room_url); chrome::AddBlankTabAt(browser(), -1, true); content::WebContents* right_tab = OpenPageAndAcceptUserMedia(room_url); ASSERT_TRUE(WaitForCallToComeUp(left_tab)); ASSERT_TRUE(WaitForCallToComeUp(right_tab)); ASSERT_TRUE(StopApprtcInstance()); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: toolbar.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: os $ $Date: 2002-05-07 13:49: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 _BIB_TOOLBAR_HXX #define _BIB_TOOLBAR_HXX #ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_ #include <com/sun/star/frame/XController.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_ #include <com/sun/star/frame/XStatusListener.hpp> #endif #ifndef _SV_TOOLBOX_HXX //autogen wg. ToolBox #include <vcl/toolbox.hxx> #endif #ifndef _SV_LSTBOX_HXX //autogen wg. ::com::sun::star::form #include <vcl/lstbox.hxx> #endif #ifndef _SV_EDIT_HXX //autogen wg. Edit #include <vcl/edit.hxx> #endif #ifndef _SV_FIXED_HXX //autogen wg. FixedText #include <vcl/fixed.hxx> #endif #ifndef _SVARRAY_HXX #include <svtools/svarray.hxx> #endif #ifndef _SV_TIMER_HXX //autogen wg. Timer #include <vcl/timer.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> // helper for implementations #endif class BibDataManager; class BibToolBar; class BibToolBarListener: public cppu::WeakImplHelper1 < ::com::sun::star::frame::XStatusListener> { private: sal_uInt16 nIndex; rtl::OUString aCommand; protected: BibToolBar *pToolBar; public: BibToolBarListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId); ~BibToolBarListener(); rtl::OUString GetCommand(); void SetCommand(const rtl::OUString& aStr); sal_uInt16 GetIndex(); void SetIndex(sal_uInt16 nIndex); // ::com::sun::star::lang::XEventListener // we do not hold References to dispatches, so there is nothing to do on disposal virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw( ::com::sun::star::uno::RuntimeException ){}; // ::com::sun::star::frame::XStatusListener virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event) throw( ::com::sun::star::uno::RuntimeException ); }; class BibTBListBoxListener: public BibToolBarListener { public: BibTBListBoxListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId); ~BibTBListBoxListener(); virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event) throw( ::com::sun::star::uno::RuntimeException ); }; class BibTBEditListener: public BibToolBarListener { public: BibTBEditListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId); ~BibTBEditListener(); virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event) throw( ::com::sun::star::uno::RuntimeException ); }; class BibTBQueryMenuListener: public BibToolBarListener { public: BibTBQueryMenuListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId); ~BibTBQueryMenuListener(); virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event) throw( ::com::sun::star::uno::RuntimeException ); }; typedef ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener>* BibToolBarListenerPtr; SV_DECL_PTRARR_DEL( BibToolBarListenerArr, BibToolBarListenerPtr, 4, 4 ); class BibToolBar: public ToolBox { private: BibToolBarListenerArr aListenerArr; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController > xController; Timer aTimer; Timer aMenuTimer; ImageList aImgLst; ImageList aImgLstHC; FixedText aFtSource; ListBox aLBSource; FixedText aFtQuery; Edit aEdQuery; PopupMenu aPopupMenu; sal_uInt16 nMenuId; sal_uInt16 nSelMenuItem; rtl::OUString aQueryField; BibDataManager* pDatMan; DECL_LINK( SelHdl, ListBox* ); DECL_LINK( SendSelHdl, Timer* ); DECL_LINK( MenuHdl, Timer* ); void ApplyImageList(); protected: void DataChanged( const DataChangedEvent& rDCEvt ); void InitListener(); virtual void Select(); virtual void Click(); void SendDispatch(sal_uInt16 nId, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rArgs); long PreNotify( NotifyEvent& rNEvt ); public: BibToolBar(Window* pParent, WinBits nStyle = WB_3DLOOK ); ~BibToolBar(); void SetXController(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController > &); void ClearSourceList(); void UpdateSourceList(sal_Bool bFlag=sal_True); void EnableSourceList(sal_Bool bFlag=sal_True); void InsertSourceEntry(const XubString&,sal_uInt16 nPos=LISTBOX_APPEND ); void SelectSourceEntry(const XubString& ); void EnableQuery(sal_Bool bFlag=sal_True); void SetQueryString(const XubString& ); void ClearFilterMenu(); sal_uInt16 InsertFilterItem(const XubString& ); void SelectFilterItem(sal_uInt16 nId); void statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event) throw( ::com::sun::star::uno::RuntimeException ); void SetDatMan(BibDataManager& rDatMan) {pDatMan = &rDatMan;} }; #endif <commit_msg>INTEGRATION: CWS os8 (1.5.70); FILE MERGED 2003/04/03 06:39:23 cd 1.5.70.1: #108520# Support automatic toolbar button size depending on menu text height<commit_after>/************************************************************************* * * $RCSfile: toolbar.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2003-04-17 16:13:03 $ * * 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 _BIB_TOOLBAR_HXX #define _BIB_TOOLBAR_HXX #ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_ #include <com/sun/star/frame/XController.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_ #include <com/sun/star/frame/XStatusListener.hpp> #endif #ifndef _SV_TOOLBOX_HXX //autogen wg. ToolBox #include <vcl/toolbox.hxx> #endif #ifndef _SV_LSTBOX_HXX //autogen wg. ::com::sun::star::form #include <vcl/lstbox.hxx> #endif #ifndef _SV_EDIT_HXX //autogen wg. Edit #include <vcl/edit.hxx> #endif #ifndef _SV_FIXED_HXX //autogen wg. FixedText #include <vcl/fixed.hxx> #endif #ifndef _SVARRAY_HXX #include <svtools/svarray.hxx> #endif #ifndef _SV_TIMER_HXX //autogen wg. Timer #include <vcl/timer.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> // helper for implementations #endif class BibDataManager; class BibToolBar; class BibToolBarListener: public cppu::WeakImplHelper1 < ::com::sun::star::frame::XStatusListener> { private: sal_uInt16 nIndex; rtl::OUString aCommand; protected: BibToolBar *pToolBar; public: BibToolBarListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId); ~BibToolBarListener(); rtl::OUString GetCommand(); void SetCommand(const rtl::OUString& aStr); sal_uInt16 GetIndex(); void SetIndex(sal_uInt16 nIndex); // ::com::sun::star::lang::XEventListener // we do not hold References to dispatches, so there is nothing to do on disposal virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw( ::com::sun::star::uno::RuntimeException ){}; // ::com::sun::star::frame::XStatusListener virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event) throw( ::com::sun::star::uno::RuntimeException ); }; class BibTBListBoxListener: public BibToolBarListener { public: BibTBListBoxListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId); ~BibTBListBoxListener(); virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event) throw( ::com::sun::star::uno::RuntimeException ); }; class BibTBEditListener: public BibToolBarListener { public: BibTBEditListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId); ~BibTBEditListener(); virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event) throw( ::com::sun::star::uno::RuntimeException ); }; class BibTBQueryMenuListener: public BibToolBarListener { public: BibTBQueryMenuListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId); ~BibTBQueryMenuListener(); virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event) throw( ::com::sun::star::uno::RuntimeException ); }; typedef ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener>* BibToolBarListenerPtr; SV_DECL_PTRARR_DEL( BibToolBarListenerArr, BibToolBarListenerPtr, 4, 4 ); class BibToolBar: public ToolBox { private: BibToolBarListenerArr aListenerArr; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController > xController; Timer aTimer; Timer aMenuTimer; ImageList aImgLst; ImageList aImgLstHC; ImageList aBigImgLst; ImageList aBigImgLstHC; FixedText aFtSource; ListBox aLBSource; FixedText aFtQuery; Edit aEdQuery; PopupMenu aPopupMenu; sal_uInt16 nMenuId; sal_uInt16 nSelMenuItem; rtl::OUString aQueryField; Link aLayoutManager; sal_Int16 nSymbolSet; sal_Int16 nOutStyle; BibDataManager* pDatMan; DECL_LINK( SelHdl, ListBox* ); DECL_LINK( SendSelHdl, Timer* ); DECL_LINK( MenuHdl, Timer* ); DECL_LINK( OptionsChanged_Impl, void* ); DECL_LINK( SettingsChanged_Impl, void* ); void ApplyImageList(); void RebuildToolbar(); protected: void DataChanged( const DataChangedEvent& rDCEvt ); void InitListener(); virtual void Select(); virtual void Click(); void SendDispatch(sal_uInt16 nId, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rArgs); long PreNotify( NotifyEvent& rNEvt ); sal_Int16 GetCurrentSymbolSet(); public: BibToolBar(Window* pParent, Link aLink, WinBits nStyle = WB_3DLOOK ); ~BibToolBar(); void SetXController(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController > &); void ClearSourceList(); void UpdateSourceList(sal_Bool bFlag=sal_True); void EnableSourceList(sal_Bool bFlag=sal_True); void InsertSourceEntry(const XubString&,sal_uInt16 nPos=LISTBOX_APPEND ); void SelectSourceEntry(const XubString& ); void EnableQuery(sal_Bool bFlag=sal_True); void SetQueryString(const XubString& ); void AdjustToolBox(); void ClearFilterMenu(); sal_uInt16 InsertFilterItem(const XubString& ); void SelectFilterItem(sal_uInt16 nId); void statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event) throw( ::com::sun::star::uno::RuntimeException ); void SetDatMan(BibDataManager& rDatMan) {pDatMan = &rDatMan;} }; #endif <|endoftext|>
<commit_before>/******************************************************************************* * This file is part of "Patrick's Programming Library", Version 7 (PPL7). * Web: http://www.pfp.de/ppl/ * * $Author$ * $Revision$ * $Date$ * $Id$ * ******************************************************************************* * Copyright (c) 2013, Patrick Fedick <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AND 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 "prolog.h" #ifdef HAVE_STDIO_H #include <stdio.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_MATH_H #include <math.h> #endif #include "ppl7.h" #include "ppl7-grafix.h" #ifdef HAVE_FREETYPE2 #include <ft2build.h> #include FT_FREETYPE_H #endif //#undef HAVE_X86_ASSEMBLER // Font-Blitter typedef struct tagGLYPH { const char *data; char *target; ppluint32 pitch; pplint32 color; } GLYPH; extern "C" { int BltGlyph_M8_32 (GLYPH *g); int BltGlyph_M1_32 (GLYPH *g); int BltGlyph_AA8_32 (GLYPH *g); int BltGlyph_AA2_32 (GLYPH *g); int BltGlyph_AA4_32 (GLYPH *g); } namespace ppl7 { namespace grafix { /*!\class FontEngineFreeType * \ingroup PPLGroupGrafik * \brief Font-Engine für von FreeType unterstützte Fonts * * Diese Engine unterstützt TrueType, OpenType, Type1 und weitere von der Freetype-Library * unterstützte Formate. * * \see * http://www.freetype.org/ */ #ifdef HAVE_FREETYPE2 typedef struct tagFreeTypeEngineData { FT_Library ftlib; } FREETYPE_ENGINE_DATA; typedef struct tagFreeTypeFaceData { FT_Byte *buffer; FT_Face face; int kerning; } FREETYPE_FACE_DATA; #endif FontEngineFreeType::FontEngineFreeType() { ft=NULL; #ifdef HAVE_FREETYPE2 #endif } FontEngineFreeType::~FontEngineFreeType() { #ifdef HAVE_FREETYPE2 FREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft; if (f) { FT_Done_FreeType(f->ftlib); free(f); } #endif } String FontEngineFreeType::name() const { return "FontEngineFreeType"; } String FontEngineFreeType::description() const { return "Rendering of TrueType and OpenType fonts"; } void FontEngineFreeType::init() { #ifndef HAVE_FREETYPE2 throw UnsupportedFeatureException("Freetype2"); #else if (ft) return; FREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA *)malloc(sizeof(FREETYPE_ENGINE_DATA)); if (!f) throw OutOfMemoryException(); int error=FT_Init_FreeType(&f->ftlib ); if (error) { free(f); throw FontEngineInitializationException(); } ft=f; #endif } int FontEngineFreeType::ident(FileObject &file) throw() { #ifndef HAVE_FREETYPE2 return 0; #else FREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft; if (!f) return 0; const FT_Byte *buffer=(const FT_Byte *)file.map(); size_t size=file.size(); FT_Face face; int error = FT_New_Memory_Face(f->ftlib, buffer, (FT_Long)size, 0, &face ); if (error!=0) return 0; FT_Done_Face(face); return 1; #endif } FontFile *FontEngineFreeType::loadFont(FileObject &file, const String &fontname) { #ifndef HAVE_FREETYPE2 throw UnsupportedFeatureException("Freetype2"); #else FREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft; if (!f) throw FontEngineUninitializedException(); FREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)malloc(sizeof(FREETYPE_FACE_DATA)); if (!face) throw OutOfMemoryException(); face->buffer=(FT_Byte *)file.load(); size_t size=file.size(); int error = FT_New_Memory_Face(f->ftlib, face->buffer, (FT_Long)size, 0, &face->face ); if (error!=0) { free(face->buffer); free(face); if (error!=0) throw InvalidFontException(); } String name=fontname; if (name.isEmpty()) name.set(face->face->family_name); face->kerning=(int)FT_HAS_KERNING(face->face); // Kerning unterstützt? FontFile *ff=new FontFile; ff->Name=fontname; ff->engine=this; ff->priv=face; return ff; #endif } void FontEngineFreeType::deleteFont(FontFile *file) { #ifndef HAVE_FREETYPE2 throw UnsupportedFeatureException("Freetype2"); #else if (!file) throw NullPointerException(); if (file->engine!=this) throw InvalidFontEngineException(); FREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file->priv; if (face) { FT_Done_Face(face->face); free(face->buffer); free(face); file->priv=NULL; } file->engine=NULL; #endif } #ifdef HAVE_FREETYPE2 static void renderGlyphAA(Drawable &draw, FT_Bitmap *bitmap, int x, int y, const Color &color) { ppluint8 v=0; ppluint8 *glyph=(ppluint8 *)bitmap->buffer; for (unsigned int gy=0;gy<bitmap->rows;gy++) { for (unsigned int gx=0;gx<bitmap->width;gx++) { v=glyph[gx]; if (v>0) { draw.blendPixel(x+gx,y+gy,color,v); } } glyph+=bitmap->pitch; } } static void renderGlyphMono(Drawable &draw, FT_Bitmap *bitmap, int x, int y, const Color &color) { ppluint8 v=0; ppluint8 *glyph=(ppluint8 *)bitmap->buffer; for (unsigned int gy=0;gy<bitmap->rows;gy++) { ppluint8 bitcount=0; ppluint8 bytecount=0; for (unsigned int gx=0;gx<bitmap->width;gx++) { if (!bitcount) { v=glyph[bytecount]; bitcount=8; bytecount++; } if(v&128) { draw.putPixel(x+gx,y+gy,color); } v=v<<1; bitcount--; } glyph+=bitmap->pitch; } } #endif void FontEngineFreeType::render(const FontFile &file, const Font &font, Drawable &draw, int x, int y, const WideString &text, const Color &color) { #ifndef HAVE_FREETYPE2 throw UnsupportedFeatureException("Freetype2"); #else if (file.priv==NULL) throw InvalidFontException(); FREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file.priv; int error=FT_Set_Pixel_Sizes(face->face,0,font.size()+2); if (error!=0) throw InvalidFontException(); int orgx=x<<6; int orgy=y<<6; int lastx=orgx; bool rotate=false; FT_Matrix matrix; /* transformation matrix */ if (font.rotation()!=0.0) { rotate=true; double angle=font.rotation()*3.14159265359/180.0; /* set up matrix */ matrix.xx = (FT_Fixed)( cos( angle ) * 0x10000L ); matrix.xy = (FT_Fixed)( sin( angle ) * 0x10000L ); matrix.yx = (FT_Fixed)( -sin( angle ) * 0x10000L ); matrix.yy = (FT_Fixed)( cos( angle ) * 0x10000L ); FT_Set_Transform( face->face, &matrix, NULL ); } else { FT_Set_Transform( face->face, NULL, NULL ); } FT_GlyphSlot slot=face->face->glyph; FT_UInt glyph_index, last_glyph=0; FT_Vector kerning; kerning.x=0; kerning.y=0; size_t p=0; size_t textlen=text.len(); while (p<textlen) { int code=text[p]; p++; if (code==10) { // Newline lastx=orgx; orgy+=(font.size()+2)<<6; last_glyph=0; } else { y=orgy; x=lastx; glyph_index=FT_Get_Char_Index(face->face,code); if (!glyph_index) continue; // Antialiasing if (font.antialias()) { error=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_RENDER|FT_LOAD_TARGET_NORMAL); } else { error=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_TARGET_MONO|FT_LOAD_RENDER); } if (error!=0) continue; //x=x+(slot->bitmap_left<<6); //y=y-(slot->bitmap_top<<6); if (face->kerning>0 && last_glyph>0 && rotate==false) { FT_Get_Kerning(face->face,last_glyph,glyph_index,FT_KERNING_DEFAULT,&kerning); x+=kerning.x; y+=kerning.y; } if (font.antialias()) { renderGlyphAA(draw,&slot->bitmap,(x>>6)+slot->bitmap_left, (y>>6)-slot->bitmap_top,color); } else { renderGlyphMono(draw,&slot->bitmap,(x>>6)+slot->bitmap_left, (y>>6)-slot->bitmap_top,color); } if (font.drawUnderline()) { } lastx=x+slot->advance.x; orgy-=slot->advance.y; last_glyph=glyph_index; } } #endif } Size FontEngineFreeType::measure(const FontFile &file, const Font &font, const WideString &text) { Size s; #ifndef HAVE_FREETYPE2 throw UnsupportedFeatureException("Freetype2"); #else if (file.priv==NULL) throw InvalidFontException(); FREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file.priv; int error=FT_Set_Pixel_Sizes(face->face,0,font.size()+2); if (error!=0) throw InvalidFontException(); FT_Set_Transform( face->face, NULL, NULL ); int width=0,height=0; FT_GlyphSlot slot=face->face->glyph; FT_UInt glyph_index, last_glyph=0; FT_Vector kerning; kerning.x=0; kerning.y=0; size_t p=0; size_t textlen=text.len(); while (p<textlen) { int code=text[p]; p++; if (code==10) { // Newline width=0; height+=(font.size()+2); last_glyph=0; } else { glyph_index=FT_Get_Char_Index(face->face,code); if (!glyph_index) continue; // Antialiasing if (font.antialias()) { error=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_RENDER|FT_LOAD_TARGET_NORMAL); } else { error=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_TARGET_MONO|FT_LOAD_RENDER); } if (error!=0) continue; //x=x+slot->bitmap_left; //y=y-slot->bitmap_top; if (face->kerning>0 && last_glyph>0) { error=FT_Get_Kerning(face->face,last_glyph,glyph_index,FT_KERNING_DEFAULT,&kerning); width+=kerning.x; } width+=(slot->advance.x); if (width>s.width) s.width=width; last_glyph=glyph_index; } } s.setHeight(height+font.size()+2); s.width=s.width>>6; return s; #endif } } // EOF namespace grafix } // EOF namespace ppl7 <commit_msg>putPixel überarbeitet<commit_after>/******************************************************************************* * This file is part of "Patrick's Programming Library", Version 7 (PPL7). * Web: http://www.pfp.de/ppl/ * * $Author$ * $Revision$ * $Date$ * $Id$ * ******************************************************************************* * Copyright (c) 2013, Patrick Fedick <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AND 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 "prolog.h" #ifdef HAVE_STDIO_H #include <stdio.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_MATH_H #include <math.h> #endif #include "ppl7.h" #include "ppl7-grafix.h" #ifdef HAVE_FREETYPE2 #include <ft2build.h> #include FT_FREETYPE_H #endif //#undef HAVE_X86_ASSEMBLER // Font-Blitter typedef struct tagGLYPH { const char *data; char *target; ppluint32 pitch; pplint32 color; } GLYPH; extern "C" { int BltGlyph_M8_32 (GLYPH *g); int BltGlyph_M1_32 (GLYPH *g); int BltGlyph_AA8_32 (GLYPH *g); int BltGlyph_AA2_32 (GLYPH *g); int BltGlyph_AA4_32 (GLYPH *g); } namespace ppl7 { namespace grafix { /*!\class FontEngineFreeType * \ingroup PPLGroupGrafik * \brief Font-Engine für von FreeType unterstützte Fonts * * Diese Engine unterstützt TrueType, OpenType, Type1 und weitere von der Freetype-Library * unterstützte Formate. * * \see * http://www.freetype.org/ */ #ifdef HAVE_FREETYPE2 typedef struct tagFreeTypeEngineData { FT_Library ftlib; } FREETYPE_ENGINE_DATA; typedef struct tagFreeTypeFaceData { FT_Byte *buffer; FT_Face face; int kerning; } FREETYPE_FACE_DATA; #endif FontEngineFreeType::FontEngineFreeType() { ft=NULL; #ifdef HAVE_FREETYPE2 #endif } FontEngineFreeType::~FontEngineFreeType() { #ifdef HAVE_FREETYPE2 FREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft; if (f) { FT_Done_FreeType(f->ftlib); free(f); } #endif } String FontEngineFreeType::name() const { return "FontEngineFreeType"; } String FontEngineFreeType::description() const { return "Rendering of TrueType and OpenType fonts"; } void FontEngineFreeType::init() { #ifndef HAVE_FREETYPE2 throw UnsupportedFeatureException("Freetype2"); #else if (ft) return; FREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA *)malloc(sizeof(FREETYPE_ENGINE_DATA)); if (!f) throw OutOfMemoryException(); int error=FT_Init_FreeType(&f->ftlib ); if (error) { free(f); throw FontEngineInitializationException(); } ft=f; #endif } int FontEngineFreeType::ident(FileObject &file) throw() { #ifndef HAVE_FREETYPE2 return 0; #else FREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft; if (!f) return 0; const FT_Byte *buffer=(const FT_Byte *)file.map(); size_t size=file.size(); FT_Face face; int error = FT_New_Memory_Face(f->ftlib, buffer, (FT_Long)size, 0, &face ); if (error!=0) return 0; FT_Done_Face(face); return 1; #endif } FontFile *FontEngineFreeType::loadFont(FileObject &file, const String &fontname) { #ifndef HAVE_FREETYPE2 throw UnsupportedFeatureException("Freetype2"); #else FREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft; if (!f) throw FontEngineUninitializedException(); FREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)malloc(sizeof(FREETYPE_FACE_DATA)); if (!face) throw OutOfMemoryException(); face->buffer=(FT_Byte *)file.load(); size_t size=file.size(); int error = FT_New_Memory_Face(f->ftlib, face->buffer, (FT_Long)size, 0, &face->face ); if (error!=0) { free(face->buffer); free(face); if (error!=0) throw InvalidFontException(); } String name=fontname; if (name.isEmpty()) name.set(face->face->family_name); face->kerning=(int)FT_HAS_KERNING(face->face); // Kerning unterstützt? FontFile *ff=new FontFile; ff->Name=fontname; ff->engine=this; ff->priv=face; return ff; #endif } void FontEngineFreeType::deleteFont(FontFile *file) { #ifndef HAVE_FREETYPE2 throw UnsupportedFeatureException("Freetype2"); #else if (!file) throw NullPointerException(); if (file->engine!=this) throw InvalidFontEngineException(); FREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file->priv; if (face) { FT_Done_Face(face->face); free(face->buffer); free(face); file->priv=NULL; } file->engine=NULL; #endif } static void putPixel(Drawable &draw, int x, int y, const Color &color, int intensity) { Color vg=color; int a=vg.alpha()*intensity/255; if (a==0) return; if (a==255) { vg.setAlpha(a); draw.putPixel(x,y,vg); } Color &bg=draw.getPixel(x,y); int reva=255-a; int red=bg.red()*reva+vg.red()*a; int green=bg.green()*reva+vg.green()*a; int blue=bg.blue()*reva+vg.blue()*a; int alpha=bg.alpha()*reva+vg.alpha()*a; draw.putPixel(x,y,Color(red,green,blue,alpha)); } #ifdef HAVE_FREETYPE2 static void renderGlyphAA(Drawable &draw, FT_Bitmap *bitmap, int x, int y, const Color &color) { ppluint8 v=0; ppluint8 *glyph=(ppluint8 *)bitmap->buffer; for (unsigned int gy=0;gy<bitmap->rows;gy++) { for (unsigned int gx=0;gx<bitmap->width;gx++) { v=glyph[gx]; if (v>0) { putPixel(x+gx,y+gy,color,v); //draw.blendPixel(x+gx,y+gy,color,v); } } glyph+=bitmap->pitch; } } static void renderGlyphMono(Drawable &draw, FT_Bitmap *bitmap, int x, int y, const Color &color) { ppluint8 v=0; ppluint8 *glyph=(ppluint8 *)bitmap->buffer; for (unsigned int gy=0;gy<bitmap->rows;gy++) { ppluint8 bitcount=0; ppluint8 bytecount=0; for (unsigned int gx=0;gx<bitmap->width;gx++) { if (!bitcount) { v=glyph[bytecount]; bitcount=8; bytecount++; } if(v&128) { putPixel(x+gx,y+gy,color,255); //draw.alphaPixel(x+gx,y+gy,color); } v=v<<1; bitcount--; } glyph+=bitmap->pitch; } } #endif void FontEngineFreeType::render(const FontFile &file, const Font &font, Drawable &draw, int x, int y, const WideString &text, const Color &color) { #ifndef HAVE_FREETYPE2 throw UnsupportedFeatureException("Freetype2"); #else if (file.priv==NULL) throw InvalidFontException(); FREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file.priv; int error=FT_Set_Pixel_Sizes(face->face,0,font.size()+2); if (error!=0) throw InvalidFontException(); int orgx=x<<6; int orgy=y<<6; int lastx=orgx; bool rotate=false; FT_Matrix matrix; /* transformation matrix */ if (font.rotation()!=0.0) { rotate=true; double angle=font.rotation()*3.14159265359/180.0; /* set up matrix */ matrix.xx = (FT_Fixed)( cos( angle ) * 0x10000L ); matrix.xy = (FT_Fixed)( sin( angle ) * 0x10000L ); matrix.yx = (FT_Fixed)( -sin( angle ) * 0x10000L ); matrix.yy = (FT_Fixed)( cos( angle ) * 0x10000L ); FT_Set_Transform( face->face, &matrix, NULL ); } else { FT_Set_Transform( face->face, NULL, NULL ); } FT_GlyphSlot slot=face->face->glyph; FT_UInt glyph_index, last_glyph=0; FT_Vector kerning; kerning.x=0; kerning.y=0; size_t p=0; size_t textlen=text.len(); while (p<textlen) { int code=text[p]; p++; if (code==10) { // Newline lastx=orgx; orgy+=(font.size()+2)<<6; last_glyph=0; } else { y=orgy; x=lastx; glyph_index=FT_Get_Char_Index(face->face,code); if (!glyph_index) continue; // Antialiasing if (font.antialias()) { error=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_RENDER|FT_LOAD_TARGET_NORMAL); } else { error=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_TARGET_MONO|FT_LOAD_RENDER); } if (error!=0) continue; //x=x+(slot->bitmap_left<<6); //y=y-(slot->bitmap_top<<6); if (face->kerning>0 && last_glyph>0 && rotate==false) { FT_Get_Kerning(face->face,last_glyph,glyph_index,FT_KERNING_DEFAULT,&kerning); x+=kerning.x; y+=kerning.y; } if (font.antialias()) { renderGlyphAA(draw,&slot->bitmap,(x>>6)+slot->bitmap_left, (y>>6)-slot->bitmap_top,color); } else { renderGlyphMono(draw,&slot->bitmap,(x>>6)+slot->bitmap_left, (y>>6)-slot->bitmap_top,color); } if (font.drawUnderline()) { } lastx=x+slot->advance.x; orgy-=slot->advance.y; last_glyph=glyph_index; } } #endif } Size FontEngineFreeType::measure(const FontFile &file, const Font &font, const WideString &text) { Size s; #ifndef HAVE_FREETYPE2 throw UnsupportedFeatureException("Freetype2"); #else if (file.priv==NULL) throw InvalidFontException(); FREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file.priv; int error=FT_Set_Pixel_Sizes(face->face,0,font.size()+2); if (error!=0) throw InvalidFontException(); FT_Set_Transform( face->face, NULL, NULL ); int width=0,height=0; FT_GlyphSlot slot=face->face->glyph; FT_UInt glyph_index, last_glyph=0; FT_Vector kerning; kerning.x=0; kerning.y=0; size_t p=0; size_t textlen=text.len(); while (p<textlen) { int code=text[p]; p++; if (code==10) { // Newline width=0; height+=(font.size()+2); last_glyph=0; } else { glyph_index=FT_Get_Char_Index(face->face,code); if (!glyph_index) continue; // Antialiasing if (font.antialias()) { error=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_RENDER|FT_LOAD_TARGET_NORMAL); } else { error=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_TARGET_MONO|FT_LOAD_RENDER); } if (error!=0) continue; //x=x+slot->bitmap_left; //y=y-slot->bitmap_top; if (face->kerning>0 && last_glyph>0) { error=FT_Get_Kerning(face->face,last_glyph,glyph_index,FT_KERNING_DEFAULT,&kerning); width+=kerning.x; } width+=(slot->advance.x); if (width>s.width) s.width=width; last_glyph=glyph_index; } } s.setHeight(height+font.size()+2); s.width=s.width>>6; return s; #endif } } // EOF namespace grafix } // EOF namespace ppl7 <|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/renderer/extensions/app_window_custom_bindings.h" #include <string> #include "base/string_util.h" #include "chrome/common/extensions/extension_action.h" #include "chrome/common/extensions/extension_messages.h" #include "chrome/common/url_constants.h" #include "chrome/renderer/extensions/extension_dispatcher.h" #include "chrome/renderer/extensions/extension_helper.h" #include "content/public/renderer/render_view.h" #include "grit/renderer_resources.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLRequest.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebWindowFeatures.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebNavigationPolicy.h" #include "webkit/glue/webkit_glue.h" #include "v8/include/v8.h" #include "content/public/renderer/render_view.h" #include "content/public/renderer/render_view_visitor.h" namespace extensions { AppWindowCustomBindings::AppWindowCustomBindings( ExtensionDispatcher* extension_dispatcher) : ChromeV8Extension(extension_dispatcher) { RouteStaticFunction("GetView", &GetView); } namespace { class FindViewByID : public content::RenderViewVisitor { public: explicit FindViewByID(int route_id) : route_id_(route_id), view_(NULL) { } content::RenderView* view() { return view_; } // Returns false to terminate the iteration. virtual bool Visit(content::RenderView* render_view) { if (render_view->GetRoutingID() == route_id_) { view_ = render_view; return false; } return true; } private: int route_id_; content::RenderView* view_; }; } // namespace v8::Handle<v8::Value> AppWindowCustomBindings::GetView( const v8::Arguments& args) { // TODO(jeremya): convert this to IDL nocompile to get validation, and turn // these argument checks into CHECK(). if (args.Length() != 1) return v8::Undefined(); if (!args[0]->IsInt32()) return v8::Undefined(); int view_id = args[0]->Int32Value(); if (view_id == MSG_ROUTING_NONE) return v8::Undefined(); // TODO(jeremya): there exists a direct map of routing_id -> RenderView as // ChildThread::current()->ResolveRoute(), but ResolveRoute returns an // IPC::Channel::Listener*, which RenderView doesn't inherit from // (RenderViewImpl does, indirectly, via RenderWidget, but the link isn't // exposed outside of content/.) FindViewByID view_finder(view_id); content::RenderView::ForEach(&view_finder); content::RenderView* view = view_finder.view(); if (!view) return v8::Undefined(); // TODO(jeremya): it doesn't really make sense to set the opener here, but we // need to make sure the security origin is set up before returning the DOM // reference. A better way to do this would be to have the browser pass the // opener through so opener_id is set in RenderViewImpl's constructor. WebKit::WebFrame* opener = GetCurrentRenderView()->GetWebView()->mainFrame(); WebKit::WebFrame* frame = view->GetWebView()->mainFrame(); frame->setOpener(opener); v8::Local<v8::Value> window = frame->mainWorldScriptContext()->Global(); return window; } } // namespace extensions <commit_msg>Coverity NULL_RETURNS issue.<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/renderer/extensions/app_window_custom_bindings.h" #include <string> #include "base/string_util.h" #include "chrome/common/extensions/extension_action.h" #include "chrome/common/extensions/extension_messages.h" #include "chrome/common/url_constants.h" #include "chrome/renderer/extensions/extension_dispatcher.h" #include "chrome/renderer/extensions/extension_helper.h" #include "content/public/renderer/render_view.h" #include "grit/renderer_resources.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" #include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLRequest.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebWindowFeatures.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebNavigationPolicy.h" #include "webkit/glue/webkit_glue.h" #include "v8/include/v8.h" #include "content/public/renderer/render_view.h" #include "content/public/renderer/render_view_visitor.h" namespace extensions { AppWindowCustomBindings::AppWindowCustomBindings( ExtensionDispatcher* extension_dispatcher) : ChromeV8Extension(extension_dispatcher) { RouteStaticFunction("GetView", &GetView); } namespace { class FindViewByID : public content::RenderViewVisitor { public: explicit FindViewByID(int route_id) : route_id_(route_id), view_(NULL) { } content::RenderView* view() { return view_; } // Returns false to terminate the iteration. virtual bool Visit(content::RenderView* render_view) { if (render_view->GetRoutingID() == route_id_) { view_ = render_view; return false; } return true; } private: int route_id_; content::RenderView* view_; }; } // namespace v8::Handle<v8::Value> AppWindowCustomBindings::GetView( const v8::Arguments& args) { // TODO(jeremya): convert this to IDL nocompile to get validation, and turn // these argument checks into CHECK(). if (args.Length() != 1) return v8::Undefined(); if (!args[0]->IsInt32()) return v8::Undefined(); int view_id = args[0]->Int32Value(); if (view_id == MSG_ROUTING_NONE) return v8::Undefined(); // TODO(jeremya): there exists a direct map of routing_id -> RenderView as // ChildThread::current()->ResolveRoute(), but ResolveRoute returns an // IPC::Channel::Listener*, which RenderView doesn't inherit from // (RenderViewImpl does, indirectly, via RenderWidget, but the link isn't // exposed outside of content/.) FindViewByID view_finder(view_id); content::RenderView::ForEach(&view_finder); content::RenderView* view = view_finder.view(); if (!view) return v8::Undefined(); // TODO(jeremya): it doesn't really make sense to set the opener here, but we // need to make sure the security origin is set up before returning the DOM // reference. A better way to do this would be to have the browser pass the // opener through so opener_id is set in RenderViewImpl's constructor. content::RenderView* render_view = GetCurrentRenderView(); if (!render_view) return v8::Undefined(); WebKit::WebFrame* opener = render_view->GetWebView()->mainFrame(); WebKit::WebFrame* frame = view->GetWebView()->mainFrame(); frame->setOpener(opener); v8::Local<v8::Value> window = frame->mainWorldScriptContext()->Global(); return window; } } // namespace extensions <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "VertexData.h" #include "GLContext.h" #include "../base/Exception.h" #include "../base/WideLine.h" #include "../base/ObjectCounter.h" #include <iostream> #include <stddef.h> #include <string.h> using namespace std; using namespace boost; namespace avg { const int MIN_VERTEXES = 100; const int MIN_INDEXES = 100; VertexData::VertexData(int reserveVerts, int reserveIndexes) : m_NumVerts(0), m_NumIndexes(0), m_ReserveVerts(reserveVerts), m_ReserveIndexes(reserveIndexes), m_bDataChanged(true) { ObjectCounter::get()->incRef(&typeid(*this)); if (m_ReserveVerts < MIN_VERTEXES) { m_ReserveVerts = MIN_VERTEXES; } if (m_ReserveIndexes < MIN_INDEXES) { m_ReserveIndexes = MIN_INDEXES; } m_pVertexData = new T2V3C4Vertex[m_ReserveVerts]; m_pIndexData = new unsigned int[m_ReserveIndexes]; } VertexData::~VertexData() { delete[] m_pVertexData; delete[] m_pIndexData; ObjectCounter::get()->decRef(&typeid(*this)); } void VertexData::appendPos(const glm::vec2& pos, const glm::vec2& texPos, const Pixel32& color) { if (m_NumVerts >= m_ReserveVerts-1) { grow(); } T2V3C4Vertex* pVertex = &(m_pVertexData[m_NumVerts]); pVertex->m_Pos[0] = (GLfloat)pos.x; pVertex->m_Pos[1] = (GLfloat)pos.y; pVertex->m_Pos[2] = 0.0; pVertex->m_Tex[0] = (GLfloat)texPos.x; pVertex->m_Tex[1] = (GLfloat)texPos.y; pVertex->m_Color = color; m_bDataChanged = true; m_NumVerts++; } void VertexData::appendTriIndexes(int v0, int v1, int v2) { if (m_NumIndexes >= m_ReserveIndexes-3) { grow(); } m_pIndexData[m_NumIndexes] = v0; m_pIndexData[m_NumIndexes+1] = v1; m_pIndexData[m_NumIndexes+2] = v2; m_NumIndexes += 3; } void VertexData::appendQuadIndexes(int v0, int v1, int v2, int v3) { if (m_NumIndexes >= m_ReserveIndexes-6) { grow(); } m_pIndexData[m_NumIndexes] = v0; m_pIndexData[m_NumIndexes+1] = v1; m_pIndexData[m_NumIndexes+2] = v2; m_pIndexData[m_NumIndexes+3] = v1; m_pIndexData[m_NumIndexes+4] = v2; m_pIndexData[m_NumIndexes+5] = v3; m_NumIndexes += 6; } void VertexData::addLineData(Pixel32 color, const glm::vec2& p1, const glm::vec2& p2, float width, float tc1, float tc2) { WideLine wl(p1, p2, width); int curVertex = getCurVert(); appendPos(wl.pl0, glm::vec2(tc1, 1), color); appendPos(wl.pr0, glm::vec2(tc1, 0), color); appendPos(wl.pl1, glm::vec2(tc2, 1), color); appendPos(wl.pr1, glm::vec2(tc2, 0), color); appendQuadIndexes(curVertex+1, curVertex, curVertex+3, curVertex+2); } void VertexData::appendVertexData(VertexDataPtr pVertexes) { int oldNumVerts = m_NumVerts; int oldNumIndexes = m_NumIndexes; m_NumVerts += pVertexes->getNumVerts(); m_NumIndexes += pVertexes->getNumIndexes(); if (m_NumVerts > m_ReserveVerts || m_NumIndexes > m_ReserveIndexes) { grow(); } for (int i=0; i<pVertexes->getNumVerts(); ++i) { m_pVertexData[oldNumVerts+i] = pVertexes->m_pVertexData[i]; } for (int i=0; i<pVertexes->getNumIndexes(); ++i) { m_pIndexData[oldNumIndexes+i] = pVertexes->m_pIndexData[i]+oldNumVerts; } m_bDataChanged = true; } bool VertexData::hasDataChanged() const { return m_bDataChanged; } void VertexData::resetDataChanged() { m_bDataChanged = false; } void VertexData::reset() { m_NumVerts = 0; m_NumIndexes = 0; } int VertexData::getCurVert() const { return m_NumVerts; } int VertexData::getCurIndex() const { return m_NumIndexes; } void VertexData::dump() const { cerr << m_NumVerts << " vertexes: "; for (int i=0; i<m_NumVerts; ++i) { cerr << m_pVertexData[i] << ", "; } cerr << endl; cerr << m_NumIndexes << " indexes: "; for (int i=0; i<m_NumIndexes; ++i) { cerr << m_pIndexData[i] << " "; } cerr << endl; } void VertexData::grow() { bool bChanged = false; if (m_NumVerts >= m_ReserveVerts-1) { bChanged = true; int oldReserveVerts = m_ReserveVerts; m_ReserveVerts = int(m_ReserveVerts*1.5); if (m_ReserveVerts < m_NumVerts) { m_ReserveVerts = m_NumVerts; } T2V3C4Vertex* pVertexData = m_pVertexData; m_pVertexData = new T2V3C4Vertex[m_ReserveVerts]; memcpy(m_pVertexData, pVertexData, sizeof(T2V3C4Vertex)*oldReserveVerts); delete[] pVertexData; } if (m_NumIndexes >= m_ReserveIndexes-6) { bChanged = true; int oldReserveIndexes = m_ReserveIndexes; m_ReserveIndexes = int(m_ReserveIndexes*1.5); if (m_ReserveIndexes < m_NumIndexes) { m_ReserveIndexes = m_NumIndexes; } unsigned int * pIndexData = m_pIndexData; m_pIndexData = new unsigned int[m_ReserveIndexes]; memcpy(m_pIndexData, pIndexData, sizeof(unsigned int)*oldReserveIndexes); delete[] pIndexData; } if (bChanged) { m_bDataChanged = true; } } int VertexData::getNumVerts() const { return m_NumVerts; } int VertexData::getNumIndexes() const { return m_NumIndexes; } int VertexData::getReserveVerts() const { return m_ReserveVerts; } int VertexData::getReserveIndexes() const { return m_ReserveIndexes; } const T2V3C4Vertex * VertexData::getVertexPointer() const { return m_pVertexData; } const unsigned int * VertexData::getIndexPointer() const { return m_pIndexData; } std::ostream& operator<<(std::ostream& os, const T2V3C4Vertex& v) { os << "(" << v.m_Pos[0] << ", " << v.m_Pos[1] << ", " << v.m_Pos[2] << ")"; return os; } } <commit_msg>Minor optimization.<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "VertexData.h" #include "GLContext.h" #include "../base/Exception.h" #include "../base/WideLine.h" #include "../base/ObjectCounter.h" #include <iostream> #include <stddef.h> #include <string.h> using namespace std; using namespace boost; namespace avg { const int MIN_VERTEXES = 100; const int MIN_INDEXES = 100; VertexData::VertexData(int reserveVerts, int reserveIndexes) : m_NumVerts(0), m_NumIndexes(0), m_ReserveVerts(reserveVerts), m_ReserveIndexes(reserveIndexes), m_bDataChanged(true) { ObjectCounter::get()->incRef(&typeid(*this)); if (m_ReserveVerts < MIN_VERTEXES) { m_ReserveVerts = MIN_VERTEXES; } if (m_ReserveIndexes < MIN_INDEXES) { m_ReserveIndexes = MIN_INDEXES; } m_pVertexData = new T2V3C4Vertex[m_ReserveVerts]; m_pIndexData = new unsigned int[m_ReserveIndexes]; } VertexData::~VertexData() { delete[] m_pVertexData; delete[] m_pIndexData; ObjectCounter::get()->decRef(&typeid(*this)); } void VertexData::appendPos(const glm::vec2& pos, const glm::vec2& texPos, const Pixel32& color) { if (m_NumVerts >= m_ReserveVerts-1) { grow(); } T2V3C4Vertex* pVertex = &(m_pVertexData[m_NumVerts]); pVertex->m_Pos[0] = (GLfloat)pos.x; pVertex->m_Pos[1] = (GLfloat)pos.y; pVertex->m_Pos[2] = 0.0; pVertex->m_Tex[0] = (GLfloat)texPos.x; pVertex->m_Tex[1] = (GLfloat)texPos.y; pVertex->m_Color = color; m_bDataChanged = true; m_NumVerts++; } void VertexData::appendTriIndexes(int v0, int v1, int v2) { if (m_NumIndexes >= m_ReserveIndexes-3) { grow(); } m_pIndexData[m_NumIndexes] = v0; m_pIndexData[m_NumIndexes+1] = v1; m_pIndexData[m_NumIndexes+2] = v2; m_NumIndexes += 3; } void VertexData::appendQuadIndexes(int v0, int v1, int v2, int v3) { if (m_NumIndexes >= m_ReserveIndexes-6) { grow(); } m_pIndexData[m_NumIndexes] = v0; m_pIndexData[m_NumIndexes+1] = v1; m_pIndexData[m_NumIndexes+2] = v2; m_pIndexData[m_NumIndexes+3] = v1; m_pIndexData[m_NumIndexes+4] = v2; m_pIndexData[m_NumIndexes+5] = v3; m_NumIndexes += 6; } void VertexData::addLineData(Pixel32 color, const glm::vec2& p1, const glm::vec2& p2, float width, float tc1, float tc2) { WideLine wl(p1, p2, width); int curVertex = getCurVert(); appendPos(wl.pl0, glm::vec2(tc1, 1), color); appendPos(wl.pr0, glm::vec2(tc1, 0), color); appendPos(wl.pl1, glm::vec2(tc2, 1), color); appendPos(wl.pr1, glm::vec2(tc2, 0), color); appendQuadIndexes(curVertex+1, curVertex, curVertex+3, curVertex+2); } void VertexData::appendVertexData(VertexDataPtr pVertexes) { int oldNumVerts = m_NumVerts; int oldNumIndexes = m_NumIndexes; m_NumVerts += pVertexes->getNumVerts(); m_NumIndexes += pVertexes->getNumIndexes(); if (m_NumVerts > m_ReserveVerts || m_NumIndexes > m_ReserveIndexes) { grow(); } memcpy(&(m_pVertexData[oldNumVerts]), pVertexes->m_pVertexData, pVertexes->getNumVerts()*sizeof(T2V3C4Vertex)); for (int i=0; i<pVertexes->getNumIndexes(); ++i) { m_pIndexData[oldNumIndexes+i] = pVertexes->m_pIndexData[i]+oldNumVerts; } m_bDataChanged = true; } bool VertexData::hasDataChanged() const { return m_bDataChanged; } void VertexData::resetDataChanged() { m_bDataChanged = false; } void VertexData::reset() { m_NumVerts = 0; m_NumIndexes = 0; } int VertexData::getCurVert() const { return m_NumVerts; } int VertexData::getCurIndex() const { return m_NumIndexes; } void VertexData::dump() const { cerr << m_NumVerts << " vertexes: "; for (int i=0; i<m_NumVerts; ++i) { cerr << m_pVertexData[i] << ", "; } cerr << endl; cerr << m_NumIndexes << " indexes: "; for (int i=0; i<m_NumIndexes; ++i) { cerr << m_pIndexData[i] << " "; } cerr << endl; } void VertexData::grow() { bool bChanged = false; if (m_NumVerts >= m_ReserveVerts-1) { bChanged = true; int oldReserveVerts = m_ReserveVerts; m_ReserveVerts = int(m_ReserveVerts*1.5); if (m_ReserveVerts < m_NumVerts) { m_ReserveVerts = m_NumVerts; } T2V3C4Vertex* pVertexData = m_pVertexData; m_pVertexData = new T2V3C4Vertex[m_ReserveVerts]; memcpy(m_pVertexData, pVertexData, sizeof(T2V3C4Vertex)*oldReserveVerts); delete[] pVertexData; } if (m_NumIndexes >= m_ReserveIndexes-6) { bChanged = true; int oldReserveIndexes = m_ReserveIndexes; m_ReserveIndexes = int(m_ReserveIndexes*1.5); if (m_ReserveIndexes < m_NumIndexes) { m_ReserveIndexes = m_NumIndexes; } unsigned int * pIndexData = m_pIndexData; m_pIndexData = new unsigned int[m_ReserveIndexes]; memcpy(m_pIndexData, pIndexData, sizeof(unsigned int)*oldReserveIndexes); delete[] pIndexData; } if (bChanged) { m_bDataChanged = true; } } int VertexData::getNumVerts() const { return m_NumVerts; } int VertexData::getNumIndexes() const { return m_NumIndexes; } int VertexData::getReserveVerts() const { return m_ReserveVerts; } int VertexData::getReserveIndexes() const { return m_ReserveIndexes; } const T2V3C4Vertex * VertexData::getVertexPointer() const { return m_pVertexData; } const unsigned int * VertexData::getIndexPointer() const { return m_pIndexData; } std::ostream& operator<<(std::ostream& os, const T2V3C4Vertex& v) { os << "(" << v.m_Pos[0] << ", " << v.m_Pos[1] << ", " << v.m_Pos[2] << ")"; return os; } } <|endoftext|>
<commit_before>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License 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. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins/solver_factory.h" // GRINS #include "grins/grins_steady_solver.h" #include "grins/grins_unsteady_solver.h" #include "grins/steady_mesh_adaptive_solver.h" // libMesh #include "libmesh/getpot.h" namespace GRINS { SolverFactory::SolverFactory() { return; } SolverFactory::~SolverFactory() { return; } std::tr1::shared_ptr<Solver> SolverFactory::build(const GetPot& input) { bool mesh_adaptive = input("MeshAdaptivity/mesh_adaptive", false ); bool transient = input("unsteady-solver/transient", false ); std::tr1::shared_ptr<Solver> solver; // Effectively NULL if(transient && !mesh_adaptive) { solver.reset( new UnsteadySolver(input) ); } else if( !transient && !mesh_adaptive ) { solver.reset( new SteadySolver(input) ); } else if( !transient && mesh_adaptive ) { solver.reset( new SteadyMeshAdaptiveSolver(input) ); } else if( transient && mesh_adaptive ) { libmesh_not_implemented(); } else { std::cerr << "Invalid solver options!" << std::endl; } return solver; } } // namespace GRINS <commit_msg>Add displacement solver to solver factory<commit_after>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License 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. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins/solver_factory.h" // GRINS #include "grins/grins_steady_solver.h" #include "grins/grins_unsteady_solver.h" #include "grins/steady_mesh_adaptive_solver.h" #include "grins/displacement_continuation_solver.h" // libMesh #include "libmesh/getpot.h" namespace GRINS { SolverFactory::SolverFactory() { return; } SolverFactory::~SolverFactory() { return; } std::tr1::shared_ptr<Solver> SolverFactory::build(const GetPot& input) { bool mesh_adaptive = input("MeshAdaptivity/mesh_adaptive", false ); bool transient = input("unsteady-solver/transient", false ); std::tr1::shared_ptr<Solver> solver; // Effectively NULL std::string solver_type = input("SolverOptions/solver_type", "DIE!"); if( solver_type == std::string("displacement_continuation") ) { solver.reset( new DisplacementContinuationSolver(input) ); } else if(transient && !mesh_adaptive) { solver.reset( new UnsteadySolver(input) ); } else if( !transient && !mesh_adaptive ) { solver.reset( new SteadySolver(input) ); } else if( !transient && mesh_adaptive ) { solver.reset( new SteadyMeshAdaptiveSolver(input) ); } else if( transient && mesh_adaptive ) { libmesh_not_implemented(); } else { std::cerr << "Invalid solver options!" << std::endl; } return solver; } } // namespace GRINS <|endoftext|>
<commit_before>#include "genstoreDefines.sqf" class genstored { idd = genstore_DIALOG; movingEnable = true; enableSimulation = true; onLoad = "[0] execVM 'client\systems\generalStore\populateGenStore.sqf'"; class controlsBackground { class MainBackground: w_RscPicture { idc = -1; colorText[] = {1, 1, 1, 1}; colorBackground[] = {0,0,0,0}; text = "#(argb,8,8,3)color(0,0,0,0.6)"; moving = true; x = 0.1875 * safezoneW + safezoneX; y = 0.15 * safezoneH + safezoneY; w = 0.55 * safezoneW; h = 0.65 * safezoneH; }; class TopBar: w_RscPicture { idc = -1; colorText[] = {1, 1, 1, 1}; colorBackground[] = {0,0,0,0}; text = "#(argb,8,8,3)color(0.25,0.51,0.96,0.8)"; x = 0.1875 * safezoneW + safezoneX; y = 0.15 * safezoneH + safezoneY; w = 0.55 * safezoneW; h = 0.05 * safezoneH; }; class DialogTitleText: w_RscText { idc = -1; text = "General Store Menu"; font = "PuristaMedium"; sizeEx = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; x = 0.20 * safezoneW + safezoneX; y = 0.155 * safezoneH + safezoneY; w = 0.19 * safezoneW; h = 0.0448148 * safezoneH; }; class PlayerMoneyText: w_RscText { idc = genstore_money; text = "Cash:"; font = "PuristaMedium"; sizeEx = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; x = 0.640 * safezoneW + safezoneX; y = 0.155 * safezoneH + safezoneY; w = 0.0844792 * safezoneW; h = 0.0448148 * safezoneH; }; class ItemSelectedPrice: w_RscStructuredTextLeft { idc = genstore_item_TEXT; text = ""; x = 0.299 * safezoneW + safezoneX; y = 0.664 * safezoneH + safezoneY; w = 0.0891667 * safezoneW; h = 0.068889 * safezoneH; }; class SellSelectedPrice: w_RscStructuredTextLeft { idc = genstore_sell_TEXT; text = ""; x = 0.517 * safezoneW + safezoneX; y = 0.664 * safezoneH + safezoneY; w = 0.0891667 * safezoneW; h = 0.068889 * safezoneH; }; }; class controls { class SelectionList: w_RscList { idc = genstore_item_list; onLBSelChanged = "[] execvm 'client\systems\generalStore\itemInfo.sqf'"; font = "PuristaMedium"; sizeEx = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; x = 0.3025 * safezoneW + safezoneX; y = 0.225 * safezoneH + safezoneY; w = 0.207 * safezoneW; h = 0.338222 * safezoneH; }; class ItemDescription: w_RscStructuredTextLeft { idc = genstore_item_desc; text = ""; sizeEx = 0.02; colorBackground[] = { 0, 0, 0, 0.1 }; x = 0.3025 * safezoneW + safezoneX; y = 0.567 * safezoneH + safezoneY; w = 0.207 * safezoneW; h = 0.088 * safezoneH; }; class SellList: w_RscList { idc = genstore_sell_list; onLBSelChanged = "[] execvm 'client\systems\generalStore\sellInfo.sqf'"; font = "PuristaMedium"; sizeEx = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; x = 0.520 * safezoneW + safezoneX; y = 0.225 * safezoneH + safezoneY; w = 0.207 * safezoneW; h = 0.422222 * safezoneH; }; class SellWeapon: w_RscButton { idc = -1; onButtonClick = "[] execVM 'client\systems\selling\sellWeapon.sqf'"; text = "Sell Weapon"; x = 0.360 * safezoneW + safezoneX; y = 0.740 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class SellUniform: w_RscButton { idc = -1; onButtonClick = "[] execVM 'client\systems\selling\sellUniform.sqf'"; text = "Sell Uniform"; x = 0.453 * safezoneW + safezoneX; y = 0.740 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class SellVest: w_RscButton { idc = -1; onButtonClick = "[] execVM 'client\systems\selling\sellVest.sqf'"; text = "Sell Vest"; x = 0.546 * safezoneW + safezoneX; y = 0.740 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class SellBackpack: w_RscButton { idc = -1; onButtonClick = "[] execVM 'client\systems\selling\sellBackpack.sqf'"; text = "Sell Backpack"; x = 0.639 * safezoneW + safezoneX; y = 0.740 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class CancelButton : w_RscButton { idc = -1; text = "Cancel"; onButtonClick = "closeDialog 0;"; x = 0.20 * safezoneW + safezoneX; y = 0.740 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class SellItem: w_RscButton { idc = genstore_sell; onButtonClick = "[0] execVM 'client\systems\generalStore\sellItems.sqf'"; text = "Sell"; x = 0.655 * safezoneW + safezoneX; y = 0.657 * safezoneH + safezoneY; w = 0.072 * safezoneW; h = 0.040 * safezoneH; }; class BuyItem: w_RscButton { idc = -1; onButtonClick = "[0] execVM 'client\systems\generalStore\buyItems.sqf'"; text = "Buy"; x = 0.438 * safezoneW + safezoneX; y = 0.657 * safezoneH + safezoneY; w = 0.072 * safezoneW; h = 0.040 * safezoneH; }; class StoreButton0: w_RscButton { idc = -1; onButtonClick = "[0] execVM 'client\systems\generalStore\populateGenStore.sqf'"; text = "Headgear"; x = 0.20 * safezoneW + safezoneX; y = 0.225 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class StoreButton1: w_RscButton { idc = -1; onButtonClick = "[1] execVM 'client\systems\generalStore\populateGenStore.sqf'"; text = "Uniforms"; x = 0.20 * safezoneW + safezoneX; y = 0.275 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class StoreButton2: w_RscButton { idc = -1; onButtonClick = "[2] execVM 'client\systems\generalStore\populateGenStore.sqf'"; text = "Vests"; x = 0.20 * safezoneW + safezoneX; y = 0.325 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class StoreButton3: w_RscButton { idc = -1; onButtonClick = "[3] execVM 'client\systems\generalStore\populateGenStore.sqf'"; text = "Backpacks"; x = 0.20 * safezoneW + safezoneX; y = 0.375 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class StoreButton4: w_RscButton { idc = -1; onButtonClick = "[4] execVM 'client\systems\generalStore\populateGenStore.sqf'"; text = "Equipment"; x = 0.20 * safezoneW + safezoneX; y = 0.425 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class StoreButton5: w_RscButton { idc = -1; onButtonClick = "[5] execVM 'client\systems\generalStore\populateGenStore.sqf'"; text = "Items"; x = 0.20 * safezoneW + safezoneX; y = 0.475 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class StoreButton6: w_RscButton { idc = -1; onButtonClick = "[6] execVM 'client\systems\generalStore\populateGenStore.sqf'"; text = "Objects"; x = 0.20 * safezoneW + safezoneX; y = 0.525 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; }; }; <commit_msg>Changed genstore categories text<commit_after>#include "genstoreDefines.sqf" class genstored { idd = genstore_DIALOG; movingEnable = true; enableSimulation = true; onLoad = "[0] execVM 'client\systems\generalStore\populateGenStore.sqf'"; class controlsBackground { class MainBackground: w_RscPicture { idc = -1; colorText[] = {1, 1, 1, 1}; colorBackground[] = {0,0,0,0}; text = "#(argb,8,8,3)color(0,0,0,0.6)"; moving = true; x = 0.1875 * safezoneW + safezoneX; y = 0.15 * safezoneH + safezoneY; w = 0.55 * safezoneW; h = 0.65 * safezoneH; }; class TopBar: w_RscPicture { idc = -1; colorText[] = {1, 1, 1, 1}; colorBackground[] = {0,0,0,0}; text = "#(argb,8,8,3)color(0.25,0.51,0.96,0.8)"; x = 0.1875 * safezoneW + safezoneX; y = 0.15 * safezoneH + safezoneY; w = 0.55 * safezoneW; h = 0.05 * safezoneH; }; class DialogTitleText: w_RscText { idc = -1; text = "General Store Menu"; font = "PuristaMedium"; sizeEx = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; x = 0.20 * safezoneW + safezoneX; y = 0.155 * safezoneH + safezoneY; w = 0.19 * safezoneW; h = 0.0448148 * safezoneH; }; class PlayerMoneyText: w_RscText { idc = genstore_money; text = "Cash:"; font = "PuristaMedium"; sizeEx = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; x = 0.640 * safezoneW + safezoneX; y = 0.155 * safezoneH + safezoneY; w = 0.0844792 * safezoneW; h = 0.0448148 * safezoneH; }; class ItemSelectedPrice: w_RscStructuredTextLeft { idc = genstore_item_TEXT; text = ""; x = 0.299 * safezoneW + safezoneX; y = 0.664 * safezoneH + safezoneY; w = 0.0891667 * safezoneW; h = 0.068889 * safezoneH; }; class SellSelectedPrice: w_RscStructuredTextLeft { idc = genstore_sell_TEXT; text = ""; x = 0.517 * safezoneW + safezoneX; y = 0.664 * safezoneH + safezoneY; w = 0.0891667 * safezoneW; h = 0.068889 * safezoneH; }; }; class controls { class SelectionList: w_RscList { idc = genstore_item_list; onLBSelChanged = "[] execvm 'client\systems\generalStore\itemInfo.sqf'"; font = "PuristaMedium"; sizeEx = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; x = 0.3025 * safezoneW + safezoneX; y = 0.225 * safezoneH + safezoneY; w = 0.207 * safezoneW; h = 0.338222 * safezoneH; }; class ItemDescription: w_RscStructuredTextLeft { idc = genstore_item_desc; text = ""; sizeEx = 0.02; colorBackground[] = { 0, 0, 0, 0.1 }; x = 0.3025 * safezoneW + safezoneX; y = 0.567 * safezoneH + safezoneY; w = 0.207 * safezoneW; h = 0.088 * safezoneH; }; class SellList: w_RscList { idc = genstore_sell_list; onLBSelChanged = "[] execvm 'client\systems\generalStore\sellInfo.sqf'"; font = "PuristaMedium"; sizeEx = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; x = 0.520 * safezoneW + safezoneX; y = 0.225 * safezoneH + safezoneY; w = 0.207 * safezoneW; h = 0.422222 * safezoneH; }; class SellWeapon: w_RscButton { idc = -1; onButtonClick = "[] execVM 'client\systems\selling\sellWeapon.sqf'"; text = "Sell Weapon"; x = 0.360 * safezoneW + safezoneX; y = 0.740 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class SellUniform: w_RscButton { idc = -1; onButtonClick = "[] execVM 'client\systems\selling\sellUniform.sqf'"; text = "Sell Uniform"; x = 0.453 * safezoneW + safezoneX; y = 0.740 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class SellVest: w_RscButton { idc = -1; onButtonClick = "[] execVM 'client\systems\selling\sellVest.sqf'"; text = "Sell Vest"; x = 0.546 * safezoneW + safezoneX; y = 0.740 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class SellBackpack: w_RscButton { idc = -1; onButtonClick = "[] execVM 'client\systems\selling\sellBackpack.sqf'"; text = "Sell Backpack"; x = 0.639 * safezoneW + safezoneX; y = 0.740 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class CancelButton : w_RscButton { idc = -1; text = "Cancel"; onButtonClick = "closeDialog 0;"; x = 0.20 * safezoneW + safezoneX; y = 0.740 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class SellItem: w_RscButton { idc = genstore_sell; onButtonClick = "[0] execVM 'client\systems\generalStore\sellItems.sqf'"; text = "Sell"; x = 0.655 * safezoneW + safezoneX; y = 0.657 * safezoneH + safezoneY; w = 0.072 * safezoneW; h = 0.040 * safezoneH; }; class BuyItem: w_RscButton { idc = -1; onButtonClick = "[0] execVM 'client\systems\generalStore\buyItems.sqf'"; text = "Buy"; x = 0.438 * safezoneW + safezoneX; y = 0.657 * safezoneH + safezoneY; w = 0.072 * safezoneW; h = 0.040 * safezoneH; }; class StoreButton0: w_RscButton { idc = -1; onButtonClick = "[0] execVM 'client\systems\generalStore\populateGenStore.sqf'"; text = "Headgear"; x = 0.20 * safezoneW + safezoneX; y = 0.225 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class StoreButton1: w_RscButton { idc = -1; onButtonClick = "[1] execVM 'client\systems\generalStore\populateGenStore.sqf'"; text = "Uniforms"; x = 0.20 * safezoneW + safezoneX; y = 0.275 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class StoreButton2: w_RscButton { idc = -1; onButtonClick = "[2] execVM 'client\systems\generalStore\populateGenStore.sqf'"; text = "Vests"; x = 0.20 * safezoneW + safezoneX; y = 0.325 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class StoreButton3: w_RscButton { idc = -1; onButtonClick = "[3] execVM 'client\systems\generalStore\populateGenStore.sqf'"; text = "Backpacks"; x = 0.20 * safezoneW + safezoneX; y = 0.375 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class StoreButton4: w_RscButton { idc = -1; onButtonClick = "[4] execVM 'client\systems\generalStore\populateGenStore.sqf'"; text = "Items"; x = 0.20 * safezoneW + safezoneX; y = 0.425 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class StoreButton5: w_RscButton { idc = -1; onButtonClick = "[5] execVM 'client\systems\generalStore\populateGenStore.sqf'"; text = "Supplies"; x = 0.20 * safezoneW + safezoneX; y = 0.475 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; class StoreButton6: w_RscButton { idc = -1; onButtonClick = "[6] execVM 'client\systems\generalStore\populateGenStore.sqf'"; text = "Objects"; x = 0.20 * safezoneW + safezoneX; y = 0.525 * safezoneH + safezoneY; w = 0.088 * safezoneW; h = 0.040 * safezoneH; }; }; }; <|endoftext|>
<commit_before> #include <iostream> using namespace std; void main() { cout << "Hello World" << endl; } <commit_msg>update func1<commit_after> #include <iostream> using namespace std; void func1() { cout << "func1" << endl; } void main() { cout << "Hello World" << endl; func1(); } <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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 #include "libmesh/diff_system.h" #include "libmesh/dof_map.h" #include "libmesh/libmesh_logging.h" #include "libmesh/petsc_diff_solver.h" #include "libmesh/petsc_matrix.h" #include "libmesh/petsc_vector.h" #include "libmesh/petsc_auto_fieldsplit.h" #ifdef LIBMESH_HAVE_PETSC namespace libMesh { //-------------------------------------------------------------------- // Functions with C linkage to pass to PETSc. PETSc will call these // methods as needed. // // Since they must have C linkage they have no knowledge of a namespace. // Give them an obscure name to avoid namespace pollution. extern "C" { // Older versions of PETSc do not have the different int typedefs. // On 64-bit machines, PetscInt may actually be a long long int. // This change occurred in Petsc-2.2.1. #if PETSC_VERSION_LESS_THAN(2,2,1) typedef int PetscErrorCode; typedef int PetscInt; #endif // Function to hand to PETSc's SNES, // which monitors convergence at X PetscErrorCode __libmesh_petsc_diff_solver_monitor (SNES snes, PetscInt its, PetscReal fnorm, void *ctx) { PetscDiffSolver& solver = *(static_cast<PetscDiffSolver*> (ctx)); if (solver.verbose) libMesh::out << " PetscDiffSolver step " << its << ", |residual|_2 = " << fnorm << std::endl; if (solver.linear_solution_monitor.get()) { int ierr = 0; Vec petsc_delta_u; ierr = SNESGetSolutionUpdate(snes, &petsc_delta_u); CHKERRABORT(solver.comm().get(), ierr); PetscVector<Number> delta_u(petsc_delta_u, solver.comm()); delta_u.close(); Vec petsc_u; ierr = SNESGetSolution(snes, &petsc_u); CHKERRABORT(solver.comm().get(), ierr); PetscVector<Number> u(petsc_u, solver.comm()); u.close(); Vec petsc_res; ierr = SNESGetFunction(snes, &petsc_res, NULL, NULL); CHKERRABORT(solver.comm().get(), ierr); PetscVector<Number> res(petsc_res, solver.comm()); res.close(); (*solver.linear_solution_monitor)( delta_u, delta_u.l2_norm(), u, u.l2_norm(), res, res.l2_norm(), its); } return 0; } // Functions to hand to PETSc's SNES, // which compute the residual or jacobian at X PetscErrorCode __libmesh_petsc_diff_solver_residual (SNES, Vec x, Vec r, void *ctx) { libmesh_assert(x); libmesh_assert(r); libmesh_assert(ctx); PetscDiffSolver& solver = *(static_cast<PetscDiffSolver*> (ctx)); ImplicitSystem &sys = solver.system(); if (solver.verbose) libMesh::out << "Assembling the residual" << std::endl; PetscVector<Number>& X_system = *cast_ptr<PetscVector<Number>*>(sys.solution.get()); PetscVector<Number>& R_system = *cast_ptr<PetscVector<Number>*>(sys.rhs); PetscVector<Number> X_input(x, sys.comm()), R_input(r, sys.comm()); // DiffSystem assembles from the solution and into the rhs, so swap // those with our input vectors before assembling. They'll probably // already be references to the same vectors, but PETSc might do // something tricky. X_input.swap(X_system); R_input.swap(R_system); // We may need to correct a non-conforming solution sys.get_dof_map().enforce_constraints_exactly(sys); // We may need to localize a parallel solution sys.update(); // Do DiffSystem assembly sys.assembly(true, false); R_system.close(); // Swap back X_input.swap(X_system); R_input.swap(R_system); // No errors, we hope return 0; } #if PETSC_RELEASE_LESS_THAN(3,5,0) PetscErrorCode __libmesh_petsc_diff_solver_jacobian (SNES, Vec x, Mat *libmesh_dbg_var(j), Mat *pc, MatStructure *msflag, void *ctx) #else PetscErrorCode __libmesh_petsc_diff_solver_jacobian (SNES, Vec x, Mat libmesh_dbg_var(j), Mat pc, void *ctx) #endif { libmesh_assert(x); libmesh_assert(j); // libmesh_assert_equal_to (pc, j); // We don't use separate preconditioners yet libmesh_assert(ctx); PetscDiffSolver& solver = *(static_cast<PetscDiffSolver*> (ctx)); ImplicitSystem &sys = solver.system(); if (solver.verbose) libMesh::out << "Assembling the Jacobian" << std::endl; PetscVector<Number>& X_system = *cast_ptr<PetscVector<Number>*>(sys.solution.get()); PetscVector<Number> X_input(x, sys.comm()); #if PETSC_RELEASE_LESS_THAN(3,5,0) PetscMatrix<Number> J_input(*pc, sys.comm()); #else PetscMatrix<Number> J_input(pc, sys.comm()); #endif PetscMatrix<Number>& J_system = *cast_ptr<PetscMatrix<Number>*>(sys.matrix); // DiffSystem assembles from the solution and into the jacobian, so // swap those with our input vectors before assembling. They'll // probably already be references to the same vectors, but PETSc // might do something tricky. X_input.swap(X_system); J_input.swap(J_system); // We may need to correct a non-conforming solution sys.get_dof_map().enforce_constraints_exactly(sys); // We may need to localize a parallel solution sys.update(); // Do DiffSystem assembly sys.assembly(false, true); J_system.close(); // Swap back X_input.swap(X_system); J_input.swap(J_system); #if PETSC_RELEASE_LESS_THAN(3,5,0) *msflag = SAME_NONZERO_PATTERN; #endif // No errors, we hope return 0; } } // extern "C" PetscDiffSolver::PetscDiffSolver (sys_type& s) : Parent(s) { } void PetscDiffSolver::init () { START_LOG("init()", "PetscDiffSolver"); Parent::init(); int ierr=0; #if PETSC_VERSION_LESS_THAN(2,1,2) // At least until Petsc 2.1.1, the SNESCreate had a different // calling syntax. The second argument was of type SNESProblemType, // and could have a value of either SNES_NONLINEAR_EQUATIONS or // SNES_UNCONSTRAINED_MINIMIZATION. ierr = SNESCreate(this->comm().get(), SNES_NONLINEAR_EQUATIONS, &_snes); LIBMESH_CHKERRABORT(ierr); #else ierr = SNESCreate(this->comm().get(),&_snes); LIBMESH_CHKERRABORT(ierr); #endif #if PETSC_VERSION_LESS_THAN(2,3,3) ierr = SNESSetMonitor (_snes, __libmesh_petsc_diff_solver_monitor, this, PETSC_NULL); #else // API name change in PETSc 2.3.3 ierr = SNESMonitorSet (_snes, __libmesh_petsc_diff_solver_monitor, this, PETSC_NULL); #endif LIBMESH_CHKERRABORT(ierr); if (libMesh::on_command_line("--solver_system_names")) { ierr = SNESSetOptionsPrefix(_snes, (_system.name()+"_").c_str()); LIBMESH_CHKERRABORT(ierr); } ierr = SNESSetFromOptions(_snes); LIBMESH_CHKERRABORT(ierr); KSP my_ksp; ierr = SNESGetKSP(_snes, &my_ksp); LIBMESH_CHKERRABORT(ierr); PC my_pc; ierr = KSPGetPC(my_ksp, &my_pc); LIBMESH_CHKERRABORT(ierr); petsc_auto_fieldsplit(my_pc, _system); STOP_LOG("init()", "PetscDiffSolver"); } PetscDiffSolver::~PetscDiffSolver () { } void PetscDiffSolver::clear() { START_LOG("clear()", "PetscDiffSolver"); int ierr = LibMeshSNESDestroy(&_snes); LIBMESH_CHKERRABORT(ierr); STOP_LOG("clear()", "PetscDiffSolver"); } void PetscDiffSolver::reinit() { Parent::reinit(); KSP my_ksp; int ierr = SNESGetKSP(_snes, &my_ksp); LIBMESH_CHKERRABORT(ierr); PC my_pc; ierr = KSPGetPC(my_ksp, &my_pc); LIBMESH_CHKERRABORT(ierr); petsc_auto_fieldsplit(my_pc, _system); } DiffSolver::SolveResult convert_solve_result(SNESConvergedReason r) { switch (r) { case SNES_CONVERGED_FNORM_ABS: return DiffSolver::CONVERGED_ABSOLUTE_RESIDUAL; case SNES_CONVERGED_FNORM_RELATIVE: return DiffSolver::CONVERGED_RELATIVE_RESIDUAL; #if PETSC_VERSION_LESS_THAN(3,2,1) case SNES_CONVERGED_PNORM_RELATIVE: #else case SNES_CONVERGED_SNORM_RELATIVE: #endif return DiffSolver::CONVERGED_RELATIVE_STEP; #if !PETSC_VERSION_LESS_THAN(2,3,3) case SNES_CONVERGED_ITS: #endif case SNES_CONVERGED_TR_DELTA: return DiffSolver::CONVERGED_NO_REASON; case SNES_DIVERGED_FUNCTION_DOMAIN: case SNES_DIVERGED_FUNCTION_COUNT: case SNES_DIVERGED_FNORM_NAN: #if !PETSC_VERSION_LESS_THAN(3,3,0) case SNES_DIVERGED_INNER: #endif #if !PETSC_VERSION_LESS_THAN(2,3,2) case SNES_DIVERGED_LINEAR_SOLVE: #endif case SNES_DIVERGED_LOCAL_MIN: return DiffSolver::DIVERGED_NO_REASON; case SNES_DIVERGED_MAX_IT: return DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS; #if PETSC_VERSION_LESS_THAN(3,2,0) case SNES_DIVERGED_LS_FAILURE: #else case SNES_DIVERGED_LINE_SEARCH: #endif return DiffSolver::DIVERGED_BACKTRACKING_FAILURE; // In PETSc, SNES_CONVERGED_ITERATING means // the solve is still iterating, but by the // time we get here, we must have either // converged or diverged, so // SNES_CONVERGED_ITERATING is invalid. case SNES_CONVERGED_ITERATING: return DiffSolver::INVALID_SOLVE_RESULT; default: } return DiffSolver::INVALID_SOLVE_RESULT; } unsigned int PetscDiffSolver::solve() { this->init(); START_LOG("solve()", "PetscDiffSolver"); PetscVector<Number> &x = *(cast_ptr<PetscVector<Number>*>(_system.solution.get())); PetscMatrix<Number> &jac = *(cast_ptr<PetscMatrix<Number>*>(_system.matrix)); PetscVector<Number> &r = *(cast_ptr<PetscVector<Number>*>(_system.rhs)); #ifdef LIBMESH_ENABLE_CONSTRAINTS _system.get_dof_map().enforce_constraints_exactly(_system); #endif int ierr = 0; ierr = SNESSetFunction (_snes, r.vec(), __libmesh_petsc_diff_solver_residual, this); LIBMESH_CHKERRABORT(ierr); ierr = SNESSetJacobian (_snes, jac.mat(), jac.mat(), __libmesh_petsc_diff_solver_jacobian, this); LIBMESH_CHKERRABORT(ierr); # if PETSC_VERSION_LESS_THAN(2,2,0) ierr = SNESSolve (_snes, x.vec(), &_outer_iterations); LIBMESH_CHKERRABORT(ierr); // 2.2.x style #elif PETSC_VERSION_LESS_THAN(2,3,0) ierr = SNESSolve (_snes, x.vec()); LIBMESH_CHKERRABORT(ierr); // 2.3.x & newer style #else ierr = SNESSolve (_snes, PETSC_NULL, x.vec()); LIBMESH_CHKERRABORT(ierr); #endif STOP_LOG("solve()", "PetscDiffSolver"); SNESConvergedReason reason; SNESGetConvergedReason(_snes, &reason); this->clear(); return convert_solve_result(reason); } } // namespace libMesh #endif // LIBMESH_HAVE_PETSC <commit_msg>Fix syntax for missing-default warning fix<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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 #include "libmesh/diff_system.h" #include "libmesh/dof_map.h" #include "libmesh/libmesh_logging.h" #include "libmesh/petsc_diff_solver.h" #include "libmesh/petsc_matrix.h" #include "libmesh/petsc_vector.h" #include "libmesh/petsc_auto_fieldsplit.h" #ifdef LIBMESH_HAVE_PETSC namespace libMesh { //-------------------------------------------------------------------- // Functions with C linkage to pass to PETSc. PETSc will call these // methods as needed. // // Since they must have C linkage they have no knowledge of a namespace. // Give them an obscure name to avoid namespace pollution. extern "C" { // Older versions of PETSc do not have the different int typedefs. // On 64-bit machines, PetscInt may actually be a long long int. // This change occurred in Petsc-2.2.1. #if PETSC_VERSION_LESS_THAN(2,2,1) typedef int PetscErrorCode; typedef int PetscInt; #endif // Function to hand to PETSc's SNES, // which monitors convergence at X PetscErrorCode __libmesh_petsc_diff_solver_monitor (SNES snes, PetscInt its, PetscReal fnorm, void *ctx) { PetscDiffSolver& solver = *(static_cast<PetscDiffSolver*> (ctx)); if (solver.verbose) libMesh::out << " PetscDiffSolver step " << its << ", |residual|_2 = " << fnorm << std::endl; if (solver.linear_solution_monitor.get()) { int ierr = 0; Vec petsc_delta_u; ierr = SNESGetSolutionUpdate(snes, &petsc_delta_u); CHKERRABORT(solver.comm().get(), ierr); PetscVector<Number> delta_u(petsc_delta_u, solver.comm()); delta_u.close(); Vec petsc_u; ierr = SNESGetSolution(snes, &petsc_u); CHKERRABORT(solver.comm().get(), ierr); PetscVector<Number> u(petsc_u, solver.comm()); u.close(); Vec petsc_res; ierr = SNESGetFunction(snes, &petsc_res, NULL, NULL); CHKERRABORT(solver.comm().get(), ierr); PetscVector<Number> res(petsc_res, solver.comm()); res.close(); (*solver.linear_solution_monitor)( delta_u, delta_u.l2_norm(), u, u.l2_norm(), res, res.l2_norm(), its); } return 0; } // Functions to hand to PETSc's SNES, // which compute the residual or jacobian at X PetscErrorCode __libmesh_petsc_diff_solver_residual (SNES, Vec x, Vec r, void *ctx) { libmesh_assert(x); libmesh_assert(r); libmesh_assert(ctx); PetscDiffSolver& solver = *(static_cast<PetscDiffSolver*> (ctx)); ImplicitSystem &sys = solver.system(); if (solver.verbose) libMesh::out << "Assembling the residual" << std::endl; PetscVector<Number>& X_system = *cast_ptr<PetscVector<Number>*>(sys.solution.get()); PetscVector<Number>& R_system = *cast_ptr<PetscVector<Number>*>(sys.rhs); PetscVector<Number> X_input(x, sys.comm()), R_input(r, sys.comm()); // DiffSystem assembles from the solution and into the rhs, so swap // those with our input vectors before assembling. They'll probably // already be references to the same vectors, but PETSc might do // something tricky. X_input.swap(X_system); R_input.swap(R_system); // We may need to correct a non-conforming solution sys.get_dof_map().enforce_constraints_exactly(sys); // We may need to localize a parallel solution sys.update(); // Do DiffSystem assembly sys.assembly(true, false); R_system.close(); // Swap back X_input.swap(X_system); R_input.swap(R_system); // No errors, we hope return 0; } #if PETSC_RELEASE_LESS_THAN(3,5,0) PetscErrorCode __libmesh_petsc_diff_solver_jacobian (SNES, Vec x, Mat *libmesh_dbg_var(j), Mat *pc, MatStructure *msflag, void *ctx) #else PetscErrorCode __libmesh_petsc_diff_solver_jacobian (SNES, Vec x, Mat libmesh_dbg_var(j), Mat pc, void *ctx) #endif { libmesh_assert(x); libmesh_assert(j); // libmesh_assert_equal_to (pc, j); // We don't use separate preconditioners yet libmesh_assert(ctx); PetscDiffSolver& solver = *(static_cast<PetscDiffSolver*> (ctx)); ImplicitSystem &sys = solver.system(); if (solver.verbose) libMesh::out << "Assembling the Jacobian" << std::endl; PetscVector<Number>& X_system = *cast_ptr<PetscVector<Number>*>(sys.solution.get()); PetscVector<Number> X_input(x, sys.comm()); #if PETSC_RELEASE_LESS_THAN(3,5,0) PetscMatrix<Number> J_input(*pc, sys.comm()); #else PetscMatrix<Number> J_input(pc, sys.comm()); #endif PetscMatrix<Number>& J_system = *cast_ptr<PetscMatrix<Number>*>(sys.matrix); // DiffSystem assembles from the solution and into the jacobian, so // swap those with our input vectors before assembling. They'll // probably already be references to the same vectors, but PETSc // might do something tricky. X_input.swap(X_system); J_input.swap(J_system); // We may need to correct a non-conforming solution sys.get_dof_map().enforce_constraints_exactly(sys); // We may need to localize a parallel solution sys.update(); // Do DiffSystem assembly sys.assembly(false, true); J_system.close(); // Swap back X_input.swap(X_system); J_input.swap(J_system); #if PETSC_RELEASE_LESS_THAN(3,5,0) *msflag = SAME_NONZERO_PATTERN; #endif // No errors, we hope return 0; } } // extern "C" PetscDiffSolver::PetscDiffSolver (sys_type& s) : Parent(s) { } void PetscDiffSolver::init () { START_LOG("init()", "PetscDiffSolver"); Parent::init(); int ierr=0; #if PETSC_VERSION_LESS_THAN(2,1,2) // At least until Petsc 2.1.1, the SNESCreate had a different // calling syntax. The second argument was of type SNESProblemType, // and could have a value of either SNES_NONLINEAR_EQUATIONS or // SNES_UNCONSTRAINED_MINIMIZATION. ierr = SNESCreate(this->comm().get(), SNES_NONLINEAR_EQUATIONS, &_snes); LIBMESH_CHKERRABORT(ierr); #else ierr = SNESCreate(this->comm().get(),&_snes); LIBMESH_CHKERRABORT(ierr); #endif #if PETSC_VERSION_LESS_THAN(2,3,3) ierr = SNESSetMonitor (_snes, __libmesh_petsc_diff_solver_monitor, this, PETSC_NULL); #else // API name change in PETSc 2.3.3 ierr = SNESMonitorSet (_snes, __libmesh_petsc_diff_solver_monitor, this, PETSC_NULL); #endif LIBMESH_CHKERRABORT(ierr); if (libMesh::on_command_line("--solver_system_names")) { ierr = SNESSetOptionsPrefix(_snes, (_system.name()+"_").c_str()); LIBMESH_CHKERRABORT(ierr); } ierr = SNESSetFromOptions(_snes); LIBMESH_CHKERRABORT(ierr); KSP my_ksp; ierr = SNESGetKSP(_snes, &my_ksp); LIBMESH_CHKERRABORT(ierr); PC my_pc; ierr = KSPGetPC(my_ksp, &my_pc); LIBMESH_CHKERRABORT(ierr); petsc_auto_fieldsplit(my_pc, _system); STOP_LOG("init()", "PetscDiffSolver"); } PetscDiffSolver::~PetscDiffSolver () { } void PetscDiffSolver::clear() { START_LOG("clear()", "PetscDiffSolver"); int ierr = LibMeshSNESDestroy(&_snes); LIBMESH_CHKERRABORT(ierr); STOP_LOG("clear()", "PetscDiffSolver"); } void PetscDiffSolver::reinit() { Parent::reinit(); KSP my_ksp; int ierr = SNESGetKSP(_snes, &my_ksp); LIBMESH_CHKERRABORT(ierr); PC my_pc; ierr = KSPGetPC(my_ksp, &my_pc); LIBMESH_CHKERRABORT(ierr); petsc_auto_fieldsplit(my_pc, _system); } DiffSolver::SolveResult convert_solve_result(SNESConvergedReason r) { switch (r) { case SNES_CONVERGED_FNORM_ABS: return DiffSolver::CONVERGED_ABSOLUTE_RESIDUAL; case SNES_CONVERGED_FNORM_RELATIVE: return DiffSolver::CONVERGED_RELATIVE_RESIDUAL; #if PETSC_VERSION_LESS_THAN(3,2,1) case SNES_CONVERGED_PNORM_RELATIVE: #else case SNES_CONVERGED_SNORM_RELATIVE: #endif return DiffSolver::CONVERGED_RELATIVE_STEP; #if !PETSC_VERSION_LESS_THAN(2,3,3) case SNES_CONVERGED_ITS: #endif case SNES_CONVERGED_TR_DELTA: return DiffSolver::CONVERGED_NO_REASON; case SNES_DIVERGED_FUNCTION_DOMAIN: case SNES_DIVERGED_FUNCTION_COUNT: case SNES_DIVERGED_FNORM_NAN: #if !PETSC_VERSION_LESS_THAN(3,3,0) case SNES_DIVERGED_INNER: #endif #if !PETSC_VERSION_LESS_THAN(2,3,2) case SNES_DIVERGED_LINEAR_SOLVE: #endif case SNES_DIVERGED_LOCAL_MIN: return DiffSolver::DIVERGED_NO_REASON; case SNES_DIVERGED_MAX_IT: return DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS; #if PETSC_VERSION_LESS_THAN(3,2,0) case SNES_DIVERGED_LS_FAILURE: #else case SNES_DIVERGED_LINE_SEARCH: #endif return DiffSolver::DIVERGED_BACKTRACKING_FAILURE; // In PETSc, SNES_CONVERGED_ITERATING means // the solve is still iterating, but by the // time we get here, we must have either // converged or diverged, so // SNES_CONVERGED_ITERATING is invalid. case SNES_CONVERGED_ITERATING: return DiffSolver::INVALID_SOLVE_RESULT; default: break; } return DiffSolver::INVALID_SOLVE_RESULT; } unsigned int PetscDiffSolver::solve() { this->init(); START_LOG("solve()", "PetscDiffSolver"); PetscVector<Number> &x = *(cast_ptr<PetscVector<Number>*>(_system.solution.get())); PetscMatrix<Number> &jac = *(cast_ptr<PetscMatrix<Number>*>(_system.matrix)); PetscVector<Number> &r = *(cast_ptr<PetscVector<Number>*>(_system.rhs)); #ifdef LIBMESH_ENABLE_CONSTRAINTS _system.get_dof_map().enforce_constraints_exactly(_system); #endif int ierr = 0; ierr = SNESSetFunction (_snes, r.vec(), __libmesh_petsc_diff_solver_residual, this); LIBMESH_CHKERRABORT(ierr); ierr = SNESSetJacobian (_snes, jac.mat(), jac.mat(), __libmesh_petsc_diff_solver_jacobian, this); LIBMESH_CHKERRABORT(ierr); # if PETSC_VERSION_LESS_THAN(2,2,0) ierr = SNESSolve (_snes, x.vec(), &_outer_iterations); LIBMESH_CHKERRABORT(ierr); // 2.2.x style #elif PETSC_VERSION_LESS_THAN(2,3,0) ierr = SNESSolve (_snes, x.vec()); LIBMESH_CHKERRABORT(ierr); // 2.3.x & newer style #else ierr = SNESSolve (_snes, PETSC_NULL, x.vec()); LIBMESH_CHKERRABORT(ierr); #endif STOP_LOG("solve()", "PetscDiffSolver"); SNESConvergedReason reason; SNESGetConvergedReason(_snes, &reason); this->clear(); return convert_solve_result(reason); } } // namespace libMesh #endif // LIBMESH_HAVE_PETSC <|endoftext|>
<commit_before> #include "application.h" SYSTEM_MODE(MANUAL); #include "rgbled.h" #include "RHT03.h" #include "TMP3x.h" #include "OledDisplay.h" #include "font_lcd6x8.h" #include "font_lcd11x16.h" #include "font_12x16_bold.h" #include "common.h" // function prototypes void drawPattern(); void drawText(); void drawTemp(); void getTemp(); int btnUp = D6; int btnDn = D5; int btnHome = D3; bool btnUpLatch = false; bool btnDnLatch = false; bool btnHomeLatch = false; double avgTemp = 0.0; uint drawMode = 0; uint textMode = 0; OledDisplay display = OledDisplay(D1, D2, D0);; RHT03 rht = RHT03(D4, D7); TMP3x tmp36 = TMP3x(A0, 10, 1000); const font_t* font_lcdSm = parseFont(FONT_LCD6X8); const font_t* font_lcdLg = parseFont(FONT_LCD11X16); const font_t* font_bold = parseFont(FONT_12X16_BOLD); void setup() { pinMode(btnUp, INPUT_PULLUP); pinMode(btnDn, INPUT_PULLUP); pinMode(btnHome, INPUT_PULLUP); // Spark.variable("reading", &reading, DOUBLE); // Spark.variable("volts", &volts, DOUBLE); // Spark.variable("temp", &avgTemp, DOUBLE); RGB.control(true); RGB.color(0, 0, 0); display.begin(); } void loop() { tmp36.poll(); if (rht.poll()) { drawTemp(); } // curTime = millis(); // // get temp once per second // if (lastTime + 3000 < curTime) { // lastTime = curTime; // display.clear(CLEAR_OLED); // drawTemp(); // } if (digitalRead(btnHome) == LOW) { if (btnHomeLatch) { // only draw once per press drawPattern(); btnHomeLatch = false; } } else { btnHomeLatch = true; } if (digitalRead(btnUp) == LOW) { RGB.color(0,0,255); if (btnUpLatch) { // only draw once per press drawTemp(); btnUpLatch = false; } } else { btnUpLatch = true; } if (digitalRead(btnDn) == LOW) { RGB.color(255,0,0); if (btnDnLatch) { // only draw once per press drawText(); btnDnLatch = false; } } else { btnDnLatch = true; } } void initStat() { } void drawTemp() { display.clear(CLEAR_OLED); display.setFont(font_lcdLg); char tempStr[8]; double ftemp = tmp36.getTempF(); ftemp = (ftemp / 10); sprintf(tempStr, "%.1f\x7f", ftemp); display.writeText(0, 0, tempStr); ftemp = rht.getTempF(); ftemp = ftemp / 10; sprintf(tempStr, "%.1f\x7f", ftemp); display.writeText(0, 1, tempStr); ftemp = rht.getRH(); ftemp = ftemp / 10; sprintf(tempStr, "%.1f%%", ftemp); display.writeText(0, 2, tempStr); // sprintf(tempStr, "%d.%d ", rht.getIntCount(), rht.getIgnCount()); // display.writeText(1, 4, tempStr); display.display(); } void drawPattern() { display.resetPage(); switch (drawMode) { case 0: // blank page RGB.color(255,0,0); display.clear(CLEAR_BUFF); break; case 1: // horizontal lines RGB.color(0,255,0); display.fill(0xaa); break; case 2: // vertical lines RGB.color(0,0,255); for (int i=0; i<6; i++) { for (int j=0; j<32; j++) { int c = j*2; display.setByte(i, c, 0xff); display.setByte(i, c+1, 0x00); } } break; case 3: {// count RGB.color(255,255,0); byte val = 0x00; for (int i=0; i<6; i++) { for (int j=0; j<64; j++) { display.setByte(i, j, val++); if (val > 0xff) val = 0x00; } } break; } case 4: // diagnal lines RGB.color(255,0,255); for (int i=0; i<6; i++) { for (int j=0; j<8; j++) { int c = j*8; display.setByte(i, c, 0x01); display.setByte(i, c+1, 0x02); display.setByte(i, c+2, 0x04); display.setByte(i, c+3, 0x08); display.setByte(i, c+4, 0x10); display.setByte(i, c+5, 0x20); display.setByte(i, c+6, 0x40); display.setByte(i, c+7, 0x80); } } break; case 5: // progression RGB.color(0,255,255); for (int i=0; i<6; i++) { for (int j=0; j<8; j++) { int c = j*8; display.setByte(i, c, 0x01); display.setByte(i, c+1, 0x03); display.setByte(i, c+2, 0x07); display.setByte(i, c+3, 0x0f); display.setByte(i, c+4, 0x1f); display.setByte(i, c+5, 0x3f); display.setByte(i, c+6, 0x7f); display.setByte(i, c+7, 0xff); } } break; } display.display(); drawMode += 1; if (drawMode > 5) { drawMode = 0; } } void drawText() { display.clear(CLEAR_OLED); // display.setFont(textMode); switch (textMode) { case 0: // small case 1: // med case 2: // bold // RGB.color(textMode==0?255:0, textMode==0?0:255, 0); display.writeText(0, 0, "12345"); display.writeText(0, 1, "Hello"); display.writeText(0, 2, "World"); break; case 3: // large case 4: case 5: // RGB.color(0,0,255); display.writeText(0, 0, "12345"); if (textMode < 5) { display.writeText(0, 1, "67890"); } break; } textMode += 1; if (textMode > 5) { textMode = 0; } } <commit_msg>Use new buttons, layout screen, general cleanup<commit_after> #include "application.h" SYSTEM_MODE(MANUAL); #include "rgbled.h" #include "common.h" #include "RHT03.h" #include "ButtonInterrupt.h" #include "OledDisplay.h" #include "font_lcd6x8.h" #include "font_lcd11x16.h" // function prototypes void drawPattern(); void drawText(); void drawTemp(); void drawSetTemp(); void getTemp(); void handleButtonHome(int mode); void handleButtonUp(int mode); void handleButtonDn(int mode); #define DRAW_CUR_TEMP 1 #define DRAW_SET_TEMP 1 #define DRAW_MENU 2 #define PUFFIN_DEBUG true bool btnHomeToggle = false; int curTemp = 0; int curRH = 0; int setTemp = 72; int setRH = 30; uint drawMode = DRAW_CUR_TEMP; uint textMode = 0; OledDisplay *display; RHT03 *rht; ButtonInterrupt *btnHome; ButtonInterrupt *btnUp; ButtonInterrupt *btnDn; const font_t* font_lcdSm = parseFont(FONT_LCD6X8); const font_t* font_lcdLg = parseFont(FONT_LCD11X16); void setup() { #ifdef PUFFIN_DEBUG Serial.begin(9600); #endif pinMode(D7, OUTPUT); digitalWrite(D7, LOW); RGB.control(true); RGB.color(0, 0, 0); display = new OledDisplay(D1, D2, D0); display->begin(); rht = new RHT03(D3); btnHome = new ButtonInterrupt(D4, 100, &handleButtonHome, 2000, 250); btnUp = new ButtonInterrupt(D6, 100, &handleButtonUp, 2000, 250); btnDn = new ButtonInterrupt(D5, 100, &handleButtonDn, 2000, 250); } void loop() { if (rht->poll()) { getTemp(); if (drawMode == DRAW_CUR_TEMP) { drawTemp(); } } btnHome->poll(); btnUp->poll(); btnDn->poll(); } void initStat() { } void handleButtonHome(int mode) { switch(mode) { case UP: digitalWrite(D7, LOW); break; case FIRST: digitalWrite(D7, HIGH); btnHomeToggle = true; break; case REPEAT: digitalWrite(D7, btnHomeToggle ? HIGH : LOW); btnHomeToggle = !btnHomeToggle; break; default: break; } } void handleButtonUp(int mode) { switch(mode) { case FIRST: case REPEAT: setTemp++; drawSetTemp(); break; default: break; } } void handleButtonDn(int mode) { switch(mode) { case FIRST: case REPEAT: setTemp--; drawSetTemp(); break; default: break; } } void getTemp() { curTemp = rht->getTempF(); curRH = rht->getRH(); // TODO: Send to server } void drawTemp() { // todo: do this only once display->clear(CLEAR_BUFF); display->setFont(font_lcdLg); char tempStr[8]; int ftemp = curTemp; int fdec = ftemp % 10; ftemp = ftemp / 10; display->setFont(font_lcdLg); sprintf(tempStr, "%d.", ftemp); display->writeText(0, 0, tempStr); display->setFont(font_lcdSm); sprintf(tempStr, "%d", fdec); display->writeText(5, 1, tempStr); int rh = curRH; int rhdec = rh % 10; rh = rh / 10; display->setFont(font_lcdLg); sprintf(tempStr, "%d.", rh); display->writeText(0, 1, tempStr); display->setFont(font_lcdSm); sprintf(tempStr, "%d%%", rhdec); display->writeText(5, 3, tempStr); display->setFont(font_lcdSm); const char *curDate = "10/14"; const char *curTime = "12:34"; display->writeText(0, 5, curDate); display->writeText(6, 5, curTime, -3); sprintf(tempStr, "%d", setTemp); display->writeText(8, 0, tempStr, 4); sprintf(tempStr, "%d", setRH); display->writeText(8, 2, tempStr, 4); display->display(); } void drawSetTemp() { char tempStr[8]; sprintf(tempStr, "%d", setTemp); display->writeText(8, 0, tempStr, 4); sprintf(tempStr, "%d", setRH); display->writeText(8, 2, tempStr, 4); display->display(); } <|endoftext|>
<commit_before>// // (c) Copyright 2017 DESY,ESS // // This file is part of h5cpp. // // 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 ofMERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public // License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor // Boston, MA 02110-1301 USA // =========================================================================== // // Authors: // Eugen Wintersberger <[email protected]> // Martin Shetty <[email protected]> // Created on: May 14, 2018 // #include <sstream> #include <h5cpp/datatype/enum.hpp> #include <h5cpp/error/error.hpp> namespace hdf5 { namespace datatype { Enum::Enum(ObjectHandle&& handle) : Datatype(std::move(handle)) {} Enum::Enum(const Datatype& type) : Datatype(type) { if (get_class() != Class::ENUM) { std::stringstream ss; ss << "Cannot create Enum datatype from " << get_class(); throw std::runtime_error(ss.str()); } } Enum Enum::create_underlying(const Datatype& base_type) { hid_t ret = H5Tenum_create(static_cast<hid_t>(base_type)); if (ret < 0) { std::stringstream ss; ss << "Could not create Enum of base type =" << base_type.get_class(); error::Singleton::instance().throw_with_stack(ss.str()); } return Enum(ObjectHandle(ret)); } // implementation same as for Compound size_t Enum::number_of_values() const { int n = H5Tget_nmembers(static_cast<hid_t>(*this)); if (n < 0) { error::Singleton::instance().throw_with_stack("Could not retrieve number of values for enum data type!"); } return static_cast<size_t>(n); } // implementation same as for Compound std::string Enum::name(size_t index) const { char *buffer = H5Tget_member_name(static_cast<hid_t>(*this), static_cast<uint32_t>(index)); if (buffer == nullptr) { std::stringstream ss; ss << "Failure to obtain name of value [" << index << "] in enum data type!"; error::Singleton::instance().throw_with_stack(ss.str()); } std::string name(buffer); if (H5free_memory(buffer) < 0) { std::stringstream ss; ss << "Failure freeing memory for name buffer of field [" << index << "]" << " in enum data type!"; error::Singleton::instance().throw_with_stack(ss.str()); } return name; } bool is_bool(const Enum & etype){ int s = etype.number_of_values(); if (s < 0) { error::Singleton::instance().throw_with_stack("Could not retrieve datatype"); return false; } if(s != 2){ return false; } if(etype.name(0) != "FALSE"){ return false; } if(etype.name(1) != "TRUE"){ return false; } return true; } } // namespace datatype } // namespace hdf5 <commit_msg>remove duplicated checks<commit_after>// // (c) Copyright 2017 DESY,ESS // // This file is part of h5cpp. // // 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 ofMERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public // License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor // Boston, MA 02110-1301 USA // =========================================================================== // // Authors: // Eugen Wintersberger <[email protected]> // Martin Shetty <[email protected]> // Created on: May 14, 2018 // #include <sstream> #include <h5cpp/datatype/enum.hpp> #include <h5cpp/error/error.hpp> namespace hdf5 { namespace datatype { Enum::Enum(ObjectHandle&& handle) : Datatype(std::move(handle)) {} Enum::Enum(const Datatype& type) : Datatype(type) { if (get_class() != Class::ENUM) { std::stringstream ss; ss << "Cannot create Enum datatype from " << get_class(); throw std::runtime_error(ss.str()); } } Enum Enum::create_underlying(const Datatype& base_type) { hid_t ret = H5Tenum_create(static_cast<hid_t>(base_type)); if (ret < 0) { std::stringstream ss; ss << "Could not create Enum of base type =" << base_type.get_class(); error::Singleton::instance().throw_with_stack(ss.str()); } return Enum(ObjectHandle(ret)); } // implementation same as for Compound size_t Enum::number_of_values() const { int n = H5Tget_nmembers(static_cast<hid_t>(*this)); if (n < 0) { error::Singleton::instance().throw_with_stack("Could not retrieve number of values for enum data type!"); } return static_cast<size_t>(n); } // implementation same as for Compound std::string Enum::name(size_t index) const { char *buffer = H5Tget_member_name(static_cast<hid_t>(*this), static_cast<uint32_t>(index)); if (buffer == nullptr) { std::stringstream ss; ss << "Failure to obtain name of value [" << index << "] in enum data type!"; error::Singleton::instance().throw_with_stack(ss.str()); } std::string name(buffer); if (H5free_memory(buffer) < 0) { std::stringstream ss; ss << "Failure freeing memory for name buffer of field [" << index << "]" << " in enum data type!"; error::Singleton::instance().throw_with_stack(ss.str()); } return name; } bool is_bool(const Enum & etype){ int s = etype.number_of_values(); if(s != 2){ return false; } if(etype.name(0) != "FALSE"){ return false; } if(etype.name(1) != "TRUE"){ return false; } return true; } } // namespace datatype } // namespace hdf5 <|endoftext|>
<commit_before>#include "core/global.h" #include "core/messages.h" #include <exception> #include <stdexcept> #include "DistributedObject.h" #include "StateServer.h" ConfigVariable<channel_t> cfg_channel("control", 0); StateServer::StateServer(RoleConfig roleconfig) : Role(roleconfig) { channel_t channel = cfg_channel.get_rval(m_roleconfig); MessageDirector::singleton.subscribe_channel(this, channel); std::stringstream name; name << "StateServer(" << channel << ")"; m_log = new LogCategory("stateserver", name.str()); } StateServer::~StateServer() { delete m_log; } void StateServer::handle_generate(DatagramIterator &dgi, bool has_other) { unsigned int parent_id = dgi.read_uint32(); unsigned int zone_id = dgi.read_uint32(); unsigned short dc_id = dgi.read_uint16(); unsigned int do_id = dgi.read_uint32(); if(dc_id >= gDCF->get_num_classes()) { m_log->error() << "Received create for unknown dclass ID=" << dc_id << std::endl; return; } if(m_objs.find(do_id) != m_objs.end()) { m_log->warning() << "Received generate for already-existing object ID=" << do_id << std::endl; return; } DCClass *dclass = gDCF->get_class(dc_id); DistributedObject *obj; try { obj = new DistributedObject(this, do_id, dclass, parent_id, zone_id, dgi, has_other); } catch(std::exception &e) { m_log->error() << "Received truncated generate for " << dclass->get_name() << "(" << do_id << ")" << std::endl; return; } m_objs[do_id] = obj; } void StateServer::handle_datagram(Datagram &in_dg, DatagramIterator &dgi) { channel_t sender = dgi.read_uint64(); unsigned short msgtype = dgi.read_uint16(); switch(msgtype) { case STATESERVER_OBJECT_GENERATE_WITH_REQUIRED: { handle_generate(dgi, false); break; } case STATESERVER_OBJECT_GENERATE_WITH_REQUIRED_OTHER: { handle_generate(dgi, true); break; } case STATESERVER_SHARD_RESET: { channel_t ai_channel = dgi.read_uint64(); std::set <channel_t> targets; for(auto it = m_objs.begin(); it != m_objs.end(); ++it) if(it->second && it->second->m_ai_channel == ai_channel && it->second->m_ai_explicitly_set) targets.insert(it->second->m_do_id); if(targets.size()) { Datagram dg(targets, sender, STATESERVER_SHARD_RESET); dg.add_uint64(ai_channel); send(dg); } break; } default: m_log->warning() << "Received unknown message: msgtype=" << msgtype << std::endl; } } RoleFactoryItem<StateServer> ss_fact("stateserver"); <commit_msg>StateServer: Fixed includes for clarity, from deletion in unpack_field<commit_after>#include "core/global.h" #include "core/messages.h" #include "dcparser/dcClass.h" #include <exception> #include <stdexcept> #include "DistributedObject.h" #include "StateServer.h" ConfigVariable<channel_t> cfg_channel("control", 0); StateServer::StateServer(RoleConfig roleconfig) : Role(roleconfig) { channel_t channel = cfg_channel.get_rval(m_roleconfig); MessageDirector::singleton.subscribe_channel(this, channel); std::stringstream name; name << "StateServer(" << channel << ")"; m_log = new LogCategory("stateserver", name.str()); } StateServer::~StateServer() { delete m_log; } void StateServer::handle_generate(DatagramIterator &dgi, bool has_other) { unsigned int parent_id = dgi.read_uint32(); unsigned int zone_id = dgi.read_uint32(); unsigned short dc_id = dgi.read_uint16(); unsigned int do_id = dgi.read_uint32(); if(dc_id >= gDCF->get_num_classes()) { m_log->error() << "Received create for unknown dclass ID=" << dc_id << std::endl; return; } if(m_objs.find(do_id) != m_objs.end()) { m_log->warning() << "Received generate for already-existing object ID=" << do_id << std::endl; return; } DCClass *dclass = gDCF->get_class(dc_id); DistributedObject *obj; try { obj = new DistributedObject(this, do_id, dclass, parent_id, zone_id, dgi, has_other); } catch(std::exception &e) { m_log->error() << "Received truncated generate for " << dclass->get_name() << "(" << do_id << ")" << std::endl; return; } m_objs[do_id] = obj; } void StateServer::handle_datagram(Datagram &in_dg, DatagramIterator &dgi) { channel_t sender = dgi.read_uint64(); unsigned short msgtype = dgi.read_uint16(); switch(msgtype) { case STATESERVER_OBJECT_GENERATE_WITH_REQUIRED: { handle_generate(dgi, false); break; } case STATESERVER_OBJECT_GENERATE_WITH_REQUIRED_OTHER: { handle_generate(dgi, true); break; } case STATESERVER_SHARD_RESET: { channel_t ai_channel = dgi.read_uint64(); std::set <channel_t> targets; for(auto it = m_objs.begin(); it != m_objs.end(); ++it) if(it->second && it->second->m_ai_channel == ai_channel && it->second->m_ai_explicitly_set) targets.insert(it->second->m_do_id); if(targets.size()) { Datagram dg(targets, sender, STATESERVER_SHARD_RESET); dg.add_uint64(ai_channel); send(dg); } break; } default: m_log->warning() << "Received unknown message: msgtype=" << msgtype << std::endl; } } RoleFactoryItem<StateServer> ss_fact("stateserver"); <|endoftext|>
<commit_before>/* * Copyright 2006-2011 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "json_loader.h" #include "util/json_parser.h" #include "json_items.h" #include "simple_item_factory.h" #include "store_defs.h" #include "simple_store.h" #include <cassert> #include <vector> namespace zorba { namespace simplestore { namespace json { /****************************************************************************** *******************************************************************************/ JSONLoader::JSONLoader(std::istream& s) : in(s) { } /****************************************************************************** *******************************************************************************/ JSONLoader::~JSONLoader() { } /****************************************************************************** *******************************************************************************/ store::Item_t JSONLoader::next( ) { using namespace zorba::json; using namespace zorba::simplestore; using namespace zorba::simplestore::json; try { BasicItemFactory& lFactory = GET_FACTORY(); JSONItem_t lRootItem; // stack of objects, arrays, and object pairs std::vector<JSONItem_t> lStack; parser lParser(in); token lToken; while (lParser.next(&lToken)) { switch (lToken.get_type()) { case token::begin_array: lStack.push_back(new SimpleJSONArray()); break; case token::begin_object: lStack.push_back(new SimpleJSONObject()); break; case token::end_array: case token::end_object: { JSONItem_t lItem = lStack.back(); lStack.pop_back(); if (lStack.empty()) { lRootItem = lItem; } else { JSONObjectPair* lOPair = cast<JSONObjectPair>(lStack.back()); lOPair->setValue(lItem); lStack.pop_back(); } break; } case token::name_separator: case token::value_separator: break; case token::string: { store::Item_t lValue; zstring s = lToken.get_value(); lFactory.createString(lValue, s); addValue(lStack, lValue); break; } case token::number: { store::Item_t lValue; zstring s = lToken.get_value(); lFactory.createJSONNumber(lValue, s); // todo check return type addValue(lStack, lValue); break; } case token::json_false: { store::Item_t lValue; lFactory.createBoolean(lValue, false); addValue(lStack, lValue); break; } case token::json_true: { store::Item_t lValue; lFactory.createBoolean(lValue, true); addValue(lStack, lValue); break; } case token::json_null: { store::Item_t lValue; lFactory.createJSONNull(lValue); addValue(lStack, lValue); break; } default: assert(false); } } return lRootItem; } catch (zorba::json::exception& e) { std::cerr << e.what() << " at " << e.get_loc() << std::endl; } return NULL; } void JSONLoader::addValue( std::vector<JSONItem_t>& aStack, const store::Item_t& aValue) { JSONItem_t lLast = aStack.back(); JSONObject* lObject = dynamic_cast<JSONObject*>(lLast.getp()); if (lObject) { // if the top of the stack is an object, then // the value must be a string which is the name // of the object's name value pair JSONObjectPair_t lOPair = new SimpleJSONObjectPair(); lOPair->setName(aValue); lObject->add(lOPair); aStack.push_back(lOPair); return; } JSONObjectPair* lOPair = dynamic_cast<JSONObjectPair*>(lLast.getp()); if (lOPair) { lOPair->setValue(aValue); aStack.pop_back(); return; } JSONArray* lArray = dynamic_cast<JSONArray*>(lLast.getp()); assert(lArray); JSONArrayPair_t lArrayPair( new SimpleJSONArrayPair( aValue, lArray ) ); lArray->push_back(lArrayPair); } template<typename T> T* JSONLoader::cast(const JSONItem_t& j) { #ifndef NDEBUG T* t = dynamic_cast<T*>(j.getp()); assert(t); #else T* t = static_cast<T*>(j.getp()); #endif return t; } } /* namespace json */ } /* namespace simplestore */ } /* namespace zorba */ /* * Local variables: * mode: c++ * End: */ /* vim:set et sw=2 ts=2: */ <commit_msg>fix for parsing json sequences<commit_after>/* * Copyright 2006-2011 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "json_loader.h" #include "util/json_parser.h" #include "json_items.h" #include "simple_item_factory.h" #include "store_defs.h" #include "simple_store.h" #include <cassert> #include <vector> namespace zorba { namespace simplestore { namespace json { /****************************************************************************** *******************************************************************************/ JSONLoader::JSONLoader(std::istream& s) : in(s) { } /****************************************************************************** *******************************************************************************/ JSONLoader::~JSONLoader() { } /****************************************************************************** *******************************************************************************/ store::Item_t JSONLoader::next( ) { using namespace zorba::json; using namespace zorba::simplestore; using namespace zorba::simplestore::json; in.peek(); if (in.eof()) { return NULL; } try { BasicItemFactory& lFactory = GET_FACTORY(); JSONItem_t lRootItem; // stack of objects, arrays, and object pairs std::vector<JSONItem_t> lStack; parser lParser(in); token lToken; while (lParser.next(&lToken)) { switch (lToken.get_type()) { case token::begin_array: lStack.push_back(new SimpleJSONArray()); break; case token::begin_object: lStack.push_back(new SimpleJSONObject()); break; case token::end_array: case token::end_object: { JSONItem_t lItem = lStack.back(); lStack.pop_back(); if (lStack.empty()) { lRootItem = lItem; } else { JSONObjectPair* lOPair = cast<JSONObjectPair>(lStack.back()); lOPair->setValue(lItem); lStack.pop_back(); } break; } case token::name_separator: case token::value_separator: break; case token::string: { store::Item_t lValue; zstring s = lToken.get_value(); lFactory.createString(lValue, s); addValue(lStack, lValue); break; } case token::number: { store::Item_t lValue; zstring s = lToken.get_value(); lFactory.createJSONNumber(lValue, s); // todo check return type addValue(lStack, lValue); break; } case token::json_false: { store::Item_t lValue; lFactory.createBoolean(lValue, false); addValue(lStack, lValue); break; } case token::json_true: { store::Item_t lValue; lFactory.createBoolean(lValue, true); addValue(lStack, lValue); break; } case token::json_null: { store::Item_t lValue; lFactory.createJSONNull(lValue); addValue(lStack, lValue); break; } default: assert(false); } } return lRootItem; } catch (zorba::json::exception& e) { std::cerr << e.what() << " at " << e.get_loc() << std::endl; } return NULL; } void JSONLoader::addValue( std::vector<JSONItem_t>& aStack, const store::Item_t& aValue) { JSONItem_t lLast = aStack.back(); JSONObject* lObject = dynamic_cast<JSONObject*>(lLast.getp()); if (lObject) { // if the top of the stack is an object, then // the value must be a string which is the name // of the object's name value pair JSONObjectPair_t lOPair = new SimpleJSONObjectPair(); lOPair->setName(aValue); lObject->add(lOPair); aStack.push_back(lOPair); return; } JSONObjectPair* lOPair = dynamic_cast<JSONObjectPair*>(lLast.getp()); if (lOPair) { lOPair->setValue(aValue); aStack.pop_back(); return; } JSONArray* lArray = dynamic_cast<JSONArray*>(lLast.getp()); assert(lArray); JSONArrayPair_t lArrayPair( new SimpleJSONArrayPair( aValue, lArray ) ); lArray->push_back(lArrayPair); } template<typename T> T* JSONLoader::cast(const JSONItem_t& j) { #ifndef NDEBUG T* t = dynamic_cast<T*>(j.getp()); assert(t); #else T* t = static_cast<T*>(j.getp()); #endif return t; } } /* namespace json */ } /* namespace simplestore */ } /* namespace zorba */ /* * Local variables: * mode: c++ * End: */ /* vim:set et sw=2 ts=2: */ <|endoftext|>
<commit_before>/* Определить функцию для вычисления по формуле Ньютона приблежённого значения арифметического квадратного корня. В формуле Ньютона итерации определяются по формуле r_[n+1] = (r_[n] + x / r_[n]) / 2 Версия для C++ */ #include <iostream> #include <cmath> #include <clocale> const double PRECISION = 0.000000001; /* Объявление функции с именем newton_root. Она принимает один аргумент типа double и возращает значение типа double. Объявление без описания тела функции (блок кода в фигурных скобках) - позволяет делать вызов этой функции в любом месте, до определения самой функции. */ double newton_root(double ); int main() { std::setlocale(LC_ALL, "RUS"); double x, result; std::cout << "Введите x: "; std::cin >> x; // вызываем функцию, передавая ей в качестве аргумента переменную x и сохраняя возращённый ею результат в переменной result result = newton_root(x); std::cout << "Корень из x: " << result; return 0; } /* Ниже производится определение функции. В отличие от объявления, здесь обязательно указание имени передаваемых аргументов. Имя аргумента используется только в теле функции. Стоит заметить, что отделение объявления и определения функции не является обязательным при записи всего в одном файле. */ double newton_root(double num) { double r_cur, r_next = num; /* Действительные числа (float, double) лучше сравнивать с некоторой заранее определённой точностью по числу знаков после запятой. num == 0.0 - не гарантирует, что сравнение будет истино даже если num = 0; */ if (num < PRECISION) return 0.0; do { r_cur = r_next; r_next = (r_cur + num / r_cur) / 2; } while (fabs(r_cur - r_next) > PRECISION); return r_next; } <commit_msg>minor fix to from_study_guide/5_1.cpp<commit_after>/* Определить функцию для вычисления по формуле Ньютона приблежённого значения арифметического квадратного корня. В формуле Ньютона итерации определяются по формуле r_[n+1] = (r_[n] + x / r_[n]) / 2 Версия для C++ */ #include <iostream> #include <cmath> #include <clocale> const double PRECISION = 0.000000001; /* Объявление функции с именем newton_root. Она принимает один аргумент типа double и возращает значение типа double. Объявление без описания тела функции (блок кода в фигурных скобках) - позволяет делать вызов этой функции в любом месте, до определения самой функции. */ double newton_root(double ); int main() { std::setlocale(LC_ALL, "RUS"); double x, result; std::cout << "Введите x: "; std::cin >> x; // вызываем функцию, передавая ей в качестве аргумента переменную x и сохраняя возращённый ею результат в переменной result result = newton_root(x); std::cout << "Корень из x: " << result; return 0; } /* Ниже производится определение функции. В отличие от объявления, здесь обязательно указание имени передаваемых аргументов. Имя аргумента используется только в теле функции. Стоит заметить, что отделение объявления и определения функции не является обязательным при записи всего в одном файле. */ double newton_root(double num) { double r_cur, r_next = num; /* Действительные числа (float, double) лучше сравнивать с некоторой заранее определённой точностью по числу знаков после запятой. num == 0.0 - не гарантирует, что сравнение будет истино даже если num = 0; */ if (num < PRECISION) return 0.0; do { r_cur = r_next; r_next = (r_cur + num / r_cur) / 2; } while ( abs(r_cur - r_next) > PRECISION ); return r_next; } <|endoftext|>
<commit_before>// This file is part of SWGANH which is released under GPL v2. // See file LICENSE or go to http://swganh.com/LICENSE #include "config_reader.h" #include <array> #include <fstream> #include <stdexcept> #ifdef WIN32 #include <regex> #else #include <boost/regex.hpp> #endif #include <boost/filesystem.hpp> #include <anh/logger.h> using namespace swganh::tre; using std::ifstream; using std::ios_base; using std::move; using std::invalid_argument; using std::string; using std::vector; #ifdef WIN32 using std::regex; using std::smatch; using std::regex_match; #else using boost::regex; using boost::smatch; using boost::regex_match; #endif ConfigReader::ConfigReader(std::string filename) : config_filename_(move(filename)) { ParseConfig(); } const std::vector<std::string>& ConfigReader::GetTreFilenames() { return tre_filenames_; } void ConfigReader::ParseConfig() { ifstream input_stream(config_filename_.c_str()); if (!input_stream.is_open()) { LOG(fatal) << "Invalid tre configuration file: " << config_filename_; throw invalid_argument("Invalid tre configuration file: " + config_filename_); } boost::filesystem::path p(config_filename_); boost::filesystem::path dir = p.parent_path(); #ifdef WIN32 regex rx("searchTree_([0-9]{2})_([0-9]{1,2})=(\")?(.*)\\3"); #else regex rx("searchTree_([0-9]{2})_([0-9]{1,2})=(\")?(.*)(\")?"); #endif smatch match; string line; while(!input_stream.eof()) { Getline(input_stream, line); if (regex_search(line, match, rx)) { boost::filesystem::path tmp = dir; boost::filesystem::path filename = match[4].str(); if (!boost::filesystem::is_regular_file(filename)) { tmp /= filename; filename = tmp; } auto native_path = boost::filesystem::system_complete(filename).native(); tre_filenames_.emplace_back(string(begin(native_path), end(native_path))); } } } std::istream& ConfigReader::Getline(std::istream& input, std::string& output) { char c; output.clear(); while(input.get(c) && c != '\n' && c != '\r') { output += c; } return input; }<commit_msg>Reverted back to the single regex syntax now that line endings are working proper.<commit_after>// This file is part of SWGANH which is released under GPL v2. // See file LICENSE or go to http://swganh.com/LICENSE #include "config_reader.h" #include <array> #include <fstream> #include <stdexcept> #ifdef WIN32 #include <regex> #else #include <boost/regex.hpp> #endif #include <boost/filesystem.hpp> #include <anh/logger.h> using namespace swganh::tre; using std::ifstream; using std::ios_base; using std::move; using std::invalid_argument; using std::string; using std::vector; #ifdef WIN32 using std::regex; using std::smatch; using std::regex_match; #else using boost::regex; using boost::smatch; using boost::regex_match; #endif ConfigReader::ConfigReader(std::string filename) : config_filename_(move(filename)) { ParseConfig(); } const std::vector<std::string>& ConfigReader::GetTreFilenames() { return tre_filenames_; } void ConfigReader::ParseConfig() { ifstream input_stream(config_filename_.c_str()); if (!input_stream.is_open()) { LOG(fatal) << "Invalid tre configuration file: " << config_filename_; throw invalid_argument("Invalid tre configuration file: " + config_filename_); } boost::filesystem::path p(config_filename_); boost::filesystem::path dir = p.parent_path(); regex rx("searchTree_([0-9]{2})_([0-9]{1,2})=(\")?(.*)\\3"); smatch match; string line; while(!input_stream.eof()) { Getline(input_stream, line); if (regex_search(line, match, rx)) { boost::filesystem::path tmp = dir; boost::filesystem::path filename = match[4].str(); if (!boost::filesystem::is_regular_file(filename)) { tmp /= filename; filename = tmp; } auto native_path = boost::filesystem::system_complete(filename).native(); tre_filenames_.emplace_back(string(begin(native_path), end(native_path))); } } } std::istream& ConfigReader::Getline(std::istream& input, std::string& output) { char c; output.clear(); while(input.get(c) && c != '\n' && c != '\r') { output += c; } return input; }<|endoftext|>
<commit_before>/* * _____ ___ ___ | * | _ |___ ___ _ _|_ |_ | | C/C++ framework for 32-bit AVRs * | | -_| _| | |_ | _| | * |__|__|___|_| |_ |___|___| | https://github.com/aery32 * |___| | * * Copyright (c) 2012, Muiku Oy * All rights reserved. * * LICENSE * * New BSD License, see the LICENSE.txt bundled with this package. If you did * not receive a copy of the license and are unable to obtain it through the * world-wide-web, please send an email to [email protected] so we can send * you a copy. */ #include "aery32/pwm.h" volatile avr32_pwm_t *aery::pwm = &AVR32_PWM; int aery::pwm_init_divab(enum Pwm_channel_clk prea, uint8_t diva, enum Pwm_channel_clk preb, uint8_t divb) { if (prea == PWM_CLKA || prea == PWM_CLKB) return -1; if (preb == PWM_CLKA || preb == PWM_CLKB) return -1; AVR32_PWM.MR.prea = prea; AVR32_PWM.MR.diva = diva; AVR32_PWM.MR.preb = preb; AVR32_PWM.MR.divb = divb; return 0; } int aery::pwm_init_channel(uint8_t chanum, enum Pwm_channel_clk clk, uint32_t duration, uint32_t period) { /* Writing in CDTYn and CPRDn is possible while the chan is disabled */ if (aery::pwm_isenabled(chanum)) return -1; if (duration > period) return -1; volatile avr32_pwm_channel_t *pwm = &AVR32_PWM.channel[chanum]; pwm->CMR.cpre = clk; pwm->cdty = duration; pwm->cprd = period; return 0; } int aery::pwm_setup_chamode(uint8_t chanum, enum Pwm_alignment align, enum Pwm_polarity polar) { /* Mode can be modified only when the channel is disabled. */ if (aery::pwm_isenabled(chanum)) return -1; AVR32_PWM.channel[chanum].CMR.calg = align; AVR32_PWM.channel[chanum].CMR.cpol = polar; return 0; } int aery::pwm_update_duration(uint8_t chanum, uint32_t newval) { if (newval > AVR32_PWM.channel[chanum].cprd) return -1; AVR32_PWM.channel[chanum].CMR.cpd = 0; AVR32_PWM.channel[chanum].cupd = newval; return 0; } int aery::pwm_update_period(uint8_t chanum, uint32_t newval) { if (newval < AVR32_PWM.channel[chanum].cdty) return -1; AVR32_PWM.channel[chanum].CMR.cpd = 1; AVR32_PWM.channel[chanum].cupd = newval; return 0; } void aery::pwm_wait_periods(uint8_t chanum, uint32_t periods) { volatile uint32_t status = AVR32_PWM.isr; AVR32_PWM.ier |= (1 << chanum); while (periods--) while ((status = AVR32_PWM.isr) & (1 << chanum)); AVR32_PWM.idr |= (1 << chanum); } int aery::pwm_update_dutycl(uint8_t chanum, double D) { volatile avr32_pwm_channel_t *pwm = &AVR32_PWM.channel[chanum]; if (D > 1.0) return -1; if (D < 0.0) return -1; if (pwm->CMR.cpd == 0) return pwm_update_duration(chanum, (uint32_t) (D * pwm->cprd)); else return pwm_update_period(chanum, (uint32_t) (pwm->cdty / D)); } void aery::pwm_enable(uint8_t chamask) { AVR32_PWM.ena = chamask; } void aery::pwm_disable(uint8_t chamask) { AVR32_PWM.dis = chamask; } bool aery::pwm_isenabled(uint8_t chanum) { return AVR32_PWM.sr & (1 << chanum); }<commit_msg>Fine tuning the if statement<commit_after>/* * _____ ___ ___ | * | _ |___ ___ _ _|_ |_ | | C/C++ framework for 32-bit AVRs * | | -_| _| | |_ | _| | * |__|__|___|_| |_ |___|___| | https://github.com/aery32 * |___| | * * Copyright (c) 2012, Muiku Oy * All rights reserved. * * LICENSE * * New BSD License, see the LICENSE.txt bundled with this package. If you did * not receive a copy of the license and are unable to obtain it through the * world-wide-web, please send an email to [email protected] so we can send * you a copy. */ #include "aery32/pwm.h" volatile avr32_pwm_t *aery::pwm = &AVR32_PWM; int aery::pwm_init_divab(enum Pwm_channel_clk prea, uint8_t diva, enum Pwm_channel_clk preb, uint8_t divb) { if (prea == PWM_CLKA || prea == PWM_CLKB) return -1; if (preb == PWM_CLKA || preb == PWM_CLKB) return -1; AVR32_PWM.MR.prea = prea; AVR32_PWM.MR.diva = diva; AVR32_PWM.MR.preb = preb; AVR32_PWM.MR.divb = divb; return 0; } int aery::pwm_init_channel(uint8_t chanum, enum Pwm_channel_clk clk, uint32_t duration, uint32_t period) { /* Writing in CDTYn and CPRDn is possible while the chan is disabled */ if (aery::pwm_isenabled(chanum)) return -1; if (duration > period) return -1; volatile avr32_pwm_channel_t *pwm = &AVR32_PWM.channel[chanum]; pwm->CMR.cpre = clk; pwm->cdty = duration; pwm->cprd = period; return 0; } int aery::pwm_setup_chamode(uint8_t chanum, enum Pwm_alignment align, enum Pwm_polarity polar) { /* Mode can be modified only when the channel is disabled. */ if (aery::pwm_isenabled(chanum)) return -1; AVR32_PWM.channel[chanum].CMR.calg = align; AVR32_PWM.channel[chanum].CMR.cpol = polar; return 0; } int aery::pwm_update_duration(uint8_t chanum, uint32_t newval) { if (newval > AVR32_PWM.channel[chanum].cprd) return -1; AVR32_PWM.channel[chanum].CMR.cpd = 0; AVR32_PWM.channel[chanum].cupd = newval; return 0; } int aery::pwm_update_period(uint8_t chanum, uint32_t newval) { if (newval < AVR32_PWM.channel[chanum].cdty) return -1; AVR32_PWM.channel[chanum].CMR.cpd = 1; AVR32_PWM.channel[chanum].cupd = newval; return 0; } void aery::pwm_wait_periods(uint8_t chanum, uint32_t periods) { volatile uint32_t status = AVR32_PWM.isr; AVR32_PWM.ier |= (1 << chanum); while (periods--) while ((status = AVR32_PWM.isr) & (1 << chanum)); AVR32_PWM.idr |= (1 << chanum); } int aery::pwm_update_dutycl(uint8_t chanum, double D) { volatile avr32_pwm_channel_t *pwm = &AVR32_PWM.channel[chanum]; if (D < 0.0 || D > 1.0) return -1; if (pwm->CMR.cpd == 0) return pwm_update_duration(chanum, (uint32_t) (D * pwm->cprd)); else return pwm_update_period(chanum, (uint32_t) (pwm->cdty / D)); } void aery::pwm_enable(uint8_t chamask) { AVR32_PWM.ena = chamask; } void aery::pwm_disable(uint8_t chamask) { AVR32_PWM.dis = chamask; } bool aery::pwm_isenabled(uint8_t chanum) { return AVR32_PWM.sr & (1 << chanum); }<|endoftext|>
<commit_before>//(c) 2016 by Authors //This file is a part of ABruijn program. //Released under the BSD license (see LICENSE file) #include "multiplicity_inferer.h" #include "graph_processing.h" #include "../common/disjoint_set.h" #include "../common/utils.h" #include <cmath> //Estimates the mean coverage and assingns edges multiplicity accordingly void MultiplicityInferer::estimateCoverage() { const int WINDOW = Config::get("coverage_estimate_window"); const int SHORT_EDGE = Config::get("unique_edge_length"); //alternative coverage std::unordered_map<GraphEdge*, std::vector<int32_t>> wndCoverage; for (auto& edge : _graph.iterEdges()) { size_t numWindows = edge->length() / WINDOW; wndCoverage[edge].assign(numWindows, 0); } for (auto& path : _aligner.getAlignments()) { for (size_t i = 0; i < path.size(); ++i) { auto& ovlp = path[i].overlap; auto& coverage = wndCoverage[path[i].edge]; for (int pos = ovlp.extBegin / WINDOW + 1; pos < ovlp.extEnd / WINDOW; ++pos) { if (pos >= 0 && pos < (int)coverage.size()) { ++coverage[pos]; } } } } int64_t sumCov = 0; int64_t sumLength = 0; for (auto& edgeCoverage : wndCoverage) { if (edgeCoverage.first->length() < SHORT_EDGE) continue; for (auto& cov : edgeCoverage.second) { sumCov += (int64_t)cov; ++sumLength; } } _meanCoverage = (sumLength != 0) ? sumCov / sumLength : 1; Logger::get().info() << "Mean edge coverage: " << _meanCoverage; std::vector<int32_t> edgesCoverage; for (auto edge : _graph.iterEdges()) { if (wndCoverage[edge].empty()) continue; GraphEdge* complEdge = _graph.complementEdge(edge); int32_t medianCov = (median(wndCoverage[edge]) + median(wndCoverage[complEdge])) / 2; int estMult = std::round((float)medianCov / _meanCoverage); if (estMult == 1) { edgesCoverage.push_back(medianCov); } //std::string match = estMult != edge->multiplicity ? "*" : " "; std::string covStr; Logger::get().debug() << edge->edgeId.signedId() << "\tlen:" << edge->length() << "\tcov:" << medianCov << "\tmult:" << (float)medianCov / _meanCoverage; //edge->multiplicity = estMult; edge->meanCoverage = medianCov; } _uniqueCovThreshold = 2; if (!edgesCoverage.empty()) { const float MULT = 1.75f; //at least 1.75x of mean coverage _uniqueCovThreshold = MULT * quantile(edgesCoverage, 75); } Logger::get().debug() << "Unique coverage threshold " << _uniqueCovThreshold; } //removes edges with low coverage support from the graph void MultiplicityInferer::removeUnsupportedEdges() { GraphProcessor proc(_graph, _asmSeqs, _readSeqs); auto unbranchingPaths = proc.getUnbranchingPaths(); int32_t coverageThreshold = this->getMeanCoverage() / Config::get("graph_cov_drop_rate"); Logger::get().debug() << "Read coverage cutoff: " << coverageThreshold; std::unordered_set<GraphEdge*> edgesRemove; for (auto& path : unbranchingPaths) { if (!path.id.strand()) continue; if (path.meanCoverage <= coverageThreshold) { Logger::get().debug() << "Low coverage: " << path.edgesStr() << " " << path.meanCoverage; for (auto& edge : path.path) { edgesRemove.insert(edge); edgesRemove.insert(_graph.complementEdge(edge)); } } } for (auto& edge : edgesRemove) _graph.removeEdge(edge); Logger::get().debug() << "Removed " << edgesRemove.size() / 2 << " unsupported edges"; _aligner.updateAlignments(); } void MultiplicityInferer::removeUnsupportedConnections() { std::unordered_map<GraphEdge*, int32_t> rightConnections; std::unordered_map<GraphEdge*, int32_t> leftConnections; for (auto& readPath : _aligner.getAlignments()) { if (readPath.size() < 2) continue; //int overhang = std::max(readPath.front().overlap.curBegin, // readPath.back().overlap.curLen - // readPath.back().overlap.curEnd); //if (overhang > (int)Config::get("maximum_overhang")) continue; for (size_t i = 0; i < readPath.size() - 1; ++i) { if (readPath[i].edge == readPath[i + 1].edge && readPath[i].edge->isLooped()) continue; if (readPath[i].edge->edgeId == readPath[i + 1].edge->edgeId.rc()) continue; ++rightConnections[readPath[i].edge]; ++leftConnections[readPath[i + 1].edge]; GraphEdge* complLeft = _graph.complementEdge(readPath[i].edge); GraphEdge* complRight = _graph.complementEdge(readPath[i + 1].edge); ++rightConnections[complRight]; ++leftConnections[complLeft]; } } auto disconnectRight = [this](GraphEdge* edge) { GraphNode* newNode = _graph.addNode(); vecRemove(edge->nodeRight->inEdges, edge); edge->nodeRight = newNode; edge->nodeRight->inEdges.push_back(edge); }; auto disconnectLeft = [this](GraphEdge* edge) { GraphNode* newNode = _graph.addNode(); vecRemove(edge->nodeLeft->outEdges, edge); edge->nodeLeft = newNode; edge->nodeLeft->outEdges.push_back(edge); }; for (auto& edge : _graph.iterEdges()) { if (!edge->edgeId.strand() || edge->isLooped()) continue; GraphEdge* complEdge = _graph.complementEdge(edge); int32_t coverageThreshold = edge->meanCoverage / Config::get("graph_cov_drop_rate"); //Logger::get().debug() << "Adjacencies: " << edge->edgeId.signedId() << " " // << leftConnections[edge] / 2 << " " << rightConnections[edge] / 2; if (!edge->nodeRight->isEnd() && rightConnections[edge] / 2 < coverageThreshold) { Logger::get().debug() << "Chimeric right: " << edge->edgeId.signedId() << " " << rightConnections[edge] / 2; disconnectRight(edge); disconnectLeft(complEdge); if (edge->selfComplement) continue; //already discinnected } if (!edge->nodeLeft->isEnd() && leftConnections[edge] / 2 < coverageThreshold) { Logger::get().debug() << "Chimeric left: " << edge->edgeId.signedId() << " " << leftConnections[edge] / 2; disconnectLeft(edge); disconnectRight(complEdge); } } GraphProcessor proc(_graph, _asmSeqs, _readSeqs); proc.trimTips(); _aligner.updateAlignments(); } //collapse loops (that also could be viewed as //bubbles with one branch of length 0) void MultiplicityInferer::collapseHeterozygousLoops() { const float COV_MULT = 1.5; GraphProcessor proc(_graph, _asmSeqs, _readSeqs); auto unbranchingPaths = proc.getUnbranchingPaths(); std::unordered_set<FastaRecord::Id> toUnroll; std::unordered_set<FastaRecord::Id> toRemove; for (auto& loop : unbranchingPaths) { if (!loop.isLooped()) continue; GraphNode* node = loop.nodeLeft(); if (node->inEdges.size() != 2 || node->outEdges.size() != 2) continue; UnbranchingPath* entrancePath = nullptr; UnbranchingPath* exitPath = nullptr; for (auto& cand : unbranchingPaths) { if (cand.nodeRight() == node && loop.id != cand.id) entrancePath = &cand; if (cand.nodeLeft() == node && loop.id != cand.id) exitPath = &cand; } if (entrancePath->isLooped()) continue; if (entrancePath->id == exitPath->id.rc()) continue; //loop coverage should be roughly equal or less if (loop.meanCoverage > COV_MULT * entrancePath->meanCoverage || loop.meanCoverage > COV_MULT * entrancePath->meanCoverage) continue; //loop should not be longer than other branches if (loop.length > entrancePath->length || loop.length > exitPath->length) continue; if (loop.meanCoverage < (entrancePath->meanCoverage + exitPath->meanCoverage) / 4) { toRemove.insert(loop.id); } else { toUnroll.insert(loop.id.rc()); } } for (auto& path : unbranchingPaths) { if (toUnroll.count(path.id)) { GraphNode* newNode = _graph.addNode(); size_t id = path.nodeLeft()->inEdges[0] == path.path.front(); GraphEdge* prevEdge = path.nodeLeft()->inEdges[id]; vecRemove(path.nodeLeft()->outEdges, path.path.front()); vecRemove(path.nodeLeft()->inEdges, prevEdge); path.nodeLeft() = newNode; newNode->outEdges.push_back(path.path.front()); prevEdge->nodeRight = newNode; newNode->inEdges.push_back(prevEdge); } if (toRemove.count(path.id)) { GraphNode* newLeft = _graph.addNode(); GraphNode* newRight = _graph.addNode(); vecRemove(path.nodeLeft()->outEdges, path.path.front()); vecRemove(path.nodeLeft()->inEdges, path.path.back()); path.nodeLeft() = newLeft; newRight->inEdges.push_back(path.path.back()); path.nodeRight() = newRight; newLeft->outEdges.push_back(path.path.front()); } } Logger::get().debug() << "Unrolled " << toUnroll.size() / 2 << " heterozygous loops"; Logger::get().debug() << "Removed " << toRemove.size() / 2 << " heterozygous loops"; _aligner.updateAlignments(); } void MultiplicityInferer::collapseHeterozygousBulges() { const float MAX_COV_VAR = 0.20; const float MAX_LEN_VAR = 0.50; GraphProcessor proc(_graph, _asmSeqs, _readSeqs); auto unbranchingPaths = proc.getUnbranchingPaths(); std::unordered_set<FastaRecord::Id> toSeparate; for (auto& path : unbranchingPaths) { if (path.isLooped()) continue; std::vector<UnbranchingPath*> twoPaths; for (auto& candEdge : unbranchingPaths) { if (candEdge.nodeLeft() == path.nodeLeft() && candEdge.nodeRight() == path.nodeRight()) { twoPaths.push_back(&candEdge); } } //making sure the structure is ok if (twoPaths.size() != 2) continue; if (twoPaths[0]->id == twoPaths[1]->id.rc()) continue; if (toSeparate.count(twoPaths[0]->id) || toSeparate.count(twoPaths[1]->id)) continue; if (twoPaths[0]->nodeLeft()->inEdges.size() != 1 || twoPaths[0]->nodeRight()->outEdges.size() != 1) continue; UnbranchingPath* entrancePath = nullptr; UnbranchingPath* exitPath = nullptr; for (auto& cand : unbranchingPaths) { if (cand.nodeRight() == twoPaths[0]->nodeLeft()) entrancePath = &cand; if (cand.nodeLeft() == twoPaths[0]->nodeRight()) exitPath = &cand; } //coverage requirement: sum over two branches roughly equals to //exit and entrance coverage float covSum = twoPaths[0]->meanCoverage + twoPaths[1]->meanCoverage; float entranceDiff = fabsf(covSum - entrancePath->meanCoverage) / covSum; float exitDiff = fabsf(covSum - exitPath->meanCoverage) / covSum; if (entranceDiff > MAX_COV_VAR || exitDiff > MAX_COV_VAR) continue; //length requirement: branches have roughly the same length //and are significantly shorter than entrance/exits if (abs(twoPaths[0]->length - twoPaths[1]->length) > MAX_LEN_VAR * std::min(twoPaths[0]->length, twoPaths[1]->length)) continue; float bubbleSize = (twoPaths[0]->length + twoPaths[1]->length) / 2; if (bubbleSize > entrancePath->length || bubbleSize > exitPath->length) continue; if (twoPaths[0]->meanCoverage < twoPaths[1]->meanCoverage) { toSeparate.insert(twoPaths[0]->id); toSeparate.insert(twoPaths[0]->id.rc()); } else { toSeparate.insert(twoPaths[1]->id); toSeparate.insert(twoPaths[1]->id.rc()); } } for (auto& path : unbranchingPaths) { if (toSeparate.count(path.id)) { GraphNode* newLeft = _graph.addNode(); GraphNode* newRight = _graph.addNode(); vecRemove(path.nodeLeft()->outEdges, path.path.front()); vecRemove(path.nodeRight()->inEdges, path.path.back()); path.nodeLeft() = newLeft; path.nodeRight() = newRight; newLeft->outEdges.push_back(path.path.front()); newRight->inEdges.push_back(path.path.back()); } } Logger::get().debug() << "Popped " << toSeparate.size() / 2 << " heterozygous bulges"; _aligner.updateAlignments(); } <commit_msg>low coverage cutoff at least 1<commit_after>//(c) 2016 by Authors //This file is a part of ABruijn program. //Released under the BSD license (see LICENSE file) #include "multiplicity_inferer.h" #include "graph_processing.h" #include "../common/disjoint_set.h" #include "../common/utils.h" #include <cmath> //Estimates the mean coverage and assingns edges multiplicity accordingly void MultiplicityInferer::estimateCoverage() { const int WINDOW = Config::get("coverage_estimate_window"); const int SHORT_EDGE = Config::get("unique_edge_length"); //alternative coverage std::unordered_map<GraphEdge*, std::vector<int32_t>> wndCoverage; for (auto& edge : _graph.iterEdges()) { size_t numWindows = edge->length() / WINDOW; wndCoverage[edge].assign(numWindows, 0); } for (auto& path : _aligner.getAlignments()) { for (size_t i = 0; i < path.size(); ++i) { auto& ovlp = path[i].overlap; auto& coverage = wndCoverage[path[i].edge]; for (int pos = ovlp.extBegin / WINDOW + 1; pos < ovlp.extEnd / WINDOW; ++pos) { if (pos >= 0 && pos < (int)coverage.size()) { ++coverage[pos]; } } } } int64_t sumCov = 0; int64_t sumLength = 0; for (auto& edgeCoverage : wndCoverage) { if (edgeCoverage.first->length() < SHORT_EDGE) continue; for (auto& cov : edgeCoverage.second) { sumCov += (int64_t)cov; ++sumLength; } } _meanCoverage = (sumLength != 0) ? sumCov / sumLength : 1; Logger::get().info() << "Mean edge coverage: " << _meanCoverage; std::vector<int32_t> edgesCoverage; for (auto edge : _graph.iterEdges()) { if (wndCoverage[edge].empty()) continue; GraphEdge* complEdge = _graph.complementEdge(edge); int32_t medianCov = (median(wndCoverage[edge]) + median(wndCoverage[complEdge])) / 2; int estMult = std::round((float)medianCov / _meanCoverage); if (estMult == 1) { edgesCoverage.push_back(medianCov); } //std::string match = estMult != edge->multiplicity ? "*" : " "; std::string covStr; Logger::get().debug() << edge->edgeId.signedId() << "\tlen:" << edge->length() << "\tcov:" << medianCov << "\tmult:" << (float)medianCov / _meanCoverage; //edge->multiplicity = estMult; edge->meanCoverage = medianCov; } _uniqueCovThreshold = 2; if (!edgesCoverage.empty()) { const float MULT = 1.75f; //at least 1.75x of mean coverage _uniqueCovThreshold = MULT * quantile(edgesCoverage, 75); } Logger::get().debug() << "Unique coverage threshold " << _uniqueCovThreshold; } //removes edges with low coverage support from the graph void MultiplicityInferer::removeUnsupportedEdges() { GraphProcessor proc(_graph, _asmSeqs, _readSeqs); auto unbranchingPaths = proc.getUnbranchingPaths(); int32_t coverageThreshold = std::round((float)this->getMeanCoverage() / Config::get("graph_cov_drop_rate")); coverageThreshold = std::max(1, coverageThreshold); Logger::get().debug() << "Read coverage cutoff: " << coverageThreshold; std::unordered_set<GraphEdge*> edgesRemove; for (auto& path : unbranchingPaths) { if (!path.id.strand()) continue; if (path.meanCoverage <= coverageThreshold) { Logger::get().debug() << "Low coverage: " << path.edgesStr() << " " << path.meanCoverage; for (auto& edge : path.path) { edgesRemove.insert(edge); edgesRemove.insert(_graph.complementEdge(edge)); } } } for (auto& edge : edgesRemove) _graph.removeEdge(edge); Logger::get().debug() << "Removed " << edgesRemove.size() / 2 << " unsupported edges"; _aligner.updateAlignments(); } void MultiplicityInferer::removeUnsupportedConnections() { std::unordered_map<GraphEdge*, int32_t> rightConnections; std::unordered_map<GraphEdge*, int32_t> leftConnections; for (auto& readPath : _aligner.getAlignments()) { if (readPath.size() < 2) continue; //int overhang = std::max(readPath.front().overlap.curBegin, // readPath.back().overlap.curLen - // readPath.back().overlap.curEnd); //if (overhang > (int)Config::get("maximum_overhang")) continue; for (size_t i = 0; i < readPath.size() - 1; ++i) { if (readPath[i].edge == readPath[i + 1].edge && readPath[i].edge->isLooped()) continue; if (readPath[i].edge->edgeId == readPath[i + 1].edge->edgeId.rc()) continue; ++rightConnections[readPath[i].edge]; ++leftConnections[readPath[i + 1].edge]; GraphEdge* complLeft = _graph.complementEdge(readPath[i].edge); GraphEdge* complRight = _graph.complementEdge(readPath[i + 1].edge); ++rightConnections[complRight]; ++leftConnections[complLeft]; } } auto disconnectRight = [this](GraphEdge* edge) { GraphNode* newNode = _graph.addNode(); vecRemove(edge->nodeRight->inEdges, edge); edge->nodeRight = newNode; edge->nodeRight->inEdges.push_back(edge); }; auto disconnectLeft = [this](GraphEdge* edge) { GraphNode* newNode = _graph.addNode(); vecRemove(edge->nodeLeft->outEdges, edge); edge->nodeLeft = newNode; edge->nodeLeft->outEdges.push_back(edge); }; for (auto& edge : _graph.iterEdges()) { if (!edge->edgeId.strand() || edge->isLooped()) continue; GraphEdge* complEdge = _graph.complementEdge(edge); int32_t coverageThreshold = edge->meanCoverage / Config::get("graph_cov_drop_rate"); //Logger::get().debug() << "Adjacencies: " << edge->edgeId.signedId() << " " // << leftConnections[edge] / 2 << " " << rightConnections[edge] / 2; if (!edge->nodeRight->isEnd() && rightConnections[edge] / 2 < coverageThreshold) { Logger::get().debug() << "Chimeric right: " << edge->edgeId.signedId() << " " << rightConnections[edge] / 2; disconnectRight(edge); disconnectLeft(complEdge); if (edge->selfComplement) continue; //already discinnected } if (!edge->nodeLeft->isEnd() && leftConnections[edge] / 2 < coverageThreshold) { Logger::get().debug() << "Chimeric left: " << edge->edgeId.signedId() << " " << leftConnections[edge] / 2; disconnectLeft(edge); disconnectRight(complEdge); } } GraphProcessor proc(_graph, _asmSeqs, _readSeqs); proc.trimTips(); _aligner.updateAlignments(); } //collapse loops (that also could be viewed as //bubbles with one branch of length 0) void MultiplicityInferer::collapseHeterozygousLoops() { const float COV_MULT = 1.5; GraphProcessor proc(_graph, _asmSeqs, _readSeqs); auto unbranchingPaths = proc.getUnbranchingPaths(); std::unordered_set<FastaRecord::Id> toUnroll; std::unordered_set<FastaRecord::Id> toRemove; for (auto& loop : unbranchingPaths) { if (!loop.isLooped()) continue; GraphNode* node = loop.nodeLeft(); if (node->inEdges.size() != 2 || node->outEdges.size() != 2) continue; UnbranchingPath* entrancePath = nullptr; UnbranchingPath* exitPath = nullptr; for (auto& cand : unbranchingPaths) { if (cand.nodeRight() == node && loop.id != cand.id) entrancePath = &cand; if (cand.nodeLeft() == node && loop.id != cand.id) exitPath = &cand; } if (entrancePath->isLooped()) continue; if (entrancePath->id == exitPath->id.rc()) continue; //loop coverage should be roughly equal or less if (loop.meanCoverage > COV_MULT * entrancePath->meanCoverage || loop.meanCoverage > COV_MULT * entrancePath->meanCoverage) continue; //loop should not be longer than other branches if (loop.length > entrancePath->length || loop.length > exitPath->length) continue; if (loop.meanCoverage < (entrancePath->meanCoverage + exitPath->meanCoverage) / 4) { toRemove.insert(loop.id); } else { toUnroll.insert(loop.id.rc()); } } for (auto& path : unbranchingPaths) { if (toUnroll.count(path.id)) { GraphNode* newNode = _graph.addNode(); size_t id = path.nodeLeft()->inEdges[0] == path.path.front(); GraphEdge* prevEdge = path.nodeLeft()->inEdges[id]; vecRemove(path.nodeLeft()->outEdges, path.path.front()); vecRemove(path.nodeLeft()->inEdges, prevEdge); path.nodeLeft() = newNode; newNode->outEdges.push_back(path.path.front()); prevEdge->nodeRight = newNode; newNode->inEdges.push_back(prevEdge); } if (toRemove.count(path.id)) { GraphNode* newLeft = _graph.addNode(); GraphNode* newRight = _graph.addNode(); vecRemove(path.nodeLeft()->outEdges, path.path.front()); vecRemove(path.nodeLeft()->inEdges, path.path.back()); path.nodeLeft() = newLeft; newRight->inEdges.push_back(path.path.back()); path.nodeRight() = newRight; newLeft->outEdges.push_back(path.path.front()); } } Logger::get().debug() << "Unrolled " << toUnroll.size() / 2 << " heterozygous loops"; Logger::get().debug() << "Removed " << toRemove.size() / 2 << " heterozygous loops"; _aligner.updateAlignments(); } void MultiplicityInferer::collapseHeterozygousBulges() { const float MAX_COV_VAR = 0.20; const float MAX_LEN_VAR = 0.50; GraphProcessor proc(_graph, _asmSeqs, _readSeqs); auto unbranchingPaths = proc.getUnbranchingPaths(); std::unordered_set<FastaRecord::Id> toSeparate; for (auto& path : unbranchingPaths) { if (path.isLooped()) continue; std::vector<UnbranchingPath*> twoPaths; for (auto& candEdge : unbranchingPaths) { if (candEdge.nodeLeft() == path.nodeLeft() && candEdge.nodeRight() == path.nodeRight()) { twoPaths.push_back(&candEdge); } } //making sure the structure is ok if (twoPaths.size() != 2) continue; if (twoPaths[0]->id == twoPaths[1]->id.rc()) continue; if (toSeparate.count(twoPaths[0]->id) || toSeparate.count(twoPaths[1]->id)) continue; if (twoPaths[0]->nodeLeft()->inEdges.size() != 1 || twoPaths[0]->nodeRight()->outEdges.size() != 1) continue; UnbranchingPath* entrancePath = nullptr; UnbranchingPath* exitPath = nullptr; for (auto& cand : unbranchingPaths) { if (cand.nodeRight() == twoPaths[0]->nodeLeft()) entrancePath = &cand; if (cand.nodeLeft() == twoPaths[0]->nodeRight()) exitPath = &cand; } //coverage requirement: sum over two branches roughly equals to //exit and entrance coverage float covSum = twoPaths[0]->meanCoverage + twoPaths[1]->meanCoverage; float entranceDiff = fabsf(covSum - entrancePath->meanCoverage) / covSum; float exitDiff = fabsf(covSum - exitPath->meanCoverage) / covSum; if (entranceDiff > MAX_COV_VAR || exitDiff > MAX_COV_VAR) continue; //length requirement: branches have roughly the same length //and are significantly shorter than entrance/exits if (abs(twoPaths[0]->length - twoPaths[1]->length) > MAX_LEN_VAR * std::min(twoPaths[0]->length, twoPaths[1]->length)) continue; float bubbleSize = (twoPaths[0]->length + twoPaths[1]->length) / 2; if (bubbleSize > entrancePath->length || bubbleSize > exitPath->length) continue; if (twoPaths[0]->meanCoverage < twoPaths[1]->meanCoverage) { toSeparate.insert(twoPaths[0]->id); toSeparate.insert(twoPaths[0]->id.rc()); } else { toSeparate.insert(twoPaths[1]->id); toSeparate.insert(twoPaths[1]->id.rc()); } } for (auto& path : unbranchingPaths) { if (toSeparate.count(path.id)) { GraphNode* newLeft = _graph.addNode(); GraphNode* newRight = _graph.addNode(); vecRemove(path.nodeLeft()->outEdges, path.path.front()); vecRemove(path.nodeRight()->inEdges, path.path.back()); path.nodeLeft() = newLeft; path.nodeRight() = newRight; newLeft->outEdges.push_back(path.path.front()); newRight->inEdges.push_back(path.path.back()); } } Logger::get().debug() << "Popped " << toSeparate.size() / 2 << " heterozygous bulges"; _aligner.updateAlignments(); } <|endoftext|>
<commit_before>// bslstl_algorithm.t.cpp -*-C++-*- #include <bslstl_algorithm.h> #include <bslma_allocator.h> #include <bslma_default.h> #include <bslma_defaultallocatorguard.h> #include <bslma_destructorguard.h> #include <bslma_testallocator.h> #include <bslma_testallocatormonitor.h> #include <bslma_usesbslmaallocator.h> #include <bsls_asserttest.h> #include <bsls_bsltestutil.h> #include <bsltf_testvaluesarray.h> #include <functional> #include <limits.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> // atoi #include <string.h> // strlen // ============================================================================ // TEST PLAN // ---------------------------------------------------------------------------- // The component under test provides implementations for algorithms not // provided by the underlying standard library implementation. // ---------------------------------------------------------------------------- // // [ 1] bool all_of (InputIter first, InputIter last, PREDICATE pred); // [ 1] bool any_of (InputIter first, InputIter last, PREDICATE pred); // [ 1] bool none_of(InputIter first, InputIter last, PREDICATE pred); // ---------------------------------------------------------------------------- // ============================================================================ // STANDARD BDE ASSERT TEST MACROS // ---------------------------------------------------------------------------- // NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY // FUNCTIONS, INCLUDING IOSTREAMS. namespace { int testStatus = 0; void aSsErT(bool b, const char *s, int i) { if (b) { printf("Error " __FILE__ "(%d): %s (failed)\n", i, s); if (testStatus >= 0 && testStatus <= 100) ++testStatus; } } } // close unnamed namespace // ============================================================================ // STANDARD BDE ASSERT TEST MACROS // ---------------------------------------------------------------------------- #define ASSERT BSLS_BSLTESTUTIL_ASSERT #define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT #define ASSERTV BSLS_BSLTESTUTIL_ASSERTV #define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally. #define P BSLS_BSLTESTUTIL_P // Print identifier and value. #define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'. #define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLS_BSLTESTUTIL_L_ // current Line number #define RUN_EACH_TYPE BSLTF_TEMPLATETESTFACILITY_RUN_EACH_TYPE // ============================================================================ // NEGATIVE-TEST MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR) #define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR) #define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR) #define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR) #define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR) #define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR) // ============================================================================ // PRINTF FORMAT MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ZU BSLS_BSLTESTUTIL_FORMAT_ZU // ============================================================================ // GLOBAL TEST ALIASES // ---------------------------------------------------------------------------- using namespace BloombergLP; // ============================================================================ // GLOBAL TEST VALUES // ---------------------------------------------------------------------------- static bool verbose; static bool veryVerbose; static bool veryVeryVerbose; static bool veryVeryVeryVerbose; // ============================================================================ // TEST FUNCTIONS // ---------------------------------------------------------------------------- #ifndef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY struct IsOdd { // A standard compliant C++03 unary predicate functor that returns 'true' // if an 'int' value is odd. // PUBLIC TYPES typedef char argument_type; typedef bool result_type; // ACCESSORS result_type operator()(argument_type value) const // Return 'true' if the specified 'value' is odd, and 'false' // otherwise. { return (value % 2) != 0; } }; // A function (as opposed to a functor) bool isEven(char value) // Return 'true' if the specified 'value' is even, and 'false' otherwise. { return (value % 2) == 0; } template <class VALUE> void runTestAllOf() // Test driver for 'all_of'. { struct { const char *d_spec; bool d_result; } DATA_EVEN[] = { { "", true }, { "0", true }, { "1", false }, { "00", true }, { "01", false }, { "10", false }, { "11", false }, { "000", true }, { "001", false }, { "010", false }, { "100", false }, { "111", false } }; const size_t NUM_DATA_EVEN = sizeof DATA_EVEN / sizeof *DATA_EVEN; for (size_t i = 0; i < NUM_DATA_EVEN; ++i) { const char *const SPEC = DATA_EVEN[i].d_spec; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_EVEN[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::all_of(values.begin(), values.end(), isEven))); } struct { const char *d_spec; bool d_result; } DATA_ODD[] = { { "", true }, { "0", false }, { "1", true }, { "00", false }, { "01", false }, { "10", false }, { "11", true }, { "000", false }, { "001", false }, { "010", false }, { "100", false }, { "111", true } }; const size_t NUM_DATA_ODD = sizeof DATA_ODD / sizeof *DATA_ODD; for (size_t i = 0; i < NUM_DATA_ODD; ++i) { const char *const SPEC = DATA_ODD[i].d_spec; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_ODD[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::all_of(values.begin(), values.end(), IsOdd()))); } } template <class VALUE> void runTestAnyOf() // Test driver for 'any_of'. { struct { const char *d_spec; bool d_result; } DATA_EVEN[] = { { "", false }, { "0", true }, { "1", false }, { "00", true }, { "01", true }, { "10", true }, { "11", false }, { "000", true }, { "001", true }, { "010", true }, { "100", true }, { "111", false } }; const size_t NUM_DATA_EVEN = sizeof DATA_EVEN / sizeof *DATA_EVEN; for (size_t i = 0; i < NUM_DATA_EVEN; ++i) { const char *const SPEC = DATA_EVEN[i].d_spec; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_EVEN[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::any_of(values.begin(), values.end(), isEven))); } struct { const char *d_spec; bool d_result; } DATA_ODD[] = { { "", false }, { "0", false }, { "1", true }, { "00", false }, { "01", true }, { "10", true }, { "11", true }, { "000", false }, { "001", true }, { "010", true }, { "100", true }, { "111", true } }; const size_t NUM_DATA_ODD = sizeof DATA_ODD / sizeof *DATA_ODD; for (size_t i = 0; i < NUM_DATA_ODD; ++i) { const char *const SPEC = DATA_ODD[i].d_spec; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_ODD[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::any_of(values.begin(), values.end(), IsOdd()))); } } template <class VALUE> void runTestNoneOf() // Test driver for 'none_of'. { struct { const char *d_spec; bool d_result; } DATA_EVEN[] = { { "", true }, { "0", false }, { "1", true }, { "00", false }, { "01", false }, { "10", false }, { "11", true }, { "000", false }, { "001", false }, { "010", false }, { "100", false }, { "111", true } }; const size_t NUM_DATA_EVEN = sizeof DATA_EVEN / sizeof *DATA_EVEN; for (size_t i = 0; i < NUM_DATA_EVEN; ++i) { const char *const SPEC = DATA_EVEN[i].d_spec; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_EVEN[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::none_of(values.begin(), values.end(), isEven))); } struct { const char *d_spec; bool d_result; } DATA_ODD[] = { { "", true }, { "0", true }, { "1", false }, { "00", true }, { "01", false }, { "10", false }, { "11", false }, { "000", true }, { "001", false }, { "010", false }, { "100", false }, { "111", false } }; const size_t NUM_DATA_ODD = sizeof DATA_ODD / sizeof *DATA_ODD; for (size_t i = 0; i < NUM_DATA_ODD; ++i) { const char *const SPEC = DATA_ODD[i].d_spec; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_ODD[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::none_of(values.begin(), values.end(), IsOdd()))); } } #endif // ============================================================================ // MAIN PROGRAM // ---------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; verbose = argc > 2; veryVerbose = argc > 3; veryVeryVerbose = argc > 4; veryVeryVeryVerbose = argc > 5; printf("TEST " __FILE__ " CASE %d\n", test); switch (test) { case 0: case 1: { // -------------------------------------------------------------------- // FUNCTIONALITY TEST // // Concerns: //: 1 That the routines exist in the 'bsl' namespace and behave as // expected. // // Plan: //: 1 Run each method with an empty input range and verify that the //: behavior is as expected. //: 2 Run each method with a single-element input range and verify that //: the behavior is as expected. //: 3 Run each method with multiple-element input range and verify that //: the behavior is as expected. // // Testing: // bool all_of (InputIter first, InputIter last, PREDICATE pred); // bool any_of (InputIter first, InputIter last, PREDICATE pred); // bool none_of(InputIter first, InputIter last, PREDICATE pred); // -------------------------------------------------------------------- if (verbose) printf("\nFUNCTIONALITY TEST" "\n==================\n"); #ifndef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY runTestAllOf<char>(); runTestAnyOf<char>(); runTestNoneOf<char>(); #endif } break; default: { fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test); testStatus = -1; } } if (testStatus > 0) { fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus); } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2020 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ---------------------------------- <commit_msg>More feedback from Clay and bde-verify; hopefully we're close now<commit_after>// bslstl_algorithm.t.cpp -*-C++-*- #include <bslstl_algorithm.h> #include <bslma_allocator.h> #include <bslma_default.h> #include <bslma_defaultallocatorguard.h> #include <bslma_destructorguard.h> #include <bslma_testallocator.h> #include <bslma_testallocatormonitor.h> #include <bslma_usesbslmaallocator.h> #include <bsls_asserttest.h> #include <bsls_bsltestutil.h> #include <bsltf_testvaluesarray.h> #include <bsltf_templatetestfacility.h> #include <functional> #include <limits.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> // atoi #include <string.h> // strlen // ============================================================================ // TEST PLAN // ---------------------------------------------------------------------------- // The component under test provides implementations for algorithms not // provided by the underlying standard library implementation. // ---------------------------------------------------------------------------- // // [ 1] bool all_of (InputIter first, InputIter last, PREDICATE pred); // [ 1] bool any_of (InputIter first, InputIter last, PREDICATE pred); // [ 1] bool none_of(InputIter first, InputIter last, PREDICATE pred); // ---------------------------------------------------------------------------- // ============================================================================ // STANDARD BDE ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- // NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY // FUNCTIONS, INCLUDING IOSTREAMS. namespace { int testStatus = 0; void aSsErT(bool b, const char *s, int i) { if (b) { printf("Error " __FILE__ "(%d): %s (failed)\n", i, s); if (testStatus >= 0 && testStatus <= 100) ++testStatus; } } } // close unnamed namespace // ============================================================================ // STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLS_BSLTESTUTIL_ASSERT #define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT #define ASSERTV BSLS_BSLTESTUTIL_ASSERTV #define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally. #define P BSLS_BSLTESTUTIL_P // Print identifier and value. #define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'. #define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLS_BSLTESTUTIL_L_ // current Line number #define RUN_EACH_TYPE BSLTF_TEMPLATETESTFACILITY_RUN_EACH_TYPE // ============================================================================ // NEGATIVE-TEST MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR) #define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR) #define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR) #define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR) #define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR) #define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR) // ============================================================================ // PRINTF FORMAT MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ZU BSLS_BSLTESTUTIL_FORMAT_ZU // ============================================================================ // GLOBAL TEST ALIASES // ---------------------------------------------------------------------------- using namespace BloombergLP; // ============================================================================ // GLOBAL TEST VALUES // ---------------------------------------------------------------------------- static bool verbose; static bool veryVerbose; static bool veryVeryVerbose; static bool veryVeryVeryVerbose; // ============================================================================ // TEST FUNCTIONS // ---------------------------------------------------------------------------- #ifndef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY struct IsOdd { // A standard compliant C++03 unary predicate functor that returns 'true' // if an 'int' value is odd. // PUBLIC TYPES typedef char argument_type; typedef bool result_type; // ACCESSORS result_type operator()(argument_type value) const // Return 'true' if the specified 'value' is odd, and 'false' // otherwise. { return (value % 2) != 0; } }; // A function (as opposed to a functor) bool isEven(char value) // Return 'true' if the specified 'value' is even, and 'false' otherwise. { return (value % 2) == 0; } template <class VALUE> void runTestAllOf() // Test driver for 'all_of'. { const struct { const char *d_spec_p; bool d_result; } DATA_EVEN[] = { { "", true }, { "0", true }, { "1", false }, { "00", true }, { "01", false }, { "10", false }, { "11", false }, { "000", true }, { "001", false }, { "010", false }, { "100", false }, { "101", false }, { "111", false } }; const size_t NUM_DATA_EVEN = sizeof DATA_EVEN / sizeof *DATA_EVEN; for (size_t i = 0; i < NUM_DATA_EVEN; ++i) { const char *const SPEC = DATA_EVEN[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_EVEN[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::all_of(values.begin(), values.end(), isEven))); } const struct { const char *d_spec_p; bool d_result; } DATA_ODD[] = { { "", true }, { "0", false }, { "1", true }, { "00", false }, { "01", false }, { "10", false }, { "11", true }, { "000", false }, { "001", false }, { "010", false }, { "100", false }, { "101", false }, { "111", true } }; const size_t NUM_DATA_ODD = sizeof DATA_ODD / sizeof *DATA_ODD; for (size_t i = 0; i < NUM_DATA_ODD; ++i) { const char *const SPEC = DATA_ODD[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_ODD[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::all_of(values.begin(), values.end(), IsOdd()))); } } template <class VALUE> void runTestAnyOf() // Test driver for 'any_of'. { const struct { const char *d_spec_p; bool d_result; } DATA_EVEN[] = { { "", false }, { "0", true }, { "1", false }, { "00", true }, { "01", true }, { "10", true }, { "11", false }, { "000", true }, { "001", true }, { "010", true }, { "100", true }, { "101", true }, { "111", false } }; const size_t NUM_DATA_EVEN = sizeof DATA_EVEN / sizeof *DATA_EVEN; for (size_t i = 0; i < NUM_DATA_EVEN; ++i) { const char *const SPEC = DATA_EVEN[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_EVEN[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::any_of(values.begin(), values.end(), isEven))); } const struct { const char *d_spec_p; bool d_result; } DATA_ODD[] = { { "", false }, { "0", false }, { "1", true }, { "00", false }, { "01", true }, { "10", true }, { "11", true }, { "000", false }, { "001", true }, { "010", true }, { "100", true }, { "101", true }, { "111", true } }; const size_t NUM_DATA_ODD = sizeof DATA_ODD / sizeof *DATA_ODD; for (size_t i = 0; i < NUM_DATA_ODD; ++i) { const char *const SPEC = DATA_ODD[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_ODD[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::any_of(values.begin(), values.end(), IsOdd()))); } } template <class VALUE> void runTestNoneOf() // Test driver for 'none_of'. { const struct { const char *d_spec_p; bool d_result; } DATA_EVEN[] = { { "", true }, { "0", false }, { "1", true }, { "00", false }, { "01", false }, { "10", false }, { "11", true }, { "000", false }, { "001", false }, { "010", false }, { "100", false }, { "101", false }, { "111", true } }; const size_t NUM_DATA_EVEN = sizeof DATA_EVEN / sizeof *DATA_EVEN; for (size_t i = 0; i < NUM_DATA_EVEN; ++i) { const char *const SPEC = DATA_EVEN[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_EVEN[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::none_of(values.begin(), values.end(), isEven))); } const struct { const char *d_spec_p; bool d_result; } DATA_ODD[] = { { "", true }, { "0", true }, { "1", false }, { "00", true }, { "01", false }, { "10", false }, { "11", false }, { "000", true }, { "001", false }, { "010", false }, { "100", false }, { "101", false }, { "111", false } }; const size_t NUM_DATA_ODD = sizeof DATA_ODD / sizeof *DATA_ODD; for (size_t i = 0; i < NUM_DATA_ODD; ++i) { const char *const SPEC = DATA_ODD[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_ODD[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::none_of(values.begin(), values.end(), IsOdd()))); } } #endif // ============================================================================ // MAIN PROGRAM // ---------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; verbose = argc > 2; veryVerbose = argc > 3; veryVeryVerbose = argc > 4; veryVeryVeryVerbose = argc > 5; printf("TEST " __FILE__ " CASE %d\n", test); switch (test) { case 0: case 1: { // -------------------------------------------------------------------- // FUNCTIONALITY TEST // // Concerns: //: 1 That the routines exist in the 'bsl' namespace and behave as // expected. // // Plan: //: 1 Run each method with an empty input range and verify that the //: behavior is as expected. //: 2 Run each method with a single-element input range and verify that //: the behavior is as expected. //: 3 Run each method with multiple-element input range and verify that //: the behavior is as expected. // // Testing: // bool all_of (InputIter first, InputIter last, PREDICATE pred); // bool any_of (InputIter first, InputIter last, PREDICATE pred); // bool none_of(InputIter first, InputIter last, PREDICATE pred); // -------------------------------------------------------------------- if (verbose) printf("\nFUNCTIONALITY TEST" "\n==================\n"); #ifndef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY runTestAllOf<char>(); runTestAnyOf<char>(); runTestNoneOf<char>(); #endif } break; default: { fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test); testStatus = -1; } } if (testStatus > 0) { fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus); } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2020 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ---------------------------------- <|endoftext|>
<commit_before>// bslstl_algorithm.t.cpp -*-C++-*- #include <bslstl_algorithm.h> #include <bslma_allocator.h> #include <bslma_default.h> #include <bslma_defaultallocatorguard.h> #include <bslma_destructorguard.h> #include <bslma_testallocator.h> #include <bslma_testallocatormonitor.h> #include <bslma_usesbslmaallocator.h> #include <bsls_asserttest.h> #include <bsls_bsltestutil.h> #include <bsltf_testvaluesarray.h> #include <bsltf_templatetestfacility.h> #include <functional> #include <limits.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> // atoi #include <string.h> // strlen // ============================================================================ // TEST PLAN // ---------------------------------------------------------------------------- // The component under test provides implementations for algorithms not // provided by the underlying standard library implementation. // ---------------------------------------------------------------------------- // // [ 1] bool all_of (InputIter first, InputIter last, PREDICATE pred); // [ 1] bool any_of (InputIter first, InputIter last, PREDICATE pred); // [ 1] bool none_of(InputIter first, InputIter last, PREDICATE pred); // ---------------------------------------------------------------------------- // ============================================================================ // STANDARD BDE ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- // NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY // FUNCTIONS, INCLUDING IOSTREAMS. namespace { int testStatus = 0; void aSsErT(bool b, const char *s, int i) { if (b) { printf("Error " __FILE__ "(%d): %s (failed)\n", i, s); if (testStatus >= 0 && testStatus <= 100) ++testStatus; } } } // close unnamed namespace // ============================================================================ // STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLS_BSLTESTUTIL_ASSERT #define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT #define ASSERTV BSLS_BSLTESTUTIL_ASSERTV #define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally. #define P BSLS_BSLTESTUTIL_P // Print identifier and value. #define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'. #define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLS_BSLTESTUTIL_L_ // current Line number #define RUN_EACH_TYPE BSLTF_TEMPLATETESTFACILITY_RUN_EACH_TYPE // ============================================================================ // NEGATIVE-TEST MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR) #define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR) #define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR) #define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR) #define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR) #define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR) // ============================================================================ // PRINTF FORMAT MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ZU BSLS_BSLTESTUTIL_FORMAT_ZU // ============================================================================ // GLOBAL TEST ALIASES // ---------------------------------------------------------------------------- using namespace BloombergLP; // ============================================================================ // GLOBAL TEST VALUES // ---------------------------------------------------------------------------- static bool verbose; static bool veryVerbose; static bool veryVeryVerbose; static bool veryVeryVeryVerbose; // ============================================================================ // TEST FUNCTIONS // ---------------------------------------------------------------------------- #ifndef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY struct IsOdd { // A standard compliant C++03 unary predicate functor that returns 'true' // if an 'int' value is odd. // PUBLIC TYPES typedef char argument_type; typedef bool result_type; // ACCESSORS result_type operator()(argument_type value) const // Return 'true' if the specified 'value' is odd, and 'false' // otherwise. { return (value % 2) != 0; } }; // A function (as opposed to a functor) bool isEven(char value) // Return 'true' if the specified 'value' is even, and 'false' otherwise. { return (value % 2) == 0; } template <class VALUE> void runTestAllOf() // Test driver for 'all_of'. { const struct { const char *d_spec_p; bool d_result; } DATA_EVEN[] = { { "", true }, { "0", true }, { "1", false }, { "00", true }, { "01", false }, { "10", false }, { "11", false }, { "000", true }, { "001", false }, { "010", false }, { "100", false }, { "101", false }, { "111", false } }; const size_t NUM_DATA_EVEN = sizeof DATA_EVEN / sizeof *DATA_EVEN; for (size_t i = 0; i < NUM_DATA_EVEN; ++i) { const char *const SPEC = DATA_EVEN[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_EVEN[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::all_of(values.begin(), values.end(), isEven))); } const struct { const char *d_spec_p; bool d_result; } DATA_ODD[] = { { "", true }, { "0", false }, { "1", true }, { "00", false }, { "01", false }, { "10", false }, { "11", true }, { "000", false }, { "001", false }, { "010", false }, { "100", false }, { "101", false }, { "111", true } }; const size_t NUM_DATA_ODD = sizeof DATA_ODD / sizeof *DATA_ODD; for (size_t i = 0; i < NUM_DATA_ODD; ++i) { const char *const SPEC = DATA_ODD[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_ODD[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::all_of(values.begin(), values.end(), IsOdd()))); } } template <class VALUE> void runTestAnyOf() // Test driver for 'any_of'. { const struct { const char *d_spec_p; bool d_result; } DATA_EVEN[] = { { "", false }, { "0", true }, { "1", false }, { "00", true }, { "01", true }, { "10", true }, { "11", false }, { "000", true }, { "001", true }, { "010", true }, { "100", true }, { "101", true }, { "111", false } }; const size_t NUM_DATA_EVEN = sizeof DATA_EVEN / sizeof *DATA_EVEN; for (size_t i = 0; i < NUM_DATA_EVEN; ++i) { const char *const SPEC = DATA_EVEN[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_EVEN[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::any_of(values.begin(), values.end(), isEven))); } const struct { const char *d_spec_p; bool d_result; } DATA_ODD[] = { { "", false }, { "0", false }, { "1", true }, { "00", false }, { "01", true }, { "10", true }, { "11", true }, { "000", false }, { "001", true }, { "010", true }, { "100", true }, { "101", true }, { "111", true } }; const size_t NUM_DATA_ODD = sizeof DATA_ODD / sizeof *DATA_ODD; for (size_t i = 0; i < NUM_DATA_ODD; ++i) { const char *const SPEC = DATA_ODD[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_ODD[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::any_of(values.begin(), values.end(), IsOdd()))); } } template <class VALUE> void runTestNoneOf() // Test driver for 'none_of'. { const struct { const char *d_spec_p; bool d_result; } DATA_EVEN[] = { { "", true }, { "0", false }, { "1", true }, { "00", false }, { "01", false }, { "10", false }, { "11", true }, { "000", false }, { "001", false }, { "010", false }, { "100", false }, { "101", false }, { "111", true } }; const size_t NUM_DATA_EVEN = sizeof DATA_EVEN / sizeof *DATA_EVEN; for (size_t i = 0; i < NUM_DATA_EVEN; ++i) { const char *const SPEC = DATA_EVEN[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_EVEN[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::none_of(values.begin(), values.end(), isEven))); } const struct { const char *d_spec_p; bool d_result; } DATA_ODD[] = { { "", true }, { "0", true }, { "1", false }, { "00", true }, { "01", false }, { "10", false }, { "11", false }, { "000", true }, { "001", false }, { "010", false }, { "100", false }, { "101", false }, { "111", false } }; const size_t NUM_DATA_ODD = sizeof DATA_ODD / sizeof *DATA_ODD; for (size_t i = 0; i < NUM_DATA_ODD; ++i) { const char *const SPEC = DATA_ODD[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_ODD[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::none_of(values.begin(), values.end(), IsOdd()))); } } #endif // ============================================================================ // MAIN PROGRAM // ---------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; verbose = argc > 2; veryVerbose = argc > 3; veryVeryVerbose = argc > 4; veryVeryVeryVerbose = argc > 5; printf("TEST " __FILE__ " CASE %d\n", test); switch (test) { case 0: case 1: { // -------------------------------------------------------------------- // FUNCTIONALITY TEST // // Concerns: //: 1 That the routines exist in the 'bsl' namespace and behave as // expected. // // Plan: //: 1 Run each method with an empty input range and verify that the //: behavior is as expected. //: 2 Run each method with a single-element input range and verify that //: the behavior is as expected. //: 3 Run each method with multiple-element input range and verify that //: the behavior is as expected. // // Testing: // bool all_of (InputIter first, InputIter last, PREDICATE pred); // bool any_of (InputIter first, InputIter last, PREDICATE pred); // bool none_of(InputIter first, InputIter last, PREDICATE pred); // -------------------------------------------------------------------- if (verbose) printf("\nFUNCTIONALITY TEST" "\n==================\n"); #ifndef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY runTestAllOf<char>(); runTestAnyOf<char>(); runTestNoneOf<char>(); #endif } break; default: { fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test); testStatus = -1; } } if (testStatus > 0) { fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus); } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2020 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ---------------------------------- <commit_msg>Alphabetize the includes of the blstf headers<commit_after>// bslstl_algorithm.t.cpp -*-C++-*- #include <bslstl_algorithm.h> #include <bslma_allocator.h> #include <bslma_default.h> #include <bslma_defaultallocatorguard.h> #include <bslma_destructorguard.h> #include <bslma_testallocator.h> #include <bslma_testallocatormonitor.h> #include <bslma_usesbslmaallocator.h> #include <bsls_asserttest.h> #include <bsls_bsltestutil.h> #include <bsltf_templatetestfacility.h> #include <bsltf_testvaluesarray.h> #include <functional> #include <limits.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> // atoi #include <string.h> // strlen // ============================================================================ // TEST PLAN // ---------------------------------------------------------------------------- // The component under test provides implementations for algorithms not // provided by the underlying standard library implementation. // ---------------------------------------------------------------------------- // // [ 1] bool all_of (InputIter first, InputIter last, PREDICATE pred); // [ 1] bool any_of (InputIter first, InputIter last, PREDICATE pred); // [ 1] bool none_of(InputIter first, InputIter last, PREDICATE pred); // ---------------------------------------------------------------------------- // ============================================================================ // STANDARD BDE ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- // NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY // FUNCTIONS, INCLUDING IOSTREAMS. namespace { int testStatus = 0; void aSsErT(bool b, const char *s, int i) { if (b) { printf("Error " __FILE__ "(%d): %s (failed)\n", i, s); if (testStatus >= 0 && testStatus <= 100) ++testStatus; } } } // close unnamed namespace // ============================================================================ // STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLS_BSLTESTUTIL_ASSERT #define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT #define ASSERTV BSLS_BSLTESTUTIL_ASSERTV #define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally. #define P BSLS_BSLTESTUTIL_P // Print identifier and value. #define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'. #define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLS_BSLTESTUTIL_L_ // current Line number #define RUN_EACH_TYPE BSLTF_TEMPLATETESTFACILITY_RUN_EACH_TYPE // ============================================================================ // NEGATIVE-TEST MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR) #define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR) #define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR) #define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR) #define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR) #define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR) // ============================================================================ // PRINTF FORMAT MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ZU BSLS_BSLTESTUTIL_FORMAT_ZU // ============================================================================ // GLOBAL TEST ALIASES // ---------------------------------------------------------------------------- using namespace BloombergLP; // ============================================================================ // GLOBAL TEST VALUES // ---------------------------------------------------------------------------- static bool verbose; static bool veryVerbose; static bool veryVeryVerbose; static bool veryVeryVeryVerbose; // ============================================================================ // TEST FUNCTIONS // ---------------------------------------------------------------------------- #ifndef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY struct IsOdd { // A standard compliant C++03 unary predicate functor that returns 'true' // if an 'int' value is odd. // PUBLIC TYPES typedef char argument_type; typedef bool result_type; // ACCESSORS result_type operator()(argument_type value) const // Return 'true' if the specified 'value' is odd, and 'false' // otherwise. { return (value % 2) != 0; } }; // A function (as opposed to a functor) bool isEven(char value) // Return 'true' if the specified 'value' is even, and 'false' otherwise. { return (value % 2) == 0; } template <class VALUE> void runTestAllOf() // Test driver for 'all_of'. { const struct { const char *d_spec_p; bool d_result; } DATA_EVEN[] = { { "", true }, { "0", true }, { "1", false }, { "00", true }, { "01", false }, { "10", false }, { "11", false }, { "000", true }, { "001", false }, { "010", false }, { "100", false }, { "101", false }, { "111", false } }; const size_t NUM_DATA_EVEN = sizeof DATA_EVEN / sizeof *DATA_EVEN; for (size_t i = 0; i < NUM_DATA_EVEN; ++i) { const char *const SPEC = DATA_EVEN[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_EVEN[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::all_of(values.begin(), values.end(), isEven))); } const struct { const char *d_spec_p; bool d_result; } DATA_ODD[] = { { "", true }, { "0", false }, { "1", true }, { "00", false }, { "01", false }, { "10", false }, { "11", true }, { "000", false }, { "001", false }, { "010", false }, { "100", false }, { "101", false }, { "111", true } }; const size_t NUM_DATA_ODD = sizeof DATA_ODD / sizeof *DATA_ODD; for (size_t i = 0; i < NUM_DATA_ODD; ++i) { const char *const SPEC = DATA_ODD[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_ODD[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::all_of(values.begin(), values.end(), IsOdd()))); } } template <class VALUE> void runTestAnyOf() // Test driver for 'any_of'. { const struct { const char *d_spec_p; bool d_result; } DATA_EVEN[] = { { "", false }, { "0", true }, { "1", false }, { "00", true }, { "01", true }, { "10", true }, { "11", false }, { "000", true }, { "001", true }, { "010", true }, { "100", true }, { "101", true }, { "111", false } }; const size_t NUM_DATA_EVEN = sizeof DATA_EVEN / sizeof *DATA_EVEN; for (size_t i = 0; i < NUM_DATA_EVEN; ++i) { const char *const SPEC = DATA_EVEN[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_EVEN[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::any_of(values.begin(), values.end(), isEven))); } const struct { const char *d_spec_p; bool d_result; } DATA_ODD[] = { { "", false }, { "0", false }, { "1", true }, { "00", false }, { "01", true }, { "10", true }, { "11", true }, { "000", false }, { "001", true }, { "010", true }, { "100", true }, { "101", true }, { "111", true } }; const size_t NUM_DATA_ODD = sizeof DATA_ODD / sizeof *DATA_ODD; for (size_t i = 0; i < NUM_DATA_ODD; ++i) { const char *const SPEC = DATA_ODD[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_ODD[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::any_of(values.begin(), values.end(), IsOdd()))); } } template <class VALUE> void runTestNoneOf() // Test driver for 'none_of'. { const struct { const char *d_spec_p; bool d_result; } DATA_EVEN[] = { { "", true }, { "0", false }, { "1", true }, { "00", false }, { "01", false }, { "10", false }, { "11", true }, { "000", false }, { "001", false }, { "010", false }, { "100", false }, { "101", false }, { "111", true } }; const size_t NUM_DATA_EVEN = sizeof DATA_EVEN / sizeof *DATA_EVEN; for (size_t i = 0; i < NUM_DATA_EVEN; ++i) { const char *const SPEC = DATA_EVEN[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_EVEN[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::none_of(values.begin(), values.end(), isEven))); } const struct { const char *d_spec_p; bool d_result; } DATA_ODD[] = { { "", true }, { "0", true }, { "1", false }, { "00", true }, { "01", false }, { "10", false }, { "11", false }, { "000", true }, { "001", false }, { "010", false }, { "100", false }, { "101", false }, { "111", false } }; const size_t NUM_DATA_ODD = sizeof DATA_ODD / sizeof *DATA_ODD; for (size_t i = 0; i < NUM_DATA_ODD; ++i) { const char *const SPEC = DATA_ODD[i].d_spec_p; const VALUE EXP = bsltf::TemplateTestFacility::create<VALUE>(DATA_ODD[i].d_result); bsltf::TestValuesArray<VALUE> values(SPEC); ASSERT((EXP == bsl::none_of(values.begin(), values.end(), IsOdd()))); } } #endif // ============================================================================ // MAIN PROGRAM // ---------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; verbose = argc > 2; veryVerbose = argc > 3; veryVeryVerbose = argc > 4; veryVeryVeryVerbose = argc > 5; printf("TEST " __FILE__ " CASE %d\n", test); switch (test) { case 0: case 1: { // -------------------------------------------------------------------- // FUNCTIONALITY TEST // // Concerns: //: 1 That the routines exist in the 'bsl' namespace and behave as // expected. // // Plan: //: 1 Run each method with an empty input range and verify that the //: behavior is as expected. //: 2 Run each method with a single-element input range and verify that //: the behavior is as expected. //: 3 Run each method with multiple-element input range and verify that //: the behavior is as expected. // // Testing: // bool all_of (InputIter first, InputIter last, PREDICATE pred); // bool any_of (InputIter first, InputIter last, PREDICATE pred); // bool none_of(InputIter first, InputIter last, PREDICATE pred); // -------------------------------------------------------------------- if (verbose) printf("\nFUNCTIONALITY TEST" "\n==================\n"); #ifndef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY runTestAllOf<char>(); runTestAnyOf<char>(); runTestNoneOf<char>(); #endif } break; default: { fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test); testStatus = -1; } } if (testStatus > 0) { fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus); } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2020 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ---------------------------------- <|endoftext|>
<commit_before>#include <mlopen/hipoc_program.hpp> #include <mlopen/kernel.hpp> #include <mlopen/errors.hpp> #include <unistd.h> namespace mlopen { std::string GetFileName(const HIPOCProgram::FilePtr& f) { auto fd = fileno(f.get()); std::string path = "/proc/self/fd/" + std::to_string(fd); std::array<char, 256> buffer{}; readlink(path.c_str(), buffer.data(), buffer.size()); return buffer.data(); } hipModulePtr CreateModule(const std::string& program_name, std::string params) { HIPOCProgram::FilePtr tmpsrc{std::tmpfile()}; std::string src = GetKernelSrc(program_name); std::string src_name = GetFileName(tmpsrc); if (std::fwrite(src.c_str(), 1, src.size(), tmpsrc.get()) != src.size()) MLOPEN_THROW("Failed to write to src file"); std::system((HIP_OC_COMPILER + std::string(" -march=hsail64 -mdevice=Fiji -cl-denorms-are-zero -save-temps=dump -nobin ") + params + " " + src_name).c_str()); std::string obj_file = src_name + "_obj"; std::system((HIP_OC_FINALIZER + std::string("-target=8:0:3 -hsail dump_0_Fiji.hsail -output=") + obj_file ).c_str()); hipModule_t raw_m; auto status = hipModuleLoad(&raw_m, obj_file.c_str()); hipModulePtr m{raw_m}; std::remove(obj_file.c_str()); if (status != hipSuccess) MLOPEN_THROW("Failed creating module"); return m; } HIPOCProgram::HIPOCProgram() {} HIPOCProgram::HIPOCProgram(const std::string &program_name, std::string params) { this->module = CreateModule(program_name, params); } } <commit_msg>Log commands<commit_after>#include <mlopen/hipoc_program.hpp> #include <mlopen/kernel.hpp> #include <mlopen/errors.hpp> #include <unistd.h> namespace mlopen { void execute(std::string s) { std::cout << s << std::endl; std::system(s.c_str()); } std::string quote(std::string s) { return '"' + s + '"'; } std::string GetFileName(const HIPOCProgram::FilePtr& f) { auto fd = fileno(f.get()); std::string path = "/proc/self/fd/" + std::to_string(fd); std::array<char, 256> buffer{}; if (readlink(path.c_str(), buffer.data(), buffer.size()-1) == -1) MLOPEN_THROW("Error reading filename"); return buffer.data(); } hipModulePtr CreateModule(const std::string& program_name, std::string params) { HIPOCProgram::FilePtr tmpsrc{std::tmpfile()}; std::string src = GetKernelSrc(program_name); std::string src_name = GetFileName(tmpsrc); if (std::fwrite(src.c_str(), 1, src.size(), tmpsrc.get()) != src.size()) MLOPEN_THROW("Failed to write to src file"); execute(HIP_OC_COMPILER + std::string(" -march=hsail64 -mdevice=Fiji -cl-denorms-are-zero -save-temps=dump -nobin ") + params + " " + quote(src_name)); std::string obj_file = src_name + "_obj"; execute(HIP_OC_FINALIZER + std::string(" -target=8:0:3 -hsail dump_0_Fiji.hsail -output=") + quote(obj_file) ); hipModule_t raw_m; auto status = hipModuleLoad(&raw_m, obj_file.c_str()); hipModulePtr m{raw_m}; std::remove(obj_file.c_str()); if (status != hipSuccess) MLOPEN_THROW("Failed creating module"); return m; } HIPOCProgram::HIPOCProgram() {} HIPOCProgram::HIPOCProgram(const std::string &program_name, std::string params) { this->module = CreateModule(program_name, params); } } <|endoftext|>
<commit_before>// Copyright 2015 Patrick Putnam // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef CLOTHO_NEUTRAL_ALLELE_HPP_ #define CLOTHO_NEUTRAL_ALLELE_HPP_ #include "clotho/data_spaces/allele_space/base_allele.hpp" #include "clotho/utility/state_object.hpp" #include "clotho/utility/log_helper.hpp" #include "clotho/utility/bit_helper.hpp" namespace clotho { namespace genetics { template < class PositionType > class neutral_allele_vectorized : public base_allele_vectorized< PositionType > { public: typedef base_allele_vectorized< PositionType > base_type; typedef neutral_allele_vectorized< PositionType > self_type; typedef unsigned long long block_type; typedef block_type * neutrality_vector_type; typedef clotho::utility::BitHelper< block_type > bit_helper_type; neutral_allele_vectorized( size_t a = 0 ) : base_type( a ) , m_neutral( NULL ) , m_block_size(0) , m_block_alloc(0) { this->grow( a ); } bool getNeutralAt( size_t index ) const { assert( 0 <= index && index < this->m_pos_size ); size_t bidx = index / bit_helper_type::BITS_PER_BLOCK; block_type bmask = bit_helper_type::bit_offset(index); return m_neutral[ bidx ] & bmask; } void setNeutralAt( size_t index, bool neu ) { assert( 0 <= index && index < this->m_pos_size ); size_t bidx = index / bit_helper_type::BITS_PER_BLOCK; block_type mask = bit_helper_type::bit_offset(index); if( ((m_neutral[ bidx ] & mask) == mask) != neu ) m_neutral[ bidx ] ^= mask; } // bool getNeutralAt( size_t index ) const { // return m_neutral[ index ]; // } // // void setNeutralAt( size_t index, bool neu ) { // if( index >= base_type::size() ) { // resize( index + 1 ); // } // // m_neutral[ index ] = neu; // } // bool isAllNeutral() const { // const_neutrality_iterator first = m_neutral.begin(), last = this->m_neutral.end(); // bool all_neutral = true; // while( all_neutral && first != last ) { // all_neutral = *first++; // } // // return all_neutral; // } bool isAllNeutral() const { for( size_t i = 0; i < m_block_size - 1; ++i ) { if( m_neutral[i] != bit_helper_type::ALL_SET ) return false; } block_type mask = bit_helper_type::low_bit_mask( this->m_pos_size - 1 ); // std::cerr << "Comparing: " << std::hex << m_neutral[m_block_size - 1] << " to " << mask << std::dec << std::endl; // std::cerr << "Checking: " << (m_block_size - 1) << std::endl; return m_neutral[m_block_size - 1] == mask; } void inherit( self_type & parent ) { // inherit positions assert( parent.size() <= this->size() ); memcpy( this->m_positions, parent.m_positions, parent.size() * sizeof(typename base_type::base_type::position_type) ); // inherit neutral assert( parent.m_block_size < this->m_block_alloc ); std::copy( parent.m_neutral, parent.m_neutral + parent.m_block_size, this->m_neutral ); } // neutrality_iterator neutral_begin() { // return m_neutral.begin(); // } // // neutrality_iterator neutral_end() { // return m_neutral.end(); // } // // const_neutrality_iterator neutral_begin() const { // return m_neutral.begin(); // } // // const_neutrality_iterator neutral_end() const { // return m_neutral.end(); // } void push_back( self_type & other, size_t idx ) { size_t e = this->size(); this->resize( e + 1 ); this->setPositionAt( e, other.getPositionAt( idx ) ); this->setNeutralAt( e, other.getNeutralAt( idx ) ); } virtual size_t grow( size_t rows ) { this->resize( rows ); return this->size(); } virtual ~neutral_allele_vectorized() { if( m_neutral != NULL ) { delete [] m_neutral; } } protected: virtual void resize( size_t s ) { base_type::resize( s ); size_t bc = bit_helper_type::padded_block_count( s ); if( bc > m_block_alloc ) { if( m_neutral != NULL ) { delete [] m_neutral; } m_neutral = new block_type[ bc ]; m_block_alloc = bc; } memset( m_neutral, 0, m_block_alloc * sizeof(block_type)); m_block_size = bc; } neutrality_vector_type m_neutral; size_t m_block_size, m_block_alloc; }; } // namespace genetics } // namespace clotho namespace clotho { namespace utility { template < class PositionType > struct state_getter< clotho::genetics::neutral_allele_vectorized< PositionType > > { typedef clotho::genetics::neutral_allele_vectorized< PositionType > object_type; void operator()( boost::property_tree::ptree & s, object_type & obj ) { size_t all_count = obj.allele_count(); size_t i = 0; while( i < all_count ) { boost::property_tree::ptree all; all.put( "position", obj.getPositionAt(i) ); all.put( "neutral", obj.getNeutralAt(i) ); s.push_back( std::make_pair("", all ) ); ++i; } } }; } // namespace utility } // namespace clotho #endif // CLOTHO_NEUTRAL_ALLELE_HPP_ <commit_msg>Correcting block calculation<commit_after>// Copyright 2015 Patrick Putnam // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef CLOTHO_NEUTRAL_ALLELE_HPP_ #define CLOTHO_NEUTRAL_ALLELE_HPP_ #include "clotho/data_spaces/allele_space/base_allele.hpp" #include "clotho/utility/state_object.hpp" #include "clotho/utility/log_helper.hpp" #include "clotho/utility/bit_helper.hpp" namespace clotho { namespace genetics { template < class PositionType > class neutral_allele_vectorized : public base_allele_vectorized< PositionType > { public: typedef base_allele_vectorized< PositionType > base_type; typedef neutral_allele_vectorized< PositionType > self_type; typedef unsigned long long block_type; typedef block_type * neutrality_vector_type; typedef clotho::utility::BitHelper< block_type > bit_helper_type; neutral_allele_vectorized( size_t a = 0 ) : base_type( a ) , m_neutral( NULL ) , m_block_size(0) , m_block_alloc(0) { this->grow( a ); } bool getNeutralAt( size_t index ) const { assert( 0 <= index && index < this->m_pos_size ); size_t bidx = index / bit_helper_type::BITS_PER_BLOCK; block_type bmask = bit_helper_type::bit_offset(index); return m_neutral[ bidx ] & bmask; } void setNeutralAt( size_t index, bool neu ) { assert( 0 <= index && index < this->m_pos_size ); size_t bidx = index / bit_helper_type::BITS_PER_BLOCK; block_type mask = bit_helper_type::bit_offset(index); if( ((m_neutral[ bidx ] & mask) == mask) != neu ) m_neutral[ bidx ] ^= mask; } // bool getNeutralAt( size_t index ) const { // return m_neutral[ index ]; // } // // void setNeutralAt( size_t index, bool neu ) { // if( index >= base_type::size() ) { // resize( index + 1 ); // } // // m_neutral[ index ] = neu; // } // bool isAllNeutral() const { // const_neutrality_iterator first = m_neutral.begin(), last = this->m_neutral.end(); // bool all_neutral = true; // while( all_neutral && first != last ) { // all_neutral = *first++; // } // // return all_neutral; // } bool isAllNeutral() const { size_t N = (this->m_pos_size - 1) / bit_helper_type::BITS_PER_BLOCK; assert( N < m_block_size ); for( size_t i = 0; i < N; ++i ) { if( m_neutral[i] != bit_helper_type::ALL_SET ) return false; } block_type mask = bit_helper_type::low_bit_mask( this->m_pos_size - 1 ); // std::cerr << "Comparing: " << std::hex << m_neutral[m_block_size - 1] << " to " << mask << std::dec << std::endl; // std::cerr << "Checking: " << (m_block_size - 1) << std::endl; return m_neutral[N] == mask; } void inherit( self_type & parent ) { // inherit positions assert( parent.size() <= this->size() ); memcpy( this->m_positions, parent.m_positions, parent.size() * sizeof(typename base_type::base_type::position_type) ); // inherit neutral assert( parent.m_block_size < this->m_block_alloc ); std::copy( parent.m_neutral, parent.m_neutral + parent.m_block_size, this->m_neutral ); } // neutrality_iterator neutral_begin() { // return m_neutral.begin(); // } // // neutrality_iterator neutral_end() { // return m_neutral.end(); // } // // const_neutrality_iterator neutral_begin() const { // return m_neutral.begin(); // } // // const_neutrality_iterator neutral_end() const { // return m_neutral.end(); // } void push_back( self_type & other, size_t idx ) { size_t e = this->size(); this->resize( e + 1 ); this->setPositionAt( e, other.getPositionAt( idx ) ); this->setNeutralAt( e, other.getNeutralAt( idx ) ); } virtual size_t grow( size_t rows ) { this->resize( rows ); return this->size(); } virtual ~neutral_allele_vectorized() { if( m_neutral != NULL ) { delete [] m_neutral; } } protected: virtual void resize( size_t s ) { base_type::resize( s ); size_t bc = bit_helper_type::padded_block_count( s ); if( bc > m_block_alloc ) { if( m_neutral != NULL ) { delete [] m_neutral; } m_neutral = new block_type[ bc ]; m_block_alloc = bc; } memset( m_neutral, 0, m_block_alloc * sizeof(block_type)); m_block_size = bc; } neutrality_vector_type m_neutral; size_t m_block_size, m_block_alloc; }; } // namespace genetics } // namespace clotho namespace clotho { namespace utility { template < class PositionType > struct state_getter< clotho::genetics::neutral_allele_vectorized< PositionType > > { typedef clotho::genetics::neutral_allele_vectorized< PositionType > object_type; void operator()( boost::property_tree::ptree & s, object_type & obj ) { size_t all_count = obj.allele_count(); size_t i = 0; while( i < all_count ) { boost::property_tree::ptree all; all.put( "position", obj.getPositionAt(i) ); all.put( "neutral", obj.getNeutralAt(i) ); s.push_back( std::make_pair("", all ) ); ++i; } } }; } // namespace utility } // namespace clotho #endif // CLOTHO_NEUTRAL_ALLELE_HPP_ <|endoftext|>
<commit_before>/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * hir_typeck/impl_ref.cpp * - Reference to a trait implementation (either a bound or a impl block) */ #include "impl_ref.hpp" #include <hir/hir.hpp> #include "static.hpp" // for monomorphise_type_with bool ImplRef::more_specific_than(const ImplRef& other) const { TU_MATCH(Data, (this->m_data), (te), (TraitImpl, if( te.impl == nullptr ) { return false; } TU_MATCH(Data, (other.m_data), (oe), (TraitImpl, if( oe.impl == nullptr ) { return true; } return te.impl->more_specific_than( *oe.impl ); ), (BoundedPtr, return false; ), (Bounded, return false; ) ) ), (BoundedPtr, if( !other.m_data.is_BoundedPtr() ) return false; const auto& oe = other.m_data.as_BoundedPtr(); assert( *te.type == *oe.type ); assert( *te.trait_args == *oe.trait_args ); if( te.assoc->size() > oe.assoc->size() ) return true; return false; ), (Bounded, if( !other.m_data.is_Bounded() ) return false; const auto& oe = other.m_data.as_Bounded(); assert( te.type == oe.type ); assert( te.trait_args == oe.trait_args ); if( te.assoc.size() > oe.assoc.size() ) return true; return false; ) ) throw ""; } bool ImplRef::overlaps_with(const ::HIR::Crate& crate, const ImplRef& other) const { if( this->m_data.tag() != other.m_data.tag() ) return false; TU_MATCH(Data, (this->m_data, other.m_data), (te, oe), (TraitImpl, if( te.impl != nullptr && oe.impl != nullptr ) return te.impl->overlaps_with( crate, *oe.impl ); ), (BoundedPtr, // TODO: Bounded and BoundedPtr are compatible if( *te.type != *oe.type ) return false; if( *te.trait_args != *oe.trait_args ) return false; // Don't check associated types return true; ), (Bounded, if( te.type != oe.type ) return false; if( te.trait_args != oe.trait_args ) return false; // Don't check associated types return true; ) ) return false; } bool ImplRef::has_magic_params() const { if(const auto* e = m_data.opt_TraitImpl()) { for(const auto& t : e->impl_params.m_types) if( visit_ty_with(t, [](const ::HIR::TypeRef& t){ return t.data().is_Generic() && (t.data().as_Generic().binding >> 8) == 2; }) ) return true; } return false; } bool ImplRef::type_is_specialisable(const char* name) const { TU_MATCH(Data, (this->m_data), (e), (TraitImpl, if( e.impl == nullptr ) { // No impl yet? This type is specialisable. return true; } //TODO(Span(), "type_is_specializable - Impl = " << *this << ", Type = " << name); auto it = e.impl->m_types.find(name); if( it == e.impl->m_types.end() ) { TODO(Span(), "Handle missing type in " << *this << ", name = " << name); return false; } return it->second.is_specialisable; ), (BoundedPtr, return false; ), (Bounded, return false; ) ) throw ""; } // Returns a closure to monomorphise including placeholders (if present) ImplRef::Monomorph ImplRef::get_cb_monomorph_traitimpl(const Span& sp) const { const auto& e = this->m_data.as_TraitImpl(); return Monomorph(e); } ::HIR::TypeRef ImplRef::Monomorph::get_type(const Span& sp, const ::HIR::GenericRef& ge) const /*override*/ { if( ge.is_self() ) { // Store (or cache) a monomorphisation of Self, and error if this recurses if( this->ti.self_cache == ::HIR::TypeRef() ) { this->ti.self_cache = ::HIR::TypeRef::new_diverge(); this->ti.self_cache = this->monomorph_type(sp, this->ti.impl->m_type); } else if( this->ti.self_cache == ::HIR::TypeRef::new_diverge() ) { // BUG! BUG(sp, "Use of `Self` in expansion of `Self`"); } else { } return this->ti.self_cache.clone(); } ASSERT_BUG(sp, ge.binding < 256, "Binding in " << ge << " out of range (>=256)"); ASSERT_BUG(sp, ge.binding < this->ti.impl_params.m_types.size(), "Binding in " << ge << " out of range (>= " << this->ti.impl_params.m_types.size() << ")"); return this->ti.impl_params.m_types.at(ge.binding).clone(); } ::HIR::ConstGeneric ImplRef::Monomorph::get_value(const Span& sp, const ::HIR::GenericRef& val) const /*override*/ { ASSERT_BUG(sp, val.binding < 256, "Generic value binding in " << val << " out of range (>=256)"); ASSERT_BUG(sp, val.binding < this->ti.impl_params.m_values.size(), "Generic value binding in " << val << " out of range (>= " << this->ti.impl_params.m_values.size() << ")"); return this->ti.impl_params.m_values.at(val.binding).clone(); } ::HIR::TypeRef ImplRef::get_impl_type() const { Span sp; TU_MATCH(Data, (this->m_data), (e), (TraitImpl, if( e.impl == nullptr ) { BUG(Span(), "nullptr"); } return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, e.impl->m_type); ), (BoundedPtr, return e.type->clone(); ), (Bounded, return e.type.clone(); ) ) throw ""; } ::HIR::PathParams ImplRef::get_trait_params() const { Span sp; TU_MATCH(Data, (this->m_data), (e), (TraitImpl, if( e.impl == nullptr ) { BUG(Span(), "nullptr"); } return this->get_cb_monomorph_traitimpl(sp).monomorph_path_params(sp, e.impl->m_trait_args, true); ), (BoundedPtr, return e.trait_args->clone(); ), (Bounded, return e.trait_args.clone(); ) ) throw ""; } ::HIR::TypeRef ImplRef::get_trait_ty_param(unsigned int idx) const { Span sp; TU_MATCH(Data, (this->m_data), (e), (TraitImpl, if( e.impl == nullptr ) { BUG(Span(), "nullptr"); } if( idx >= e.impl->m_trait_args.m_types.size() ) return ::HIR::TypeRef(); return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, e.impl->m_trait_args.m_types[idx]); ), (BoundedPtr, if( idx >= e.trait_args->m_types.size() ) return ::HIR::TypeRef(); return e.trait_args->m_types.at(idx).clone(); ), (Bounded, if( idx >= e.trait_args.m_types.size() ) return ::HIR::TypeRef(); return e.trait_args.m_types.at(idx).clone(); ) ) throw ""; TODO(Span(), ""); } ::HIR::TypeRef ImplRef::get_type(const char* name) const { if( !name[0] ) return ::HIR::TypeRef(); static Span sp; TU_MATCH(Data, (this->m_data), (e), (TraitImpl, auto it = e.impl->m_types.find(name); if( it == e.impl->m_types.end() ) return ::HIR::TypeRef(); const ::HIR::TypeRef& tpl_ty = it->second.data; DEBUG("name=" << name << " tpl_ty=" << tpl_ty << " " << *this); if( monomorphise_type_needed(tpl_ty) ) { return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, tpl_ty); } else { return tpl_ty.clone(); } ), (BoundedPtr, auto it = e.assoc->find(name); if(it == e.assoc->end()) return ::HIR::TypeRef(); return it->second.type.clone(); ), (Bounded, auto it = e.assoc.find(name); if(it == e.assoc.end()) return ::HIR::TypeRef(); return it->second.type.clone(); ) ) return ::HIR::TypeRef(); } ::std::ostream& operator<<(::std::ostream& os, const ImplRef& x) { TU_MATCH_HDR( (x.m_data), { ) TU_ARM(x.m_data, TraitImpl, e) { if( e.impl == nullptr ) { os << "none"; } else { os << "impl"; os << "(" << e.impl << ")"; if( e.impl->m_params.m_types.size() ) { os << "<"; for( unsigned int i = 0; i < e.impl->m_params.m_types.size(); i ++ ) { const auto& ty_d = e.impl->m_params.m_types[i]; os << ty_d.m_name; os << ","; } os << ">"; } os << " " << *e.trait_path << e.impl->m_trait_args << " for " << e.impl->m_type << e.impl->m_params.fmt_bounds(); os << " {"; for( unsigned int i = 0; i < e.impl->m_params.m_types.size(); i ++ ) { const auto& ty_d = e.impl->m_params.m_types[i]; os << ty_d.m_name << " = "; if( e.impl_params.m_types[i] != HIR::TypeRef() ) { os << e.impl_params.m_types[i]; } else { os << "?"; } os << ","; } for(const auto& aty : e.impl->m_types) { os << "Self::" << aty.first << " = " << aty.second.data << ","; } os << "}"; } } TU_ARM(x.m_data, BoundedPtr, e) { assert(e.type); assert(e.trait_args); assert(e.assoc); os << "bound (ptr) " << *e.type << " : ?" << *e.trait_args << " + {" << *e.assoc << "}"; } TU_ARM(x.m_data, Bounded, e) { os << "bound " << e.type << " : ?" << e.trait_args << " + {"<<e.assoc<<"}"; } } return os; } <commit_msg>HIR Typecheck - Tweak logic for `type_is_specialisable`<commit_after>/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * hir_typeck/impl_ref.cpp * - Reference to a trait implementation (either a bound or a impl block) */ #include "impl_ref.hpp" #include <hir/hir.hpp> #include "static.hpp" // for monomorphise_type_with bool ImplRef::more_specific_than(const ImplRef& other) const { TU_MATCH(Data, (this->m_data), (te), (TraitImpl, if( te.impl == nullptr ) { return false; } TU_MATCH(Data, (other.m_data), (oe), (TraitImpl, if( oe.impl == nullptr ) { return true; } return te.impl->more_specific_than( *oe.impl ); ), (BoundedPtr, return false; ), (Bounded, return false; ) ) ), (BoundedPtr, if( !other.m_data.is_BoundedPtr() ) return false; const auto& oe = other.m_data.as_BoundedPtr(); assert( *te.type == *oe.type ); assert( *te.trait_args == *oe.trait_args ); if( te.assoc->size() > oe.assoc->size() ) return true; return false; ), (Bounded, if( !other.m_data.is_Bounded() ) return false; const auto& oe = other.m_data.as_Bounded(); assert( te.type == oe.type ); assert( te.trait_args == oe.trait_args ); if( te.assoc.size() > oe.assoc.size() ) return true; return false; ) ) throw ""; } bool ImplRef::overlaps_with(const ::HIR::Crate& crate, const ImplRef& other) const { if( this->m_data.tag() != other.m_data.tag() ) return false; TU_MATCH(Data, (this->m_data, other.m_data), (te, oe), (TraitImpl, if( te.impl != nullptr && oe.impl != nullptr ) return te.impl->overlaps_with( crate, *oe.impl ); ), (BoundedPtr, // TODO: Bounded and BoundedPtr are compatible if( *te.type != *oe.type ) return false; if( *te.trait_args != *oe.trait_args ) return false; // Don't check associated types return true; ), (Bounded, if( te.type != oe.type ) return false; if( te.trait_args != oe.trait_args ) return false; // Don't check associated types return true; ) ) return false; } bool ImplRef::has_magic_params() const { if(const auto* e = m_data.opt_TraitImpl()) { for(const auto& t : e->impl_params.m_types) if( visit_ty_with(t, [](const ::HIR::TypeRef& t){ return t.data().is_Generic() && (t.data().as_Generic().binding >> 8) == 2; }) ) return true; } return false; } bool ImplRef::type_is_specialisable(const char* name) const { TU_MATCH_HDRA( (this->m_data), {) TU_ARMA(TraitImpl, e) { if( e.impl == nullptr ) { // No impl yet? This type is specialisable. return true; } auto it = e.impl->m_types.find(name); if( it == e.impl->m_types.end() ) { // If not present (which might happen during UFCS resolution), assume that it's specialisable return true; } return it->second.is_specialisable; } TU_ARMA(BoundedPtr, e) { return false; } TU_ARMA(Bounded, E) { return false; } } throw ""; } // Returns a closure to monomorphise including placeholders (if present) ImplRef::Monomorph ImplRef::get_cb_monomorph_traitimpl(const Span& sp) const { const auto& e = this->m_data.as_TraitImpl(); return Monomorph(e); } ::HIR::TypeRef ImplRef::Monomorph::get_type(const Span& sp, const ::HIR::GenericRef& ge) const /*override*/ { if( ge.is_self() ) { // Store (or cache) a monomorphisation of Self, and error if this recurses if( this->ti.self_cache == ::HIR::TypeRef() ) { this->ti.self_cache = ::HIR::TypeRef::new_diverge(); this->ti.self_cache = this->monomorph_type(sp, this->ti.impl->m_type); } else if( this->ti.self_cache == ::HIR::TypeRef::new_diverge() ) { // BUG! BUG(sp, "Use of `Self` in expansion of `Self`"); } else { } return this->ti.self_cache.clone(); } ASSERT_BUG(sp, ge.binding < 256, "Binding in " << ge << " out of range (>=256)"); ASSERT_BUG(sp, ge.binding < this->ti.impl_params.m_types.size(), "Binding in " << ge << " out of range (>= " << this->ti.impl_params.m_types.size() << ")"); return this->ti.impl_params.m_types.at(ge.binding).clone(); } ::HIR::ConstGeneric ImplRef::Monomorph::get_value(const Span& sp, const ::HIR::GenericRef& val) const /*override*/ { ASSERT_BUG(sp, val.binding < 256, "Generic value binding in " << val << " out of range (>=256)"); ASSERT_BUG(sp, val.binding < this->ti.impl_params.m_values.size(), "Generic value binding in " << val << " out of range (>= " << this->ti.impl_params.m_values.size() << ")"); return this->ti.impl_params.m_values.at(val.binding).clone(); } ::HIR::TypeRef ImplRef::get_impl_type() const { Span sp; TU_MATCH(Data, (this->m_data), (e), (TraitImpl, if( e.impl == nullptr ) { BUG(Span(), "nullptr"); } return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, e.impl->m_type); ), (BoundedPtr, return e.type->clone(); ), (Bounded, return e.type.clone(); ) ) throw ""; } ::HIR::PathParams ImplRef::get_trait_params() const { Span sp; TU_MATCH(Data, (this->m_data), (e), (TraitImpl, if( e.impl == nullptr ) { BUG(Span(), "nullptr"); } return this->get_cb_monomorph_traitimpl(sp).monomorph_path_params(sp, e.impl->m_trait_args, true); ), (BoundedPtr, return e.trait_args->clone(); ), (Bounded, return e.trait_args.clone(); ) ) throw ""; } ::HIR::TypeRef ImplRef::get_trait_ty_param(unsigned int idx) const { Span sp; TU_MATCH(Data, (this->m_data), (e), (TraitImpl, if( e.impl == nullptr ) { BUG(Span(), "nullptr"); } if( idx >= e.impl->m_trait_args.m_types.size() ) return ::HIR::TypeRef(); return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, e.impl->m_trait_args.m_types[idx]); ), (BoundedPtr, if( idx >= e.trait_args->m_types.size() ) return ::HIR::TypeRef(); return e.trait_args->m_types.at(idx).clone(); ), (Bounded, if( idx >= e.trait_args.m_types.size() ) return ::HIR::TypeRef(); return e.trait_args.m_types.at(idx).clone(); ) ) throw ""; TODO(Span(), ""); } ::HIR::TypeRef ImplRef::get_type(const char* name) const { if( !name[0] ) return ::HIR::TypeRef(); static Span sp; TU_MATCH(Data, (this->m_data), (e), (TraitImpl, auto it = e.impl->m_types.find(name); if( it == e.impl->m_types.end() ) return ::HIR::TypeRef(); const ::HIR::TypeRef& tpl_ty = it->second.data; DEBUG("name=" << name << " tpl_ty=" << tpl_ty << " " << *this); if( monomorphise_type_needed(tpl_ty) ) { return this->get_cb_monomorph_traitimpl(sp).monomorph_type(sp, tpl_ty); } else { return tpl_ty.clone(); } ), (BoundedPtr, auto it = e.assoc->find(name); if(it == e.assoc->end()) return ::HIR::TypeRef(); return it->second.type.clone(); ), (Bounded, auto it = e.assoc.find(name); if(it == e.assoc.end()) return ::HIR::TypeRef(); return it->second.type.clone(); ) ) return ::HIR::TypeRef(); } ::std::ostream& operator<<(::std::ostream& os, const ImplRef& x) { TU_MATCH_HDR( (x.m_data), { ) TU_ARM(x.m_data, TraitImpl, e) { if( e.impl == nullptr ) { os << "none"; } else { os << "impl"; os << "(" << e.impl << ")"; if( e.impl->m_params.m_types.size() ) { os << "<"; for( unsigned int i = 0; i < e.impl->m_params.m_types.size(); i ++ ) { const auto& ty_d = e.impl->m_params.m_types[i]; os << ty_d.m_name; os << ","; } os << ">"; } os << " " << *e.trait_path << e.impl->m_trait_args << " for " << e.impl->m_type << e.impl->m_params.fmt_bounds(); os << " {"; for( unsigned int i = 0; i < e.impl->m_params.m_types.size(); i ++ ) { const auto& ty_d = e.impl->m_params.m_types[i]; os << ty_d.m_name << " = "; if( e.impl_params.m_types[i] != HIR::TypeRef() ) { os << e.impl_params.m_types[i]; } else { os << "?"; } os << ","; } for(const auto& aty : e.impl->m_types) { os << "Self::" << aty.first << " = " << aty.second.data << ","; } os << "}"; } } TU_ARM(x.m_data, BoundedPtr, e) { assert(e.type); assert(e.trait_args); assert(e.assoc); os << "bound (ptr) " << *e.type << " : ?" << *e.trait_args << " + {" << *e.assoc << "}"; } TU_ARM(x.m_data, Bounded, e) { os << "bound " << e.type << " : ?" << e.trait_args << " + {"<<e.assoc<<"}"; } } return os; } <|endoftext|>
<commit_before>/*++ Copyright (c) 2012 Microsoft Corporation Module Name: qffpa_tactic.cpp Abstract: Tactic for QF_FPA benchmarks. Author: Christoph (cwinter) 2012-01-16 Notes: --*/ #include"tactical.h" #include"simplify_tactic.h" #include"bit_blaster_tactic.h" #include"sat_tactic.h" #include"fpa2bv_tactic.h" #include"qffpa_tactic.h" tactic * mk_qffpa_tactic(ast_manager & m, params_ref const & p) { params_ref sat_simp_p = p; sat_simp_p .set_bool("elim_and", true); return and_then(mk_simplify_tactic(m, p), mk_fpa2bv_tactic(m, p), using_params(mk_simplify_tactic(m, p), sat_simp_p), mk_bit_blaster_tactic(m, p), using_params(mk_simplify_tactic(m, p), sat_simp_p), mk_sat_tactic(m, p), mk_fail_if_undecided_tactic()); } struct is_non_qffpa_predicate { struct found {}; ast_manager & m; float_util u; is_non_qffpa_predicate(ast_manager & _m) :m(_m), u(m) {} void operator()(var *) { throw found(); } void operator()(quantifier *) { throw found(); } void operator()(app * n) { sort * s = get_sort(n); if (!m.is_bool(s) && !(u.is_float(s) || u.is_rm(s))) throw found(); family_id fid = s->get_family_id(); if (fid == m.get_basic_family_id()) return; if (fid == u.get_family_id()) return; throw found(); } }; struct is_non_qffpabv_predicate { struct found {}; ast_manager & m; bv_util bu; float_util fu; is_non_qffpabv_predicate(ast_manager & _m) :m(_m), bu(m), fu(m) {} void operator()(var *) { throw found(); } void operator()(quantifier *) { throw found(); } void operator()(app * n) { sort * s = get_sort(n); if (!m.is_bool(s) && !(fu.is_float(s) || fu.is_rm(s) || bu.is_bv_sort(s))) throw found(); family_id fid = s->get_family_id(); if (fid == m.get_basic_family_id()) return; if (fid == fu.get_family_id() || fid == bu.get_family_id()) return; throw found(); } }; class is_qffpa_probe : public probe { public: virtual result operator()(goal const & g) { return !test<is_non_qffpa_predicate>(g); } }; class is_qffpabv_probe : public probe { public: virtual result operator()(goal const & g) { return !test<is_non_qffpabv_predicate>(g); } }; probe * mk_is_qffpa_probe() { return alloc(is_qffpa_probe); } probe * mk_is_qffpabv_probe() { return alloc(is_qffpabv_probe); } <commit_msg>bugfix for FPA<commit_after>/*++ Copyright (c) 2012 Microsoft Corporation Module Name: qffpa_tactic.cpp Abstract: Tactic for QF_FPA benchmarks. Author: Christoph (cwinter) 2012-01-16 Notes: --*/ #include"tactical.h" #include"simplify_tactic.h" #include"bit_blaster_tactic.h" #include"sat_tactic.h" #include"fpa2bv_tactic.h" #include"qffpa_tactic.h" tactic * mk_qffpa_tactic(ast_manager & m, params_ref const & p) { params_ref sat_simp_p = p; sat_simp_p .set_bool("elim_and", true); return and_then(mk_simplify_tactic(m, p), mk_fpa2bv_tactic(m, p), using_params(mk_simplify_tactic(m, p), sat_simp_p), mk_bit_blaster_tactic(m, p), using_params(mk_simplify_tactic(m, p), sat_simp_p), mk_sat_tactic(m, p), mk_fail_if_undecided_tactic()); } struct is_non_qffpa_predicate { struct found {}; ast_manager & m; float_util u; is_non_qffpa_predicate(ast_manager & _m) :m(_m), u(m) {} void operator()(var *) { throw found(); } void operator()(quantifier *) { throw found(); } void operator()(app * n) { sort * s = get_sort(n); if (!m.is_bool(s) && !(u.is_float(s) || u.is_rm(s))) throw found(); if (is_uninterp(n)) throw found(); family_id fid = s->get_family_id(); if (fid == m.get_basic_family_id()) return; if (fid == u.get_family_id()) return; throw found(); } }; struct is_non_qffpabv_predicate { struct found {}; ast_manager & m; bv_util bu; float_util fu; is_non_qffpabv_predicate(ast_manager & _m) :m(_m), bu(m), fu(m) {} void operator()(var *) { throw found(); } void operator()(quantifier *) { throw found(); } void operator()(app * n) { sort * s = get_sort(n); if (!m.is_bool(s) && !(fu.is_float(s) || fu.is_rm(s) || bu.is_bv_sort(s))) throw found(); if (is_uninterp(n)) throw found(); family_id fid = s->get_family_id(); if (fid == m.get_basic_family_id()) return; if (fid == fu.get_family_id() || fid == bu.get_family_id()) return; throw found(); } }; class is_qffpa_probe : public probe { public: virtual result operator()(goal const & g) { return !test<is_non_qffpa_predicate>(g); } }; class is_qffpabv_probe : public probe { public: virtual result operator()(goal const & g) { return !test<is_non_qffpabv_predicate>(g); } }; probe * mk_is_qffpa_probe() { return alloc(is_qffpa_probe); } probe * mk_is_qffpabv_probe() { return alloc(is_qffpabv_probe); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <oleacc.h> #include "app/l10n_util.h" #include "base/scoped_comptr_win.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/view_ids.h" #include "chrome/browser/views/bookmark_bar_view.h" #include "chrome/browser/views/frame/browser_view.h" #include "chrome/browser/views/toolbar_view.h" #include "chrome/common/url_constants.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "views/accessibility/view_accessibility_wrapper.h" #include "views/widget/root_view.h" #include "views/widget/widget_win.h" #include "views/window/window.h" namespace { VARIANT id_self = {VT_I4, CHILDID_SELF}; // Dummy class to force creation of ATL module, needed by COM to instantiate // ViewAccessibility. class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {}; TestAtlModule test_atl_module_; class BrowserViewsAccessibilityTest : public InProcessBrowserTest { public: BrowserViewsAccessibilityTest() { ::CoInitialize(NULL); } ~BrowserViewsAccessibilityTest() { ::CoUninitialize(); } // Retrieves an instance of BrowserWindowTesting BrowserWindowTesting* GetBrowserWindowTesting() { BrowserWindow* browser_window = browser()->window(); if (!browser_window) return NULL; return browser_window->GetBrowserWindowTesting(); } // Retrieve an instance of BrowserView BrowserView* GetBrowserView() { return BrowserView::GetBrowserViewForNativeWindow( browser()->window()->GetNativeHandle()); } // Retrieves and initializes an instance of LocationBarView. LocationBarView* GetLocationBarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return GetBrowserWindowTesting()->GetLocationBarView(); } // Retrieves and initializes an instance of ToolbarView. ToolbarView* GetToolbarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return browser_window_testing->GetToolbarView(); } // Retrieves and initializes an instance of BookmarkBarView. BookmarkBarView* GetBookmarkBarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return browser_window_testing->GetBookmarkBarView(); } // Retrieves and verifies the accessibility object for the given View. void TestViewAccessibilityObject(views::View* view, std::wstring name, int32 role) { ASSERT_TRUE(NULL != view); IAccessible* acc_obj = NULL; HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance( IID_IAccessible, reinterpret_cast<void**>(&acc_obj)); ASSERT_EQ(S_OK, hr); ASSERT_TRUE(NULL != acc_obj); TestAccessibilityInfo(acc_obj, name, role); } // Verifies MSAA Name and Role properties of the given IAccessible. void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name, int32 role) { // Verify MSAA Name property. BSTR acc_name; HRESULT hr = acc_obj->get_accName(id_self, &acc_name); ASSERT_EQ(S_OK, hr); EXPECT_STREQ(acc_name, name.c_str()); // Verify MSAA Role property. VARIANT acc_role; ::VariantInit(&acc_role); hr = acc_obj->get_accRole(id_self, &acc_role); ASSERT_EQ(S_OK, hr); EXPECT_EQ(VT_I4, acc_role.vt); EXPECT_EQ(role, acc_role.lVal); ::VariantClear(&acc_role); ::SysFreeString(acc_name); } }; // Retrieve accessibility object for main window and verify accessibility info. // Fails, http://crbug.com/44486. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, FAILS_TestChromeWindowAccObj) { BrowserWindow* browser_window = browser()->window(); ASSERT_TRUE(NULL != browser_window); HWND hwnd = browser_window->GetNativeHandle(); ASSERT_TRUE(NULL != hwnd); // Get accessibility object. ScopedComPtr<IAccessible> acc_obj; HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible, reinterpret_cast<void**>(&acc_obj)); ASSERT_EQ(S_OK, hr); ASSERT_TRUE(NULL != acc_obj); ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL)); std::wstring title = l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT, ASCIIToWide(chrome::kAboutBlankURL)); TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW); } // Retrieve accessibility object for non client view and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) { views::View* non_client_view = GetBrowserView()->GetWindow()->GetNonClientView(); TestViewAccessibilityObject(non_client_view, l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_WINDOW); } // Retrieve accessibility object for browser root view and verify // accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserRootViewAccObj) { views::View* browser_root_view = GetBrowserView()->frame()->GetFrameView()->GetRootView(); TestViewAccessibilityObject(browser_root_view, l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_APPLICATION); } // Retrieve accessibility object for browser view and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) { // Verify root view MSAA name and role. TestViewAccessibilityObject(GetBrowserView(), l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_CLIENT); } // Retrieve accessibility object for toolbar view and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) { // Verify toolbar MSAA name and role. TestViewAccessibilityObject(GetToolbarView(), l10n_util::GetString(IDS_ACCNAME_TOOLBAR), ROLE_SYSTEM_TOOLBAR); } // Retrieve accessibility object for Back button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) { // Verify Back button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON), l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN); } // Retrieve accessibility object for Forward button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) { // Verify Forward button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON), l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN); } // Retrieve accessibility object for Reload button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) { // Verify Reload button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON), l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Home button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) { // Verify Home button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON), l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Star button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestStarButtonAccObj) { // Verify Star button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON), l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for location bar view and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestLocationBarViewAccObj) { // Verify location bar MSAA name and role. TestViewAccessibilityObject(GetLocationBarView(), l10n_util::GetString(IDS_ACCNAME_LOCATION), ROLE_SYSTEM_GROUPING); } // Retrieve accessibility object for Go button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) { // Verify Go button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON), l10n_util::GetString(IDS_ACCNAME_GO), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Page menu button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) { // Verify Page menu button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU), l10n_util::GetString(IDS_ACCNAME_PAGE), ROLE_SYSTEM_BUTTONMENU); } // Retrieve accessibility object for App menu button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) { // Verify App menu button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU), l10n_util::GetString(IDS_ACCNAME_APP), ROLE_SYSTEM_BUTTONMENU); } IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBookmarkBarViewAccObj) { TestViewAccessibilityObject(GetBookmarkBarView(), l10n_util::GetString(IDS_ACCNAME_BOOKMARKS), ROLE_SYSTEM_TOOLBAR); } // Fails, http://crbug.com/44486. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, FAILS_TestAboutChromeViewAccObj) { // Firstly, test that the WindowDelegate got updated. views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog(); EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(), l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str()); EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(), AccessibilityTypes::ROLE_DIALOG); // Also test the accessibility object directly. IAccessible* acc_obj = NULL; HRESULT hr = ::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(), OBJID_CLIENT, IID_IAccessible, reinterpret_cast<void**>(&acc_obj)); ASSERT_EQ(S_OK, hr); ASSERT_TRUE(NULL != acc_obj); TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE), ROLE_SYSTEM_DIALOG); acc_obj->Release(); } } // Namespace. <commit_msg>Re-enabling TestAboutChromeViewAccObj.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <oleacc.h> #include "app/l10n_util.h" #include "base/scoped_comptr_win.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/view_ids.h" #include "chrome/browser/views/bookmark_bar_view.h" #include "chrome/browser/views/frame/browser_view.h" #include "chrome/browser/views/toolbar_view.h" #include "chrome/common/url_constants.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "views/accessibility/view_accessibility_wrapper.h" #include "views/widget/root_view.h" #include "views/widget/widget_win.h" #include "views/window/window.h" namespace { VARIANT id_self = {VT_I4, CHILDID_SELF}; // Dummy class to force creation of ATL module, needed by COM to instantiate // ViewAccessibility. class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {}; TestAtlModule test_atl_module_; class BrowserViewsAccessibilityTest : public InProcessBrowserTest { public: BrowserViewsAccessibilityTest() { ::CoInitialize(NULL); } ~BrowserViewsAccessibilityTest() { ::CoUninitialize(); } // Retrieves an instance of BrowserWindowTesting BrowserWindowTesting* GetBrowserWindowTesting() { BrowserWindow* browser_window = browser()->window(); if (!browser_window) return NULL; return browser_window->GetBrowserWindowTesting(); } // Retrieve an instance of BrowserView BrowserView* GetBrowserView() { return BrowserView::GetBrowserViewForNativeWindow( browser()->window()->GetNativeHandle()); } // Retrieves and initializes an instance of LocationBarView. LocationBarView* GetLocationBarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return GetBrowserWindowTesting()->GetLocationBarView(); } // Retrieves and initializes an instance of ToolbarView. ToolbarView* GetToolbarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return browser_window_testing->GetToolbarView(); } // Retrieves and initializes an instance of BookmarkBarView. BookmarkBarView* GetBookmarkBarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return browser_window_testing->GetBookmarkBarView(); } // Retrieves and verifies the accessibility object for the given View. void TestViewAccessibilityObject(views::View* view, std::wstring name, int32 role) { ASSERT_TRUE(NULL != view); IAccessible* acc_obj = NULL; HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance( IID_IAccessible, reinterpret_cast<void**>(&acc_obj)); ASSERT_EQ(S_OK, hr); ASSERT_TRUE(NULL != acc_obj); TestAccessibilityInfo(acc_obj, name, role); } // Verifies MSAA Name and Role properties of the given IAccessible. void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name, int32 role) { // Verify MSAA Name property. BSTR acc_name; HRESULT hr = acc_obj->get_accName(id_self, &acc_name); ASSERT_EQ(S_OK, hr); EXPECT_STREQ(acc_name, name.c_str()); // Verify MSAA Role property. VARIANT acc_role; ::VariantInit(&acc_role); hr = acc_obj->get_accRole(id_self, &acc_role); ASSERT_EQ(S_OK, hr); EXPECT_EQ(VT_I4, acc_role.vt); EXPECT_EQ(role, acc_role.lVal); ::VariantClear(&acc_role); ::SysFreeString(acc_name); } }; // Retrieve accessibility object for main window and verify accessibility info. // Fails, http://crbug.com/44486. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, FAILS_TestChromeWindowAccObj) { BrowserWindow* browser_window = browser()->window(); ASSERT_TRUE(NULL != browser_window); HWND hwnd = browser_window->GetNativeHandle(); ASSERT_TRUE(NULL != hwnd); // Get accessibility object. ScopedComPtr<IAccessible> acc_obj; HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible, reinterpret_cast<void**>(&acc_obj)); ASSERT_EQ(S_OK, hr); ASSERT_TRUE(NULL != acc_obj); ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL)); std::wstring title = l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT, ASCIIToWide(chrome::kAboutBlankURL)); TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW); } // Retrieve accessibility object for non client view and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) { views::View* non_client_view = GetBrowserView()->GetWindow()->GetNonClientView(); TestViewAccessibilityObject(non_client_view, l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_WINDOW); } // Retrieve accessibility object for browser root view and verify // accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserRootViewAccObj) { views::View* browser_root_view = GetBrowserView()->frame()->GetFrameView()->GetRootView(); TestViewAccessibilityObject(browser_root_view, l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_APPLICATION); } // Retrieve accessibility object for browser view and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) { // Verify root view MSAA name and role. TestViewAccessibilityObject(GetBrowserView(), l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_CLIENT); } // Retrieve accessibility object for toolbar view and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) { // Verify toolbar MSAA name and role. TestViewAccessibilityObject(GetToolbarView(), l10n_util::GetString(IDS_ACCNAME_TOOLBAR), ROLE_SYSTEM_TOOLBAR); } // Retrieve accessibility object for Back button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) { // Verify Back button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON), l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN); } // Retrieve accessibility object for Forward button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) { // Verify Forward button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON), l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN); } // Retrieve accessibility object for Reload button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) { // Verify Reload button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON), l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Home button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) { // Verify Home button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON), l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Star button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestStarButtonAccObj) { // Verify Star button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON), l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for location bar view and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestLocationBarViewAccObj) { // Verify location bar MSAA name and role. TestViewAccessibilityObject(GetLocationBarView(), l10n_util::GetString(IDS_ACCNAME_LOCATION), ROLE_SYSTEM_GROUPING); } // Retrieve accessibility object for Go button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) { // Verify Go button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON), l10n_util::GetString(IDS_ACCNAME_GO), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Page menu button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) { // Verify Page menu button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU), l10n_util::GetString(IDS_ACCNAME_PAGE), ROLE_SYSTEM_BUTTONMENU); } // Retrieve accessibility object for App menu button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) { // Verify App menu button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU), l10n_util::GetString(IDS_ACCNAME_APP), ROLE_SYSTEM_BUTTONMENU); } IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBookmarkBarViewAccObj) { TestViewAccessibilityObject(GetBookmarkBarView(), l10n_util::GetString(IDS_ACCNAME_BOOKMARKS), ROLE_SYSTEM_TOOLBAR); } IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAboutChromeViewAccObj) { // Firstly, test that the WindowDelegate got updated. views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog(); EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(), l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str()); EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(), AccessibilityTypes::ROLE_DIALOG); // Also test the accessibility object directly. IAccessible* acc_obj = NULL; HRESULT hr = ::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(), OBJID_CLIENT, IID_IAccessible, reinterpret_cast<void**>(&acc_obj)); ASSERT_EQ(S_OK, hr); ASSERT_TRUE(NULL != acc_obj); TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE), ROLE_SYSTEM_DIALOG); acc_obj->Release(); } } // Namespace. <|endoftext|>