text
stringlengths
54
60.6k
<commit_before>#ifndef __TENSOR_BLOB_HPP__ #define __TENSOR_BLOB_HPP__ #include <string> #include <vector> #include <memory> #include "../device_context/context.hpp" namespace mlfe{ template <class DeviceContext, class = typename std::enable_if<std::is_base_of<Context, DeviceContext>::value, DeviceContext>::type > class TensorBlob{ public: TensorBlob() : size(0), context(new DeviceContext){} ~TensorBlob() { Clear(); } TensorBlob(const TensorBlob &) = delete; TensorBlob& operator=(const TensorBlob &) = delete; /* * @brief reshape tensor's shape. */ template <typename T, class = typename std::enable_if<std::is_fundamental<T>::value, T>::type > void Reshape(const std::vector<int> new_dims){ int new_size = 1; dims.clear(); for(int n = 0; n < new_dims.size(); ++n){ new_size *= new_dims[n]; dims.push_back(new_dims[n]); } if(new_size > size){ size = new_size; context->Allocate<T>(size); } else{ size = new_size; } } template <typename T, class = typename std::enable_if<std::is_fundamental<T>::value, T>::type > void ReshapeLike(const std::shared_ptr<TensorBlob> tb) { std::vector<int> new_size; for (int i = 0; i < tb->dims.size(); ++i) { new_size.push_back(tb->dims[i]); } Reshape<T>(new_size); } /* * @brief clear tensor data. */ void Clear() { size = 0; dims.clear(); } /* * @brief returns total size. */ int Size() const { return size; } /* * @brief returns number of dimensions. */ int Dims() const { return dims.size(); } /* * @brief returns dimension size. */ int Dim(int idx) const { return dims[idx]; } /* * @brief returns const tensor data address. */ template <typename T, typename = typename std::enable_if<std::is_fundamental<T>::value, T>::type > const T * GetPtrConst() const{ return static_cast<const T *>(context->GetDevicePtr()); } /* * @brief returns tensor data address. */ template <typename T, typename = typename std::enable_if<std::is_fundamental<T>::value, T>::type > T * GetPtrMutable() const{ return static_cast<T *>(context->GetDevicePtr()); } /* * @brief copy data from device to host. */ template <typename T, typename = typename std::enable_if<std::is_fundamental<T>::value, T>::type > void CopyToHost(const int size, T *host_mem) { context->CopyToHost<T>(size, host_mem); } /* * @brief copy data from host to device. */ template <typename T, typename = typename std::enable_if<std::is_fundamental<T>::value, T>::type > void CopyToDevice(const int size, const T *host_mem) { context->CopyToDevice<T>(size, host_mem); } /* * @brief set all tensor's elements by const value. */ template <typename T, typename U = T, typename = typename std::enable_if<std::is_fundamental<T>::value, T>::type > void SetByConst(const U val){ U * data_ptr = static_cast<U *>(context->GetDevicePtr()); for(int i = 0; i < size; ++i){ data_ptr[i] = val; } } private: std::vector<int> dims; int size; std::unique_ptr<Context> context; }; } /* namespace mlfe */ #endif /* __TENSOR_BLOB_HPP__ */ <commit_msg>add CompareSizeWith function in TensorBlob class.<commit_after>#ifndef __TENSOR_BLOB_HPP__ #define __TENSOR_BLOB_HPP__ #include <string> #include <vector> #include <memory> #include "../device_context/context.hpp" namespace mlfe{ template <class DeviceContext, class = typename std::enable_if<std::is_base_of<Context, DeviceContext>::value, DeviceContext>::type > class TensorBlob{ public: TensorBlob() : size(0), context(new DeviceContext){} ~TensorBlob() { Clear(); } TensorBlob(const TensorBlob &) = delete; TensorBlob& operator=(const TensorBlob &) = delete; /* * @brief reshape tensor's shape. */ template <typename T, class = typename std::enable_if<std::is_fundamental<T>::value, T>::type > void Reshape(const std::vector<int> new_dims){ int new_size = 1; dims.clear(); for(int n = 0; n < new_dims.size(); ++n){ new_size *= new_dims[n]; dims.push_back(new_dims[n]); } if(new_size > size){ size = new_size; context->Allocate<T>(size); } else{ size = new_size; } } template <typename T, class = typename std::enable_if<std::is_fundamental<T>::value, T>::type > void ReshapeLike(const std::shared_ptr<TensorBlob> tb) { std::vector<int> new_size; for (int i = 0; i < tb->dims.size(); ++i) { new_size.push_back(tb->dims[i]); } Reshape<T>(new_size); } /* * @brief compare tensor's size. * if same then returns true, or not returns false. */ bool CompareSizeWith(const std::shared_ptr<TensorBlob> tb){ if(this->Dims() != tb->Dims()){ return false; } for(int i = 0; i < this->Dims(); ++i){ if(this->Dim(i) != tb->Dim(i)){ return false; } } return true; } /* * @brief clear tensor data. */ void Clear() { size = 0; dims.clear(); } /* * @brief returns total size. */ int Size() const { return size; } /* * @brief returns number of dimensions. */ int Dims() const { return dims.size(); } /* * @brief returns dimension size. */ int Dim(int idx) const { return dims[idx]; } /* * @brief returns const tensor data address. */ template <typename T, typename = typename std::enable_if<std::is_fundamental<T>::value, T>::type > const T * GetPtrConst() const{ return static_cast<const T *>(context->GetDevicePtr()); } /* * @brief returns tensor data address. */ template <typename T, typename = typename std::enable_if<std::is_fundamental<T>::value, T>::type > T * GetPtrMutable() const{ return static_cast<T *>(context->GetDevicePtr()); } /* * @brief copy data from device to host. */ template <typename T, typename = typename std::enable_if<std::is_fundamental<T>::value, T>::type > void CopyToHost(const int size, T *host_mem) { context->CopyToHost<T>(size, host_mem); } /* * @brief copy data from host to device. */ template <typename T, typename = typename std::enable_if<std::is_fundamental<T>::value, T>::type > void CopyToDevice(const int size, const T *host_mem) { context->CopyToDevice<T>(size, host_mem); } /* * @brief set all tensor's elements by const value. */ template <typename T, typename U = T, typename = typename std::enable_if<std::is_fundamental<T>::value, T>::type > void SetByConst(const U val){ U * data_ptr = static_cast<U *>(context->GetDevicePtr()); for(int i = 0; i < size; ++i){ data_ptr[i] = val; } } private: std::vector<int> dims; int size; std::unique_ptr<Context> context; }; } /* namespace mlfe */ #endif /* __TENSOR_BLOB_HPP__ */ <|endoftext|>
<commit_before>/* Copyright 2011 Brain Research Institute, Melbourne, Australia Written by Robert E. Smith, 2013. This file is part of MRtrix. MRtrix is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MRtrix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include <map> #include <vector> #include "command.h" #include "point.h" #include "image/buffer.h" #include "image/loop.h" #include "image/voxel.h" #include "math/rng.h" #include "dwi/tractography/connectomics/config.h" #include "dwi/tractography/connectomics/connectomics.h" #include "dwi/tractography/connectomics/lut.h" using namespace MR; using namespace App; using namespace MR::DWI::Tractography::Connectomics; void usage () { AUTHOR = "Robert E. Smith (r.smith@brain.org.au)"; DESCRIPTION + "convert a parcellated image (where values are node indices) into a colour image " "(many software packages handle this colouring internally within their viewer program; this binary " "explicitly converts a parcellation image into a colour image that should be viewable in any software)"; ARGUMENTS + Argument ("nodes_in", "the input node parcellation image").type_image_in() + Argument ("colour_out", "the output colour image").type_image_out(); OPTIONS + LookupTableOption + Option ("config", "If the input parcellation image was created using labelconfig, provide the connectome config file used so that the node indices are converted correctly") + Argument ("file").type_file_in(); }; void run () { Image::Buffer<node_t> nodes_data (argument[0]); Image::Buffer<node_t>::voxel_type nodes (nodes_data); Node_map node_map; load_lookup_table (node_map); Options opt = get_options ("config"); if (opt.size()) { if (node_map.empty()) throw Exception ("Cannot properly interpret connectome config file if no lookup table is provided"); ConfigInvLookup config; load_config (opt[0][0], config); // Now that we know the configuration, can convert the lookup table to reflect the new indices // If no corresponding entry exists in the config file, then the node doesn't get coloured Node_map new_node_map; for (Node_map::iterator i = node_map.begin(); i != node_map.end(); ++i) { ConfigInvLookup::const_iterator existing = config.find (i->second.get_name()); if (existing != config.end()) new_node_map.insert (std::make_pair (existing->second, i->second)); } if (new_node_map.empty()) throw Exception ("Config file and parcellation lookup table do not appear to belong to one another"); new_node_map.insert (std::make_pair (0, Node_info ("Unknown", Point<uint8_t> (0, 0, 0), 0))); node_map = new_node_map; } if (node_map.empty()) { INFO ("No lookup table provided; colouring nodes randomly"); node_t max_index = 0; Image::LoopInOrder loop (nodes); for (loop.start (nodes); loop.ok(); loop.next (nodes)) { const node_t index = nodes.value(); if (index > max_index) max_index = index; } node_map.insert (std::make_pair (0, Node_info ("None", 0, 0, 0, 0))); Math::RNG rng; for (node_t i = 1; i <= max_index; ++i) { Point<uint8_t> colour; do { colour[0] = rng.uniform_int (255); colour[1] = rng.uniform_int (255); colour[2] = rng.uniform_int (255); } while (int(colour[0]) + int(colour[1]) + int(colour[2]) < 100); node_map.insert (std::make_pair (i, Node_info (str(i), colour))); } } Image::Header H; H.info() = nodes_data.info(); H.set_ndim (4); H.dim(3) = 3; H.datatype() = DataType::UInt8; H.comments().push_back ("Coloured parcellation image generated by mrparc2colour"); Image::Buffer<uint8_t> out_data (argument[1], H); Image::Buffer<uint8_t>::voxel_type out (out_data); Image::LoopInOrder loop (nodes, "Colourizing parcellated node image... "); for (loop.start (nodes, out); loop.ok(); loop.next (nodes, out)) { const node_t index = nodes.value(); Node_map::const_iterator i = node_map.find (index); if (i == node_map.end()) { out[3] = 0; out.value() = 0; out[3] = 1; out.value() = 0; out[3] = 2; out.value() = 0; } else { const Point<uint8_t>& colour (i->second.get_colour()); out[3] = 0; out.value() = colour[0]; out[3] = 1; out.value() = colour[1]; out[3] = 2; out.value() = colour[2]; } } } <commit_msg>label2colour: Update output image header to reflect command name change<commit_after>/* Copyright 2011 Brain Research Institute, Melbourne, Australia Written by Robert E. Smith, 2013. This file is part of MRtrix. MRtrix is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MRtrix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include <map> #include <vector> #include "command.h" #include "point.h" #include "image/buffer.h" #include "image/loop.h" #include "image/voxel.h" #include "math/rng.h" #include "dwi/tractography/connectomics/config.h" #include "dwi/tractography/connectomics/connectomics.h" #include "dwi/tractography/connectomics/lut.h" using namespace MR; using namespace App; using namespace MR::DWI::Tractography::Connectomics; void usage () { AUTHOR = "Robert E. Smith (r.smith@brain.org.au)"; DESCRIPTION + "convert a parcellated image (where values are node indices) into a colour image " "(many software packages handle this colouring internally within their viewer program; this binary " "explicitly converts a parcellation image into a colour image that should be viewable in any software)"; ARGUMENTS + Argument ("nodes_in", "the input node parcellation image").type_image_in() + Argument ("colour_out", "the output colour image").type_image_out(); OPTIONS + LookupTableOption + Option ("config", "If the input parcellation image was created using labelconfig, provide the connectome config file used so that the node indices are converted correctly") + Argument ("file").type_file_in(); }; void run () { Image::Buffer<node_t> nodes_data (argument[0]); Image::Buffer<node_t>::voxel_type nodes (nodes_data); Node_map node_map; load_lookup_table (node_map); Options opt = get_options ("config"); if (opt.size()) { if (node_map.empty()) throw Exception ("Cannot properly interpret connectome config file if no lookup table is provided"); ConfigInvLookup config; load_config (opt[0][0], config); // Now that we know the configuration, can convert the lookup table to reflect the new indices // If no corresponding entry exists in the config file, then the node doesn't get coloured Node_map new_node_map; for (Node_map::iterator i = node_map.begin(); i != node_map.end(); ++i) { ConfigInvLookup::const_iterator existing = config.find (i->second.get_name()); if (existing != config.end()) new_node_map.insert (std::make_pair (existing->second, i->second)); } if (new_node_map.empty()) throw Exception ("Config file and parcellation lookup table do not appear to belong to one another"); new_node_map.insert (std::make_pair (0, Node_info ("Unknown", Point<uint8_t> (0, 0, 0), 0))); node_map = new_node_map; } if (node_map.empty()) { INFO ("No lookup table provided; colouring nodes randomly"); node_t max_index = 0; Image::LoopInOrder loop (nodes); for (loop.start (nodes); loop.ok(); loop.next (nodes)) { const node_t index = nodes.value(); if (index > max_index) max_index = index; } node_map.insert (std::make_pair (0, Node_info ("None", 0, 0, 0, 0))); Math::RNG rng; for (node_t i = 1; i <= max_index; ++i) { Point<uint8_t> colour; do { colour[0] = rng.uniform_int (255); colour[1] = rng.uniform_int (255); colour[2] = rng.uniform_int (255); } while (int(colour[0]) + int(colour[1]) + int(colour[2]) < 100); node_map.insert (std::make_pair (i, Node_info (str(i), colour))); } } Image::Header H; H.info() = nodes_data.info(); H.set_ndim (4); H.dim(3) = 3; H.datatype() = DataType::UInt8; H.comments().push_back ("Coloured parcellation image generated by label2colour"); Image::Buffer<uint8_t> out_data (argument[1], H); Image::Buffer<uint8_t>::voxel_type out (out_data); Image::LoopInOrder loop (nodes, "Colourizing parcellated node image... "); for (loop.start (nodes, out); loop.ok(); loop.next (nodes, out)) { const node_t index = nodes.value(); Node_map::const_iterator i = node_map.find (index); if (i == node_map.end()) { out[3] = 0; out.value() = 0; out[3] = 1; out.value() = 0; out[3] = 2; out.value() = 0; } else { const Point<uint8_t>& colour (i->second.get_colour()); out[3] = 0; out.value() = colour[0]; out[3] = 1; out.value() = colour[1]; out[3] = 2; out.value() = colour[2]; } } } <|endoftext|>
<commit_before>/* * By Jesse Blagg and Ryan Morris * Huffman Compression program * for CSCI 480 * September 2014 */ #include "../headers/huffman.h" Huffman::Huffman() { file_to_compress = ""; header_table = ""; encoded_text = ""; } void Huffman::bit_write(unsigned char &src, unsigned char &dest, const short int bits) //write the number of bits passed into the function from unsigned char src to unsigned char dest { enum bit_codes{ BIT8 = 0x80, BIT7 = 0x40, BIT6 = 0X20, BIT5 = 0X10, BIT4 = 0X8, BIT3 = 0X4, BIT2 = 0X2, BIT1 = 0X1 }; switch(bits) { case 8: dest |= (src & BIT8); case 7: dest |= (src & BIT7); case 6: dest |= (src & BIT6); case 5: dest |= (src & BIT5); case 4: dest |= (src & BIT4); case 3: dest |= (src & BIT3); case 2: dest |= (src & BIT2); case 1: dest |= (src & BIT1); break; default: break; } } void Huffman::dump_buffer() { ofstream write("test.dat"); for(unsigned int i=0; i<len; i++) { write << "/" << (int)file_buffer[i]; } write.close(); } /* Created with the help of Dr. MacEvoy */ bool Huffman::getbit(unsigned long int* buffer, short int offset)//get the bit value at byte[offset] starting at the right wiht least significant bit { unsigned long int mask = 0; if(offset >= MAX_BIT_SIZE) return false; mask = (1 << offset); return (*buffer & mask) != 0; } /* Created with the help of Dr. MacEvoy */ void Huffman::setbit(unsigned char* buffer, int index, short int offset, bool value) { unsigned long int mask = 0; if(offset >= MAX_BIT_SIZE) return; mask = (0x80 >> ((offset % 8)-1)); if(value) buffer[index] |= mask; } short int Huffman::get_bit(int l_carry, short int length) { short int offset = (8 - (length % 8)); if(offset == 8) offset = 0; return (l_carry - offset); } short int Huffman::get_byte(int length) { return ceil(((sizeof(unsigned long int)*8)-length)/8); } short int Huffman::get_offset(int length) { short int offset = (8 - (length % 8)); if(offset == 8) offset = 0; return offset; } string getMcpName(string fname) { return ""; } void Huffman::compress() //compress the original message { bool write_over = false; unsigned char ch = 0; int code_length = 0; int index = 0; short int offset = 0; unsigned long int* bit_code = NULL; unsigned long int bit_count = 1; huffman_buffer = new unsigned char[H_BUF];//allocate the buffer for(unsigned short int k=0; k<H_BUF; k++) huffman_buffer[k] = 0; for(unsigned long int i=0; i<len; i++) { ch = file_buffer[i]; //get the character we are encoding bit_code = &charTable[ch].encoding; //look up its bit_code code_length = charTable[ch].encodeLength; //look up the length (in bits) of the bitcode for(short int j=code_length-1; j>=0; j--) { setbit(huffman_buffer, index, bit_count++ , getbit(bit_code, j)); //write the bitcodes to the buffer if(bit_count%8 == 0) index++; } } if(huffman_buffer[index] != 0) huffman_buffer[index++]; //nullpad the buffer if it isn't already h_len = index+1; //index; //return the length of the huffman trie in bytes } int Huffman::readHeader(string hfile) { int num; int i=0; int f_len = hfile.size(); cout << endl << endl << " charmax = " << UCHAR_MAX << endl << endl; string m_number; string f_name; string table; string e_o_f; ifstream inf(hfile.c_str()); if(!inf) cout << "Error reading file..." << endl; else { getline(inf,m_number); //sstream conversion found here: http://www.cplusplus.com/forum/articles/9645/ stringstream convert(m_number); // stringstream used for the conversion initialized with the contents of the string if ( !(convert >> num) )//give the value to an integer using the characters in the string { cout << "Not a valid compressed file. Exiting..." << endl; return -1; } else cout << " Magic number matches!" << endl; getline(inf,f_name); cout << "Original file: " << f_name << endl; //getline(inf,table); //cout << " Table: " << endl << table; for (int i=0;i<UCHAR_MAX;i++) // trouble reading in table with getline and double delimiter ... 762 retrieves complete table. { inf >> table[i]; if(table[i]=='' && table[i+1] == '') { i+=2; cout << ' '; } cout << table[i]; i++; } getline(inf, e_o_f); cout << endl << "eof: " << e_o_f; // not working... } return 0; } void Huffman::populateHeader(string hfile,string fname) // Write the header { ofstream outf(hfile.c_str()); outf << MAGIC_NUMBER << endl; //write magic number outf << fname << endl; //Write file name for(int i=0; i<UCHAR_MAX; i++) if(charTable[i].active) outf << charTable[i].character << DELIM << charTable[i].occurrence << DELIM << DELIM; //Write char table and int with with double delimiter for(int i=0;i<h_len;i++) outf << huffman_buffer[i]; //write encoded test outf << endl << O_EOF; //write our "Output" EOF character outf.close(); //close the filestream } void Huffman::print_huffman() { for(unsigned int i=0; i<h_len; i++) { cout << "\\" << (int)huffman_buffer[i]; } cout << endl << "Length of huffman codeing = " << h_len << " characters" << endl; } void Huffman::test() { } Huffman::~Huffman() //Destructor deletes entire header { } <commit_msg>HeaderUpdated...<commit_after>/* * By Jesse Blagg and Ryan Morris * Huffman Compression program * for CSCI 480 * September 2014 */ #include "../headers/huffman.h" Huffman::Huffman() { file_to_compress = ""; header_table = ""; encoded_text = ""; } void Huffman::bit_write(unsigned char &src, unsigned char &dest, const short int bits) //write the number of bits passed into the function from unsigned char src to unsigned char dest { enum bit_codes{ BIT8 = 0x80, BIT7 = 0x40, BIT6 = 0X20, BIT5 = 0X10, BIT4 = 0X8, BIT3 = 0X4, BIT2 = 0X2, BIT1 = 0X1 }; switch(bits) { case 8: dest |= (src & BIT8); case 7: dest |= (src & BIT7); case 6: dest |= (src & BIT6); case 5: dest |= (src & BIT5); case 4: dest |= (src & BIT4); case 3: dest |= (src & BIT3); case 2: dest |= (src & BIT2); case 1: dest |= (src & BIT1); break; default: break; } } void Huffman::dump_buffer() { ofstream write("test.dat"); for(unsigned int i=0; i<len; i++) { write << "/" << (int)file_buffer[i]; } write.close(); } /* Created with the help of Dr. MacEvoy */ bool Huffman::getbit(unsigned long int* buffer, short int offset)//get the bit value at byte[offset] starting at the right wiht least significant bit { unsigned long int mask = 0; if(offset >= MAX_BIT_SIZE) return false; mask = (1 << offset); return (*buffer & mask) != 0; } /* Created with the help of Dr. MacEvoy */ void Huffman::setbit(unsigned char* buffer, int index, short int offset, bool value) { unsigned long int mask = 0; if(offset >= MAX_BIT_SIZE) return; mask = (0x80 >> ((offset % 8)-1)); if(value) buffer[index] |= mask; } short int Huffman::get_bit(int l_carry, short int length) { short int offset = (8 - (length % 8)); if(offset == 8) offset = 0; return (l_carry - offset); } short int Huffman::get_byte(int length) { return ceil(((sizeof(unsigned long int)*8)-length)/8); } short int Huffman::get_offset(int length) { short int offset = (8 - (length % 8)); if(offset == 8) offset = 0; return offset; } string getMcpName(string fname) { return ""; } void Huffman::compress() //compress the original message { bool write_over = false; unsigned char ch = 0; int code_length = 0; int index = 0; short int offset = 0; unsigned long int* bit_code = NULL; unsigned long int bit_count = 1; huffman_buffer = new unsigned char[H_BUF];//allocate the buffer for(unsigned short int k=0; k<H_BUF; k++) huffman_buffer[k] = 0; for(unsigned long int i=0; i<len; i++) { ch = file_buffer[i]; //get the character we are encoding bit_code = &charTable[ch].encoding; //look up its bit_code code_length = charTable[ch].encodeLength; //look up the length (in bits) of the bitcode for(short int j=code_length-1; j>=0; j--) { setbit(huffman_buffer, index, bit_count++ , getbit(bit_code, j)); //write the bitcodes to the buffer if(bit_count%8 == 0) index++; } } if(huffman_buffer[index] != 0) huffman_buffer[index++]; //nullpad the buffer if it isn't already h_len = index+1; //index; //return the length of the huffman trie in bytes } int Huffman::readHeader(string hfile) { int num; int i=0; int f_len = hfile.size(); cout << endl << endl << " charmax = " << UCHAR_MAX << endl << endl; string m_number; string f_name; string table; string enc_text; string e_o_f; ifstream inf(hfile.c_str()); if(!inf) cout << "Error reading file..." << endl; else { getline(inf,m_number); //sstream conversion found here: http://www.cplusplus.com/forum/articles/9645/ stringstream convert(m_number); // stringstream used for the conversion initialized with the contents of the string if ( !(convert >> num) )//give the value to an integer using the characters in the string { cout << "Not a valid compressed file. Exiting..." << endl; return -1; } else cout << " Magic number matches!" << endl; getline(inf,f_name); cout << "Original file: " << f_name << endl; //getline(inf,table); //cout << " Table: " << endl << table; for (int i=0;i<UCHAR_MAX;i++) // trouble reading in table with getline and double delimiter ... 762 retrieves complete table. { inf >> table[i]; if(table[i]=='' && table[i+1] == '') { i+=2; cout << ' '; } cout << table[i]; i++; } getline(inf,enc_text); cout << endl << "enc_text = " << enc_text << endl; getline(inf, e_o_f); cout << endl << "eof: " << e_o_f; } return 0; } void Huffman::populateHeader(string hfile,string fname) // Write the header { ofstream outf(hfile.c_str()); outf << MAGIC_NUMBER << endl; //write magic number outf << fname << endl; //Write file name for(int i=0; i<UCHAR_MAX; i++) if(charTable[i].active) outf << charTable[i].character << DELIM << charTable[i].occurrence ; outf << DELIM << DELIM << endl; //Write char table and int with with double delimiter for(int i=0;i<h_len;i++) outf << huffman_buffer[i]; //write encoded test outf << endl; outf << O_EOF; //write our "Output" EOF character outf.close(); //close the filestream } void Huffman::print_huffman() { for(unsigned int i=0; i<h_len; i++) { cout << "\\" << (int)huffman_buffer[i]; } cout << endl << "Length of huffman codeing = " << h_len << " characters" << endl; } void Huffman::test() { } Huffman::~Huffman() //Destructor deletes entire header { } <|endoftext|>
<commit_before>#include "GlSystem.hpp" #include "GlDevice.hpp" #include "GlContext.hpp" #if defined(___INANITY_PLATFORM_WINDOWS) #include "Win32Adapter.hpp" #include "../platform/Win32Window.hpp" #include "../Strings.hpp" #elif defined(___INANITY_PLATFORM_LINUX) || defined(___INANITY_PLATFORM_FREEBSD) #include "SdlAdapter.hpp" #elif defined(___INANITY_PLATFORM_EMSCRIPTEN) #include "EmsAdapter.hpp" #include "../platform/EmsWindow.hpp" #else #error Unknown platform #endif #include "../Exception.hpp" BEGIN_INANITY_GRAPHICS GlSystem::GlSystem() : adaptersInitialized(false) {} const std::vector<ptr<Adapter> >& GlSystem::GetAdapters() { if(!adaptersInitialized) { #if defined(___INANITY_PLATFORM_WINDOWS) Win32Adapter::GetAdapters(adapters); #elif defined(___INANITY_PLATFORM_LINUX) || defined(___INANITY_PLATFORM_FREEBSD) SdlAdapter::GetAdapters(adapters); #elif defined(___INANITY_PLATFORM_EMSCRIPTEN) EmsAdapter::GetAdapters(adapters); #else #error Unknown platform #endif adaptersInitialized = true; } return adapters; } ptr<Device> GlSystem::CreateDevice(ptr<Adapter> abstractAdapter) { BEGIN_TRY(); #if defined(___INANITY_PLATFORM_WINDOWS) ptr<Win32Adapter> adapter = abstractAdapter.DynamicCast<Win32Adapter>(); if(!adapter) THROW("Wrong adapter type"); return NEW(GlDevice(this, adapter->GetId())); #elif defined(___INANITY_PLATFORM_LINUX) || defined(___INANITY_PLATFORM_FREEBSD) || defined(___INANITY_PLATFORM_EMSCRIPTEN) return NEW(GlDevice(this)); #else #error Unknown platform #endif // TODO THROW("Not implemented"); END_TRY("Can't create OpenGL device"); } ptr<Context> GlSystem::CreateContext(ptr<Device> abstractDevice) { BEGIN_TRY(); ptr<GlDevice> device = abstractDevice.DynamicCast<GlDevice>(); if(!device) THROW("Wrong device type"); return NEW(GlContext(device)); END_TRY("Can't create OpenGL context"); } void GlSystem::InitGLEW() { GLenum err = glewInit(); if(err != GLEW_OK) #ifdef ___INANITY_PLATFORM_EMSCRIPTEN THROW("Can't initialize GLEW"); #else THROW(String("Can't initialize GLEW: ") + (const char*)glewGetErrorString(err)); #endif } void GlSystem::ClearErrors() { while(glGetError() != GL_NO_ERROR); } void GlSystem::CheckErrors(const char* primaryExceptionString) { #ifdef _DEBUG GLenum error = glGetError(); // если есть хотя бы одна ошибка if(error != GL_NO_ERROR) { // согласно спецификации, может быть несколько ошибок // получаем их, пока не кончатся String errorStrings = "OpenGL error(s):"; do { // получить строку ошибки const char* errorString; #define DEFINE_GL_ERROR(code) \ case code: \ errorString = " " #code; \ break switch(error) { DEFINE_GL_ERROR(GL_INVALID_ENUM); DEFINE_GL_ERROR(GL_INVALID_VALUE); DEFINE_GL_ERROR(GL_INVALID_OPERATION); DEFINE_GL_ERROR(GL_INVALID_FRAMEBUFFER_OPERATION); DEFINE_GL_ERROR(GL_OUT_OF_MEMORY); default: errorString = "Unknown OpenGL error"; break; } #undef DEFINE_GL_ERROR errorStrings += errorString; } while((error = glGetError()) != GL_NO_ERROR); // всё, ошибки кончились, и флаги ошибок очищены // бросить исключение if(primaryExceptionString) THROW_SECONDARY(primaryExceptionString, NEW(Exception(errorStrings))); else THROW(errorStrings); } #endif } bool GlSystem::GetTextureFormat(PixelFormat pixelFormat, bool renderbuffer, bool& compressed, GLint& internalFormat, GLenum& format, GLenum& type) { #define T(t) PixelFormat::type##t #define P(p) PixelFormat::pixel##p #define F(f) PixelFormat::format##f #define S(s) PixelFormat::size##s #define C(c) PixelFormat::compression##c bool ok = false; compressed = false; switch(pixelFormat.type) { case T(Unknown): break; case T(Uncompressed): // sRGB is only allowed for RGBA with 8-bit components if(pixelFormat.srgb && (pixelFormat.pixel != P(RGBA) || pixelFormat.format != F(Uint) || pixelFormat.size != S(32bit))) break; switch(pixelFormat.pixel) { case P(R): format = GL_RED; switch(pixelFormat.format) { case F(Untyped): break; case F(Uint): switch(pixelFormat.size) { case S(8bit): type = GL_UNSIGNED_BYTE; internalFormat = GL_R8; ok = true; break; case S(16bit): type = GL_UNSIGNED_SHORT; internalFormat = GL_R16; ok = true; break; default: break; } break; case F(Float): switch(pixelFormat.size) { case S(16bit): type = GL_FLOAT; internalFormat = GL_R16F; ok = true; break; case S(32bit): type = GL_FLOAT; internalFormat = GL_R32F; ok = true; break; default: break; } break; } break; case PixelFormat::pixelRG: format = GL_RG; switch(pixelFormat.format) { case F(Untyped): break; case F(Uint): switch(pixelFormat.size) { case S(16bit): type = GL_UNSIGNED_BYTE; internalFormat = GL_RG8; ok = true; break; case S(32bit): type = GL_UNSIGNED_SHORT; internalFormat = GL_RG16; ok = true; break; default: break; } break; case F(Float): switch(pixelFormat.size) { case S(32bit): type = GL_FLOAT; internalFormat = GL_RG16F; ok = true; break; case S(64bit): type = GL_FLOAT; internalFormat = GL_RG32F; ok = true; break; default: break; } break; } break; case PixelFormat::pixelRGB: format = GL_RGB; switch(pixelFormat.format) { case F(Untyped): break; case F(Uint): break; case F(Float): switch(pixelFormat.size) { case S(32bit): type = GL_FLOAT; internalFormat = GL_R11F_G11F_B10F; ok = true; break; case S(96bit): type = GL_FLOAT; internalFormat = GL_RGB32F; ok = true; break; default: break; } break; } break; case PixelFormat::pixelRGBA: format = GL_RGBA; switch(pixelFormat.format) { case F(Untyped): break; case F(Uint): switch(pixelFormat.size) { case S(32bit): type = GL_UNSIGNED_BYTE; internalFormat = pixelFormat.srgb ? GL_SRGB8_ALPHA8 : GL_RGBA8; ok = true; break; case S(64bit): type = GL_UNSIGNED_SHORT; internalFormat = GL_RGBA16; ok = true; break; default: break; } break; case F(Float): switch(pixelFormat.size) { case S(64bit): type = GL_FLOAT; internalFormat = GL_RGBA16F; ok = true; break; case S(128bit): type = GL_FLOAT; internalFormat = GL_RGBA32F; ok = true; break; default: break; } break; } break; } break; case T(Compressed): compressed = true; switch(pixelFormat.compression) { case C(Bc1): internalFormat = pixelFormat.srgb ? GL_COMPRESSED_SRGB_S3TC_DXT1_EXT : GL_COMPRESSED_RGB_S3TC_DXT1_EXT; ok = true; break; case C(Bc1Alpha): internalFormat = pixelFormat.srgb ? GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT : GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; ok = true; break; case C(Bc2): internalFormat = pixelFormat.srgb ? GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT : GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; ok = true; break; case C(Bc3): internalFormat = pixelFormat.srgb ? GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT : GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; ok = true; break; case C(Bc4): internalFormat = GL_COMPRESSED_RED_RGTC1; ok = true; break; case C(Bc4Signed): internalFormat = GL_COMPRESSED_SIGNED_RED_RGTC1; ok = true; break; case C(Bc5): internalFormat = GL_COMPRESSED_RG_RGTC2; ok = true; break; case C(Bc5Signed): internalFormat = GL_COMPRESSED_SIGNED_RG_RGTC2; ok = true; break; } break; } if(ok) { #ifdef ___INANITY_PLATFORM_EMSCRIPTEN if(!compressed) { if(format == GL_RED) format = renderbuffer ? GL_RGB : GL_LUMINANCE; internalFormat = format; } #endif return true; } THROW("Pixel format is unsupported in OpenGL"); #undef T #undef P #undef F #undef S #undef C } int GlSystem::AttributeNameToSemantic(const String& name) { // имя атрибута должно начинаться с "attr_" static const char beginStr[] = "attr_"; size_t i; for(i = 0; i < name.length() && beginStr[i]; ++i) if(name[i] != beginStr[i]) break; if(beginStr[i]) THROW("Wrong attribute name"); // перевести имя в семантику int semantic = 0; for(; i < name.length(); ++i) { char ch = name[i]; if(ch < 'a' || ch > 'z') THROW("Wrong symbol in attribute semantic"); semantic = semantic * 26 + ch - 'a'; } return semantic; } END_INANITY_GRAPHICS <commit_msg>cosmetic<commit_after>#include "GlSystem.hpp" #include "GlDevice.hpp" #include "GlContext.hpp" #if defined(___INANITY_PLATFORM_WINDOWS) #include "Win32Adapter.hpp" #include "../platform/Win32Window.hpp" #include "../Strings.hpp" #elif defined(___INANITY_PLATFORM_LINUX) || defined(___INANITY_PLATFORM_FREEBSD) #include "SdlAdapter.hpp" #elif defined(___INANITY_PLATFORM_EMSCRIPTEN) #include "EmsAdapter.hpp" #include "../platform/EmsWindow.hpp" #else #error Unknown platform #endif #include "../Exception.hpp" BEGIN_INANITY_GRAPHICS GlSystem::GlSystem() : adaptersInitialized(false) {} const std::vector<ptr<Adapter> >& GlSystem::GetAdapters() { if(!adaptersInitialized) { #if defined(___INANITY_PLATFORM_WINDOWS) Win32Adapter::GetAdapters(adapters); #elif defined(___INANITY_PLATFORM_LINUX) || defined(___INANITY_PLATFORM_FREEBSD) SdlAdapter::GetAdapters(adapters); #elif defined(___INANITY_PLATFORM_EMSCRIPTEN) EmsAdapter::GetAdapters(adapters); #else #error Unknown platform #endif adaptersInitialized = true; } return adapters; } ptr<Device> GlSystem::CreateDevice(ptr<Adapter> abstractAdapter) { BEGIN_TRY(); #if defined(___INANITY_PLATFORM_WINDOWS) ptr<Win32Adapter> adapter = abstractAdapter.DynamicCast<Win32Adapter>(); if(!adapter) THROW("Wrong adapter type"); return NEW(GlDevice(this, adapter->GetId())); #elif defined(___INANITY_PLATFORM_LINUX) || defined(___INANITY_PLATFORM_FREEBSD) || defined(___INANITY_PLATFORM_EMSCRIPTEN) return NEW(GlDevice(this)); #else #error Unknown platform #endif // TODO THROW("Not implemented"); END_TRY("Can't create OpenGL device"); } ptr<Context> GlSystem::CreateContext(ptr<Device> abstractDevice) { BEGIN_TRY(); ptr<GlDevice> device = abstractDevice.DynamicCast<GlDevice>(); if(!device) THROW("Wrong device type"); return NEW(GlContext(device)); END_TRY("Can't create OpenGL context"); } void GlSystem::InitGLEW() { GLenum err = glewInit(); if(err != GLEW_OK) #ifdef ___INANITY_PLATFORM_EMSCRIPTEN THROW("Can't initialize GLEW"); #else THROW(String("Can't initialize GLEW: ") + (const char*)glewGetErrorString(err)); #endif } void GlSystem::ClearErrors() { while(glGetError() != GL_NO_ERROR); } void GlSystem::CheckErrors(const char* primaryExceptionString) { #ifdef _DEBUG GLenum error = glGetError(); // если есть хотя бы одна ошибка if(error != GL_NO_ERROR) { // согласно спецификации, может быть несколько ошибок // получаем их, пока не кончатся String errorStrings = "OpenGL error(s):"; do { // получить строку ошибки const char* errorString; #define DEFINE_GL_ERROR(code) \ case code: \ errorString = " " #code; \ break switch(error) { DEFINE_GL_ERROR(GL_INVALID_ENUM); DEFINE_GL_ERROR(GL_INVALID_VALUE); DEFINE_GL_ERROR(GL_INVALID_OPERATION); DEFINE_GL_ERROR(GL_INVALID_FRAMEBUFFER_OPERATION); DEFINE_GL_ERROR(GL_OUT_OF_MEMORY); default: errorString = "Unknown OpenGL error"; break; } #undef DEFINE_GL_ERROR errorStrings += errorString; } while((error = glGetError()) != GL_NO_ERROR); // всё, ошибки кончились, и флаги ошибок очищены // бросить исключение if(primaryExceptionString) THROW_SECONDARY(primaryExceptionString, NEW(Exception(errorStrings))); else THROW(errorStrings); } #endif } bool GlSystem::GetTextureFormat(PixelFormat pixelFormat, bool renderbuffer, bool& compressed, GLint& internalFormat, GLenum& format, GLenum& type) { #define T(t) PixelFormat::type##t #define P(p) PixelFormat::pixel##p #define F(f) PixelFormat::format##f #define S(s) PixelFormat::size##s #define C(c) PixelFormat::compression##c bool ok = false; compressed = false; switch(pixelFormat.type) { case T(Unknown): break; case T(Uncompressed): // sRGB is only allowed for RGBA with 8-bit components if(pixelFormat.srgb && (pixelFormat.pixel != P(RGBA) || pixelFormat.format != F(Uint) || pixelFormat.size != S(32bit))) break; switch(pixelFormat.pixel) { case P(R): format = GL_RED; switch(pixelFormat.format) { case F(Untyped): break; case F(Uint): switch(pixelFormat.size) { case S(8bit): type = GL_UNSIGNED_BYTE; internalFormat = GL_R8; ok = true; break; case S(16bit): type = GL_UNSIGNED_SHORT; internalFormat = GL_R16; ok = true; break; default: break; } break; case F(Float): switch(pixelFormat.size) { case S(16bit): type = GL_FLOAT; internalFormat = GL_R16F; ok = true; break; case S(32bit): type = GL_FLOAT; internalFormat = GL_R32F; ok = true; break; default: break; } break; } break; case P(RG): format = GL_RG; switch(pixelFormat.format) { case F(Untyped): break; case F(Uint): switch(pixelFormat.size) { case S(16bit): type = GL_UNSIGNED_BYTE; internalFormat = GL_RG8; ok = true; break; case S(32bit): type = GL_UNSIGNED_SHORT; internalFormat = GL_RG16; ok = true; break; default: break; } break; case F(Float): switch(pixelFormat.size) { case S(32bit): type = GL_FLOAT; internalFormat = GL_RG16F; ok = true; break; case S(64bit): type = GL_FLOAT; internalFormat = GL_RG32F; ok = true; break; default: break; } break; } break; case P(RGB): format = GL_RGB; switch(pixelFormat.format) { case F(Untyped): break; case F(Uint): break; case F(Float): switch(pixelFormat.size) { case S(32bit): type = GL_FLOAT; internalFormat = GL_R11F_G11F_B10F; ok = true; break; case S(96bit): type = GL_FLOAT; internalFormat = GL_RGB32F; ok = true; break; default: break; } break; } break; case P(RGBA): format = GL_RGBA; switch(pixelFormat.format) { case F(Untyped): break; case F(Uint): switch(pixelFormat.size) { case S(32bit): type = GL_UNSIGNED_BYTE; internalFormat = pixelFormat.srgb ? GL_SRGB8_ALPHA8 : GL_RGBA8; ok = true; break; case S(64bit): type = GL_UNSIGNED_SHORT; internalFormat = GL_RGBA16; ok = true; break; default: break; } break; case F(Float): switch(pixelFormat.size) { case S(64bit): type = GL_FLOAT; internalFormat = GL_RGBA16F; ok = true; break; case S(128bit): type = GL_FLOAT; internalFormat = GL_RGBA32F; ok = true; break; default: break; } break; } break; } break; case T(Compressed): compressed = true; switch(pixelFormat.compression) { case C(Bc1): internalFormat = pixelFormat.srgb ? GL_COMPRESSED_SRGB_S3TC_DXT1_EXT : GL_COMPRESSED_RGB_S3TC_DXT1_EXT; ok = true; break; case C(Bc1Alpha): internalFormat = pixelFormat.srgb ? GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT : GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; ok = true; break; case C(Bc2): internalFormat = pixelFormat.srgb ? GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT : GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; ok = true; break; case C(Bc3): internalFormat = pixelFormat.srgb ? GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT : GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; ok = true; break; case C(Bc4): internalFormat = GL_COMPRESSED_RED_RGTC1; ok = true; break; case C(Bc4Signed): internalFormat = GL_COMPRESSED_SIGNED_RED_RGTC1; ok = true; break; case C(Bc5): internalFormat = GL_COMPRESSED_RG_RGTC2; ok = true; break; case C(Bc5Signed): internalFormat = GL_COMPRESSED_SIGNED_RG_RGTC2; ok = true; break; } break; } if(ok) { #ifdef ___INANITY_PLATFORM_EMSCRIPTEN if(!compressed) { if(format == GL_RED) format = renderbuffer ? GL_RGB : GL_LUMINANCE; internalFormat = format; } #endif return true; } THROW("Pixel format is unsupported in OpenGL"); #undef T #undef P #undef F #undef S #undef C } int GlSystem::AttributeNameToSemantic(const String& name) { // имя атрибута должно начинаться с "attr_" static const char beginStr[] = "attr_"; size_t i; for(i = 0; i < name.length() && beginStr[i]; ++i) if(name[i] != beginStr[i]) break; if(beginStr[i]) THROW("Wrong attribute name"); // перевести имя в семантику int semantic = 0; for(; i < name.length(); ++i) { char ch = name[i]; if(ch < 'a' || ch > 'z') THROW("Wrong symbol in attribute semantic"); semantic = semantic * 26 + ch - 'a'; } return semantic; } END_INANITY_GRAPHICS <|endoftext|>
<commit_before>#include "rowindow.h" #include "ui_rowindow.h" ROWindow::ROWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::ROWindow) { ui->setupUi(this); this->game = new Reversi(); ui->lineEdit_playAt->setMaxLength(2); ui->lineEdit_playAt->setInputMask(">AD"); connect(ui->restartButton, SIGNAL(released()), this, SLOT(restartGame())); connect(ui->playCPUButton, SIGNAL(released()), this, SLOT(playCPU())); connect(ui->skipTurnButton, SIGNAL(released()), this, SLOT(skipTurn())); } ROWindow::~ROWindow() { delete ui; } void ROWindow::initGame() { this->initTable(); QGraphicsScene *scene = new QGraphicsScene(); QString imageTableFile = "imgs/reversi_table.png"; QString imageGridFile = "imgs/reversi_grid.png"; QImage imageTable(imageTableFile); QImage imageGrid(imageGridFile); if(imageTable.isNull()) { std::cout << "Error: file " << imageTableFile.toStdString() << " not found." << std::endl; return; } if(imageGrid.isNull()) { std::cout << "Error: file " << imageGridFile.toStdString() << " not found." << std::endl; return; } QGraphicsPixmapItem *itemTable = new QGraphicsPixmapItem(QPixmap::fromImage(imageTable)); QGraphicsPixmapItem *itemGrid = new QGraphicsPixmapItem(QPixmap::fromImage(imageGrid)); scene->addItem(itemTable); scene->addItem(itemGrid); ui->graphicsView->setScene(scene); ui->graphicsView->show(); this->game->initGame(); this->updateTable(); } void ROWindow::initTable() { for(int i=0; i<Reversi::BOARD_SIZE; i++) { for(int j=0; j<Reversi::BOARD_SIZE; j++) { this->tableOfPieces[i][j] = NULL; } } } void ROWindow::setPieceOnTable(QString pieceName, int x, int y) { if(x < 0 || y < 0 || x >= Reversi::BOARD_SIZE || y >= Reversi::BOARD_SIZE) { std::cout << "Error: index x:" << x << " or y:" << y << " out of bounding." << std::endl; return; } QGraphicsScene *scene = ui->graphicsView->scene(); if(pieceName == "empty") { Piece *piece = this->tableOfPieces[x][y]; if(piece == NULL) return; this->tableOfPieces[x][y] = NULL; scene->removeItem(piece->getImage()); delete piece; return; } int x_pixel = calculatePixel(y); int y_pixel = calculatePixel(x); if(this->tableOfPieces[x][y] != NULL) { Piece *piece = this->tableOfPieces[x][y]; if(piece->getType() == pieceName) return; this->tableOfPieces[x][y] = NULL; scene->removeItem(piece->getImage()); delete piece; } this->tableOfPieces[x][y] = new Piece(pieceName,x_pixel,y_pixel); scene->addItem(this->tableOfPieces[x][y]->getImage()); } int ROWindow::calculatePixel(int x) { int x_pixel = 1 + x*50; return x_pixel; } void ROWindow::verifyEndGame() { if(this->game->endGame()){ ui->statusBar->showMessage("End Game!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); if(game->getBlackScore() == game->getWhiteScore() ) { QMessageBox::question(this,"Reversi", "Game set! There was no winner!",QMessageBox::Ok); } else { QString winner = game->getBlackScore() > game->getWhiteScore() ? "Black" : "White"; QMessageBox::question(this,"Reversi", "Game set! "+winner+" wins.",QMessageBox::Ok); } } } void ROWindow::updateTable() { for(int i=0; i<Reversi::BOARD_SIZE; i++) { for(int j=0; j<Reversi::BOARD_SIZE; j++) { int pieceType = game->getPiece(i,j); switch(pieceType) { case Reversi::EMPTY: this->setPieceOnTable("empty",i,j); break; case Reversi::BLACK: this->setPieceOnTable("black",i,j); break; case Reversi::WHITE: this->setPieceOnTable("white",i,j); break; case Reversi::MARKER: this->setPieceOnTable("marker",i,j); break; } } } int x=0,y=0; if(this->game->getLastMove(x,y)) { QChar line = 'A'+x; QChar column = '1'+y; QString pos = " "+(QString)line+""+(QString)column; ui->statusBar->showMessage("Move on "+pos, 5000); ui->label_lastMove->setText(pos); } else { ui->label_lastMove->setText(""); } QString turn = this->game->getTurn() == Reversi::WHITE ? "White" : "Black"; QString black_score = QString::number(this->game->getBlackScore()); QString white_score = QString::number(this->game->getWhiteScore()); ui->label_scoreBlack->setText(black_score); ui->label_scoreWhite->setText(white_score); ui->label_turn->setText(turn); this->verifyEndGame(); } void ROWindow::playGame(int i, int j) { if(i < 0 || j < 0 || i >= Reversi::BOARD_SIZE || j >= Reversi::BOARD_SIZE) { std::cout << "Error: index i:" << i << " or j:" << j << " out of bounding." << std::endl; return; } bool validMove = this->game->play(i,j); if(validMove){ this->updateTable(); } else{ ui->statusBar->showMessage("Invalid move! ", 5000); } } void ROWindow::mousePressEvent(QMouseEvent *event) { int x = QCursor::pos().x(); x -= 12; x -= this->pos().x(); x -= ui->frame->pos().x(); x -= ui->graphicsView->pos().x(); int y = QCursor::pos().y(); y -= 58; y -= this->pos().y(); y -= ui->frame->pos().y(); y -= ui->graphicsView->pos().y(); if( x < 0 || y < 0 || x >= ui->graphicsView->width() || y >= ui->graphicsView->height()) return; int i=0,j=0; i = y/50; j = x/50; this->playGame(i,j); } void ROWindow::playCPU() { /*while(!this->game->endGame()) { if(this->game->getTotalMarkers() == 0) { this->game->changeTurn(); } //h2 - black if(this->game->getTurn() == Reversi::BLACK) { int i=0,j=0; ArtificialIntelligence ia(this->game); ia.setAgent(2); ia.calculateBetterMove(i,j); this->playGame(i,j); } else {*/ //h3 - white int i=0,j=0; ArtificialIntelligence ia(this->game); ia.setAgent(2); ia.setLevel(3); ia.calculateBetterMove(i,j); this->playGame(i,j); /*} }*/ } void ROWindow::restartGame() { this->game->restartGame(); this->updateTable(); } void ROWindow::skipTurn() { int totalMarkers = this->game->getTotalMarkers(); if(totalMarkers > 0) { ui->statusBar->showMessage("You can only skip when you can't play.", 5000); return; } else { this->game->changeTurn(); this->updateTable(); } } void ROWindow::on_lineEdit_playAt_returnPressed() { QString pos = ui->lineEdit_playAt->text(); int i = pos.at(0).toUpper().toLatin1() - 'A'; int j = pos.at(1).toUpper().toLatin1() - '1'; this->playGame(i,j); } void ROWindow::on_undoLastMoveButton_released() { this->game->undoLastMove(); this->updateTable(); } <commit_msg>Added message thinking in status bar when cpu is thinking.<commit_after>#include "rowindow.h" #include "ui_rowindow.h" ROWindow::ROWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::ROWindow) { ui->setupUi(this); this->game = new Reversi(); ui->lineEdit_playAt->setMaxLength(2); ui->lineEdit_playAt->setInputMask(">AD"); connect(ui->restartButton, SIGNAL(released()), this, SLOT(restartGame())); connect(ui->playCPUButton, SIGNAL(released()), this, SLOT(playCPU())); connect(ui->skipTurnButton, SIGNAL(released()), this, SLOT(skipTurn())); } ROWindow::~ROWindow() { delete ui; } void ROWindow::initGame() { this->initTable(); QGraphicsScene *scene = new QGraphicsScene(); QString imageTableFile = "imgs/reversi_table.png"; QString imageGridFile = "imgs/reversi_grid.png"; QImage imageTable(imageTableFile); QImage imageGrid(imageGridFile); if(imageTable.isNull()) { std::cout << "Error: file " << imageTableFile.toStdString() << " not found." << std::endl; return; } if(imageGrid.isNull()) { std::cout << "Error: file " << imageGridFile.toStdString() << " not found." << std::endl; return; } QGraphicsPixmapItem *itemTable = new QGraphicsPixmapItem(QPixmap::fromImage(imageTable)); QGraphicsPixmapItem *itemGrid = new QGraphicsPixmapItem(QPixmap::fromImage(imageGrid)); scene->addItem(itemTable); scene->addItem(itemGrid); ui->graphicsView->setScene(scene); ui->graphicsView->show(); this->game->initGame(); this->updateTable(); } void ROWindow::initTable() { for(int i=0; i<Reversi::BOARD_SIZE; i++) { for(int j=0; j<Reversi::BOARD_SIZE; j++) { this->tableOfPieces[i][j] = NULL; } } } void ROWindow::setPieceOnTable(QString pieceName, int x, int y) { if(x < 0 || y < 0 || x >= Reversi::BOARD_SIZE || y >= Reversi::BOARD_SIZE) { std::cout << "Error: index x:" << x << " or y:" << y << " out of bounding." << std::endl; return; } QGraphicsScene *scene = ui->graphicsView->scene(); if(pieceName == "empty") { Piece *piece = this->tableOfPieces[x][y]; if(piece == NULL) return; this->tableOfPieces[x][y] = NULL; scene->removeItem(piece->getImage()); delete piece; return; } int x_pixel = calculatePixel(y); int y_pixel = calculatePixel(x); if(this->tableOfPieces[x][y] != NULL) { Piece *piece = this->tableOfPieces[x][y]; if(piece->getType() == pieceName) return; this->tableOfPieces[x][y] = NULL; scene->removeItem(piece->getImage()); delete piece; } this->tableOfPieces[x][y] = new Piece(pieceName,x_pixel,y_pixel); scene->addItem(this->tableOfPieces[x][y]->getImage()); } int ROWindow::calculatePixel(int x) { int x_pixel = 1 + x*50; return x_pixel; } void ROWindow::verifyEndGame() { if(this->game->endGame()){ ui->statusBar->showMessage("End Game!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); if(game->getBlackScore() == game->getWhiteScore() ) { QMessageBox::question(this,"Reversi", "Game set! There was no winner!",QMessageBox::Ok); } else { QString winner = game->getBlackScore() > game->getWhiteScore() ? "Black" : "White"; QMessageBox::question(this,"Reversi", "Game set! "+winner+" wins.",QMessageBox::Ok); } } } void ROWindow::updateTable() { for(int i=0; i<Reversi::BOARD_SIZE; i++) { for(int j=0; j<Reversi::BOARD_SIZE; j++) { int pieceType = game->getPiece(i,j); switch(pieceType) { case Reversi::EMPTY: this->setPieceOnTable("empty",i,j); break; case Reversi::BLACK: this->setPieceOnTable("black",i,j); break; case Reversi::WHITE: this->setPieceOnTable("white",i,j); break; case Reversi::MARKER: this->setPieceOnTable("marker",i,j); break; } } } int x=0,y=0; if(this->game->getLastMove(x,y)) { QChar line = 'A'+x; QChar column = '1'+y; QString pos = " "+(QString)line+""+(QString)column; ui->statusBar->showMessage("Move on "+pos, 5000); ui->label_lastMove->setText(pos); } else { ui->label_lastMove->setText(""); } QString turn = this->game->getTurn() == Reversi::WHITE ? "White" : "Black"; QString black_score = QString::number(this->game->getBlackScore()); QString white_score = QString::number(this->game->getWhiteScore()); ui->label_scoreBlack->setText(black_score); ui->label_scoreWhite->setText(white_score); ui->label_turn->setText(turn); this->verifyEndGame(); } void ROWindow::playGame(int i, int j) { if(i < 0 || j < 0 || i >= Reversi::BOARD_SIZE || j >= Reversi::BOARD_SIZE) { std::cout << "Error: index i:" << i << " or j:" << j << " out of bounding." << std::endl; return; } bool validMove = this->game->play(i,j); if(validMove){ this->updateTable(); } else{ ui->statusBar->showMessage("Invalid move! ", 5000); } } void ROWindow::mousePressEvent(QMouseEvent *event) { int x = QCursor::pos().x(); x -= 12; x -= this->pos().x(); x -= ui->frame->pos().x(); x -= ui->graphicsView->pos().x(); int y = QCursor::pos().y(); y -= 58; y -= this->pos().y(); y -= ui->frame->pos().y(); y -= ui->graphicsView->pos().y(); if( x < 0 || y < 0 || x >= ui->graphicsView->width() || y >= ui->graphicsView->height()) return; int i=0,j=0; i = y/50; j = x/50; this->playGame(i,j); } void ROWindow::playCPU() { /*while(!this->game->endGame()) { if(this->game->getTotalMarkers() == 0) { this->game->changeTurn(); } //h2 - black if(this->game->getTurn() == Reversi::BLACK) { int i=0,j=0; ArtificialIntelligence ia(this->game); ia.setAgent(2); ia.calculateBetterMove(i,j); this->playGame(i,j); } else {*/ //h3 - white int i=0,j=0; ArtificialIntelligence ia(this->game); ia.setAgent(2); ia.setLevel(3); ui->statusBar->showMessage("Thinking..."); ia.calculateBetterMove(i,j); ui->statusBar->showMessage(""); this->playGame(i,j); /*} }*/ } void ROWindow::restartGame() { this->game->restartGame(); this->updateTable(); } void ROWindow::skipTurn() { int totalMarkers = this->game->getTotalMarkers(); if(totalMarkers > 0) { ui->statusBar->showMessage("You can only skip when you can't play.", 5000); return; } else { this->game->changeTurn(); this->updateTable(); } } void ROWindow::on_lineEdit_playAt_returnPressed() { QString pos = ui->lineEdit_playAt->text(); int i = pos.at(0).toUpper().toLatin1() - 'A'; int j = pos.at(1).toUpper().toLatin1() - '1'; this->playGame(i,j); } void ROWindow::on_undoLastMoveButton_released() { this->game->undoLastMove(); this->updateTable(); } <|endoftext|>
<commit_before>/* Copyright (c) 2012-2013 LevelDOWN contributors * See list at <https://github.com/rvagg/node-leveldown#contributing> * MIT +no-false-attribs License <https://github.com/rvagg/node-leveldown/blob/master/LICENSE> */ #include <node.h> #include <node_buffer.h> #include "database.h" #include "iterator.h" #include "iterator_async.h" namespace leveldown { static v8::Persistent<v8::FunctionTemplate> iterator_constructor; Iterator::Iterator ( Database* database , uint32_t id , leveldb::Slice* start , std::string* end , bool reverse , bool keys , bool values , int limit , bool fillCache , bool keyAsBuffer , bool valueAsBuffer , v8::Local<v8::Object> &startHandle , std::string* lt , std::string* lte , std::string* gt , std::string* gte ) : database(database) , id(id) , start(start) , end(end) , reverse(reverse) , keys(keys) , values(values) , limit(limit) , keyAsBuffer(keyAsBuffer) , valueAsBuffer(valueAsBuffer) , lt(lt) , lte(lte) , gt(gt) , gte(gte) { NanScope(); v8::Local<v8::Object> obj = v8::Object::New(); if (!startHandle.IsEmpty()) obj->Set(NanSymbol("start"), startHandle); NanAssignPersistent(v8::Object, persistentHandle, obj); options = new leveldb::ReadOptions(); options->fill_cache = fillCache; dbIterator = NULL; count = 0; nexting = false; ended = false; endWorker = NULL; }; Iterator::~Iterator () { delete options; if (!persistentHandle.IsEmpty()) NanDispose(persistentHandle); if (start != NULL) delete start; if (end != NULL) delete end; }; bool Iterator::GetIterator () { if (dbIterator == NULL) { dbIterator = database->NewIterator(options); if (start != NULL) { dbIterator->Seek(*start); if (reverse) { if (!dbIterator->Valid()) dbIterator->SeekToLast(); else if (start->compare(dbIterator->key())) dbIterator->Prev(); } } else if (reverse) dbIterator->SeekToLast(); else dbIterator->SeekToFirst(); return true; } return false; } bool Iterator::IteratorNext (std::string& key, std::string& value) { if (!GetIterator()) { if (reverse) dbIterator->Prev(); else dbIterator->Next(); } // 'end' here is an inclusive test int isEnd = end == NULL ? 1 : end->compare(dbIterator->key().ToString()); bool endInclusive = true; bool startInclusive = true; if (dbIterator->Valid() && (limit < 0 || ++count <= limit) && (end == NULL || (reverse && (endInclusive ? isEnd <= 0 : isEnd < 0)) || (!reverse && (endInclusive ? isEnd >= 0 : isEnd > 0)))) { if (keys) key.assign(dbIterator->key().data(), dbIterator->key().size()); if (values) value.assign(dbIterator->value().data(), dbIterator->value().size()); return true; } else { return false; } } leveldb::Status Iterator::IteratorStatus () { return dbIterator->status(); } void Iterator::IteratorEnd () { //TODO: could return it->status() delete dbIterator; dbIterator = NULL; } void Iterator::Release () { database->ReleaseIterator(id); } void checkEndCallback (Iterator* iterator) { iterator->nexting = false; if (iterator->endWorker != NULL) { NanAsyncQueueWorker(iterator->endWorker); iterator->endWorker = NULL; } } //void *ctx, void (*callback)(void *ctx, leveldb::Slice key, leveldb::Slice value) NAN_METHOD(Iterator::Next) { NanScope(); Iterator* iterator = node::ObjectWrap::Unwrap<Iterator>(args.This()); if (args.Length() == 0 || !args[0]->IsFunction()) return NanThrowError("next() requires a callback argument"); v8::Local<v8::Function> callback = args[0].As<v8::Function>(); if (iterator->ended) { LD_RETURN_CALLBACK_OR_ERROR(callback, "cannot call next() after end()") } if (iterator->nexting) { LD_RETURN_CALLBACK_OR_ERROR(callback, "cannot call next() before previous next() has completed") } NextWorker* worker = new NextWorker( iterator , new NanCallback(callback) , checkEndCallback ); iterator->nexting = true; NanAsyncQueueWorker(worker); NanReturnValue(args.Holder()); } NAN_METHOD(Iterator::End) { NanScope(); Iterator* iterator = node::ObjectWrap::Unwrap<Iterator>(args.This()); if (args.Length() == 0 || !args[0]->IsFunction()) return NanThrowError("end() requires a callback argument"); v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(args[0]); if (iterator->ended) { LD_RETURN_CALLBACK_OR_ERROR(callback, "end() already called on iterator") } EndWorker* worker = new EndWorker( iterator , new NanCallback(callback) ); iterator->ended = true; if (iterator->nexting) { // waiting for a next() to return, queue the end iterator->endWorker = worker; } else { NanAsyncQueueWorker(worker); } NanReturnValue(args.Holder()); } void Iterator::Init () { v8::Local<v8::FunctionTemplate> tpl = v8::FunctionTemplate::New(Iterator::New); NanAssignPersistent(v8::FunctionTemplate, iterator_constructor, tpl); tpl->SetClassName(NanSymbol("Iterator")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl, "next", Iterator::Next); NODE_SET_PROTOTYPE_METHOD(tpl, "end", Iterator::End); } v8::Local<v8::Object> Iterator::NewInstance ( v8::Local<v8::Object> database , v8::Local<v8::Number> id , v8::Local<v8::Object> optionsObj ) { NanScope(); v8::Local<v8::Object> instance; v8::Local<v8::FunctionTemplate> constructorHandle = NanPersistentToLocal(iterator_constructor); if (optionsObj.IsEmpty()) { v8::Handle<v8::Value> argv[2] = { database, id }; instance = constructorHandle->GetFunction()->NewInstance(2, argv); } else { v8::Handle<v8::Value> argv[3] = { database, id, optionsObj }; instance = constructorHandle->GetFunction()->NewInstance(3, argv); } return instance; } NAN_METHOD(Iterator::New) { NanScope(); Database* database = node::ObjectWrap::Unwrap<Database>(args[0]->ToObject()); //TODO: remove this, it's only here to make LD_STRING_OR_BUFFER_TO_SLICE happy v8::Handle<v8::Function> callback; v8::Local<v8::Object> startHandle; leveldb::Slice* start = NULL; std::string* end = NULL; int limit = -1; v8::Local<v8::Value> id = args[1]; v8::Local<v8::Object> optionsObj; v8::Local<v8::Object> ltHandle; v8::Local<v8::Object> lteHandle; v8::Local<v8::Object> gtHandle; v8::Local<v8::Object> gteHandle; std::string* lt = NULL; std::string* lte = NULL; std::string* gt = NULL; std::string* gte = NULL; if (args.Length() > 1 && args[2]->IsObject()) { optionsObj = v8::Local<v8::Object>::Cast(args[2]); if (optionsObj->Has(NanSymbol("start")) && (node::Buffer::HasInstance(optionsObj->Get(NanSymbol("start"))) || optionsObj->Get(NanSymbol("start"))->IsString())) { startHandle = optionsObj->Get(NanSymbol("start")).As<v8::Object>(); // ignore start if it has size 0 since a Slice can't have length 0 if (StringOrBufferLength(startHandle) > 0) { LD_STRING_OR_BUFFER_TO_SLICE(_start, startHandle, start) start = new leveldb::Slice(_start.data(), _start.size()); } } if (optionsObj->Has(NanSymbol("end")) && (node::Buffer::HasInstance(optionsObj->Get(NanSymbol("end"))) || optionsObj->Get(NanSymbol("end"))->IsString())) { v8::Local<v8::Value> endBuffer = v8::Local<v8::Value>::New(optionsObj->Get(NanSymbol("end"))); // ignore end if it has size 0 since a Slice can't have length 0 if (StringOrBufferLength(endBuffer) > 0) { LD_STRING_OR_BUFFER_TO_SLICE(_end, endBuffer, end) end = new std::string(_end.data(), _end.size()); } } if (!optionsObj.IsEmpty() && optionsObj->Has(NanSymbol("limit"))) { limit = v8::Local<v8::Integer>::Cast(optionsObj->Get( NanSymbol("limit")))->Value(); } if (optionsObj->Has(NanSymbol("lt")) && (node::Buffer::HasInstance(optionsObj->Get(NanSymbol("lt"))) || optionsObj->Get(NanSymbol("lt"))->IsString())) { v8::Local<v8::Value> ltBuffer = v8::Local<v8::Value>::New(optionsObj->Get(NanSymbol("lt"))); // ignore end if it has size 0 since a Slice can't have length 0 if (StringOrBufferLength(ltBuffer) > 0) { LD_STRING_OR_BUFFER_TO_SLICE(_lt, ltBuffer, lt) lt = new std::string(_lt.data(), _lt.size()); } } } bool reverse = NanBooleanOptionValue(optionsObj, NanSymbol("reverse")); bool keys = NanBooleanOptionValue(optionsObj, NanSymbol("keys"), true); bool values = NanBooleanOptionValue(optionsObj, NanSymbol("values"), true); bool keyAsBuffer = NanBooleanOptionValue( optionsObj , NanSymbol("keyAsBuffer") , true ); bool valueAsBuffer = NanBooleanOptionValue( optionsObj , NanSymbol("valueAsBuffer") , true ); bool fillCache = NanBooleanOptionValue(optionsObj, NanSymbol("fillCache")); Iterator* iterator = new Iterator( database , (uint32_t)id->Int32Value() , start , end , reverse , keys , values , limit , fillCache , keyAsBuffer , valueAsBuffer , startHandle , lt , lte , gt , gte ); iterator->Wrap(args.This()); NanReturnValue(args.This()); } } // namespace leveldown <commit_msg>1st pass at lt, lte, gt, gte<commit_after>/* Copyright (c) 2012-2013 LevelDOWN contributors * See list at <https://github.com/rvagg/node-leveldown#contributing> * MIT +no-false-attribs License <https://github.com/rvagg/node-leveldown/blob/master/LICENSE> */ #include <node.h> #include <node_buffer.h> #include <iostream> #include "database.h" #include "iterator.h" #include "iterator_async.h" namespace leveldown { static v8::Persistent<v8::FunctionTemplate> iterator_constructor; Iterator::Iterator ( Database* database , uint32_t id , leveldb::Slice* start , std::string* end , bool reverse , bool keys , bool values , int limit , bool fillCache , bool keyAsBuffer , bool valueAsBuffer , v8::Local<v8::Object> &startHandle , std::string* lt , std::string* lte , std::string* gt , std::string* gte ) : database(database) , id(id) , start(start) , end(end) , reverse(reverse) , keys(keys) , values(values) , limit(limit) , keyAsBuffer(keyAsBuffer) , valueAsBuffer(valueAsBuffer) , lt(lt) , lte(lte) , gt(gt) , gte(gte) { NanScope(); v8::Local<v8::Object> obj = v8::Object::New(); if (!startHandle.IsEmpty()) obj->Set(NanSymbol("start"), startHandle); NanAssignPersistent(v8::Object, persistentHandle, obj); options = new leveldb::ReadOptions(); options->fill_cache = fillCache; dbIterator = NULL; count = 0; nexting = false; ended = false; endWorker = NULL; }; Iterator::~Iterator () { delete options; if (!persistentHandle.IsEmpty()) NanDispose(persistentHandle); if (start != NULL) delete start; if (end != NULL) delete end; }; bool Iterator::GetIterator () { if (dbIterator == NULL) { dbIterator = database->NewIterator(options); if (start != NULL) { dbIterator->Seek(*start); if (reverse) { if (!dbIterator->Valid()) dbIterator->SeekToLast(); //if it's past the last key, step back else if (start->compare(dbIterator->key()) != 0) dbIterator->Prev(); if(lt != NULL) { if(lt->compare(dbIterator->key().ToString()) >= 0) dbIterator->Prev(); } } else { if(gt != NULL && gt->compare(dbIterator->key().ToString()) == 0) dbIterator->Next(); } } else if (reverse) dbIterator->SeekToLast(); else dbIterator->SeekToFirst(); return true; } return false; } //seems these argument are no longer used // v v bool Iterator::IteratorNext (std::string& key, std::string& value) { //if it's not the first call, move to next item. if (!GetIterator()) { if (reverse) dbIterator->Prev(); else dbIterator->Next(); } // 'end' here is an inclusive test int isEnd = end == NULL ? 1 : end->compare(dbIterator->key().ToString()); // std::cout << "key:" << dbIterator->key().ToString() << "\n"; // std::cout << "value:" << dbIterator->value().ToString() << "\n"; // if(gt != NULL) // printf("gt: %s\n", gt->c_str()); // if(gte != NULL) // printf("gte: %s\n", gte->c_str()); // if(lt != NULL) { // printf("lt: %s\n", lt->c_str()); // printf("lt: %d\n", lt->compare(key_)); // } // if(lte != NULL) // printf("lte: %d\n", lte->compare(key_)); if (dbIterator->Valid()) { std::string key_ = dbIterator->key().ToString(); if((limit < 0 || ++count <= limit) && (end == NULL || (reverse && (isEnd <= 0)) || (!reverse && (isEnd >= 0))) && ( lt != NULL ? (lt->compare(key_) > 0) : lte != NULL ? (lte->compare(key_) >= 0) : true ) && ( gt != NULL ? (gt->compare(key_) < 0) : gte != NULL ? (gte->compare(key_) <= 0) : true ) ) { if (keys) key.assign(dbIterator->key().data(), dbIterator->key().size()); if (values) value.assign(dbIterator->value().data(), dbIterator->value().size()); return true; } else { return false; } } else return false; } leveldb::Status Iterator::IteratorStatus () { return dbIterator->status(); } void Iterator::IteratorEnd () { //TODO: could return it->status() delete dbIterator; dbIterator = NULL; } void Iterator::Release () { database->ReleaseIterator(id); } void checkEndCallback (Iterator* iterator) { iterator->nexting = false; if (iterator->endWorker != NULL) { NanAsyncQueueWorker(iterator->endWorker); iterator->endWorker = NULL; } } //void *ctx, void (*callback)(void *ctx, leveldb::Slice key, leveldb::Slice value) NAN_METHOD(Iterator::Next) { NanScope(); Iterator* iterator = node::ObjectWrap::Unwrap<Iterator>(args.This()); if (args.Length() == 0 || !args[0]->IsFunction()) return NanThrowError("next() requires a callback argument"); v8::Local<v8::Function> callback = args[0].As<v8::Function>(); if (iterator->ended) { LD_RETURN_CALLBACK_OR_ERROR(callback, "cannot call next() after end()") } if (iterator->nexting) { LD_RETURN_CALLBACK_OR_ERROR(callback, "cannot call next() before previous next() has completed") } NextWorker* worker = new NextWorker( iterator , new NanCallback(callback) , checkEndCallback ); iterator->nexting = true; NanAsyncQueueWorker(worker); NanReturnValue(args.Holder()); } NAN_METHOD(Iterator::End) { NanScope(); Iterator* iterator = node::ObjectWrap::Unwrap<Iterator>(args.This()); if (args.Length() == 0 || !args[0]->IsFunction()) return NanThrowError("end() requires a callback argument"); v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(args[0]); if (iterator->ended) { LD_RETURN_CALLBACK_OR_ERROR(callback, "end() already called on iterator") } EndWorker* worker = new EndWorker( iterator , new NanCallback(callback) ); iterator->ended = true; if (iterator->nexting) { // waiting for a next() to return, queue the end iterator->endWorker = worker; } else { NanAsyncQueueWorker(worker); } NanReturnValue(args.Holder()); } void Iterator::Init () { v8::Local<v8::FunctionTemplate> tpl = v8::FunctionTemplate::New(Iterator::New); NanAssignPersistent(v8::FunctionTemplate, iterator_constructor, tpl); tpl->SetClassName(NanSymbol("Iterator")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl, "next", Iterator::Next); NODE_SET_PROTOTYPE_METHOD(tpl, "end", Iterator::End); } v8::Local<v8::Object> Iterator::NewInstance ( v8::Local<v8::Object> database , v8::Local<v8::Number> id , v8::Local<v8::Object> optionsObj ) { NanScope(); v8::Local<v8::Object> instance; v8::Local<v8::FunctionTemplate> constructorHandle = NanPersistentToLocal(iterator_constructor); if (optionsObj.IsEmpty()) { v8::Handle<v8::Value> argv[2] = { database, id }; instance = constructorHandle->GetFunction()->NewInstance(2, argv); } else { v8::Handle<v8::Value> argv[3] = { database, id, optionsObj }; instance = constructorHandle->GetFunction()->NewInstance(3, argv); } return instance; } NAN_METHOD(Iterator::New) { NanScope(); Database* database = node::ObjectWrap::Unwrap<Database>(args[0]->ToObject()); //TODO: remove this, it's only here to make LD_STRING_OR_BUFFER_TO_SLICE happy v8::Handle<v8::Function> callback; v8::Local<v8::Object> startHandle; leveldb::Slice* start = NULL; std::string* end = NULL; int limit = -1; v8::Local<v8::Value> id = args[1]; v8::Local<v8::Object> optionsObj; v8::Local<v8::Object> ltHandle; v8::Local<v8::Object> lteHandle; v8::Local<v8::Object> gtHandle; v8::Local<v8::Object> gteHandle; std::string* lt = NULL; std::string* lte = NULL; std::string* gt = NULL; std::string* gte = NULL; //default to forward. bool reverse = false; if (args.Length() > 1 && args[2]->IsObject()) { optionsObj = v8::Local<v8::Object>::Cast(args[2]); reverse = NanBooleanOptionValue(optionsObj, NanSymbol("reverse")); if (optionsObj->Has(NanSymbol("start")) && (node::Buffer::HasInstance(optionsObj->Get(NanSymbol("start"))) || optionsObj->Get(NanSymbol("start"))->IsString())) { startHandle = optionsObj->Get(NanSymbol("start")).As<v8::Object>(); // ignore start if it has size 0 since a Slice can't have length 0 if (StringOrBufferLength(startHandle) > 0) { LD_STRING_OR_BUFFER_TO_SLICE(_start, startHandle, start) start = new leveldb::Slice(_start.data(), _start.size()); } } if (optionsObj->Has(NanSymbol("end")) && (node::Buffer::HasInstance(optionsObj->Get(NanSymbol("end"))) || optionsObj->Get(NanSymbol("end"))->IsString())) { v8::Local<v8::Value> endBuffer = v8::Local<v8::Value>::New(optionsObj->Get(NanSymbol("end"))); // ignore end if it has size 0 since a Slice can't have length 0 if (StringOrBufferLength(endBuffer) > 0) { LD_STRING_OR_BUFFER_TO_SLICE(_end, endBuffer, end) end = new std::string(_end.data(), _end.size()); } } if (!optionsObj.IsEmpty() && optionsObj->Has(NanSymbol("limit"))) { limit = v8::Local<v8::Integer>::Cast(optionsObj->Get( NanSymbol("limit")))->Value(); } if (optionsObj->Has(NanSymbol("lt")) && (node::Buffer::HasInstance(optionsObj->Get(NanSymbol("lt"))) || optionsObj->Get(NanSymbol("lt"))->IsString())) { v8::Local<v8::Value> ltBuffer = v8::Local<v8::Value>::New(optionsObj->Get(NanSymbol("lt"))); // ignore end if it has size 0 since a Slice can't have length 0 if (StringOrBufferLength(ltBuffer) > 0) { LD_STRING_OR_BUFFER_TO_SLICE(_lt, ltBuffer, lt) lt = new std::string(_lt.data(), _lt.size()); if (reverse) start = new leveldb::Slice(_lt.data(), _lt.size()); } } if (optionsObj->Has(NanSymbol("lte")) && (node::Buffer::HasInstance(optionsObj->Get(NanSymbol("lte"))) || optionsObj->Get(NanSymbol("lte"))->IsString())) { v8::Local<v8::Value> lteBuffer = v8::Local<v8::Value>::New(optionsObj->Get(NanSymbol("lte"))); // ignore end if it has size 0 since a Slice can't have length 0 if (StringOrBufferLength(lteBuffer) > 0) { LD_STRING_OR_BUFFER_TO_SLICE(_lte, lteBuffer, lte) lte = new std::string(_lte.data(), _lte.size()); if (reverse) start = new leveldb::Slice(_lte.data(), _lte.size()); } } if (optionsObj->Has(NanSymbol("gt")) && (node::Buffer::HasInstance(optionsObj->Get(NanSymbol("gt"))) || optionsObj->Get(NanSymbol("gt"))->IsString())) { v8::Local<v8::Value> gtBuffer = v8::Local<v8::Value>::New(optionsObj->Get(NanSymbol("gt"))); // ignore end if it has size 0 since a Slice can't have length 0 if (StringOrBufferLength(gtBuffer) > 0) { LD_STRING_OR_BUFFER_TO_SLICE(_gt, gtBuffer, gt) gt = new std::string(_gt.data(), _gt.size()); if (!reverse) start = new leveldb::Slice(_gt.data(), _gt.size()); } } if (optionsObj->Has(NanSymbol("gte")) && (node::Buffer::HasInstance(optionsObj->Get(NanSymbol("gte"))) || optionsObj->Get(NanSymbol("gte"))->IsString())) { v8::Local<v8::Value> gteBuffer = v8::Local<v8::Value>::New(optionsObj->Get(NanSymbol("gte"))); // ignore end if it has size 0 since a Slice can't have length 0 if (StringOrBufferLength(gteBuffer) > 0) { LD_STRING_OR_BUFFER_TO_SLICE(_gte, gteBuffer, gte) gte = new std::string(_gte.data(), _gte.size()); if (!reverse) start = new leveldb::Slice(_gte.data(), _gte.size()); } } } bool keys = NanBooleanOptionValue(optionsObj, NanSymbol("keys"), true); bool values = NanBooleanOptionValue(optionsObj, NanSymbol("values"), true); bool keyAsBuffer = NanBooleanOptionValue( optionsObj , NanSymbol("keyAsBuffer") , true ); bool valueAsBuffer = NanBooleanOptionValue( optionsObj , NanSymbol("valueAsBuffer") , true ); bool fillCache = NanBooleanOptionValue(optionsObj, NanSymbol("fillCache")); Iterator* iterator = new Iterator( database , (uint32_t)id->Int32Value() , start , end , reverse , keys , values , limit , fillCache , keyAsBuffer , valueAsBuffer , startHandle , lt , lte , gt , gte ); iterator->Wrap(args.This()); NanReturnValue(args.This()); } } // namespace leveldown <|endoftext|>
<commit_before>#include "SensorSubsystem.h" #include "../RobotMap.h" #include <iostream> #include <math.h> #define PI 3.141592 SensorSubsystem::SensorSubsystem() : Subsystem("SensorSubsystem") { gyro = new AnalogInput(GYRO_SENSOR); dist_left = new AnalogInput(DIST_LEFT); dist_right = new AnalogInput(DIST_RIGHT); acceleration = new I2C(I2C::kOnboard , 0b0011000); compass = new I2C(I2C::kOnboard , 0x1E); clock = new Timer(); deg = 0; base = 0; prespeed = 0; beforetime = 0; acceleration->Write(0x20 , 0x7F); acceleration->Write(0x23 , 0x08); compass->Write(0x02 , 0x00); clock->Start(); for(short i = 0 ; i < 10 ; i++){ base += GetGyro(); } base /= 10.0; beforetime = clock->Get(); } void SensorSubsystem::InitDefaultCommand() { //b Set the default command for a subsystem here. //SetDefaultCommand(new MySpecialCommand()); } // Put methods for controlling this subsystem // here. Call these from Commands. int SensorSubsystem::GetGyro(void) { return(gyro->GetValue()); } //Dist sensor is unsustainable, so we may calculate average value. float SensorSubsystem::GetDistLeft(void) { float ans = 0; for(short i = 0 ; i < 10 ; i++){ ans += dist_left->GetVoltage(); } ans /= 10.0; ans = 30.0 / ans; //for meter from input return(ans); } float SensorSubsystem::GetDistRight(void) { float ans = 0; for(short i = 0 ; i < 10 ; i++){ ans += dist_right->GetVoltage(); } ans /= 10.0; ans = 30.0 / ans; //for meter from input return(ans); } int SensorSubsystem::GetXacceleration(void) { unsigned char array[2]; short x; acceleration->Write(0x20 , 0x7F);//These sentenses should be always done? acceleration->Write(0x23 , 0x08);// acceleration->Read(0x28 , 1 , &array[0]); acceleration->Read(0x29 , 1 , &array[1]); x = (array[1] << 8) | array[0]; std::cout << "x = " << x << std::endl; return(x); } int SensorSubsystem::GetYacceleration(void) { unsigned char array[2]; short y; acceleration->Write(0x20 , 0x7F); acceleration->Write(0x23 , 0x08); acceleration->Read(0x30 , 1 , &array[0]); acceleration->Read(0x31 , 1 , &array[1]); y = (array[1] << 8) | array[0]; std::cout << "y = " << y << std::endl; return(y); } int SensorSubsystem::GetZacceleration(void) { unsigned char array[2]; short z; acceleration->Write(0x20 , 0x7F); acceleration->Write(0x23 , 0x08); acceleration->Read(0x32 , 1 , &array[0]); acceleration->Read(0x33 , 1 , &array[1]); z = (array[1] << 8) | array[0]; std::cout << "z = " << z << std::endl; return(z); } //This function is used in loop to check degree. float SensorSubsystem::GetDegree(void) { float data = 0; float time; float speed; for(short i = 0 ; i < 10 ; i++){ data += gyro->GetVoltage(); } data /= 10.0; data -= base; if(-0.006 < data && data < 0.006) data = 0; speed = data / 0.0067; time = clock->Get() - beforetime; beforetime = clock->Get(); deg += (prespeed + speed) / 2.0 * time; prespeed = speed; std::cout << deg << std::endl; return(deg); } float SensorSubsystem::GetCompass(void) { unsigned char array[4]; short x , y; float tan; for(short i = 0 ; i < 4 ; i++){ compass->Read(0x03 + i , 1 , &array[i]); } x = (array[0] << 8) | array[1]; y = (array[2] << 8) | array[3]; if(x){ tan = y; tan /= x; return((atan(tan) / PI * 180) + ((y > 0) ? 0 : 180)); }else{ return((y > 0) ? 90 : 270); } } <commit_msg>compass<commit_after>#include "SensorSubsystem.h" #include "../RobotMap.h" #include <iostream> #include <math.h> #define PI 3.141592 SensorSubsystem::SensorSubsystem() : Subsystem("SensorSubsystem") { gyro = new AnalogInput(GYRO_SENSOR); dist_left = new AnalogInput(DIST_LEFT); dist_right = new AnalogInput(DIST_RIGHT); acceleration = new I2C(I2C::kOnboard , 0b0011000); compass = new I2C(I2C::kOnboard , 0x1E); clock = new Timer(); deg = 0; base = 0; prespeed = 0; beforetime = 0; acceleration->Write(0x20 , 0x7F); acceleration->Write(0x23 , 0x08); compass->Write(0x02 , 0x00); clock->Start(); for(short i = 0 ; i < 10 ; i++){ base += GetGyro(); } base /= 10.0; beforetime = clock->Get(); } void SensorSubsystem::InitDefaultCommand() { //b Set the default command for a subsystem here. //SetDefaultCommand(new MySpecialCommand()); } // Put methods for controlling this subsystem // here. Call these from Commands. int SensorSubsystem::GetGyro(void) { return(gyro->GetValue()); } //Dist sensor is unsustainable, so we may calculate average value. float SensorSubsystem::GetDistLeft(void) { float ans = 0; for(short i = 0 ; i < 10 ; i++){ ans += dist_left->GetVoltage(); } ans /= 10.0; ans = 30.0 / ans; //for meter from input return(ans); } float SensorSubsystem::GetDistRight(void) { float ans = 0; for(short i = 0 ; i < 10 ; i++){ ans += dist_right->GetVoltage(); } ans /= 10.0; ans = 30.0 / ans; //for meter from input return(ans); } int SensorSubsystem::GetXacceleration(void) { unsigned char array[2]; short x; acceleration->Write(0x20 , 0x7F);//These sentenses should be always done? acceleration->Write(0x23 , 0x08);// acceleration->Read(0x28 , 1 , &array[0]); acceleration->Read(0x29 , 1 , &array[1]); x = (array[1] << 8) | array[0]; std::cout << "x = " << x << std::endl; return(x); } int SensorSubsystem::GetYacceleration(void) { unsigned char array[2]; short y; acceleration->Write(0x20 , 0x7F); acceleration->Write(0x23 , 0x08); acceleration->Read(0x30 , 1 , &array[0]); acceleration->Read(0x31 , 1 , &array[1]); y = (array[1] << 8) | array[0]; std::cout << "y = " << y << std::endl; return(y); } int SensorSubsystem::GetZacceleration(void) { unsigned char array[2]; short z; acceleration->Write(0x20 , 0x7F); acceleration->Write(0x23 , 0x08); acceleration->Read(0x32 , 1 , &array[0]); acceleration->Read(0x33 , 1 , &array[1]); z = (array[1] << 8) | array[0]; std::cout << "z = " << z << std::endl; return(z); } //This function is used in loop to check degree. float SensorSubsystem::GetDegree(void) { float data = 0; float time; float speed; for(short i = 0 ; i < 10 ; i++){ data += gyro->GetVoltage(); } data /= 10.0; data -= base; if(-0.006 < data && data < 0.006) data = 0; speed = data / 0.0067; time = clock->Get() - beforetime; beforetime = clock->Get(); deg += (prespeed + speed) / 2.0 * time; prespeed = speed; std::cout << deg << std::endl; return(deg); } float SensorSubsystem::GetCompass(void) { unsigned char array[4]; short x , y; float X , Y; for(short i = 0 ; i < 4 ; i++){ compass->Read(0x03 + i , 1 , &array[i]); } x = (array[0] << 8) | array[1]; y = (array[2] << 8) | array[3]; if(x){ X = x; Y = y; return((atan(Y / X) / PI * 180) + 90 + ((x > 0) ? 0 : 180)); }else{ return((y > 0) ? 180 : 360); } } <|endoftext|>
<commit_before>// $Id: numeric_vector.C,v 1.19 2007-10-21 20:48:52 benkirk Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson // 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 // C++ includes #include <cmath> // for std::abs // Local Includes #include "numeric_vector.h" #include "laspack_vector.h" #include "petsc_vector.h" //------------------------------------------------------------------ // NumericVector methods // Full specialization for Real datatypes template <typename T> AutoPtr<NumericVector<T> > NumericVector<T>::build(const SolverPackage solver_package) { // Build the appropriate vector switch (solver_package) { #ifdef HAVE_LASPACK case LASPACK_SOLVERS: { AutoPtr<NumericVector<T> > ap(new LaspackVector<T>); return ap; } #endif #ifdef HAVE_PETSC case PETSC_SOLVERS: { AutoPtr<NumericVector<T> > ap(new PetscVector<T>); return ap; } #endif default: std::cerr << "ERROR: Unrecognized solver package: " << solver_package << std::endl; error(); } AutoPtr<NumericVector<T> > ap(NULL); return ap; } // Full specialization for float datatypes (DistributedVector wants this) template <> int NumericVector<float>::compare (const NumericVector<float> &other_vector, const Real threshold) const { assert (this->initialized()); assert (other_vector.initialized()); assert (this->first_local_index() == other_vector.first_local_index()); assert (this->last_local_index() == other_vector.last_local_index()); int rvalue = -1; unsigned int i = first_local_index(); do { if ( std::abs( (*this)(i) - other_vector(i) ) > threshold ) rvalue = i; else i++; } while (rvalue==-1 && i<last_local_index()); return rvalue; } // Full specialization for double datatypes template <> int NumericVector<double>::compare (const NumericVector<double> &other_vector, const Real threshold) const { assert (this->initialized()); assert (other_vector.initialized()); assert (this->first_local_index() == other_vector.first_local_index()); assert (this->last_local_index() == other_vector.last_local_index()); int rvalue = -1; unsigned int i = first_local_index(); do { if ( std::abs( (*this)(i) - other_vector(i) ) > threshold ) rvalue = i; else i++; } while (rvalue==-1 && i<last_local_index()); return rvalue; } #ifdef TRIPLE_PRECISION // Full specialization for long double datatypes template <> int NumericVector<long double>::compare (const NumericVector<long double> &other_vector, const Real threshold) const { assert (this->initialized()); assert (other_vector.initialized()); assert (this->first_local_index() == other_vector.first_local_index()); assert (this->last_local_index() == other_vector.last_local_index()); int rvalue = -1; unsigned int i = first_local_index(); do { if ( std::abs( (*this)(i) - other_vector(i) ) > threshold ) rvalue = i; else i++; } while (rvalue==-1 && i<last_local_index()); return rvalue; } #endif // Full specialization for Complex datatypes template <> int NumericVector<Complex>::compare (const NumericVector<Complex> &other_vector, const Real threshold) const { assert (this->initialized()); assert (other_vector.initialized()); assert (this->first_local_index() == other_vector.first_local_index()); assert (this->last_local_index() == other_vector.last_local_index()); int rvalue = -1; unsigned int i = first_local_index(); do { if (( std::abs( (*this)(i).real() - other_vector(i).real() ) > threshold ) || ( std::abs( (*this)(i).imag() - other_vector(i).imag() ) > threshold )) rvalue = i; else i++; } while (rvalue==-1 && i<this->last_local_index()); return rvalue; } //------------------------------------------------------------------ // Explicit instantiations template class NumericVector<Number>; <commit_msg>back-port for no laspack or petsc<commit_after>// $Id: numeric_vector.C,v 1.19 2007-10-21 20:48:52 benkirk Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson // 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 // C++ includes #include <cmath> // for std::abs // Local Includes #include "numeric_vector.h" #include "distributed_vector.h" #include "laspack_vector.h" #include "petsc_vector.h" //------------------------------------------------------------------ // NumericVector methods // Full specialization for Real datatypes template <typename T> AutoPtr<NumericVector<T> > NumericVector<T>::build(const SolverPackage solver_package) { // Build the appropriate vector switch (solver_package) { #ifdef HAVE_LASPACK case LASPACK_SOLVERS: { AutoPtr<NumericVector<T> > ap(new LaspackVector<T>); return ap; } #endif #ifdef HAVE_PETSC case PETSC_SOLVERS: { AutoPtr<NumericVector<T> > ap(new PetscVector<T>); return ap; } #endif default: AutoPtr<NumericVector<T> > ap(new DistributedVector<T>); return ap; } AutoPtr<NumericVector<T> > ap(NULL); return ap; } // Full specialization for float datatypes (DistributedVector wants this) template <> int NumericVector<float>::compare (const NumericVector<float> &other_vector, const Real threshold) const { assert (this->initialized()); assert (other_vector.initialized()); assert (this->first_local_index() == other_vector.first_local_index()); assert (this->last_local_index() == other_vector.last_local_index()); int rvalue = -1; unsigned int i = first_local_index(); do { if ( std::abs( (*this)(i) - other_vector(i) ) > threshold ) rvalue = i; else i++; } while (rvalue==-1 && i<last_local_index()); return rvalue; } // Full specialization for double datatypes template <> int NumericVector<double>::compare (const NumericVector<double> &other_vector, const Real threshold) const { assert (this->initialized()); assert (other_vector.initialized()); assert (this->first_local_index() == other_vector.first_local_index()); assert (this->last_local_index() == other_vector.last_local_index()); int rvalue = -1; unsigned int i = first_local_index(); do { if ( std::abs( (*this)(i) - other_vector(i) ) > threshold ) rvalue = i; else i++; } while (rvalue==-1 && i<last_local_index()); return rvalue; } #ifdef TRIPLE_PRECISION // Full specialization for long double datatypes template <> int NumericVector<long double>::compare (const NumericVector<long double> &other_vector, const Real threshold) const { assert (this->initialized()); assert (other_vector.initialized()); assert (this->first_local_index() == other_vector.first_local_index()); assert (this->last_local_index() == other_vector.last_local_index()); int rvalue = -1; unsigned int i = first_local_index(); do { if ( std::abs( (*this)(i) - other_vector(i) ) > threshold ) rvalue = i; else i++; } while (rvalue==-1 && i<last_local_index()); return rvalue; } #endif // Full specialization for Complex datatypes template <> int NumericVector<Complex>::compare (const NumericVector<Complex> &other_vector, const Real threshold) const { assert (this->initialized()); assert (other_vector.initialized()); assert (this->first_local_index() == other_vector.first_local_index()); assert (this->last_local_index() == other_vector.last_local_index()); int rvalue = -1; unsigned int i = first_local_index(); do { if (( std::abs( (*this)(i).real() - other_vector(i).real() ) > threshold ) || ( std::abs( (*this)(i).imag() - other_vector(i).imag() ) > threshold )) rvalue = i; else i++; } while (rvalue==-1 && i<this->last_local_index()); return rvalue; } //------------------------------------------------------------------ // Explicit instantiations template class NumericVector<Number>; <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include "unique_store.h" #include "datastore.hpp" #include <vespa/searchlib/btree/btree.hpp> #include <vespa/searchlib/btree/btreebuilder.hpp> #include <vespa/searchlib/btree/btreeroot.hpp> #include <vespa/searchlib/btree/btreenodeallocator.hpp> #include <vespa/searchlib/btree/btreeiterator.hpp> #include <vespa/searchlib/btree/btreenode.hpp> #include <vespa/searchlib/util/bufferwriter.h> #include "unique_store_builder.hpp" #include "unique_store_saver.hpp" #include <atomic> namespace search { namespace datastore { constexpr size_t NUMCLUSTERS_FOR_NEW_UNIQUESTORE_BUFFER = 1024u; template <typename EntryT, typename RefT> UniqueStore<EntryT, RefT>::UniqueStore() : _store(), _typeHandler(1, 2u, RefT::offsetSize(), NUMCLUSTERS_FOR_NEW_UNIQUESTORE_BUFFER), _typeId(0), _dict() { _typeId = _store.addType(&_typeHandler); assert(_typeId == 0u); _store.initActiveBuffers(); } template <typename EntryT, typename RefT> UniqueStore<EntryT, RefT>::~UniqueStore() { _store.clearHoldLists(); _store.dropBuffers(); } template <typename EntryT, typename RefT> typename UniqueStore<EntryT, RefT>::AddResult UniqueStore<EntryT, RefT>::add(const EntryType &value) { Compare comp(_store, value); auto itr = _dict.lowerBound(RefType(), comp); if (itr.valid() && !comp(EntryRef(), itr.getKey())) { uint32_t refCount = itr.getData(); assert(refCount != std::numeric_limits<uint32_t>::max()); itr.writeData(refCount + 1); RefType iRef(itr.getKey()); return AddResult(itr.getKey(), false); } else { EntryRef newRef = _store.template allocator<EntryType>(_typeId).alloc(value).ref; _dict.insert(itr, newRef, 1u); return AddResult(newRef, true); } } template <typename EntryT, typename RefT> EntryRef UniqueStore<EntryT, RefT>::find(const EntryType &value) { Compare comp(_store, value); auto itr = _dict.lowerBound(RefType(), comp); if (itr.valid() && !comp(EntryRef(), itr.getKey())) { return itr.getKey(); } else { return EntryRef(); } } template <typename EntryT, typename RefT> EntryRef UniqueStore<EntryT, RefT>::move(EntryRef ref) { return _store.template allocator<EntryType>(_typeId).alloc(get(ref)).ref; } template <typename T> T defaultValue() { return T(); } template <uint32_t> uint32_t defaultValue() { return 0u; } template <typename EntryT, typename RefT> void UniqueStore<EntryT, RefT>::remove(EntryRef ref) { assert(ref.valid()); EntryType unused(defaultValue<EntryType>()); Compare comp(_store, unused); auto itr = _dict.lowerBound(ref, comp); if (itr.valid() && itr.getKey() == ref) { uint32_t refCount = itr.getData(); if (refCount > 1) { itr.writeData(refCount - 1); } else { _dict.remove(itr); _store.holdElem(ref, 1); } } } namespace uniquestore { template <typename EntryT, typename RefT> class CompactionContext : public ICompactionContext { private: using UniqueStoreType = UniqueStore<EntryT, RefT>; using Dictionary = typename UniqueStoreType::Dictionary; DataStoreBase &_dataStore; Dictionary &_dict; UniqueStoreType &_store; std::vector<uint32_t> _bufferIdsToCompact; std::vector<std::vector<EntryRef>> _mapping; bool compactingBuffer(uint32_t bufferId) { return std::find(_bufferIdsToCompact.begin(), _bufferIdsToCompact.end(), bufferId) != _bufferIdsToCompact.end(); } void allocMapping() { _mapping.resize(RefT::numBuffers()); for (const auto bufferId : _bufferIdsToCompact) { BufferState &state = _dataStore.getBufferState(bufferId); _mapping[bufferId].resize(state.size()); } } void fillMapping() { auto itr = _dict.begin(); while (itr.valid()) { RefT iRef(itr.getKey()); assert(iRef.valid()); if (compactingBuffer(iRef.bufferId())) { assert(iRef.offset() < _mapping[iRef.bufferId()].size()); EntryRef &mappedRef = _mapping[iRef.bufferId()][iRef.offset()]; assert(!mappedRef.valid()); EntryRef newRef = _store.move(itr.getKey()); std::atomic_thread_fence(std::memory_order_release); mappedRef = newRef; itr.writeKey(newRef); } ++itr; } } public: CompactionContext(DataStoreBase &dataStore, Dictionary &dict, UniqueStoreType &store, std::vector<uint32_t> bufferIdsToCompact) : _dataStore(dataStore), _dict(dict), _store(store), _bufferIdsToCompact(std::move(bufferIdsToCompact)), _mapping() { } virtual ~CompactionContext() { _dataStore.finishCompact(_bufferIdsToCompact); } virtual void compact(vespalib::ArrayRef<EntryRef> refs) override { if (!_bufferIdsToCompact.empty()) { if (_mapping.empty()) { allocMapping(); fillMapping(); } for (auto &ref : refs) { if (ref.valid()) { RefT internalRef(ref); if (compactingBuffer(internalRef.bufferId())) { assert(internalRef.offset() < _mapping[internalRef.bufferId()].size()); EntryRef newRef = _mapping[internalRef.bufferId()][internalRef.offset()]; assert(newRef.valid()); ref = newRef; } } } } } }; } template <typename EntryT, typename RefT> ICompactionContext::UP UniqueStore<EntryT, RefT>::compactWorst() { std::vector<uint32_t> bufferIdsToCompact = _store.startCompactWorstBuffers(true, true); return std::make_unique<uniquestore::CompactionContext<EntryT, RefT>> (_store, _dict, *this, std::move(bufferIdsToCompact)); } template <typename EntryT, typename RefT> MemoryUsage UniqueStore<EntryT, RefT>::getMemoryUsage() const { MemoryUsage usage = _store.getMemoryUsage(); usage.merge(_dict.getMemoryUsage()); return usage; } template <typename EntryT, typename RefT> const BufferState & UniqueStore<EntryT, RefT>::bufferState(EntryRef ref) const { RefT internalRef(ref); return _store.getBufferState(internalRef.bufferId()); } template <typename EntryT, typename RefT> void UniqueStore<EntryT, RefT>::transferHoldLists(generation_t generation) { _dict.getAllocator().transferHoldLists(generation); _store.transferHoldLists(generation); } template <typename EntryT, typename RefT> void UniqueStore<EntryT, RefT>::trimHoldLists(generation_t firstUsed) { _dict.getAllocator().trimHoldLists(firstUsed); _store.trimHoldLists(firstUsed); } template <typename EntryT, typename RefT> void UniqueStore<EntryT, RefT>::freeze() { _dict.getAllocator().freeze(); } template <typename EntryT, typename RefT> typename UniqueStore<EntryT, RefT>::Builder UniqueStore<EntryT, RefT>::getBuilder(uint32_t uniqueValuesHint) { return Builder(_store, _typeId, _dict, uniqueValuesHint); } template <typename EntryT, typename RefT> typename UniqueStore<EntryT, RefT>::Saver UniqueStore<EntryT, RefT>::getSaver() const { return Saver(_dict, _store); } template <typename EntryT, typename RefT> uint32_t UniqueStore<EntryT, RefT>::getNumUniques() const { return _dict.getFrozenView().size(); } } } <commit_msg>Use fresh initialiser style covering both Objects and primitives.<commit_after>// Copyright 2017 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include "unique_store.h" #include "datastore.hpp" #include <vespa/searchlib/btree/btree.hpp> #include <vespa/searchlib/btree/btreebuilder.hpp> #include <vespa/searchlib/btree/btreeroot.hpp> #include <vespa/searchlib/btree/btreenodeallocator.hpp> #include <vespa/searchlib/btree/btreeiterator.hpp> #include <vespa/searchlib/btree/btreenode.hpp> #include <vespa/searchlib/util/bufferwriter.h> #include "unique_store_builder.hpp" #include "unique_store_saver.hpp" #include <atomic> namespace search { namespace datastore { constexpr size_t NUMCLUSTERS_FOR_NEW_UNIQUESTORE_BUFFER = 1024u; template <typename EntryT, typename RefT> UniqueStore<EntryT, RefT>::UniqueStore() : _store(), _typeHandler(1, 2u, RefT::offsetSize(), NUMCLUSTERS_FOR_NEW_UNIQUESTORE_BUFFER), _typeId(0), _dict() { _typeId = _store.addType(&_typeHandler); assert(_typeId == 0u); _store.initActiveBuffers(); } template <typename EntryT, typename RefT> UniqueStore<EntryT, RefT>::~UniqueStore() { _store.clearHoldLists(); _store.dropBuffers(); } template <typename EntryT, typename RefT> typename UniqueStore<EntryT, RefT>::AddResult UniqueStore<EntryT, RefT>::add(const EntryType &value) { Compare comp(_store, value); auto itr = _dict.lowerBound(RefType(), comp); if (itr.valid() && !comp(EntryRef(), itr.getKey())) { uint32_t refCount = itr.getData(); assert(refCount != std::numeric_limits<uint32_t>::max()); itr.writeData(refCount + 1); RefType iRef(itr.getKey()); return AddResult(itr.getKey(), false); } else { EntryRef newRef = _store.template allocator<EntryType>(_typeId).alloc(value).ref; _dict.insert(itr, newRef, 1u); return AddResult(newRef, true); } } template <typename EntryT, typename RefT> EntryRef UniqueStore<EntryT, RefT>::find(const EntryType &value) { Compare comp(_store, value); auto itr = _dict.lowerBound(RefType(), comp); if (itr.valid() && !comp(EntryRef(), itr.getKey())) { return itr.getKey(); } else { return EntryRef(); } } template <typename EntryT, typename RefT> void UniqueStore<EntryT, RefT>::remove(EntryRef ref) { assert(ref.valid()); EntryType unused {}; Compare comp(_store, unused); auto itr = _dict.lowerBound(ref, comp); if (itr.valid() && itr.getKey() == ref) { uint32_t refCount = itr.getData(); if (refCount > 1) { itr.writeData(refCount - 1); } else { _dict.remove(itr); _store.holdElem(ref, 1); } } } namespace uniquestore { template <typename EntryT, typename RefT> class CompactionContext : public ICompactionContext { private: using UniqueStoreType = UniqueStore<EntryT, RefT>; using Dictionary = typename UniqueStoreType::Dictionary; DataStoreBase &_dataStore; Dictionary &_dict; UniqueStoreType &_store; std::vector<uint32_t> _bufferIdsToCompact; std::vector<std::vector<EntryRef>> _mapping; bool compactingBuffer(uint32_t bufferId) { return std::find(_bufferIdsToCompact.begin(), _bufferIdsToCompact.end(), bufferId) != _bufferIdsToCompact.end(); } void allocMapping() { _mapping.resize(RefT::numBuffers()); for (const auto bufferId : _bufferIdsToCompact) { BufferState &state = _dataStore.getBufferState(bufferId); _mapping[bufferId].resize(state.size()); } } void fillMapping() { auto itr = _dict.begin(); while (itr.valid()) { RefT iRef(itr.getKey()); assert(iRef.valid()); if (compactingBuffer(iRef.bufferId())) { assert(iRef.offset() < _mapping[iRef.bufferId()].size()); EntryRef &mappedRef = _mapping[iRef.bufferId()][iRef.offset()]; assert(!mappedRef.valid()); EntryRef newRef = _store.move(itr.getKey()); std::atomic_thread_fence(std::memory_order_release); mappedRef = newRef; itr.writeKey(newRef); } ++itr; } } public: CompactionContext(DataStoreBase &dataStore, Dictionary &dict, UniqueStoreType &store, std::vector<uint32_t> bufferIdsToCompact) : _dataStore(dataStore), _dict(dict), _store(store), _bufferIdsToCompact(std::move(bufferIdsToCompact)), _mapping() { } virtual ~CompactionContext() { _dataStore.finishCompact(_bufferIdsToCompact); } virtual void compact(vespalib::ArrayRef<EntryRef> refs) override { if (!_bufferIdsToCompact.empty()) { if (_mapping.empty()) { allocMapping(); fillMapping(); } for (auto &ref : refs) { if (ref.valid()) { RefT internalRef(ref); if (compactingBuffer(internalRef.bufferId())) { assert(internalRef.offset() < _mapping[internalRef.bufferId()].size()); EntryRef newRef = _mapping[internalRef.bufferId()][internalRef.offset()]; assert(newRef.valid()); ref = newRef; } } } } } }; } template <typename EntryT, typename RefT> ICompactionContext::UP UniqueStore<EntryT, RefT>::compactWorst() { std::vector<uint32_t> bufferIdsToCompact = _store.startCompactWorstBuffers(true, true); return std::make_unique<uniquestore::CompactionContext<EntryT, RefT>> (_store, _dict, *this, std::move(bufferIdsToCompact)); } template <typename EntryT, typename RefT> MemoryUsage UniqueStore<EntryT, RefT>::getMemoryUsage() const { MemoryUsage usage = _store.getMemoryUsage(); usage.merge(_dict.getMemoryUsage()); return usage; } template <typename EntryT, typename RefT> const BufferState & UniqueStore<EntryT, RefT>::bufferState(EntryRef ref) const { RefT internalRef(ref); return _store.getBufferState(internalRef.bufferId()); } template <typename EntryT, typename RefT> void UniqueStore<EntryT, RefT>::transferHoldLists(generation_t generation) { _dict.getAllocator().transferHoldLists(generation); _store.transferHoldLists(generation); } template <typename EntryT, typename RefT> void UniqueStore<EntryT, RefT>::trimHoldLists(generation_t firstUsed) { _dict.getAllocator().trimHoldLists(firstUsed); _store.trimHoldLists(firstUsed); } template <typename EntryT, typename RefT> void UniqueStore<EntryT, RefT>::freeze() { _dict.getAllocator().freeze(); } template <typename EntryT, typename RefT> typename UniqueStore<EntryT, RefT>::Builder UniqueStore<EntryT, RefT>::getBuilder(uint32_t uniqueValuesHint) { return Builder(_store, _typeId, _dict, uniqueValuesHint); } template <typename EntryT, typename RefT> typename UniqueStore<EntryT, RefT>::Saver UniqueStore<EntryT, RefT>::getSaver() const { return Saver(_dict, _store); } template <typename EntryT, typename RefT> uint32_t UniqueStore<EntryT, RefT>::getNumUniques() const { return _dict.getFrozenView().size(); } } } <|endoftext|>
<commit_before>#include "struct_metal.h" #include <algorithm> #include <functional> #include <sstream> #include <string> #include <vector> #include "taichi/backends/metal/constants.h" #include "taichi/backends/metal/data_types.h" #include "taichi/backends/metal/features.h" #include "taichi/backends/metal/kernel_util.h" #include "taichi/math/arithmetic.h" #include "taichi/util/line_appender.h" TLANG_NAMESPACE_BEGIN namespace metal { namespace { namespace shaders { #define TI_INSIDE_METAL_CODEGEN #include "taichi/backends/metal/shaders/runtime_structs.metal.h" #include "taichi/backends/metal/shaders/runtime_utils.metal.h" #undef TI_INSIDE_METAL_CODEGEN #include "taichi/backends/metal/shaders/runtime_structs.metal.h" } // namespace shaders constexpr size_t kListManagerDataSize = sizeof(shaders::ListManagerData); constexpr size_t kSNodeMetaSize = sizeof(shaders::SNodeMeta); constexpr size_t kSNodeExtractorsSize = sizeof(shaders::SNodeExtractors); constexpr int kAlignment = 8; inline size_t bitmasks_stride(int n) { constexpr int kBitsPerByte = 8; const int bytes_needed = iroundup(n, kBitsPerByte) / kBitsPerByte; // The roundup is to align the stride to 8-bytes. return iroundup(bytes_needed, kAlignment); } inline int get_n(const SNode &sn) { // For root, sn.n is 0. return sn.type == SNodeType::root ? 1 : sn.n; } class StructCompiler { public: CompiledStructs run(SNode &root) { TI_ASSERT(root.type == SNodeType::root); collect_snodes(root); // The host side has run this! // infer_snode_properties(node); auto snodes_rev = snodes_; std::reverse(snodes_rev.begin(), snodes_rev.end()); { max_snodes_ = 0; has_sparse_snode_ = false; for (const auto &sn : snodes_) { const auto ty = sn->type; if (ty == SNodeType::root || ty == SNodeType::dense || ty == SNodeType::bitmasked || ty == SNodeType::dynamic) { max_snodes_ = std::max(max_snodes_, sn->id); } has_sparse_snode_ = has_sparse_snode_ || is_supported_sparse_type(ty); } ++max_snodes_; } CompiledStructs result; result.root_size = compute_snode_size(&root); emit_runtime_structs(); line_appender_.dump(&result.runtime_utils_source_code); result.runtime_size = compute_runtime_size(); for (auto &n : snodes_rev) { generate_types(*n); } line_appender_.dump(&result.snode_structs_source_code); result.need_snode_lists_data = has_sparse_snode_; result.max_snodes = max_snodes_; result.snode_descriptors = std::move(snode_descriptors_); TI_DEBUG("Metal: root_size={} runtime_size={}", result.root_size, result.runtime_size); return result; } private: void collect_snodes(SNode &snode) { snodes_.push_back(&snode); for (int ch_id = 0; ch_id < (int)snode.ch.size(); ch_id++) { auto &ch = snode.ch[ch_id]; collect_snodes(*ch); } } void emit_snode_stride(SNodeType ty, const std::string &ch_name, int n) { emit(" constant static constexpr int elem_stride = {}::stride;", ch_name); if (ty == SNodeType::bitmasked) { emit( " constant static constexpr int stride = elem_stride * n + " "/*bitmasked=*/{};", bitmasks_stride(n)); } else if (ty == SNodeType::dynamic) { emit( " constant static constexpr int stride = elem_stride * n + " "/*dynamic=*/{};", kAlignment); } else { // `root`, `dense` emit(" constant static constexpr int stride = elem_stride * n;"); } emit(""); } void emit_snode_constructor(const SNode &sn) { // TODO(k-ye): handle `pointer` const auto ty = sn.type; const auto &name = sn.node_type_name; if (ty == SNodeType::root) { emit(" {}(device byte *addr) {{", name); } else { emit( " {}(device byte *addr, device Runtime *rtm, device MemoryAllocator " "*ma) {{", name); } if (ty == SNodeType::bitmasked || ty == SNodeType::dynamic) { emit(" rep_.init(addr, /*meta_offset=*/elem_stride * n);"); } else { // `dense` or `root` emit(" rep_.init(addr);"); } emit(" }}\n"); } void emit_snode_get_child_func(SNodeType ty, const std::string &ch_name) { // TODO(k-ye): handle `pointer` emit(" {} children(int i) {{", ch_name); emit(" return {{rep_.addr() + (i * elem_stride)}};"); emit(" }}\n"); } void emit_snode_activation_funcs(SNodeType ty) { emit(" inline bool is_active(int i) {{"); emit(" return rep_.is_active(i);"); emit(" }}\n"); emit(" inline void activate(int i) {{"); emit(" rep_.activate(i);"); emit(" }}\n"); if (ty == SNodeType::dynamic) { emit(" inline void deactivate() {{"); emit(" rep_.deactivate();"); emit(" }}\n"); } else { emit(" inline void deactivate(int i) {{"); emit(" rep_.deactivate(i);"); emit(" }}\n"); } } void generate_types(const SNode &snode) { const bool is_place = snode.is_place(); if (!is_place) { // Generate {snode}_ch const std::string class_name = snode.node_type_name + "_ch"; emit("class {} {{", class_name); emit(" public:"); emit(" {}(device byte *a) : addr_(a) {{}}", class_name); std::string stride_str = "0"; for (int i = 0; i < (int)snode.ch.size(); i++) { const auto &ch_node_name = snode.ch[i]->node_type_name; emit(" {} get{}(device Runtime *rtm, device MemoryAllocator *ma) {{", ch_node_name, i); emit(" return {{addr_ + ({}), rtm, ma}};", stride_str); stride_str += " + " + ch_node_name + "::stride"; emit(" }}"); emit(""); } emit(" device byte *addr() {{ return addr_; }}"); emit(""); // Is it possible for this to have no children? emit(" constant static constexpr int stride = {};", stride_str); emit(" private:"); emit(" device byte *addr_;"); emit("}};"); } emit(""); const auto &node_name = snode.node_type_name; const auto snty = snode.type; if (is_place) { const auto dt_name = metal_data_type_name(snode.dt); emit("struct {} {{", node_name); emit(" // place"); emit(" constant static constexpr int stride = sizeof({});", dt_name); emit(""); // `place` constructor emit(" {}(device byte *v, device Runtime *, device MemoryAllocator *)", node_name); emit(" : val((device {}*)v) {{}}", dt_name); emit(""); emit(" device {}* val;", dt_name); emit("}};"); } else if (snty == SNodeType::dense || snty == SNodeType::root || snty == SNodeType::bitmasked || snty == SNodeType::dynamic) { const std::string ch_name = fmt::format("{}_ch", node_name); emit("struct {} {{", node_name); const auto snty_name = snode_type_name(snty); emit(" // {}", snty_name); const int n = get_n(snode); emit(" constant static constexpr int n = {};", n); emit_snode_stride(snty, ch_name, n); emit_snode_constructor(snode); emit_snode_get_child_func(snty, ch_name); emit_snode_activation_funcs(snty); if (snty == SNodeType::dynamic) { emit(" inline int append(int32_t data) {{"); emit(" return rep_.append(data);"); emit(" }}\n"); emit(" inline int length() {{"); emit(" return rep_.length();"); emit(" }}\n"); } emit(" private:"); emit(" SNodeRep_{} rep_;", snty_name); emit("}};"); } else { TI_ERROR( "SNodeType={} not supported on OpenGL\n" "Consider use ti.init(ti.cpu) or ti.init(ti.cuda) if you " "want to use sparse data structures", snode_type_name(snode.type)); } emit(""); } size_t compute_snode_size(const SNode *sn) { if (sn->is_place()) { return metal_data_type_bytes(to_metal_type(sn->dt)); } const int n = get_n(*sn); size_t ch_size = 0; for (const auto &ch : sn->ch) { const size_t ch_offset = ch_size; const auto *ch_sn = ch.get(); ch_size += compute_snode_size(ch_sn); if (!ch_sn->is_place()) { snode_descriptors_.find(ch_sn->id)->second.mem_offset_in_parent = ch_offset; } } SNodeDescriptor sn_desc; sn_desc.snode = sn; sn_desc.element_stride = ch_size; sn_desc.num_slots = n; sn_desc.stride = ch_size * n; if (sn->type == SNodeType::bitmasked) { sn_desc.stride += bitmasks_stride(n); } else if (sn->type == SNodeType::dynamic) { sn_desc.stride += kAlignment; } sn_desc.total_num_elems_from_root = 1; for (const auto &e : sn->extractors) { sn_desc.total_num_elems_from_root *= e.num_elements; } TI_ASSERT(snode_descriptors_.find(sn->id) == snode_descriptors_.end()); snode_descriptors_[sn->id] = sn_desc; return sn_desc.stride; } void emit_runtime_structs() { line_appender_.append_raw(shaders::kMetalRuntimeStructsSourceCode); emit(""); emit("struct Runtime {{"); emit(" SNodeMeta snode_metas[{}];", max_snodes_); emit(" SNodeExtractors snode_extractors[{}];", max_snodes_); emit(" ListManagerData snode_lists[{}];", max_snodes_); emit(" uint32_t rand_seeds[{}];", kNumRandSeeds); emit("}};"); line_appender_.append_raw(shaders::kMetalRuntimeUtilsSourceCode); emit(""); } size_t compute_runtime_size() { size_t result = (max_snodes_) * (kSNodeMetaSize + kSNodeExtractorsSize + kListManagerDataSize); result += sizeof(uint32_t) * kNumRandSeeds; return result; } template <typename... Args> void emit(std::string f, Args &&... args) { line_appender_.append(std::move(f), std::move(args)...); } std::vector<SNode *> snodes_; int max_snodes_; LineAppender line_appender_; std::unordered_map<int, SNodeDescriptor> snode_descriptors_; bool has_sparse_snode_; }; } // namespace int SNodeDescriptor::total_num_self_from_root( const std::unordered_map<int, SNodeDescriptor> &sn_descs) const { if (snode->type == SNodeType::root) { return 1; } const auto *psn = snode->parent; TI_ASSERT(psn != nullptr); return sn_descs.find(psn->id)->second.total_num_elems_from_root; } int total_num_self_from_root(const SNodeDescriptorsMap &m, int snode_id) { return m.at(snode_id).total_num_self_from_root(m); } CompiledStructs compile_structs(SNode &root) { return StructCompiler().run(root); } } // namespace metal TLANG_NAMESPACE_END <commit_msg>[metal] Fix error message (#1916)<commit_after>#include "struct_metal.h" #include <algorithm> #include <functional> #include <sstream> #include <string> #include <vector> #include "taichi/backends/metal/constants.h" #include "taichi/backends/metal/data_types.h" #include "taichi/backends/metal/features.h" #include "taichi/backends/metal/kernel_util.h" #include "taichi/math/arithmetic.h" #include "taichi/util/line_appender.h" TLANG_NAMESPACE_BEGIN namespace metal { namespace { namespace shaders { #define TI_INSIDE_METAL_CODEGEN #include "taichi/backends/metal/shaders/runtime_structs.metal.h" #include "taichi/backends/metal/shaders/runtime_utils.metal.h" #undef TI_INSIDE_METAL_CODEGEN #include "taichi/backends/metal/shaders/runtime_structs.metal.h" } // namespace shaders constexpr size_t kListManagerDataSize = sizeof(shaders::ListManagerData); constexpr size_t kSNodeMetaSize = sizeof(shaders::SNodeMeta); constexpr size_t kSNodeExtractorsSize = sizeof(shaders::SNodeExtractors); constexpr int kAlignment = 8; inline size_t bitmasks_stride(int n) { constexpr int kBitsPerByte = 8; const int bytes_needed = iroundup(n, kBitsPerByte) / kBitsPerByte; // The roundup is to align the stride to 8-bytes. return iroundup(bytes_needed, kAlignment); } inline int get_n(const SNode &sn) { // For root, sn.n is 0. return sn.type == SNodeType::root ? 1 : sn.n; } class StructCompiler { public: CompiledStructs run(SNode &root) { TI_ASSERT(root.type == SNodeType::root); collect_snodes(root); // The host side has run this! // infer_snode_properties(node); auto snodes_rev = snodes_; std::reverse(snodes_rev.begin(), snodes_rev.end()); { max_snodes_ = 0; has_sparse_snode_ = false; for (const auto &sn : snodes_) { const auto ty = sn->type; if (ty == SNodeType::root || ty == SNodeType::dense || ty == SNodeType::bitmasked || ty == SNodeType::dynamic) { max_snodes_ = std::max(max_snodes_, sn->id); } has_sparse_snode_ = has_sparse_snode_ || is_supported_sparse_type(ty); } ++max_snodes_; } CompiledStructs result; result.root_size = compute_snode_size(&root); emit_runtime_structs(); line_appender_.dump(&result.runtime_utils_source_code); result.runtime_size = compute_runtime_size(); for (auto &n : snodes_rev) { generate_types(*n); } line_appender_.dump(&result.snode_structs_source_code); result.need_snode_lists_data = has_sparse_snode_; result.max_snodes = max_snodes_; result.snode_descriptors = std::move(snode_descriptors_); TI_DEBUG("Metal: root_size={} runtime_size={}", result.root_size, result.runtime_size); return result; } private: void collect_snodes(SNode &snode) { snodes_.push_back(&snode); for (int ch_id = 0; ch_id < (int)snode.ch.size(); ch_id++) { auto &ch = snode.ch[ch_id]; collect_snodes(*ch); } } void emit_snode_stride(SNodeType ty, const std::string &ch_name, int n) { emit(" constant static constexpr int elem_stride = {}::stride;", ch_name); if (ty == SNodeType::bitmasked) { emit( " constant static constexpr int stride = elem_stride * n + " "/*bitmasked=*/{};", bitmasks_stride(n)); } else if (ty == SNodeType::dynamic) { emit( " constant static constexpr int stride = elem_stride * n + " "/*dynamic=*/{};", kAlignment); } else { // `root`, `dense` emit(" constant static constexpr int stride = elem_stride * n;"); } emit(""); } void emit_snode_constructor(const SNode &sn) { // TODO(k-ye): handle `pointer` const auto ty = sn.type; const auto &name = sn.node_type_name; if (ty == SNodeType::root) { emit(" {}(device byte *addr) {{", name); } else { emit( " {}(device byte *addr, device Runtime *rtm, device MemoryAllocator " "*ma) {{", name); } if (ty == SNodeType::bitmasked || ty == SNodeType::dynamic) { emit(" rep_.init(addr, /*meta_offset=*/elem_stride * n);"); } else { // `dense` or `root` emit(" rep_.init(addr);"); } emit(" }}\n"); } void emit_snode_get_child_func(SNodeType ty, const std::string &ch_name) { // TODO(k-ye): handle `pointer` emit(" {} children(int i) {{", ch_name); emit(" return {{rep_.addr() + (i * elem_stride)}};"); emit(" }}\n"); } void emit_snode_activation_funcs(SNodeType ty) { emit(" inline bool is_active(int i) {{"); emit(" return rep_.is_active(i);"); emit(" }}\n"); emit(" inline void activate(int i) {{"); emit(" rep_.activate(i);"); emit(" }}\n"); if (ty == SNodeType::dynamic) { emit(" inline void deactivate() {{"); emit(" rep_.deactivate();"); emit(" }}\n"); } else { emit(" inline void deactivate(int i) {{"); emit(" rep_.deactivate(i);"); emit(" }}\n"); } } void generate_types(const SNode &snode) { const bool is_place = snode.is_place(); if (!is_place) { // Generate {snode}_ch const std::string class_name = snode.node_type_name + "_ch"; emit("class {} {{", class_name); emit(" public:"); emit(" {}(device byte *a) : addr_(a) {{}}", class_name); std::string stride_str = "0"; for (int i = 0; i < (int)snode.ch.size(); i++) { const auto &ch_node_name = snode.ch[i]->node_type_name; emit(" {} get{}(device Runtime *rtm, device MemoryAllocator *ma) {{", ch_node_name, i); emit(" return {{addr_ + ({}), rtm, ma}};", stride_str); stride_str += " + " + ch_node_name + "::stride"; emit(" }}"); emit(""); } emit(" device byte *addr() {{ return addr_; }}"); emit(""); // Is it possible for this to have no children? emit(" constant static constexpr int stride = {};", stride_str); emit(" private:"); emit(" device byte *addr_;"); emit("}};"); } emit(""); const auto &node_name = snode.node_type_name; const auto snty = snode.type; if (is_place) { const auto dt_name = metal_data_type_name(snode.dt); emit("struct {} {{", node_name); emit(" // place"); emit(" constant static constexpr int stride = sizeof({});", dt_name); emit(""); // `place` constructor emit(" {}(device byte *v, device Runtime *, device MemoryAllocator *)", node_name); emit(" : val((device {}*)v) {{}}", dt_name); emit(""); emit(" device {}* val;", dt_name); emit("}};"); } else if (snty == SNodeType::dense || snty == SNodeType::root || snty == SNodeType::bitmasked || snty == SNodeType::dynamic) { const std::string ch_name = fmt::format("{}_ch", node_name); emit("struct {} {{", node_name); const auto snty_name = snode_type_name(snty); emit(" // {}", snty_name); const int n = get_n(snode); emit(" constant static constexpr int n = {};", n); emit_snode_stride(snty, ch_name, n); emit_snode_constructor(snode); emit_snode_get_child_func(snty, ch_name); emit_snode_activation_funcs(snty); if (snty == SNodeType::dynamic) { emit(" inline int append(int32_t data) {{"); emit(" return rep_.append(data);"); emit(" }}\n"); emit(" inline int length() {{"); emit(" return rep_.length();"); emit(" }}\n"); } emit(" private:"); emit(" SNodeRep_{} rep_;", snty_name); emit("}};"); } else { TI_ERROR( "SNodeType={} not supported on Metal.\nConsider using " "ti.init(ti.cpu) if you want to use sparse data structures.", snode_type_name(snode.type)); } emit(""); } size_t compute_snode_size(const SNode *sn) { if (sn->is_place()) { return metal_data_type_bytes(to_metal_type(sn->dt)); } const int n = get_n(*sn); size_t ch_size = 0; for (const auto &ch : sn->ch) { const size_t ch_offset = ch_size; const auto *ch_sn = ch.get(); ch_size += compute_snode_size(ch_sn); if (!ch_sn->is_place()) { snode_descriptors_.find(ch_sn->id)->second.mem_offset_in_parent = ch_offset; } } SNodeDescriptor sn_desc; sn_desc.snode = sn; sn_desc.element_stride = ch_size; sn_desc.num_slots = n; sn_desc.stride = ch_size * n; if (sn->type == SNodeType::bitmasked) { sn_desc.stride += bitmasks_stride(n); } else if (sn->type == SNodeType::dynamic) { sn_desc.stride += kAlignment; } sn_desc.total_num_elems_from_root = 1; for (const auto &e : sn->extractors) { sn_desc.total_num_elems_from_root *= e.num_elements; } TI_ASSERT(snode_descriptors_.find(sn->id) == snode_descriptors_.end()); snode_descriptors_[sn->id] = sn_desc; return sn_desc.stride; } void emit_runtime_structs() { line_appender_.append_raw(shaders::kMetalRuntimeStructsSourceCode); emit(""); emit("struct Runtime {{"); emit(" SNodeMeta snode_metas[{}];", max_snodes_); emit(" SNodeExtractors snode_extractors[{}];", max_snodes_); emit(" ListManagerData snode_lists[{}];", max_snodes_); emit(" uint32_t rand_seeds[{}];", kNumRandSeeds); emit("}};"); line_appender_.append_raw(shaders::kMetalRuntimeUtilsSourceCode); emit(""); } size_t compute_runtime_size() { size_t result = (max_snodes_) * (kSNodeMetaSize + kSNodeExtractorsSize + kListManagerDataSize); result += sizeof(uint32_t) * kNumRandSeeds; return result; } template <typename... Args> void emit(std::string f, Args &&... args) { line_appender_.append(std::move(f), std::move(args)...); } std::vector<SNode *> snodes_; int max_snodes_; LineAppender line_appender_; std::unordered_map<int, SNodeDescriptor> snode_descriptors_; bool has_sparse_snode_; }; } // namespace int SNodeDescriptor::total_num_self_from_root( const std::unordered_map<int, SNodeDescriptor> &sn_descs) const { if (snode->type == SNodeType::root) { return 1; } const auto *psn = snode->parent; TI_ASSERT(psn != nullptr); return sn_descs.find(psn->id)->second.total_num_elems_from_root; } int total_num_self_from_root(const SNodeDescriptorsMap &m, int snode_id) { return m.at(snode_id).total_num_self_from_root(m); } CompiledStructs compile_structs(SNode &root) { return StructCompiler().run(root); } } // namespace metal TLANG_NAMESPACE_END <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file ContractCallDataEncoder.cpp * @author Yann yann@ethdev.com * @date 2014 * Ethereum IDE client. */ #include <QDebug> #include <QMap> #include <QStringList> #include <libethcore/CommonJS.h> #include <libsolidity/AST.h> #include "QVariableDeclaration.h" #include "QVariableDefinition.h" #include "QFunctionDefinition.h" #include "ContractCallDataEncoder.h" using namespace dev; using namespace dev::solidity; using namespace dev::mix; bytes ContractCallDataEncoder::encodedData() { bytes r(m_encodedData); r.insert(r.end(), m_dynamicData.begin(), m_dynamicData.end()); return r; } void ContractCallDataEncoder::encode(QFunctionDefinition const* _function) { bytes hash = _function->hash().asBytes(); m_encodedData.insert(m_encodedData.end(), hash.begin(), hash.end()); } void ContractCallDataEncoder::encode(QVariant const& _data, SolidityType const& _type) { if (_type.dynamicSize) { u256 count = 0; if (_type.type == SolidityType::Type::Bytes) count = encodeSingleItem(_data, _type, m_dynamicData); else { QVariantList list = qvariant_cast<QVariantList>(_data); for (auto const& item: list) encodeSingleItem(item, _type, m_dynamicData); count = list.size(); } bytes sizeEnc(32); toBigEndian(count, sizeEnc); m_encodedData.insert(m_encodedData.end(), sizeEnc.begin(), sizeEnc.end()); } else encodeSingleItem(_data, _type, m_encodedData); } unsigned ContractCallDataEncoder::encodeSingleItem(QVariant const& _data, SolidityType const& _type, bytes& _dest) { if (_type.type == SolidityType::Type::Struct) BOOST_THROW_EXCEPTION(dev::Exception() << dev::errinfo_comment("Struct parameters are not supported yet")); unsigned const alignSize = 32; QString src = _data.toString(); bytes result; if ((src.startsWith("\"") && src.endsWith("\"")) || (src.startsWith("\'") && src.endsWith("\'"))) src = src.remove(src.length() - 1, 1).remove(0, 1); QRegExp rx("[a-z]+"); if (src.startsWith("0x")) { result = fromHex(src.toStdString().substr(2)); if (_type.type != SolidityType::Type::Bytes) result = padded(result, alignSize); } else if (rx.indexIn(src.toLower(), 0) != -1) { QByteArray bytesAr = src.toLocal8Bit(); result = bytes(bytesAr.begin(), bytesAr.end()); result = paddedRight(result, alignSize); } else { bigint i(src.toStdString()); result = bytes(alignSize); toBigEndian((u256)i, result); } unsigned dataSize = _type.dynamicSize ? result.size() : alignSize; _dest.insert(_dest.end(), result.begin(), result.end()); if ((_dest.size() - 4) % alignSize != 0) _dest.resize((_dest.size() & ~(alignSize - 1)) + alignSize); return dataSize; } void ContractCallDataEncoder::push(bytes const& _b) { m_encodedData.insert(m_encodedData.end(), _b.begin(), _b.end()); } bigint ContractCallDataEncoder::decodeInt(dev::bytes const& _rawValue) { dev::u256 un = dev::fromBigEndian<dev::u256>(_rawValue); if (un >> 255) return (-s256(~un + 1)); return un; } QString ContractCallDataEncoder::toString(dev::bigint const& _int) { std::stringstream str; str << std::dec << _int; return QString::fromStdString(str.str()); } dev::bytes ContractCallDataEncoder::encodeBool(QString const& _str) { bytes b(1); b[0] = _str == "1" || _str.toLower() == "true " ? 1 : 0; return padded(b, 32); } bool ContractCallDataEncoder::decodeBool(dev::bytes const& _rawValue) { byte ret = _rawValue.at(_rawValue.size() - 1); return (ret != 0); } QString ContractCallDataEncoder::toString(bool _b) { return _b ? "true" : "false"; } dev::bytes ContractCallDataEncoder::encodeBytes(QString const& _str) { QByteArray bytesAr = _str.toLocal8Bit(); bytes r = bytes(bytesAr.begin(), bytesAr.end()); return padded(r, 32); } dev::bytes ContractCallDataEncoder::decodeBytes(dev::bytes const& _rawValue) { return _rawValue; } QString ContractCallDataEncoder::toString(dev::bytes const& _b) { QString str; if (isString(_b, str)) return "- " + str + " - " + QString::fromStdString(dev::toJS(_b)); else return QString::fromStdString(dev::toJS(_b)); } QVariant ContractCallDataEncoder::decode(SolidityType const& _type, bytes const& _value) { bytesConstRef value(&_value); bytes rawParam(32); value.populate(&rawParam); QSolidityType::Type type = _type.type; if (type == QSolidityType::Type::SignedInteger || type == QSolidityType::Type::UnsignedInteger || type == QSolidityType::Type::Address) return QVariant::fromValue(toString(decodeInt(rawParam))); else if (type == QSolidityType::Type::Bool) return QVariant::fromValue(toString(decodeBool(rawParam))); else if (type == QSolidityType::Type::Bytes || type == QSolidityType::Type::Hash) return QVariant::fromValue(toString(decodeBytes(rawParam))); else if (type == QSolidityType::Type::Struct) return QVariant::fromValue(QString("struct")); //TODO else BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Parameter declaration not found")); } QStringList ContractCallDataEncoder::decode(QList<QVariableDeclaration*> const& _returnParameters, bytes _value) { bytesConstRef value(&_value); bytes rawParam(32); QStringList r; for (int k = 0; k <_returnParameters.length(); k++) { value.populate(&rawParam); value = value.cropped(32); QVariableDeclaration* dec = static_cast<QVariableDeclaration*>(_returnParameters.at(k)); SolidityType const& type = dec->type()->type(); r.append(decode(type, rawParam).toString()); } return r; } bool ContractCallDataEncoder::isString(dev::bytes const& _b, QString& _str) { dev::bytes bunPad = unpadded(_b); for (unsigned i = 0; i < bunPad.size(); i++) { u256 value(bunPad.at(i)); if (value > 127) return false; else _str += QString::fromStdString(dev::toJS(bunPad.at(i))).replace("0x", ""); } return true; } <commit_msg>changes on encode input parameters.<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file ContractCallDataEncoder.cpp * @author Yann yann@ethdev.com * @date 2014 * Ethereum IDE client. */ #include <QDebug> #include <QMap> #include <QStringList> #include <libethcore/CommonJS.h> #include <libsolidity/AST.h> #include "QVariableDeclaration.h" #include "QVariableDefinition.h" #include "QFunctionDefinition.h" #include "ContractCallDataEncoder.h" using namespace dev; using namespace dev::solidity; using namespace dev::mix; bytes ContractCallDataEncoder::encodedData() { bytes r(m_encodedData); r.insert(r.end(), m_dynamicData.begin(), m_dynamicData.end()); return r; } void ContractCallDataEncoder::encode(QFunctionDefinition const* _function) { bytes hash = _function->hash().asBytes(); m_encodedData.insert(m_encodedData.end(), hash.begin(), hash.end()); } void ContractCallDataEncoder::encode(QVariant const& _data, SolidityType const& _type) { if (_type.dynamicSize) { u256 count = 0; if (_type.type == SolidityType::Type::Bytes) count = encodeSingleItem(_data, _type, m_dynamicData); else { QVariantList list = qvariant_cast<QVariantList>(_data); for (auto const& item: list) encodeSingleItem(item, _type, m_dynamicData); count = list.size(); } bytes sizeEnc(32); toBigEndian(count, sizeEnc); m_encodedData.insert(m_encodedData.end(), sizeEnc.begin(), sizeEnc.end()); } else encodeSingleItem(_data, _type, m_encodedData); } unsigned ContractCallDataEncoder::encodeSingleItem(QVariant const& _data, SolidityType const& _type, bytes& _dest) { if (_type.type == SolidityType::Type::Struct) BOOST_THROW_EXCEPTION(dev::Exception() << dev::errinfo_comment("Struct parameters are not supported yet")); unsigned const alignSize = 32; QString src = _data.toString(); bytes result; if ((src.startsWith("\"") && src.endsWith("\"")) || (src.startsWith("\'") && src.endsWith("\'"))) src = src.remove(src.length() - 1, 1).remove(0, 1); if (src.startsWith("0x")) { result = fromHex(src.toStdString().substr(2)); if (_type.type != SolidityType::Type::Bytes) result = padded(result, alignSize); } else { try { bigint i(src.toStdString()); result = bytes(alignSize); toBigEndian((u256)i, result); } catch (std::exception const& ex) { // manage input as a string. QByteArray bytesAr = src.toLocal8Bit(); result = bytes(bytesAr.begin(), bytesAr.end()); result = paddedRight(result, alignSize); } } unsigned dataSize = _type.dynamicSize ? result.size() : alignSize; _dest.insert(_dest.end(), result.begin(), result.end()); if ((_dest.size() - 4) % alignSize != 0) _dest.resize((_dest.size() & ~(alignSize - 1)) + alignSize); return dataSize; } void ContractCallDataEncoder::push(bytes const& _b) { m_encodedData.insert(m_encodedData.end(), _b.begin(), _b.end()); } bigint ContractCallDataEncoder::decodeInt(dev::bytes const& _rawValue) { dev::u256 un = dev::fromBigEndian<dev::u256>(_rawValue); if (un >> 255) return (-s256(~un + 1)); return un; } QString ContractCallDataEncoder::toString(dev::bigint const& _int) { std::stringstream str; str << std::dec << _int; return QString::fromStdString(str.str()); } dev::bytes ContractCallDataEncoder::encodeBool(QString const& _str) { bytes b(1); b[0] = _str == "1" || _str.toLower() == "true " ? 1 : 0; return padded(b, 32); } bool ContractCallDataEncoder::decodeBool(dev::bytes const& _rawValue) { byte ret = _rawValue.at(_rawValue.size() - 1); return (ret != 0); } QString ContractCallDataEncoder::toString(bool _b) { return _b ? "true" : "false"; } dev::bytes ContractCallDataEncoder::encodeBytes(QString const& _str) { QByteArray bytesAr = _str.toLocal8Bit(); bytes r = bytes(bytesAr.begin(), bytesAr.end()); return padded(r, 32); } dev::bytes ContractCallDataEncoder::decodeBytes(dev::bytes const& _rawValue) { return _rawValue; } QString ContractCallDataEncoder::toString(dev::bytes const& _b) { QString str; if (isString(_b, str)) return "\"" + str + "\" " + QString::fromStdString(dev::toJS(_b)); else return QString::fromStdString(dev::toJS(_b)); } QVariant ContractCallDataEncoder::decode(SolidityType const& _type, bytes const& _value) { bytesConstRef value(&_value); bytes rawParam(32); value.populate(&rawParam); QSolidityType::Type type = _type.type; if (type == QSolidityType::Type::SignedInteger || type == QSolidityType::Type::UnsignedInteger || type == QSolidityType::Type::Address) return QVariant::fromValue(toString(decodeInt(rawParam))); else if (type == QSolidityType::Type::Bool) return QVariant::fromValue(toString(decodeBool(rawParam))); else if (type == QSolidityType::Type::Bytes || type == QSolidityType::Type::Hash) return QVariant::fromValue(toString(decodeBytes(rawParam))); else if (type == QSolidityType::Type::Struct) return QVariant::fromValue(QString("struct")); //TODO else BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Parameter declaration not found")); } QStringList ContractCallDataEncoder::decode(QList<QVariableDeclaration*> const& _returnParameters, bytes _value) { bytesConstRef value(&_value); bytes rawParam(32); QStringList r; for (int k = 0; k <_returnParameters.length(); k++) { value.populate(&rawParam); value = value.cropped(32); QVariableDeclaration* dec = static_cast<QVariableDeclaration*>(_returnParameters.at(k)); SolidityType const& type = dec->type()->type(); r.append(decode(type, rawParam).toString()); } return r; } bool ContractCallDataEncoder::isString(dev::bytes const& _b, QString& _str) { dev::bytes bunPad = unpadded(_b); for (unsigned i = 0; i < bunPad.size(); i++) { if (bunPad.at(i) < 9 || bunPad.at(i) > 127) return false; else _str += QString::fromStdString(dev::toJS(bunPad.at(i))).replace("0x", ""); } return true; } <|endoftext|>
<commit_before>/************************************************************************************ ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file g_fileinputstream.cpp * @version * @brief * @author ylh * @date 2014-07-11 * @note * * 1. 2014-07-11 ylh Created this file * */ #include <g_fileinputstream.h> #include <g_private_define.h> using namespace std; using namespace GCommon; FileInputStream::FileInputStream(shared_ptr<GFile> file) : m_file(file) { if (m_file == NULL) { throw invalid_argument(EXCEPTION_DESCRIPTION("invalid_argument")); } } FileInputStream::FileInputStream(const string filepath) : m_file((shared_ptr<GFile>(new GFile(filepath.c_str())))) { if (m_file->open(G_OPEN_READ) == G_NO) { throw ios_base::failure(EXCEPTION_DESCRIPTION("ios_base::failure")); } } FileInputStream::~FileInputStream() { } GInt32 FileInputStream::available() throw(std::ios_base::failure) { // TODO: GFile return 0; } void FileInputStream::close() throw(std::ios_base::failure) { // m_file->close(); // do nothing } GInt32 FileInputStream::read() throw(std::ios_base::failure, std::logic_error) { GInt8 pBuffer[1] = {0}; return this->read(pBuffer, 1); } GInt32 FileInputStream::read(GInt8 * pBuffer, GInt32 iBufferLen, GInt32 iOffset, GInt32 iLen) throw(std::ios_base::failure, std::logic_error) { if (!pBuffer) { throw invalid_argument(EXCEPTION_DESCRIPTION("invalid_argument")); } else if (iOffset < 0 || iLen < 0 ||iBufferLen < iOffset + iLen) { throw out_of_range(EXCEPTION_DESCRIPTION("out_of_range")); } else if (iLen == 0) { return 0; } return m_file->read(pBuffer + iOffset, iLen); } GInt64 FileInputStream::skip(GInt64 lNum) throw(std::ios_base::failure) { if (lNum == 0) { return 0; } if (lNum < 0) { throw out_of_range(""); } // TODO: GFile if (m_file->seek(lNum, G_SEEK_CUR)) { throw ios_base::failure(EXCEPTION_DESCRIPTION("ios_base::failure")); } return 0; } shared_ptr<GFile> FileInputStream::GetFile() { return m_file; } <commit_msg>Update g_fileinputstream.cpp<commit_after>/************************************************************************************ ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file g_fileinputstream.cpp * @version * @brief * @author ylh * @date 2014-07-11 * @note * * 1. 2014-07-11 ylh Created this file * */ #include <g_fileinputstream.h> #include <g_private_define.h> using namespace std; using namespace GCommon; FileInputStream::FileInputStream(shared_ptr<GFile> file) : m_file(file) { if (m_file == NULL) { throw invalid_argument(EXCEPTION_DESCRIPTION("invalid_argument")); } } FileInputStream::FileInputStream(const string filepath) : m_file((shared_ptr<GFile>(new GFile(filepath.c_str())))) { if (m_file->open(G_OPEN_READ) == G_NO) { throw ios_base::failure(EXCEPTION_DESCRIPTION("ios_base::failure")); } } FileInputStream::~FileInputStream() { } GInt32 FileInputStream::available() throw(std::ios_base::failure) { // TODO: GFile return 0; } void FileInputStream::close() throw(std::ios_base::failure) { // m_file->close(); // do nothing } GInt32 FileInputStream::read() throw(std::ios_base::failure, std::logic_error) { GInt8 pBuffer[1] = {0}; return this->read(pBuffer, 1); } GInt32 FileInputStream::read(GInt8 * pBuffer, GInt32 iBufferLen, GInt32 iOffset, GInt32 iLen) throw(std::ios_base::failure, std::logic_error) { if (!pBuffer) { throw invalid_argument(EXCEPTION_DESCRIPTION("invalid_argument")); } else if (iOffset < 0 || iLen < 0 ||iBufferLen < iOffset + iLen) { throw out_of_range(EXCEPTION_DESCRIPTION("out_of_range")); } else if (iLen == 0) { return 0; } GInt32 ret = m_file->read(pBuffer + iOffset, iLen); if (ret < 0) { throw ios_base::failure(EXCEPTION_DESCRIPTION("ios_base::failure")); } if (ret == 0) { ret = -1; } return ret; } GInt64 FileInputStream::skip(GInt64 lNum) throw(std::ios_base::failure) { if (lNum == 0) { return 0; } if (lNum < 0) { throw out_of_range(""); } // TODO: GFile if (m_file->seek(lNum, G_SEEK_CUR)) { throw ios_base::failure(EXCEPTION_DESCRIPTION("ios_base::failure")); } return 0; } shared_ptr<GFile> FileInputStream::GetFile() { return m_file; } <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "MortarSegmentHelper.h" #include <vector> MortarSegmentHelper::MortarSegmentHelper(const Elem * secondary_elem_ptr, Point & center, Point & normal) : _secondary_elem_ptr(secondary_elem_ptr), _center(center), _normal(normal), _debug(false) { _secondary_poly.clear(); _secondary_poly.reserve(secondary_elem_ptr->n_vertices()); // Get orientation of secondary poly Point e1 = _secondary_elem_ptr->point(0) - _secondary_elem_ptr->point(1); Point e2 = _secondary_elem_ptr->point(2) - _secondary_elem_ptr->point(1); Real orient = e2.cross(e1) * _normal; // u and v define the tangent plane of the element (at center) // Note we embed orientation into our transformation to make 2D poly always // positively oriented _u = _normal.cross(_secondary_elem_ptr->point(0) - center).unit(); _v = (orient > 0) ? _normal.cross(_u).unit() : _u.cross(_normal).unit(); // Transform problem to 2D plane spanned by u and v for (auto n : make_range(_secondary_elem_ptr->n_vertices())) { Point pt = _secondary_elem_ptr->point(n) - _center; _secondary_poly.emplace_back(pt * _u, pt * _v, 0); } // Initialize area of secondary polygon _remaining_area_fraction = 1.0; _secondary_area = polyArea(_secondary_poly); _scaled_tol = _tolerance * _secondary_area; } Point MortarSegmentHelper::getIntersection(Point & p1, Point & p2, Point & q1, Point & q2, Real & s) { Point dp = p2 - p1; Point dq = q2 - q1; Real cp1q1 = p1(0) * q1(1) - p1(1) * q1(0); Real cp1q2 = p1(0) * q2(1) - p1(1) * q2(0); Real cp1p2 = p1(0) * p2(1) - p1(1) * p2(0); Real cq1q2 = q1(0) * q2(1) - q1(1) * q2(0); Real alpha = 1. / (dp(0) * dq(1) - dp(1) * dq(0)); s = -alpha * (cp1q2 - cp1q1 - cq1q2); if (alpha > 1e12) mooseWarning("MortarSegmentHelper intersection calculation is poorly conditioned"); return alpha * (cq1q2 * dp - cp1p2 * dq); } bool MortarSegmentHelper::isInsideSecondary(Point & pt) { for (auto i : make_range(_secondary_poly.size())) { Point & q1 = _secondary_poly[(i - 1) % _secondary_poly.size()]; Point & q2 = _secondary_poly[i]; Point e1 = q2 - q1; Point e2 = pt - q1; // If point corresponds to one of the secondary vertices, skip if (e2.norm() < _tolerance) return true; bool inside = (e1(0) * e2(1) - e1(1) * e2(0)) < _scaled_tol; if (!inside) return false; } return true; } bool MortarSegmentHelper::isDisjoint(std::vector<Point> & poly) { for (auto i : make_range(poly.size())) { // Get edge to check const Point edg = poly[(i + 1) % poly.size()] - poly[i]; const Real cp = poly[(i + 1) % poly.size()](0) * poly[i](1) - poly[(i + 1) % poly.size()](1) * poly[i](0); // If more optimization needed, could store these values for later // Check if point is to the left of (or on) clip_edge auto is_inside = [&edg, cp](Point & pt, Real tol) { return pt(0) * edg(1) - pt(1) * edg(0) + cp < -tol; }; bool all_outside = true; for (auto pt : _secondary_poly) { if(is_inside(pt, _scaled_tol)) all_outside = false; } if (all_outside) return true; } return false; } void MortarSegmentHelper::clipPoly(const Elem * primary_elem_ptr, std::vector<Point> & clipped_poly) { // Check orientation of primary_poly Point e1 = primary_elem_ptr->point(0) - primary_elem_ptr->point(1); Point e2 = primary_elem_ptr->point(2) - primary_elem_ptr->point(1); Real orient = e2.cross(e1) * _u.cross(_v); // Get primary_poly (primary is clipping poly). If negatively oriented, reverse std::vector<Point> primary_poly; const int n_verts = primary_elem_ptr->n_vertices(); for (auto n : make_range(n_verts)) { Point pt = (orient > 0) ? primary_elem_ptr->point(n) - _center : primary_elem_ptr->point(n_verts - 1 - n) - _center; primary_poly.emplace_back(pt * _u, pt * _v, 0.); } if (isDisjoint(primary_poly)) return; // Initialize clipped poly with secondary poly (secondary is target poly) clipped_poly = _secondary_poly; // Loop through clipping edges for (auto i : make_range(primary_poly.size())) { if (clipped_poly.size() < 3) { clipped_poly.clear(); } // Set input poly to current clipped poly std::vector<Point> input_poly(clipped_poly); clipped_poly.clear(); // If clipped poly trivial, return if (input_poly.size() < 3) return; // Get clipping edge Point & clip_pt1 = primary_poly[i]; Point & clip_pt2 = primary_poly[(i + 1) % primary_poly.size()]; const Point edg = clip_pt2 - clip_pt1; const Real cp = clip_pt2(0) * clip_pt1(1) - clip_pt2(1) * clip_pt1(0); // Check if point is to the left of (or on) clip_edge /* * Note that use of tolerance here is to avoid degenerate case when lines are * essentially on top of each other (common when meshes match across interface) * since finding intersection is ill-conditioned in this case. Dividing by * secondary_area is to non-dimensionalize before tolerancing */ auto is_inside = [&edg, cp](Point & pt, Real tol) { return pt(0) * edg(1) - pt(1) * edg(0) + cp < tol; }; // Loop through edges of target polygon (with previous clippings already included) for (auto j : make_range(input_poly.size())) { // Get target edge Point & curr_pt = input_poly[(j + 1) % input_poly.size()]; Point & prev_pt = input_poly[j]; // TODO: Don't need to calculate both each loop bool is_current_inside = is_inside(curr_pt, _scaled_tol); bool is_previous_inside = is_inside(prev_pt, _scaled_tol); if (is_current_inside) { if (!is_previous_inside) { Real s; Point intersect = getIntersection(prev_pt, curr_pt, clip_pt1, clip_pt2, s); /* * s is the fraction of distance along clip poly edge that intersection lies * It is used here to avoid degenerate polygon cases. For example, consider a * case like: * o * | (inside) * ------|------ * | (outside) * when the distance is small (< 1e-7) we don't want to to add both the point * and intersection. Also note that when distance on the scale of 1e-7, * area on scale of 1e-14 so is insignificant if this results in dropping * a tri (for example if next edge crosses again) */ if (s < (1 - _tolerance)) clipped_poly.push_back(intersect); } clipped_poly.push_back(curr_pt); } else if (is_previous_inside) { Real s; Point intersect = getIntersection(prev_pt, curr_pt, clip_pt1, clip_pt2, s); if (s > _tolerance) clipped_poly.push_back(intersect); } } } } void MortarSegmentHelper::plotPoly(std::vector<Point> & poly) { if (poly.size() < 2) return; std::cout << "plt.plot(["; for (auto pt : poly) std::cout << pt(0) << ", "; std::cout << poly[0](0) << "], ["; for (auto pt : poly) std::cout << pt(1) << ", "; std::cout << poly[0](1) << "])" << std::endl; } void MortarSegmentHelper::plotTriangulation(std::vector<Point> & nodes, std::vector<std::array<int, 3>> & elem_to_nodes) { for (auto el : elem_to_nodes) { std::vector<Point> poly; poly.push_back(nodes[el[0]]); poly.push_back(nodes[el[1]]); poly.push_back(nodes[el[2]]); plotPoly(poly); } } void MortarSegmentHelper::triangulatePoly(std::vector<Point> & nodes, std::vector<std::array<int, 3>> & tri_map) { // Initialize output map tri_map.clear(); // If fewer than 3 nodes, error if (nodes.size() < 3) { mooseError("Can't triangulate poly with fewer than 3 nodes"); } // If three nodes, already a triangle, simply pass back map else if (nodes.size() == 3) { tri_map.push_back({{0,1,2}}); return; } // Otherwise add center point node and make simple triangulation else { Point poly_center; int n_verts = nodes.size(); // Get geometric center of polygon for (auto node : nodes) poly_center += node; poly_center /= n_verts; // Add triangles formed by outer edge and center point for (auto i : make_range(n_verts)) tri_map.push_back({{i, (i + 1) % n_verts, n_verts}}); // Add center point to end nodes nodes.push_back(poly_center); return; } } void MortarSegmentHelper::getMortarSegments(const Elem * primary_elem_ptr, std::vector<Point> & nodes, std::vector<std::array<int, 3>> & elem_to_nodes) { nodes.clear(); // Clip primary elem against secondary elem std::vector<Point> clipped_poly; clipPoly(primary_elem_ptr, clipped_poly); if (clipped_poly.size() < 3) { elem_to_nodes.clear(); return; } if(_debug) { for(auto pt : clipped_poly) { if (!isInsideSecondary(pt)) mooseError("Clipped polygon not inside linearized secondary element"); } } // Compute area of clipped polygon, update remaining area fraction _remaining_area_fraction -= polyArea(clipped_poly) / _secondary_area; // Triangulate clip polygon triangulatePoly(clipped_poly, elem_to_nodes); // Transform clipped poly back to (linearized) 3d and output nodes nodes.reserve(clipped_poly.size()); for (auto pt : clipped_poly) nodes.emplace_back((pt(0) * _u) + (pt(1) * _v) + _center); } Real MortarSegmentHelper::polyArea(std::vector<Point> & nodes) { Real poly_area = 0; for (auto i : make_range(nodes.size())) poly_area += nodes[i](0) * nodes[(i + 1) % nodes.size()](1) - nodes[i](1) * nodes[(i + 1) % nodes.size()](0); poly_area *= 0.5; return poly_area; } <commit_msg>Remove banned words<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "MortarSegmentHelper.h" #include <vector> MortarSegmentHelper::MortarSegmentHelper(const Elem * secondary_elem_ptr, Point & center, Point & normal) : _secondary_elem_ptr(secondary_elem_ptr), _center(center), _normal(normal), _debug(false) { _secondary_poly.clear(); _secondary_poly.reserve(secondary_elem_ptr->n_vertices()); // Get orientation of secondary poly Point e1 = _secondary_elem_ptr->point(0) - _secondary_elem_ptr->point(1); Point e2 = _secondary_elem_ptr->point(2) - _secondary_elem_ptr->point(1); Real orient = e2.cross(e1) * _normal; // u and v define the tangent plane of the element (at center) // Note we embed orientation into our transformation to make 2D poly always // positively oriented _u = _normal.cross(_secondary_elem_ptr->point(0) - center).unit(); _v = (orient > 0) ? _normal.cross(_u).unit() : _u.cross(_normal).unit(); // Transform problem to 2D plane spanned by u and v for (auto n : make_range(_secondary_elem_ptr->n_vertices())) { Point pt = _secondary_elem_ptr->point(n) - _center; _secondary_poly.emplace_back(pt * _u, pt * _v, 0); } // Initialize area of secondary polygon _remaining_area_fraction = 1.0; _secondary_area = polyArea(_secondary_poly); _scaled_tol = _tolerance * _secondary_area; } Point MortarSegmentHelper::getIntersection(Point & p1, Point & p2, Point & q1, Point & q2, Real & s) { Point dp = p2 - p1; Point dq = q2 - q1; Real cp1q1 = p1(0) * q1(1) - p1(1) * q1(0); Real cp1q2 = p1(0) * q2(1) - p1(1) * q2(0); Real cp1p2 = p1(0) * p2(1) - p1(1) * p2(0); Real cq1q2 = q1(0) * q2(1) - q1(1) * q2(0); Real alpha = 1. / (dp(0) * dq(1) - dp(1) * dq(0)); s = -alpha * (cp1q2 - cp1q1 - cq1q2); if (alpha > 1e12) mooseWarning("MortarSegmentHelper intersection calculation is poorly conditioned"); return alpha * (cq1q2 * dp - cp1p2 * dq); } bool MortarSegmentHelper::isInsideSecondary(Point & pt) { for (auto i : make_range(_secondary_poly.size())) { Point & q1 = _secondary_poly[(i - 1) % _secondary_poly.size()]; Point & q2 = _secondary_poly[i]; Point e1 = q2 - q1; Point e2 = pt - q1; // If point corresponds to one of the secondary vertices, skip if (e2.norm() < _tolerance) return true; bool inside = (e1(0) * e2(1) - e1(1) * e2(0)) < _scaled_tol; if (!inside) return false; } return true; } bool MortarSegmentHelper::isDisjoint(std::vector<Point> & poly) { for (auto i : make_range(poly.size())) { // Get edge to check const Point edg = poly[(i + 1) % poly.size()] - poly[i]; const Real cp = poly[(i + 1) % poly.size()](0) * poly[i](1) - poly[(i + 1) % poly.size()](1) * poly[i](0); // If more optimization needed, could store these values for later // Check if point is to the left of (or on) clip_edge auto is_inside = [&edg, cp](Point & pt, Real tol) { return pt(0) * edg(1) - pt(1) * edg(0) + cp < -tol; }; bool all_outside = true; for (auto pt : _secondary_poly) { if(is_inside(pt, _scaled_tol)) all_outside = false; } if (all_outside) return true; } return false; } void MortarSegmentHelper::clipPoly(const Elem * primary_elem_ptr, std::vector<Point> & clipped_poly) { // Check orientation of primary_poly Point e1 = primary_elem_ptr->point(0) - primary_elem_ptr->point(1); Point e2 = primary_elem_ptr->point(2) - primary_elem_ptr->point(1); Real orient = e2.cross(e1) * _u.cross(_v); // Get primary_poly (primary is clipping poly). If negatively oriented, reverse std::vector<Point> primary_poly; const int n_verts = primary_elem_ptr->n_vertices(); for (auto n : make_range(n_verts)) { Point pt = (orient > 0) ? primary_elem_ptr->point(n) - _center : primary_elem_ptr->point(n_verts - 1 - n) - _center; primary_poly.emplace_back(pt * _u, pt * _v, 0.); } if (isDisjoint(primary_poly)) return; // Initialize clipped poly with secondary poly (secondary is target poly) clipped_poly = _secondary_poly; // Loop through clipping edges for (auto i : make_range(primary_poly.size())) { if (clipped_poly.size() < 3) { clipped_poly.clear(); } // Set input poly to current clipped poly std::vector<Point> input_poly(clipped_poly); clipped_poly.clear(); // If clipped poly trivial, return if (input_poly.size() < 3) return; // Get clipping edge Point & clip_pt1 = primary_poly[i]; Point & clip_pt2 = primary_poly[(i + 1) % primary_poly.size()]; const Point edg = clip_pt2 - clip_pt1; const Real cp = clip_pt2(0) * clip_pt1(1) - clip_pt2(1) * clip_pt1(0); // Check if point is to the left of (or on) clip_edge /* * Note that use of tolerance here is to avoid degenerate case when lines are * essentially on top of each other (common when meshes match across interface) * since finding intersection is ill-conditioned in this case. Dividing by * secondary_area is to non-dimensionalize before tolerancing */ auto is_inside = [&edg, cp](Point & pt, Real tol) { return pt(0) * edg(1) - pt(1) * edg(0) + cp < tol; }; // Loop through edges of target polygon (with previous clippings already included) for (auto j : make_range(input_poly.size())) { // Get target edge Point & curr_pt = input_poly[(j + 1) % input_poly.size()]; Point & prev_pt = input_poly[j]; // TODO: Don't need to calculate both each loop bool is_current_inside = is_inside(curr_pt, _scaled_tol); bool is_previous_inside = is_inside(prev_pt, _scaled_tol); if (is_current_inside) { if (!is_previous_inside) { Real s; Point intersect = getIntersection(prev_pt, curr_pt, clip_pt1, clip_pt2, s); /* * s is the fraction of distance along clip poly edge that intersection lies * It is used here to avoid degenerate polygon cases. For example, consider a * case like: * o * | (inside) * ------|------ * | (outside) * when the distance is small (< 1e-7) we don't want to to add both the point * and intersection. Also note that when distance on the scale of 1e-7, * area on scale of 1e-14 so is insignificant if this results in dropping * a tri (for example if next edge crosses again) */ if (s < (1 - _tolerance)) clipped_poly.push_back(intersect); } clipped_poly.push_back(curr_pt); } else if (is_previous_inside) { Real s; Point intersect = getIntersection(prev_pt, curr_pt, clip_pt1, clip_pt2, s); if (s > _tolerance) clipped_poly.push_back(intersect); } } } } void MortarSegmentHelper::plotPoly(std::vector<Point> & poly) { if (poly.size() < 2) return; MOOSE::out << "plt.plot(["; for (auto pt : poly) MOOSE::out << pt(0) << ", "; MOOSE::out << poly[0](0) << "], ["; for (auto pt : poly) MOOSE::out << pt(1) << ", "; MOOSE::out << poly[0](1) << "])" << std::endl; } void MortarSegmentHelper::plotTriangulation(std::vector<Point> & nodes, std::vector<std::array<int, 3>> & elem_to_nodes) { for (auto el : elem_to_nodes) { std::vector<Point> poly; poly.push_back(nodes[el[0]]); poly.push_back(nodes[el[1]]); poly.push_back(nodes[el[2]]); plotPoly(poly); } } void MortarSegmentHelper::triangulatePoly(std::vector<Point> & nodes, std::vector<std::array<int, 3>> & tri_map) { // Initialize output map tri_map.clear(); // If fewer than 3 nodes, error if (nodes.size() < 3) { mooseError("Can't triangulate poly with fewer than 3 nodes"); } // If three nodes, already a triangle, simply pass back map else if (nodes.size() == 3) { tri_map.push_back({{0,1,2}}); return; } // Otherwise add center point node and make simple triangulation else { Point poly_center; int n_verts = nodes.size(); // Get geometric center of polygon for (auto node : nodes) poly_center += node; poly_center /= n_verts; // Add triangles formed by outer edge and center point for (auto i : make_range(n_verts)) tri_map.push_back({{i, (i + 1) % n_verts, n_verts}}); // Add center point to end nodes nodes.push_back(poly_center); return; } } void MortarSegmentHelper::getMortarSegments(const Elem * primary_elem_ptr, std::vector<Point> & nodes, std::vector<std::array<int, 3>> & elem_to_nodes) { nodes.clear(); // Clip primary elem against secondary elem std::vector<Point> clipped_poly; clipPoly(primary_elem_ptr, clipped_poly); if (clipped_poly.size() < 3) { elem_to_nodes.clear(); return; } if(_debug) { for(auto pt : clipped_poly) { if (!isInsideSecondary(pt)) mooseError("Clipped polygon not inside linearized secondary element"); } } // Compute area of clipped polygon, update remaining area fraction _remaining_area_fraction -= polyArea(clipped_poly) / _secondary_area; // Triangulate clip polygon triangulatePoly(clipped_poly, elem_to_nodes); // Transform clipped poly back to (linearized) 3d and output nodes nodes.reserve(clipped_poly.size()); for (auto pt : clipped_poly) nodes.emplace_back((pt(0) * _u) + (pt(1) * _v) + _center); } Real MortarSegmentHelper::polyArea(std::vector<Point> & nodes) { Real poly_area = 0; for (auto i : make_range(nodes.size())) poly_area += nodes[i](0) * nodes[(i + 1) % nodes.size()](1) - nodes[i](1) * nodes[(i + 1) % nodes.size()](0); poly_area *= 0.5; return poly_area; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_coding/neteq/buffer_level_filter.h" #include <algorithm> // Provide access to std::max. namespace webrtc { BufferLevelFilter::BufferLevelFilter() { Reset(); } void BufferLevelFilter::Reset() { filtered_current_level_ = 0; level_factor_ = 253; } void BufferLevelFilter::Update(size_t buffer_size_packets, int time_stretched_samples, size_t packet_len_samples) { // Filter: // |filtered_current_level_| = |level_factor_| * |filtered_current_level_| + // (1 - |level_factor_|) * |buffer_size_packets| // |level_factor_| and |filtered_current_level_| are in Q8. // |buffer_size_packets| is in Q0. filtered_current_level_ = ((level_factor_ * filtered_current_level_) >> 8) + ((256 - level_factor_) * static_cast<int>(buffer_size_packets)); // Account for time-scale operations (accelerate and pre-emptive expand). if (time_stretched_samples && packet_len_samples > 0) { // Time-scaling has been performed since last filter update. Subtract the // value of |time_stretched_samples| from |filtered_current_level_| after // converting |time_stretched_samples| from samples to packets in Q8. // Make sure that the filtered value remains non-negative. filtered_current_level_ = std::max(0, filtered_current_level_ - (time_stretched_samples << 8) / static_cast<int>(packet_len_samples)); } } void BufferLevelFilter::SetTargetBufferLevel(int target_buffer_level) { if (target_buffer_level <= 1) { level_factor_ = 251; } else if (target_buffer_level <= 3) { level_factor_ = 252; } else if (target_buffer_level <= 7) { level_factor_ = 253; } else { level_factor_ = 254; } } int BufferLevelFilter::filtered_current_level() const { return filtered_current_level_; } } // namespace webrtc <commit_msg>NetEq: Fix an UBSan error<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_coding/neteq/buffer_level_filter.h" #include <algorithm> // Provide access to std::max. namespace webrtc { BufferLevelFilter::BufferLevelFilter() { Reset(); } void BufferLevelFilter::Reset() { filtered_current_level_ = 0; level_factor_ = 253; } void BufferLevelFilter::Update(size_t buffer_size_packets, int time_stretched_samples, size_t packet_len_samples) { // Filter: // |filtered_current_level_| = |level_factor_| * |filtered_current_level_| + // (1 - |level_factor_|) * |buffer_size_packets| // |level_factor_| and |filtered_current_level_| are in Q8. // |buffer_size_packets| is in Q0. filtered_current_level_ = ((level_factor_ * filtered_current_level_) >> 8) + ((256 - level_factor_) * static_cast<int>(buffer_size_packets)); // Account for time-scale operations (accelerate and pre-emptive expand). if (time_stretched_samples && packet_len_samples > 0) { // Time-scaling has been performed since last filter update. Subtract the // value of |time_stretched_samples| from |filtered_current_level_| after // converting |time_stretched_samples| from samples to packets in Q8. // Make sure that the filtered value remains non-negative. filtered_current_level_ = std::max( 0, filtered_current_level_ - (time_stretched_samples * (1 << 8)) / static_cast<int>(packet_len_samples)); } } void BufferLevelFilter::SetTargetBufferLevel(int target_buffer_level) { if (target_buffer_level <= 1) { level_factor_ = 251; } else if (target_buffer_level <= 3) { level_factor_ = 252; } else if (target_buffer_level <= 7) { level_factor_ = 253; } else { level_factor_ = 254; } } int BufferLevelFilter::filtered_current_level() const { return filtered_current_level_; } } // namespace webrtc <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the Avogadro project. Copyright 2012 Kitware, Inc. This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ #include "cjsonformat.h" #include <avogadro/core/crystaltools.h> #include <avogadro/core/elements.h> #include <avogadro/core/gaussianset.h> #include <avogadro/core/molecule.h> #include <avogadro/core/unitcell.h> #include <jsoncpp.cpp> namespace Avogadro { namespace Io { using std::string; using std::vector; using Json::Value; using Json::Reader; using Json::StyledStreamWriter; using Core::Array; using Core::Atom; using Core::BasisSet; using Core::Bond; using Core::CrystalTools; using Core::Elements; using Core::GaussianSet; using Core::Molecule; using Core::Variant; CjsonFormat::CjsonFormat() { } CjsonFormat::~CjsonFormat() { } bool CjsonFormat::read(std::istream &file, Molecule &molecule) { Value root; Reader reader; bool ok = reader.parse(file, root); if (!ok) { appendError("Error parsing JSON: " + reader.getFormatedErrorMessages()); return false; } if (!root.isObject()) { appendError("Error: Input is not a JSON object."); return false; } Value value = root["chemical json"]; if (value.empty()) { appendError("Error: no \"chemical json\" key found."); return false; } // It looks like a valid Chemical JSON file - attempt to read data. value = root["name"]; if (!value.empty() && value.isString()) molecule.setData("name", value.asString()); value = root["inchi"]; if (!value.empty() && value.isString()) molecule.setData("inchi", value.asString()); value = root["unit cell"]; if (value.type() == Json::objectValue) { if (!value["a"].isNumeric() || !value["b"].isNumeric() || !value["c"].isNumeric() || !value["alpha"].isNumeric() || !value["beta"].isNumeric() || !value["gamma"].isNumeric()) { appendError("Invalid unit cell specification: a, b, c, alpha, beta, gamma" " must be present and numeric."); return false; } Real a = static_cast<Real>(value["a"].asDouble()); Real b = static_cast<Real>(value["b"].asDouble()); Real c = static_cast<Real>(value["c"].asDouble()); Real alpha = static_cast<Real>(value["alpha"].asDouble()) * DEG_TO_RAD; Real beta = static_cast<Real>(value["beta" ].asDouble()) * DEG_TO_RAD; Real gamma = static_cast<Real>(value["gamma"].asDouble()) * DEG_TO_RAD; Core::UnitCell *unitCell = new Core::UnitCell(a, b, c, alpha, beta, gamma); molecule.setUnitCell(unitCell); } // Read in the atomic data. Value atoms = root["atoms"]; if (atoms.empty()) { appendError("Error: no \"atom\" key found"); return false; } else if (atoms.type() != Json::objectValue) { appendError("Error: \"atom\" is not of type object"); return false; } value = atoms["elements"]; if (value.empty()) { appendError("Error: no \"atoms.elements\" key found"); return false; } else if (value.type() != Json::objectValue) { appendError("Error: \"atoms.elements\" is not of type object"); return false; } value = value["number"]; if (value.empty()) { appendError("Error: no \"atoms.elements.number\" key found"); return false; } Index atomCount(0); if (value.isArray()) { atomCount = static_cast<Index>(value.size()); for (Index i = 0; i < atomCount; ++i) molecule.addAtom(static_cast<unsigned char>(value.get(i, 0).asInt())); } else { appendError("Error: \"atoms.elements.number\" is not of type array"); return false; } Value coords = atoms["coords"]; if (!coords.empty()) { value = coords["3d"]; if (value.isArray()) { if (value.size() && atomCount != static_cast<Index>(value.size() / 3)) { appendError("Error: number of elements != number of 3D coordinates."); return false; } for (Index i = 0; i < atomCount; ++i) { Atom a = molecule.atom(i); a.setPosition3d(Vector3(value.get(3 * i + 0, 0).asDouble(), value.get(3 * i + 1, 0).asDouble(), value.get(3 * i + 2, 0).asDouble())); } } value = coords["2d"]; if (value.isArray()) { if (value.size() && atomCount != static_cast<Index>(value.size() / 2)) { appendError("Error: number of elements != number of 2D coordinates."); return false; } for (Index i = 0; i < atomCount; ++i) { Atom a = molecule.atom(i); a.setPosition2d(Vector2(value.get(2 * i + 0, 0).asDouble(), value.get(2 * i + 1, 0).asDouble())); } } value = coords["3d fractional"]; if (value.type() == Json::arrayValue) { if (!molecule.unitCell()) { appendError("Cannot interpret fractional coordinates without " "unit cell."); return false; } if (value.size() && atomCount != static_cast<size_t>(value.size() / 3)) { appendError("Error: number of elements != number of fractional " "coordinates."); return false; } Array<Vector3> fcoords; fcoords.reserve(atomCount); for (Index i = 0; i < atomCount; ++i) { fcoords.push_back( Vector3(static_cast<Real>(value.get(i * 3 + 0, 0).asDouble()), static_cast<Real>(value.get(i * 3 + 1, 0).asDouble()), static_cast<Real>(value.get(i * 3 + 2, 0).asDouble()))); } CrystalTools::setFractionalCoordinates(molecule, fcoords); } } // Now for the bonding data. Value bonds = root["bonds"]; if (!bonds.empty()) { value = bonds["connections"]; if (value.empty()) { appendError("Error: no \"bonds.connections\" key found"); return false; } value = value["index"]; Index bondCount(0); if (value.isArray()) { bondCount = static_cast<Index>(value.size() / 2); for (Index i = 0; i < bondCount * 2; i += 2) { molecule.addBond( molecule.atom(static_cast<Index>(value.get(i + 0, 0).asInt())), molecule.atom(static_cast<Index>(value.get(i + 1, 0).asInt()))); } } else { appendError("Warning, no bonding information found."); } value = bonds["order"]; if (value.isArray()) { if (bondCount != static_cast<Index>(value.size())) { appendError("Error: number of bonds != number of bond orders."); return false; } for (Index i = 0; i < bondCount; ++i) molecule.bond(i).setOrder( static_cast<unsigned char>(value.get(i, 1).asInt())); } } return true; } bool CjsonFormat::write(std::ostream &file, const Molecule &molecule) { StyledStreamWriter writer(" "); Value root; root["chemical json"] = 0; if (molecule.data("name").type() == Variant::String) root["name"] = molecule.data("name").toString().c_str(); if (molecule.data("inchi").type() == Variant::String) root["inchi"] = molecule.data("inchi").toString().c_str(); if (molecule.unitCell()) { Value unitCell = Value(Json::objectValue); unitCell["a"] = molecule.unitCell()->a(); unitCell["b"] = molecule.unitCell()->b(); unitCell["c"] = molecule.unitCell()->c(); unitCell["alpha"] = molecule.unitCell()->alpha() * RAD_TO_DEG; unitCell["beta"] = molecule.unitCell()->beta() * RAD_TO_DEG; unitCell["gamma"] = molecule.unitCell()->gamma() * RAD_TO_DEG; root["unit cell"] = unitCell; } // Write out the basis set if we have one. FIXME: Complete implemnentation. if (molecule.basisSet()) { Value basis = Value(Json::objectValue); const GaussianSet *gaussian = dynamic_cast<const GaussianSet *>(molecule.basisSet()); if (gaussian) { basis["basisType"] = "GTO"; string type = "unknown"; switch (gaussian->scfType()) { case Core::Rhf: type = "rhf"; break; case Core::Rohf: type = "rohf"; break; case Core::Uhf: type = "uhf"; break; default: type = "unknown"; } basis["scfType"] = type; root["basisSet"] = basis; } } // Create and populate the atom arrays. if (molecule.atomCount()) { Value elements(Json::arrayValue); for (Index i = 0; i < molecule.atomCount(); ++i) elements.append(molecule.atom(i).atomicNumber()); root["atoms"]["elements"]["number"] = elements; // 3d positions: if (molecule.atomPositions3d().size() == molecule.atomCount()) { if (molecule.unitCell()) { Value coordsFractional(Json::arrayValue); Array<Vector3> fcoords; CrystalTools::fractionalCoordinates(*molecule.unitCell(), molecule.atomPositions3d(), fcoords); for (vector<Vector3>::const_iterator it = fcoords.begin(), itEnd = fcoords.end(); it != itEnd; ++it) { coordsFractional.append(it->x()); coordsFractional.append(it->y()); coordsFractional.append(it->z()); } root["atoms"]["coords"]["3d fractional"] = coordsFractional; } else { Value coords3d(Json::arrayValue); for (vector<Vector3>::const_iterator it = molecule.atomPositions3d().begin(), itEnd = molecule.atomPositions3d().end(); it != itEnd; ++it) { coords3d.append(it->x()); coords3d.append(it->y()); coords3d.append(it->z()); } root["atoms"]["coords"]["3d"] = coords3d; } } // 2d positions: if (molecule.atomPositions2d().size() == molecule.atomCount()) { Value coords2d(Json::arrayValue); for (vector<Vector2>::const_iterator it = molecule.atomPositions2d().begin(), itEnd = molecule.atomPositions2d().end(); it != itEnd; ++it) { coords2d.append(it->x()); coords2d.append(it->y()); } root["atoms"]["coords"]["2d"] = coords2d; } } // Create and populate the bond arrays. if (molecule.bondCount()) { Value connections(Json::arrayValue); Value order(Json::arrayValue); for (Index i = 0; i < molecule.bondCount(); ++i) { Bond bond = molecule.bond(i); connections.append(static_cast<Value::UInt>(bond.atom1().index())); connections.append(static_cast<Value::UInt>(bond.atom2().index())); order.append(bond.order()); } root["bonds"]["connections"]["index"] = connections; root["bonds"]["order"] = order; } writer.write(file, root); return true; } vector<std::string> CjsonFormat::fileExtensions() const { vector<std::string> ext; ext.push_back("cjson"); return ext; } vector<std::string> CjsonFormat::mimeTypes() const { vector<std::string> mime; mime.push_back("chemical/x-cjson"); return mime; } } // end Io namespace } // end Avogadro namespace <commit_msg>Read/write vibrational data in Chemical JSON files<commit_after>/****************************************************************************** This source file is part of the Avogadro project. Copyright 2012 Kitware, Inc. This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ #include "cjsonformat.h" #include <avogadro/core/crystaltools.h> #include <avogadro/core/elements.h> #include <avogadro/core/gaussianset.h> #include <avogadro/core/molecule.h> #include <avogadro/core/unitcell.h> #include <jsoncpp.cpp> namespace Avogadro { namespace Io { using std::string; using std::vector; using Json::Value; using Json::Reader; using Json::StyledStreamWriter; using Core::Array; using Core::Atom; using Core::BasisSet; using Core::Bond; using Core::CrystalTools; using Core::Elements; using Core::GaussianSet; using Core::Molecule; using Core::Variant; CjsonFormat::CjsonFormat() { } CjsonFormat::~CjsonFormat() { } bool CjsonFormat::read(std::istream &file, Molecule &molecule) { Value root; Reader reader; bool ok = reader.parse(file, root); if (!ok) { appendError("Error parsing JSON: " + reader.getFormatedErrorMessages()); return false; } if (!root.isObject()) { appendError("Error: Input is not a JSON object."); return false; } Value value = root["chemical json"]; if (value.empty()) { appendError("Error: no \"chemical json\" key found."); return false; } // It looks like a valid Chemical JSON file - attempt to read data. value = root["name"]; if (!value.empty() && value.isString()) molecule.setData("name", value.asString()); value = root["inchi"]; if (!value.empty() && value.isString()) molecule.setData("inchi", value.asString()); value = root["unit cell"]; if (value.type() == Json::objectValue) { if (!value["a"].isNumeric() || !value["b"].isNumeric() || !value["c"].isNumeric() || !value["alpha"].isNumeric() || !value["beta"].isNumeric() || !value["gamma"].isNumeric()) { appendError("Invalid unit cell specification: a, b, c, alpha, beta, gamma" " must be present and numeric."); return false; } Real a = static_cast<Real>(value["a"].asDouble()); Real b = static_cast<Real>(value["b"].asDouble()); Real c = static_cast<Real>(value["c"].asDouble()); Real alpha = static_cast<Real>(value["alpha"].asDouble()) * DEG_TO_RAD; Real beta = static_cast<Real>(value["beta" ].asDouble()) * DEG_TO_RAD; Real gamma = static_cast<Real>(value["gamma"].asDouble()) * DEG_TO_RAD; Core::UnitCell *unitCell = new Core::UnitCell(a, b, c, alpha, beta, gamma); molecule.setUnitCell(unitCell); } // Read in the atomic data. Value atoms = root["atoms"]; if (atoms.empty()) { appendError("Error: no \"atom\" key found"); return false; } else if (atoms.type() != Json::objectValue) { appendError("Error: \"atom\" is not of type object"); return false; } value = atoms["elements"]; if (value.empty()) { appendError("Error: no \"atoms.elements\" key found"); return false; } else if (value.type() != Json::objectValue) { appendError("Error: \"atoms.elements\" is not of type object"); return false; } value = value["number"]; if (value.empty()) { appendError("Error: no \"atoms.elements.number\" key found"); return false; } Index atomCount(0); if (value.isArray()) { atomCount = static_cast<Index>(value.size()); for (Index i = 0; i < atomCount; ++i) molecule.addAtom(static_cast<unsigned char>(value.get(i, 0).asInt())); } else { appendError("Error: \"atoms.elements.number\" is not of type array"); return false; } Value coords = atoms["coords"]; if (!coords.empty()) { value = coords["3d"]; if (value.isArray()) { if (value.size() && atomCount != static_cast<Index>(value.size() / 3)) { appendError("Error: number of elements != number of 3D coordinates."); return false; } for (Index i = 0; i < atomCount; ++i) { Atom a = molecule.atom(i); a.setPosition3d(Vector3(value.get(3 * i + 0, 0).asDouble(), value.get(3 * i + 1, 0).asDouble(), value.get(3 * i + 2, 0).asDouble())); } } value = coords["2d"]; if (value.isArray()) { if (value.size() && atomCount != static_cast<Index>(value.size() / 2)) { appendError("Error: number of elements != number of 2D coordinates."); return false; } for (Index i = 0; i < atomCount; ++i) { Atom a = molecule.atom(i); a.setPosition2d(Vector2(value.get(2 * i + 0, 0).asDouble(), value.get(2 * i + 1, 0).asDouble())); } } value = coords["3d fractional"]; if (value.type() == Json::arrayValue) { if (!molecule.unitCell()) { appendError("Cannot interpret fractional coordinates without " "unit cell."); return false; } if (value.size() && atomCount != static_cast<size_t>(value.size() / 3)) { appendError("Error: number of elements != number of fractional " "coordinates."); return false; } Array<Vector3> fcoords; fcoords.reserve(atomCount); for (Index i = 0; i < atomCount; ++i) { fcoords.push_back( Vector3(static_cast<Real>(value.get(i * 3 + 0, 0).asDouble()), static_cast<Real>(value.get(i * 3 + 1, 0).asDouble()), static_cast<Real>(value.get(i * 3 + 2, 0).asDouble()))); } CrystalTools::setFractionalCoordinates(molecule, fcoords); } } // Now for the bonding data. Value bonds = root["bonds"]; if (!bonds.empty()) { value = bonds["connections"]; if (value.empty()) { appendError("Error: no \"bonds.connections\" key found"); return false; } value = value["index"]; Index bondCount(0); if (value.isArray()) { bondCount = static_cast<Index>(value.size() / 2); for (Index i = 0; i < bondCount * 2; i += 2) { molecule.addBond( molecule.atom(static_cast<Index>(value.get(i + 0, 0).asInt())), molecule.atom(static_cast<Index>(value.get(i + 1, 0).asInt()))); } } else { appendError("Warning, no bonding information found."); } value = bonds["order"]; if (value.isArray()) { if (bondCount != static_cast<Index>(value.size())) { appendError("Error: number of bonds != number of bond orders."); return false; } for (Index i = 0; i < bondCount; ++i) molecule.bond(i).setOrder( static_cast<unsigned char>(value.get(i, 1).asInt())); } } // Check for vibrational data. Value vibrations = root["vibrations"]; if (!vibrations.empty() && vibrations.isObject()) { Value modes = vibrations["modes"]; Value freqs = vibrations["frequencies"]; Value inten = vibrations["intensities"]; Value eigenVectors = vibrations["eigenVectors"]; assert(modes.size() == freqs.size()); assert(modes.size() == inten.size()); assert(modes.size() == eigenVectors.size()); Array<double> frequencies; Array<double> intensities; Array< Array<Vector3> > Lx; for (size_t i = 0; i < modes.size(); ++i) { frequencies.push_back(freqs.get(i, 0).asDouble()); intensities.push_back(inten.get(i, 0).asDouble()); Array<Vector3> modeLx; Value lx = eigenVectors.get(i, 0); if (!lx.empty() && lx.isArray()) { modeLx.resize(lx.size() / 3); for (size_t k = 0; k < lx.size(); ++k) modeLx[k / 3][k % 3] = lx.get(k, 0).asDouble(); Lx.push_back(modeLx); } } molecule.setVibrationFrequencies(frequencies); molecule.setVibrationIntensities(intensities); molecule.setVibrationLx(Lx); } return true; } bool CjsonFormat::write(std::ostream &file, const Molecule &molecule) { StyledStreamWriter writer(" "); Value root; root["chemical json"] = 0; if (molecule.data("name").type() == Variant::String) root["name"] = molecule.data("name").toString().c_str(); if (molecule.data("inchi").type() == Variant::String) root["inchi"] = molecule.data("inchi").toString().c_str(); if (molecule.unitCell()) { Value unitCell = Value(Json::objectValue); unitCell["a"] = molecule.unitCell()->a(); unitCell["b"] = molecule.unitCell()->b(); unitCell["c"] = molecule.unitCell()->c(); unitCell["alpha"] = molecule.unitCell()->alpha() * RAD_TO_DEG; unitCell["beta"] = molecule.unitCell()->beta() * RAD_TO_DEG; unitCell["gamma"] = molecule.unitCell()->gamma() * RAD_TO_DEG; root["unit cell"] = unitCell; } // Write out the basis set if we have one. FIXME: Complete implemnentation. if (molecule.basisSet()) { Value basis = Value(Json::objectValue); const GaussianSet *gaussian = dynamic_cast<const GaussianSet *>(molecule.basisSet()); if (gaussian) { basis["basisType"] = "GTO"; string type = "unknown"; switch (gaussian->scfType()) { case Core::Rhf: type = "rhf"; break; case Core::Rohf: type = "rohf"; break; case Core::Uhf: type = "uhf"; break; default: type = "unknown"; } basis["scfType"] = type; root["basisSet"] = basis; } } // Create and populate the atom arrays. if (molecule.atomCount()) { Value elements(Json::arrayValue); for (Index i = 0; i < molecule.atomCount(); ++i) elements.append(molecule.atom(i).atomicNumber()); root["atoms"]["elements"]["number"] = elements; // 3d positions: if (molecule.atomPositions3d().size() == molecule.atomCount()) { if (molecule.unitCell()) { Value coordsFractional(Json::arrayValue); Array<Vector3> fcoords; CrystalTools::fractionalCoordinates(*molecule.unitCell(), molecule.atomPositions3d(), fcoords); for (vector<Vector3>::const_iterator it = fcoords.begin(), itEnd = fcoords.end(); it != itEnd; ++it) { coordsFractional.append(it->x()); coordsFractional.append(it->y()); coordsFractional.append(it->z()); } root["atoms"]["coords"]["3d fractional"] = coordsFractional; } else { Value coords3d(Json::arrayValue); for (vector<Vector3>::const_iterator it = molecule.atomPositions3d().begin(), itEnd = molecule.atomPositions3d().end(); it != itEnd; ++it) { coords3d.append(it->x()); coords3d.append(it->y()); coords3d.append(it->z()); } root["atoms"]["coords"]["3d"] = coords3d; } } // 2d positions: if (molecule.atomPositions2d().size() == molecule.atomCount()) { Value coords2d(Json::arrayValue); for (vector<Vector2>::const_iterator it = molecule.atomPositions2d().begin(), itEnd = molecule.atomPositions2d().end(); it != itEnd; ++it) { coords2d.append(it->x()); coords2d.append(it->y()); } root["atoms"]["coords"]["2d"] = coords2d; } } // Create and populate the bond arrays. if (molecule.bondCount()) { Value connections(Json::arrayValue); Value order(Json::arrayValue); for (Index i = 0; i < molecule.bondCount(); ++i) { Bond bond = molecule.bond(i); connections.append(static_cast<Value::UInt>(bond.atom1().index())); connections.append(static_cast<Value::UInt>(bond.atom2().index())); order.append(bond.order()); } root["bonds"]["connections"]["index"] = connections; root["bonds"]["order"] = order; } // If there is vibrational data write this out too. if (molecule.vibrationFrequencies().size() > 0) { // A few sanity checks before we begin. assert(molecule.vibrationFrequencies().size() == molecule.vibrationIntensities().size()); assert(molecule.vibrationFrequencies().size() == molecule.vibrationLx().size()); Value modes(Json::arrayValue); Value freqs(Json::arrayValue); Value inten(Json::arrayValue); Value eigenVectors(Json::arrayValue); for (size_t i = 0; i < molecule.vibrationFrequencies().size(); ++i) { modes.append(static_cast<unsigned int>(i) + 1); freqs.append(molecule.vibrationFrequencies()[i]); inten.append(molecule.vibrationIntensities()[i]); Core::Array<Vector3> atomDisplacements = molecule.vibrationLx(i); Value eigenVector(Json::arrayValue); for (size_t j = 0; j < atomDisplacements.size(); ++j) { Vector3 pos = atomDisplacements[j]; eigenVector.append(pos[0]); eigenVector.append(pos[1]); eigenVector.append(pos[2]); } eigenVectors.append(eigenVector); } root["vibrations"]["modes"] = modes; root["vibrations"]["frequencies"] = freqs; root["vibrations"]["intensities"] = inten; root["vibrations"]["eigenVectors"] = eigenVectors; } writer.write(file, root); return true; } vector<std::string> CjsonFormat::fileExtensions() const { vector<std::string> ext; ext.push_back("cjson"); return ext; } vector<std::string> CjsonFormat::mimeTypes() const { vector<std::string> mime; mime.push_back("chemical/x-cjson"); return mime; } } // end Io namespace } // end Avogadro namespace <|endoftext|>
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/torrent_handle.hpp> #include <boost/python.hpp> #include <libtorrent/bitfield.hpp> using namespace boost::python; using namespace libtorrent; object pieces(torrent_status const& s) { list result; for (bitfield::const_iterator i(s.pieces.begin()), e(s.pieces.end()); i != e; ++i) result.append(*i); return result; } void bind_torrent_status() { scope status = class_<torrent_status>("torrent_status") .def_readonly("state", &torrent_status::state) .def_readonly("paused", &torrent_status::paused) .def_readonly("progress", &torrent_status::progress) .add_property( "next_announce" , make_getter( &torrent_status::next_announce, return_value_policy<return_by_value>() ) ) .add_property( "announce_interval" , make_getter( &torrent_status::announce_interval, return_value_policy<return_by_value>() ) ) .def_readonly("current_tracker", &torrent_status::current_tracker) .def_readonly("total_download", &torrent_status::total_download) .def_readonly("total_upload", &torrent_status::total_upload) .def_readonly("total_payload_download", &torrent_status::total_payload_download) .def_readonly("total_payload_upload", &torrent_status::total_payload_upload) .def_readonly("total_failed_bytes", &torrent_status::total_failed_bytes) .def_readonly("total_redundant_bytes", &torrent_status::total_redundant_bytes) .def_readonly("download_rate", &torrent_status::download_rate) .def_readonly("upload_rate", &torrent_status::upload_rate) .def_readonly("download_payload_rate", &torrent_status::download_payload_rate) .def_readonly("upload_payload_rate", &torrent_status::upload_payload_rate) .def_readonly("num_seeds", &torrent_status::num_seeds) .def_readonly("num_peers", &torrent_status::num_peers) .def_readonly("num_complete", &torrent_status::num_complete) .def_readonly("num_incomplete", &torrent_status::num_incomplete) .def_readonly("list_seeds", &torrent_status::list_seeds) .def_readonly("list_peers", &torrent_status::list_peers) .add_property("pieces", pieces) .def_readonly("num_pieces", &torrent_status::num_pieces) .def_readonly("total_done", &torrent_status::total_done) .def_readonly("total_wanted_done", &torrent_status::total_wanted_done) .def_readonly("total_wanted", &torrent_status::total_wanted) .def_readonly("distributed_copies", &torrent_status::distributed_copies) .def_readonly("block_size", &torrent_status::block_size) .def_readonly("num_uploads", &torrent_status::num_uploads) .def_readonly("num_connections", &torrent_status::num_connections) .def_readonly("uploads_limit", &torrent_status::uploads_limit) .def_readonly("connections_limit", &torrent_status::connections_limit) .def_readonly("storage_mode", &torrent_status::storage_mode) .def_readonly("up_bandwidth_queue", &torrent_status::up_bandwidth_queue) .def_readonly("down_bandwidth_queue", &torrent_status::down_bandwidth_queue) .def_readonly("all_time_upload", &torrent_status::all_time_upload) .def_readonly("all_time_download", &torrent_status::all_time_download) .def_readonly("active_time", &torrent_status::active_time) .def_readonly("seeding_time", &torrent_status::seeding_time) .def_readonly("seed_rank", &torrent_status::seed_rank) .def_readonly("last_scrape", &torrent_status::last_scrape) .def_readonly("error", &torrent_status::error) ; enum_<torrent_status::state_t>("states") .value("queued_for_checking", torrent_status::queued_for_checking) .value("checking_files", torrent_status::checking_files) .value("connecting_to_tracker", torrent_status::connecting_to_tracker) .value("downloading", torrent_status::downloading) .value("finished", torrent_status::finished) .value("seeding", torrent_status::seeding) .value("allocating", torrent_status::allocating) .export_values() ; } <commit_msg>Remove 'connecting_to_tracker' state from bindings<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/torrent_handle.hpp> #include <boost/python.hpp> #include <libtorrent/bitfield.hpp> using namespace boost::python; using namespace libtorrent; object pieces(torrent_status const& s) { list result; for (bitfield::const_iterator i(s.pieces.begin()), e(s.pieces.end()); i != e; ++i) result.append(*i); return result; } void bind_torrent_status() { scope status = class_<torrent_status>("torrent_status") .def_readonly("state", &torrent_status::state) .def_readonly("paused", &torrent_status::paused) .def_readonly("progress", &torrent_status::progress) .add_property( "next_announce" , make_getter( &torrent_status::next_announce, return_value_policy<return_by_value>() ) ) .add_property( "announce_interval" , make_getter( &torrent_status::announce_interval, return_value_policy<return_by_value>() ) ) .def_readonly("current_tracker", &torrent_status::current_tracker) .def_readonly("total_download", &torrent_status::total_download) .def_readonly("total_upload", &torrent_status::total_upload) .def_readonly("total_payload_download", &torrent_status::total_payload_download) .def_readonly("total_payload_upload", &torrent_status::total_payload_upload) .def_readonly("total_failed_bytes", &torrent_status::total_failed_bytes) .def_readonly("total_redundant_bytes", &torrent_status::total_redundant_bytes) .def_readonly("download_rate", &torrent_status::download_rate) .def_readonly("upload_rate", &torrent_status::upload_rate) .def_readonly("download_payload_rate", &torrent_status::download_payload_rate) .def_readonly("upload_payload_rate", &torrent_status::upload_payload_rate) .def_readonly("num_seeds", &torrent_status::num_seeds) .def_readonly("num_peers", &torrent_status::num_peers) .def_readonly("num_complete", &torrent_status::num_complete) .def_readonly("num_incomplete", &torrent_status::num_incomplete) .def_readonly("list_seeds", &torrent_status::list_seeds) .def_readonly("list_peers", &torrent_status::list_peers) .add_property("pieces", pieces) .def_readonly("num_pieces", &torrent_status::num_pieces) .def_readonly("total_done", &torrent_status::total_done) .def_readonly("total_wanted_done", &torrent_status::total_wanted_done) .def_readonly("total_wanted", &torrent_status::total_wanted) .def_readonly("distributed_copies", &torrent_status::distributed_copies) .def_readonly("block_size", &torrent_status::block_size) .def_readonly("num_uploads", &torrent_status::num_uploads) .def_readonly("num_connections", &torrent_status::num_connections) .def_readonly("uploads_limit", &torrent_status::uploads_limit) .def_readonly("connections_limit", &torrent_status::connections_limit) .def_readonly("storage_mode", &torrent_status::storage_mode) .def_readonly("up_bandwidth_queue", &torrent_status::up_bandwidth_queue) .def_readonly("down_bandwidth_queue", &torrent_status::down_bandwidth_queue) .def_readonly("all_time_upload", &torrent_status::all_time_upload) .def_readonly("all_time_download", &torrent_status::all_time_download) .def_readonly("active_time", &torrent_status::active_time) .def_readonly("seeding_time", &torrent_status::seeding_time) .def_readonly("seed_rank", &torrent_status::seed_rank) .def_readonly("last_scrape", &torrent_status::last_scrape) .def_readonly("error", &torrent_status::error) ; enum_<torrent_status::state_t>("states") .value("queued_for_checking", torrent_status::queued_for_checking) .value("checking_files", torrent_status::checking_files) .value("downloading", torrent_status::downloading) .value("finished", torrent_status::finished) .value("seeding", torrent_status::seeding) .value("allocating", torrent_status::allocating) .export_values() ; } <|endoftext|>
<commit_before>class CfgServerInfoMenu { addAction = 0; // Enable/disable action menu item | use 0 to disable | default: 1 (enabled) // antiHACK = "infiSTAR + BattlEye"; antiHACK = "BattlEye"; hostedBy = "HC Corp"; ipPort = "189.1.169.221:2342"; openKey = "User7"; // https://community.bistudio.com/wiki/inputAction/actions openAtLogin = no; restart = 3; // Amount of hours before server automatically restarts serverName = "HC Corp A3Wasteland Altis"; class menuItems { // title AND content accept formatted text ( since update Oct5.2016 ) class first { menuName = "Rules"; title = "Regras do servidor|Server rules"; content[] = { "<t size='1.70'>Regras do servidor A3Wasteland Altis <t color='#b8870a'>HC Corp</t>|<t color='#b8870a'>HC Corp</t> A3Wasteland Altis server rules<br />", "1. &Eacute; proibido o uso de cheats, exploits e/ou hacks. Penalidade: <t color='#ff0000'>banimento</t><br />", "1. Using cheats, exploits and/or hacks is forbidden. Penalty: <t color='#ff0000'>ban</t><br />", "2. Seja educado. Respeite o servidor, os administradores, os membros da HC Corp e todos os outros jogadores. Penalidades: primeira ofensa; aviso; ofensas seguintes; <t color='#ff0000'>banimento</t><br />", "2. Be polite. Respect the server, the administrators, the HC Corp members and all the other players. Penalties: first offense; warning; following offenses; <t color='#ff0000'>ban</t><br />" }; }; class second { menuName = "Missions"; title = "<t color='#b8870a'>Miss&otilde;es do servidor|Server missions</t>"; content[] = { "<br/>• Small Money Shipment: $50,000<br />• Medium Money Shipment: $75,000<br />• Large Money Shipment: $100,000<br />• Heavy Money Shipment: $150,000<br />• Sunken Treasure: $150,000<br /></p>" }; }; class third { menuName = "Events"; title = "<t color='#b8870a'>Eventos todo fim de semana|Events every weekend</t>"; content[] = {"<t size='1.75'>Pr&oacute;ximo evento|Next event</t><br />• N&Atilde;O DISPON&Iacute;VEL|NOT AVAILABLE<br />"}; }; class fourth { menuName = "Admins"; title = "<t color='#b8870a'>Administradores|Administrators</t>"; content[] = {"<t size='1.75'>Admin</t><br /><t color='#b8870a'>• leonbarba<br />• rover047</t><br />"}; // content[] = {"<t size='1.75'>Admin</t><br /><t color='#b8870a'>• NICK 1<br />• NICK 2 <br />• NICK 3</t><br />", // "<t size='1.75'>Editor</t><br /><t color='#b8870a'>• NICK 1<br />• NICK 2</t><br />"}; }; // class fifth // { // menuName = "Rank"; // title = "<t color='#b8870a'>Top 10</t>"; // content[] = {"<t size='1.75'>Rank</t><br />• EM BREVE|SOON<br />"}; // }; // class sixth class fifth { menuName = "Communication"; title = "<t color='#b8870a'>Servidor de voz|Voice server</t>"; content[] = { "<t size='1.75'>TeamSpeak:</t><br /><t color='#b8870a'><a href='http://invite.teamspeak.com/192.99.182.72/?port=32104'>192.99.182.72:32104</a></t><br />" }; }; // class seventh // { // menuName = "Updates"; // title = "<t color='#b8870a'>Atualiza&ccedil;&otilde;es|Updates</t>"; // content[] = { // "<t size='1.75'>Atualiza&ccedil;&otilde;es|Updates</t><br /><t color='#b8870a'><a href='http://www.hccorp.com.br'>www.hccorp.com.br</a></t><br />" // }; // }; }; }; <commit_msg>Caracteres acentuados, hostedBy, corrigiu Rules<commit_after>class CfgServerInfoMenu { addAction = 0; // Enable/disable action menu item | use 0 to disable | default: 1 (enabled) // antiHACK = "infiSTAR + BattlEye"; antiHACK = "BattlEye"; hostedBy = "Mgthost1"; ipPort = "189.1.169.221:2342"; openKey = "User7"; // https://community.bistudio.com/wiki/inputAction/actions openAtLogin = no; restart = 3; // Amount of hours before server automatically restarts serverName = "HC Corp A3Wasteland Altis"; class menuItems { // title AND content accept formatted text ( since update Oct5.2016 ) class first { menuName = "Rules"; title = "Regras do servidor|Server rules"; content[] = { "<t size='1.70'>Regras do servidor A3Wasteland Altis <t color='#b8870a'>HC Corp</t>|<t color='#b8870a'>HC Corp</t> A3Wasteland Altis server rules</t><br />", "1. É proibido o uso de cheats, exploits e/ou hacks. Penalidade: <t color='#ff0000'>banimento</t><br />", "1. Using cheats, exploits and/or hacks is forbidden. Penalty: <t color='#ff0000'>ban</t><br />", "2. Seja educado. Respeite o servidor, os administradores, os membros da HC Corp e todos os outros jogadores. Penalidades: primeira ofensa; aviso; ofensas seguintes; <t color='#ff0000'>banimento</t><br />", "2. Be polite. Respect the server, the administrators, the HC Corp members and all the other players. Penalties: first offense; warning; following offenses; <t color='#ff0000'>ban</t><br />" }; }; class second { menuName = "Missions"; title = "<t color='#b8870a'>Missões do servidor|Server missions</t>"; content[] = { "<br/>• Small Money Shipment: $50,000<br />• Medium Money Shipment: $75,000<br />• Large Money Shipment: $100,000<br />• Heavy Money Shipment: $150,000<br />• Sunken Treasure: $150,000<br /></p>" }; }; class third { menuName = "Events"; title = "<t color='#b8870a'>Eventos todo fim de semana|Events every weekend</t>"; content[] = {"<t size='1.75'>Próximo evento|Next event</t><br />• NÃO DISPONÍVEL|NOT AVAILABLE<br />"}; }; class fourth { menuName = "Admins"; title = "<t color='#b8870a'>Administradores|Administrators</t>"; content[] = {"<t size='1.75'>Admin</t><br /><t color='#b8870a'>• leonbarba<br />• rover047</t><br />"}; // content[] = {"<t size='1.75'>Admin</t><br /><t color='#b8870a'>• NICK 1<br />• NICK 2 <br />• NICK 3</t><br />", // "<t size='1.75'>Editor</t><br /><t color='#b8870a'>• NICK 1<br />• NICK 2</t><br />"}; }; // class fifth // { // menuName = "Rank"; // title = "<t color='#b8870a'>Top 10</t>"; // content[] = {"<t size='1.75'>Rank</t><br />• EM BREVE|SOON<br />"}; // }; // class sixth class fifth { menuName = "Communication"; title = "<t color='#b8870a'>Servidor de voz|Voice server</t>"; content[] = { "<t size='1.75'>TeamSpeak:</t><br /><t color='#b8870a'><a href='http://invite.teamspeak.com/192.99.182.72/?port=32104'>192.99.182.72:32104</a></t><br />" }; }; // class seventh // { // menuName = "Updates"; // title = "<t color='#b8870a'>Atualiza&ccedil;&otilde;es|Updates</t>"; // content[] = { // "<t size='1.75'>Atualiza&ccedil;&otilde;es|Updates</t><br /><t color='#b8870a'><a href='http://www.hccorp.com.br'>www.hccorp.com.br</a></t><br />" // }; // }; }; }; <|endoftext|>
<commit_before>#include "../include/DateTime.hpp" #include <ctime> namespace Kelly { static const int DaysInMonths[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; static constexpr int64_t DaysPerYear = 365; static constexpr int64_t TicksPerYear = TicksPerDay * DaysPerYear; static constexpr int64_t DaysPerFourCenturies = DaysPerYear * 400 + 97; static constexpr int64_t DaysPerCentury = DaysPerYear * 100 + 24; static constexpr int64_t DaysPerFourYears = DaysPerYear * 4 + 1; std::pair<int, int> ExtractYears(int days) { int64_t year = 1; if (days >= DaysPerFourCenturies) { int64_t chunks = days / DaysPerFourCenturies; year += chunks * 400; days -= chunks * DaysPerFourCenturies; } if (days >= DaysPerCentury) { int64_t chunks = days / DaysPerCentury; if (chunks == 4) chunks = 3; year += chunks * 100; days -= chunks * DaysPerCentury; } if (days >= DaysPerFourYears) { int64_t chunks = days / DaysPerFourYears; year += chunks * 4; days -= chunks * DaysPerFourYears; } if (days >= DaysPerYear) { int64_t chunks = days / DaysPerYear; if (chunks == 4) chunks = 3; year += chunks; days -= chunks * DaysPerYear; } return {year, days}; } std::pair<int, int> ExtractMonth(int days, int year) { int64_t month = 1; for (int64_t daysInMonth = DateTime::DaysInMonth(month, year); days >= daysInMonth; daysInMonth = DateTime::DaysInMonth(month, year)) { ++month; days -= daysInMonth; } return {month, days}; } DateTime::DateTime( int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond, int ticks) { if (InRange(year, 1, 9999) && InRange(day, 1, DaysInMonth(month, year)) && InRange(hour, 0, 23) && InRange(minute, 0, 59) && InRange(second, 0, 59) && InRange(millisecond, 0, 999) && InRange(microsecond, 0, 999) && InRange(ticks, 0, 9)) { int64_t days = day - 1; for (int i = 1; i < month; ++i) days += DaysInMonth(i, year); --year; days += (year * DaysPerYear) + (year / 4) - (year / 100) + (year / 400); _ticks = days * TicksPerDay + hour * TicksPerHour + minute * TicksPerMinute + second * TicksPerSecond + millisecond * TicksPerMillisecond + microsecond * TicksPerMicrosecond + ticks; } else { _ticks = 0; } } int DateTime::Year() const { int days = _ticks / TicksPerDay; return ExtractYears(days).first; } int DateTime::Month() const { int days = _ticks / TicksPerDay; auto y = ExtractYears(days); return ExtractMonth(y.second, y.first).first; } int DateTime::Day() const { int64_t days = _ticks / TicksPerDay; auto y = ExtractYears(days); auto m = ExtractMonth(y.second, y.first); return m.second + 1; } DateTime& DateTime::operator+=(TimeSpan timeSpan) { _ticks = SafeTicks(_ticks += timeSpan.Ticks()); return *this; } DateTime& DateTime::operator-=(TimeSpan timeSpan) { _ticks = SafeTicks(_ticks -= timeSpan.Ticks()); return *this; } int DateTime::DaysInMonth(int month, int year) { if (InRange(month, 1, 12)) { if (month == 2 && IsLeapYear(year)) return 29; return DaysInMonths[month]; } return 0; } const char* DateTime::DayToString(int dayOfWeek) { const char* DayNames[7] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; return InRange(dayOfWeek, 0, 6) ? DayNames[dayOfWeek] : nullptr; } static DateTime GetDateTime(const tm& timeInfo) { return DateTime( timeInfo.tm_year + 1900, timeInfo.tm_mon + 1, timeInfo.tm_mday, timeInfo.tm_hour, timeInfo.tm_min, Min(timeInfo.tm_sec, 59)); // Can exceed 59! :( // http://www.cplusplus.com/reference/clibrary/ctime/tm/ } DateTime DateTime::LocalTime() { time_t rawTime; time(&rawTime); return GetDateTime(*localtime(&rawTime)); } DateTime DateTime::UtcTime() { time_t rawTime; time(&rawTime); return GetDateTime(*gmtime(&rawTime)); } } <commit_msg>Shrink teh ints<commit_after>#include "../include/DateTime.hpp" #include <ctime> namespace Kelly { static const int DaysInMonths[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; static constexpr int DaysPerYear = 365; static constexpr int TicksPerYear = TicksPerDay * DaysPerYear; static constexpr int DaysPerFourCenturies = DaysPerYear * 400 + 97; static constexpr int DaysPerCentury = DaysPerYear * 100 + 24; static constexpr int DaysPerFourYears = DaysPerYear * 4 + 1; std::pair<int, int> ExtractYears(int days) { int year = 1; if (days >= DaysPerFourCenturies) { int chunks = days / DaysPerFourCenturies; year += chunks * 400; days -= chunks * DaysPerFourCenturies; } if (days >= DaysPerCentury) { int chunks = days / DaysPerCentury; if (chunks == 4) chunks = 3; year += chunks * 100; days -= chunks * DaysPerCentury; } if (days >= DaysPerFourYears) { int chunks = days / DaysPerFourYears; year += chunks * 4; days -= chunks * DaysPerFourYears; } if (days >= DaysPerYear) { int chunks = days / DaysPerYear; if (chunks == 4) chunks = 3; year += chunks; days -= chunks * DaysPerYear; } return {year, days}; } std::pair<int, int> ExtractMonth(int days, int year) { int month = 1; for (int daysInMonth = DateTime::DaysInMonth(month, year); days >= daysInMonth; daysInMonth = DateTime::DaysInMonth(month, year)) { ++month; days -= daysInMonth; } return {month, days}; } DateTime::DateTime( int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond, int ticks) { if (InRange(year, 1, 9999) && InRange(day, 1, DaysInMonth(month, year)) && InRange(hour, 0, 23) && InRange(minute, 0, 59) && InRange(second, 0, 59) && InRange(millisecond, 0, 999) && InRange(microsecond, 0, 999) && InRange(ticks, 0, 9)) { int64_t days = day - 1; for (int i = 1; i < month; ++i) days += DaysInMonth(i, year); --year; days += (year * DaysPerYear) + (year / 4) - (year / 100) + (year / 400); _ticks = days * TicksPerDay + hour * TicksPerHour + minute * TicksPerMinute + second * TicksPerSecond + millisecond * TicksPerMillisecond + microsecond * TicksPerMicrosecond + ticks; } else { _ticks = 0; } } int DateTime::Year() const { int days = _ticks / TicksPerDay; return ExtractYears(days).first; } int DateTime::Month() const { int days = _ticks / TicksPerDay; auto y = ExtractYears(days); return ExtractMonth(y.second, y.first).first; } int DateTime::Day() const { int64_t days = _ticks / TicksPerDay; auto y = ExtractYears(days); auto m = ExtractMonth(y.second, y.first); return m.second + 1; } DateTime& DateTime::operator+=(TimeSpan timeSpan) { _ticks = SafeTicks(_ticks += timeSpan.Ticks()); return *this; } DateTime& DateTime::operator-=(TimeSpan timeSpan) { _ticks = SafeTicks(_ticks -= timeSpan.Ticks()); return *this; } int DateTime::DaysInMonth(int month, int year) { if (InRange(month, 1, 12)) { if (month == 2 && IsLeapYear(year)) return 29; return DaysInMonths[month]; } return 0; } const char* DateTime::DayToString(int dayOfWeek) { const char* DayNames[7] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; return InRange(dayOfWeek, 0, 6) ? DayNames[dayOfWeek] : nullptr; } static DateTime GetDateTime(const tm& timeInfo) { return DateTime( timeInfo.tm_year + 1900, timeInfo.tm_mon + 1, timeInfo.tm_mday, timeInfo.tm_hour, timeInfo.tm_min, Min(timeInfo.tm_sec, 59)); // Can exceed 59! :( // http://www.cplusplus.com/reference/clibrary/ctime/tm/ } DateTime DateTime::LocalTime() { time_t rawTime; time(&rawTime); return GetDateTime(*localtime(&rawTime)); } DateTime DateTime::UtcTime() { time_t rawTime; time(&rawTime); return GetDateTime(*gmtime(&rawTime)); } } <|endoftext|>
<commit_before> #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "WebAdmin.h" #include "StringMap.h" #include "WebPlugin.h" #include "PluginManager.h" #include "Plugin.h" #include "World.h" #include "Entities/Player.h" #include "Server.h" #include "Root.h" #include "HTTPServer/HTTPMessage.h" #include "HTTPServer/HTTPConnection.h" /// Helper class - appends all player names together in a HTML list class cPlayerAccum : public cPlayerListCallback { virtual bool Item(cPlayer * a_Player) override { m_Contents.append("<li>"); m_Contents.append(a_Player->GetName()); m_Contents.append("</li>"); return false; } public: AString m_Contents; } ; cWebAdmin::cWebAdmin(void) : m_IsInitialized(false), m_TemplateScript("<webadmin_template>"), m_IniFile("webadmin.ini") { } cWebAdmin::~cWebAdmin() { if (m_IsInitialized) { LOG("Stopping WebAdmin..."); } } void cWebAdmin::AddPlugin( cWebPlugin * a_Plugin ) { m_Plugins.remove( a_Plugin ); m_Plugins.push_back( a_Plugin ); } void cWebAdmin::RemovePlugin( cWebPlugin * a_Plugin ) { m_Plugins.remove( a_Plugin ); } bool cWebAdmin::Init(void) { if (!m_IniFile.ReadFile()) { return false; } LOG("Initialising WebAdmin..."); if (!m_IniFile.GetValueSetB("WebAdmin", "Enabled", true)) { // WebAdmin is disabled, bail out faking a success return true; } AString PortsIPv4 = m_IniFile.GetValueSet("WebAdmin", "Port", "8080"); AString PortsIPv6 = m_IniFile.GetValueSet("WebAdmin", "PortsIPv6", ""); if (!m_HTTPServer.Initialize(PortsIPv4, PortsIPv6)) { return false; } m_IsInitialized = true; return true; } bool cWebAdmin::Start(void) { if (!m_IsInitialized) { // Not initialized return false; } LOG("Starting WebAdmin..."); // Initialize the WebAdmin template script and load the file m_TemplateScript.Create(); if (!m_TemplateScript.LoadFile(FILE_IO_PREFIX "webadmin/template.lua")) { LOGWARN("Could not load WebAdmin template \"%s\", using default template.", FILE_IO_PREFIX "webadmin/template.lua"); m_TemplateScript.Close(); } return m_HTTPServer.Start(*this); } AString cWebAdmin::GetTemplate() { AString retVal = ""; char SourceFile[] = "webadmin/template.html"; cFile f; if (!f.Open(SourceFile, cFile::fmRead)) { return ""; } // copy the file into the buffer: f.ReadRestOfFile(retVal); return retVal; } void cWebAdmin::HandleWebadminRequest(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) { if (!a_Request.HasAuth()) { a_Connection.SendNeedAuth("MCServer WebAdmin"); return; } // Check auth: AString UserPassword = m_IniFile.GetValue("User:" + a_Request.GetAuthUsername(), "Password", ""); if ((UserPassword == "") || (a_Request.GetAuthPassword() != UserPassword)) { a_Connection.SendNeedAuth("MCServer WebAdmin - bad username or password"); return; } // Check if the contents should be wrapped in the template: AString URL = a_Request.GetBareURL(); ASSERT(URL.length() > 0); bool ShouldWrapInTemplate = ((URL.length() > 1) && (URL[1] != '~')); // Retrieve the request data: cWebadminRequestData * Data = (cWebadminRequestData *)(a_Request.GetUserData()); if (Data == NULL) { a_Connection.SendStatusAndReason(500, "Bad UserData"); return; } // Wrap it all up for the Lua call: AString Template; HTTPTemplateRequest TemplateRequest; TemplateRequest.Request.Username = a_Request.GetAuthUsername(); TemplateRequest.Request.Method = a_Request.GetMethod(); TemplateRequest.Request.Path = URL.substr(1); if (Data->m_Form.Finish()) { for (cHTTPFormParser::const_iterator itr = Data->m_Form.begin(), end = Data->m_Form.end(); itr != end; ++itr) { HTTPFormData HTTPfd; HTTPfd.Value = itr->second; HTTPfd.Type = ""; HTTPfd.Name = itr->first; TemplateRequest.Request.FormData[itr->first] = HTTPfd; TemplateRequest.Request.PostParams[itr->first] = itr->second; } // for itr - Data->m_Form[] // Parse the URL into individual params: size_t idxQM = a_Request.GetURL().find('?'); if (idxQM != AString::npos) { cHTTPFormParser URLParams(cHTTPFormParser::fpkURL, a_Request.GetURL().c_str() + idxQM + 1, a_Request.GetURL().length() - idxQM - 1, *Data); URLParams.Finish(); for (cHTTPFormParser::const_iterator itr = URLParams.begin(), end = URLParams.end(); itr != end; ++itr) { TemplateRequest.Request.Params[itr->first] = itr->second; } // for itr - URLParams[] } } // Try to get the template from the Lua template script if (ShouldWrapInTemplate) { if (m_TemplateScript.Call("ShowPage", this, &TemplateRequest, cLuaState::Return, Template)) { cHTTPResponse Resp; Resp.SetContentType("text/html"); a_Connection.Send(Resp); a_Connection.Send(Template.c_str(), Template.length()); return; } a_Connection.SendStatusAndReason(500, "m_TemplateScript failed"); return; } AString BaseURL = GetBaseURL(URL); AString Menu; Template = "{CONTENT}"; AString FoundPlugin; for (PluginList::iterator itr = m_Plugins.begin(); itr != m_Plugins.end(); ++itr) { cWebPlugin * WebPlugin = *itr; std::list< std::pair<AString, AString> > NameList = WebPlugin->GetTabNames(); for (std::list< std::pair<AString, AString> >::iterator Names = NameList.begin(); Names != NameList.end(); ++Names) { Menu += "<li><a href='" + BaseURL + WebPlugin->GetWebTitle().c_str() + "/" + (*Names).second + "'>" + (*Names).first + "</a></li>"; } } sWebAdminPage Page = GetPage(TemplateRequest.Request); AString Content = Page.Content; FoundPlugin = Page.PluginName; if (!Page.TabName.empty()) { FoundPlugin += " - " + Page.TabName; } if (FoundPlugin.empty()) // Default page { Content = GetDefaultPage(); } if (ShouldWrapInTemplate && (URL.size() > 1)) { Content += "\n<p><a href='" + BaseURL + "'>Go back</a></p>"; } int MemUsageKiB = GetMemoryUsage(); if (MemUsageKiB > 0) { ReplaceString(Template, "{MEM}", Printf("%.02f", (double)MemUsageKiB / 1024)); ReplaceString(Template, "{MEMKIB}", Printf("%d", MemUsageKiB)); } else { ReplaceString(Template, "{MEM}", "unknown"); ReplaceString(Template, "{MEMKIB}", "unknown"); } ReplaceString(Template, "{USERNAME}", a_Request.GetAuthUsername()); ReplaceString(Template, "{MENU}", Menu); ReplaceString(Template, "{PLUGIN_NAME}", FoundPlugin); ReplaceString(Template, "{CONTENT}", Content); ReplaceString(Template, "{TITLE}", "MCServer"); AString NumChunks; Printf(NumChunks, "%d", cRoot::Get()->GetTotalChunkCount()); ReplaceString(Template, "{NUMCHUNKS}", NumChunks); cHTTPResponse Resp; Resp.SetContentType("text/html"); a_Connection.Send(Resp); a_Connection.Send(Template.c_str(), Template.length()); } void cWebAdmin::HandleRootRequest(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) { static const char LoginForm[] = \ "<h1>MCServer WebAdmin</h1>" \ "<center>" \ "<form method='get' action='webadmin/'>" \ "<input type='submit' value='Log in'>" \ "</form>" \ "</center>"; cHTTPResponse Resp; Resp.SetContentType("text/html"); a_Connection.Send(Resp); a_Connection.Send(LoginForm, sizeof(LoginForm) - 1); a_Connection.FinishResponse(); } sWebAdminPage cWebAdmin::GetPage(const HTTPRequest & a_Request) { sWebAdminPage Page; AStringVector Split = StringSplit(a_Request.Path, "/"); // Find the plugin that corresponds to the requested path AString FoundPlugin; if (Split.size() > 1) { for (PluginList::iterator itr = m_Plugins.begin(); itr != m_Plugins.end(); ++itr) { if ((*itr)->GetWebTitle() == Split[1]) { Page.Content = (*itr)->HandleWebRequest(&a_Request); cWebPlugin * WebPlugin = *itr; FoundPlugin = WebPlugin->GetWebTitle(); AString TabName = WebPlugin->GetTabNameForRequest(&a_Request).first; Page.PluginName = FoundPlugin; Page.TabName = TabName; break; } } } // Return the page contents return Page; } AString cWebAdmin::GetDefaultPage(void) { AString Content; Content += "<h4>Server Name:</h4>"; Content += "<p>" + AString( cRoot::Get()->GetServer()->GetServerID() ) + "</p>"; Content += "<h4>Plugins:</h4><ul>"; cPluginManager * PM = cPluginManager::Get(); const cPluginManager::PluginMap & List = PM->GetAllPlugins(); for (cPluginManager::PluginMap::const_iterator itr = List.begin(); itr != List.end(); ++itr) { if (itr->second == NULL) { continue; } AString VersionNum; AppendPrintf(Content, "<li>%s V.%i</li>", itr->second->GetName().c_str(), itr->second->GetVersion()); } Content += "</ul>"; Content += "<h4>Players:</h4><ul>"; cPlayerAccum PlayerAccum; cWorld * World = cRoot::Get()->GetDefaultWorld(); // TODO - Create a list of worlds and players if( World != NULL ) { World->ForEachPlayer(PlayerAccum); Content.append(PlayerAccum.m_Contents); } Content += "</ul><br>"; return Content; } AString cWebAdmin::GetBaseURL( const AString& a_URL ) { return GetBaseURL(StringSplit(a_URL, "/")); } AString cWebAdmin::GetHTMLEscapedString( const AString& a_Input ) { // Define a stringstream to write the output to. std::stringstream dst; // Loop over input and substitute HTML characters for their alternatives. for (int i = 0; i < a_Input.length(); i++) { switch ( a_Input[i] ) { case '&': dst << "&amp;"; break; case '\'': dst << "&apos;"; break; case '"': dst << "&quot;"; break; case '<': dst << "&lt;"; break; case '>': dst << "&gt;"; break; default: dst << a_Input[i]; break; } } return dst.str(); } AString cWebAdmin::GetBaseURL( const AStringVector& a_URLSplit ) { AString BaseURL = "./"; if (a_URLSplit.size() > 1) { for (unsigned int i = 0; i < a_URLSplit.size(); i++) { BaseURL += "../"; } BaseURL += "webadmin/"; } return BaseURL; } int cWebAdmin::GetMemoryUsage(void) { LOGWARNING("%s: This function is obsolete, use cRoot::GetPhysicalRAMUsage() or cRoot::GetVirtualRAMUsage() instead", __FUNCTION__); return cRoot::GetPhysicalRAMUsage(); } void cWebAdmin::OnRequestBegun(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) { const AString & URL = a_Request.GetURL(); if ( (strncmp(URL.c_str(), "/webadmin", 9) == 0) || (strncmp(URL.c_str(), "/~webadmin", 10) == 0) ) { a_Request.SetUserData(new cWebadminRequestData(a_Request)); return; } if (URL == "/") { // The root needs no body handler and is fully handled in the OnRequestFinished() call return; } // TODO: Handle other requests } void cWebAdmin::OnRequestBody(cHTTPConnection & a_Connection, cHTTPRequest & a_Request, const char * a_Data, int a_Size) { cRequestData * Data = (cRequestData *)(a_Request.GetUserData()); if (Data == NULL) { return; } Data->OnBody(a_Data, a_Size); } void cWebAdmin::OnRequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) { const AString & URL = a_Request.GetURL(); if ( (strncmp(URL.c_str(), "/webadmin", 9) == 0) || (strncmp(URL.c_str(), "/~webadmin", 10) == 0) ) { HandleWebadminRequest(a_Connection, a_Request); } else if (URL == "/") { // The root needs no body handler and is fully handled in the OnRequestFinished() call HandleRootRequest(a_Connection, a_Request); } else { // TODO: Handle other requests } // Delete any request data assigned to the request: cRequestData * Data = (cRequestData *)(a_Request.GetUserData()); delete Data; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cWebAdmin::cWebadminRequestData void cWebAdmin::cWebadminRequestData::OnBody(const char * a_Data, int a_Size) { m_Form.Parse(a_Data, a_Size); } <commit_msg>Changed the code according to xoft's suggestions.<commit_after> #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "WebAdmin.h" #include "StringMap.h" #include "WebPlugin.h" #include "PluginManager.h" #include "Plugin.h" #include "World.h" #include "Entities/Player.h" #include "Server.h" #include "Root.h" #include "HTTPServer/HTTPMessage.h" #include "HTTPServer/HTTPConnection.h" /// Helper class - appends all player names together in a HTML list class cPlayerAccum : public cPlayerListCallback { virtual bool Item(cPlayer * a_Player) override { m_Contents.append("<li>"); m_Contents.append(a_Player->GetName()); m_Contents.append("</li>"); return false; } public: AString m_Contents; } ; cWebAdmin::cWebAdmin(void) : m_IsInitialized(false), m_TemplateScript("<webadmin_template>"), m_IniFile("webadmin.ini") { } cWebAdmin::~cWebAdmin() { if (m_IsInitialized) { LOG("Stopping WebAdmin..."); } } void cWebAdmin::AddPlugin( cWebPlugin * a_Plugin ) { m_Plugins.remove( a_Plugin ); m_Plugins.push_back( a_Plugin ); } void cWebAdmin::RemovePlugin( cWebPlugin * a_Plugin ) { m_Plugins.remove( a_Plugin ); } bool cWebAdmin::Init(void) { if (!m_IniFile.ReadFile()) { return false; } LOG("Initialising WebAdmin..."); if (!m_IniFile.GetValueSetB("WebAdmin", "Enabled", true)) { // WebAdmin is disabled, bail out faking a success return true; } AString PortsIPv4 = m_IniFile.GetValueSet("WebAdmin", "Port", "8080"); AString PortsIPv6 = m_IniFile.GetValueSet("WebAdmin", "PortsIPv6", ""); if (!m_HTTPServer.Initialize(PortsIPv4, PortsIPv6)) { return false; } m_IsInitialized = true; return true; } bool cWebAdmin::Start(void) { if (!m_IsInitialized) { // Not initialized return false; } LOG("Starting WebAdmin..."); // Initialize the WebAdmin template script and load the file m_TemplateScript.Create(); if (!m_TemplateScript.LoadFile(FILE_IO_PREFIX "webadmin/template.lua")) { LOGWARN("Could not load WebAdmin template \"%s\", using default template.", FILE_IO_PREFIX "webadmin/template.lua"); m_TemplateScript.Close(); } return m_HTTPServer.Start(*this); } AString cWebAdmin::GetTemplate() { AString retVal = ""; char SourceFile[] = "webadmin/template.html"; cFile f; if (!f.Open(SourceFile, cFile::fmRead)) { return ""; } // copy the file into the buffer: f.ReadRestOfFile(retVal); return retVal; } void cWebAdmin::HandleWebadminRequest(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) { if (!a_Request.HasAuth()) { a_Connection.SendNeedAuth("MCServer WebAdmin"); return; } // Check auth: AString UserPassword = m_IniFile.GetValue("User:" + a_Request.GetAuthUsername(), "Password", ""); if ((UserPassword == "") || (a_Request.GetAuthPassword() != UserPassword)) { a_Connection.SendNeedAuth("MCServer WebAdmin - bad username or password"); return; } // Check if the contents should be wrapped in the template: AString URL = a_Request.GetBareURL(); ASSERT(URL.length() > 0); bool ShouldWrapInTemplate = ((URL.length() > 1) && (URL[1] != '~')); // Retrieve the request data: cWebadminRequestData * Data = (cWebadminRequestData *)(a_Request.GetUserData()); if (Data == NULL) { a_Connection.SendStatusAndReason(500, "Bad UserData"); return; } // Wrap it all up for the Lua call: AString Template; HTTPTemplateRequest TemplateRequest; TemplateRequest.Request.Username = a_Request.GetAuthUsername(); TemplateRequest.Request.Method = a_Request.GetMethod(); TemplateRequest.Request.Path = URL.substr(1); if (Data->m_Form.Finish()) { for (cHTTPFormParser::const_iterator itr = Data->m_Form.begin(), end = Data->m_Form.end(); itr != end; ++itr) { HTTPFormData HTTPfd; HTTPfd.Value = itr->second; HTTPfd.Type = ""; HTTPfd.Name = itr->first; TemplateRequest.Request.FormData[itr->first] = HTTPfd; TemplateRequest.Request.PostParams[itr->first] = itr->second; } // for itr - Data->m_Form[] // Parse the URL into individual params: size_t idxQM = a_Request.GetURL().find('?'); if (idxQM != AString::npos) { cHTTPFormParser URLParams(cHTTPFormParser::fpkURL, a_Request.GetURL().c_str() + idxQM + 1, a_Request.GetURL().length() - idxQM - 1, *Data); URLParams.Finish(); for (cHTTPFormParser::const_iterator itr = URLParams.begin(), end = URLParams.end(); itr != end; ++itr) { TemplateRequest.Request.Params[itr->first] = itr->second; } // for itr - URLParams[] } } // Try to get the template from the Lua template script if (ShouldWrapInTemplate) { if (m_TemplateScript.Call("ShowPage", this, &TemplateRequest, cLuaState::Return, Template)) { cHTTPResponse Resp; Resp.SetContentType("text/html"); a_Connection.Send(Resp); a_Connection.Send(Template.c_str(), Template.length()); return; } a_Connection.SendStatusAndReason(500, "m_TemplateScript failed"); return; } AString BaseURL = GetBaseURL(URL); AString Menu; Template = "{CONTENT}"; AString FoundPlugin; for (PluginList::iterator itr = m_Plugins.begin(); itr != m_Plugins.end(); ++itr) { cWebPlugin * WebPlugin = *itr; std::list< std::pair<AString, AString> > NameList = WebPlugin->GetTabNames(); for (std::list< std::pair<AString, AString> >::iterator Names = NameList.begin(); Names != NameList.end(); ++Names) { Menu += "<li><a href='" + BaseURL + WebPlugin->GetWebTitle().c_str() + "/" + (*Names).second + "'>" + (*Names).first + "</a></li>"; } } sWebAdminPage Page = GetPage(TemplateRequest.Request); AString Content = Page.Content; FoundPlugin = Page.PluginName; if (!Page.TabName.empty()) { FoundPlugin += " - " + Page.TabName; } if (FoundPlugin.empty()) // Default page { Content = GetDefaultPage(); } if (ShouldWrapInTemplate && (URL.size() > 1)) { Content += "\n<p><a href='" + BaseURL + "'>Go back</a></p>"; } int MemUsageKiB = GetMemoryUsage(); if (MemUsageKiB > 0) { ReplaceString(Template, "{MEM}", Printf("%.02f", (double)MemUsageKiB / 1024)); ReplaceString(Template, "{MEMKIB}", Printf("%d", MemUsageKiB)); } else { ReplaceString(Template, "{MEM}", "unknown"); ReplaceString(Template, "{MEMKIB}", "unknown"); } ReplaceString(Template, "{USERNAME}", a_Request.GetAuthUsername()); ReplaceString(Template, "{MENU}", Menu); ReplaceString(Template, "{PLUGIN_NAME}", FoundPlugin); ReplaceString(Template, "{CONTENT}", Content); ReplaceString(Template, "{TITLE}", "MCServer"); AString NumChunks; Printf(NumChunks, "%d", cRoot::Get()->GetTotalChunkCount()); ReplaceString(Template, "{NUMCHUNKS}", NumChunks); cHTTPResponse Resp; Resp.SetContentType("text/html"); a_Connection.Send(Resp); a_Connection.Send(Template.c_str(), Template.length()); } void cWebAdmin::HandleRootRequest(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) { static const char LoginForm[] = \ "<h1>MCServer WebAdmin</h1>" \ "<center>" \ "<form method='get' action='webadmin/'>" \ "<input type='submit' value='Log in'>" \ "</form>" \ "</center>"; cHTTPResponse Resp; Resp.SetContentType("text/html"); a_Connection.Send(Resp); a_Connection.Send(LoginForm, sizeof(LoginForm) - 1); a_Connection.FinishResponse(); } sWebAdminPage cWebAdmin::GetPage(const HTTPRequest & a_Request) { sWebAdminPage Page; AStringVector Split = StringSplit(a_Request.Path, "/"); // Find the plugin that corresponds to the requested path AString FoundPlugin; if (Split.size() > 1) { for (PluginList::iterator itr = m_Plugins.begin(); itr != m_Plugins.end(); ++itr) { if ((*itr)->GetWebTitle() == Split[1]) { Page.Content = (*itr)->HandleWebRequest(&a_Request); cWebPlugin * WebPlugin = *itr; FoundPlugin = WebPlugin->GetWebTitle(); AString TabName = WebPlugin->GetTabNameForRequest(&a_Request).first; Page.PluginName = FoundPlugin; Page.TabName = TabName; break; } } } // Return the page contents return Page; } AString cWebAdmin::GetDefaultPage(void) { AString Content; Content += "<h4>Server Name:</h4>"; Content += "<p>" + AString( cRoot::Get()->GetServer()->GetServerID() ) + "</p>"; Content += "<h4>Plugins:</h4><ul>"; cPluginManager * PM = cPluginManager::Get(); const cPluginManager::PluginMap & List = PM->GetAllPlugins(); for (cPluginManager::PluginMap::const_iterator itr = List.begin(); itr != List.end(); ++itr) { if (itr->second == NULL) { continue; } AString VersionNum; AppendPrintf(Content, "<li>%s V.%i</li>", itr->second->GetName().c_str(), itr->second->GetVersion()); } Content += "</ul>"; Content += "<h4>Players:</h4><ul>"; cPlayerAccum PlayerAccum; cWorld * World = cRoot::Get()->GetDefaultWorld(); // TODO - Create a list of worlds and players if( World != NULL ) { World->ForEachPlayer(PlayerAccum); Content.append(PlayerAccum.m_Contents); } Content += "</ul><br>"; return Content; } AString cWebAdmin::GetBaseURL( const AString& a_URL ) { return GetBaseURL(StringSplit(a_URL, "/")); } AString cWebAdmin::GetHTMLEscapedString( const AString& a_Input ) { // Define a string to write the output to. AString dst = ""; // Loop over input and substitute HTML characters for their alternatives. for (size_t i = 0; i < a_Input.length(); i++) { switch ( a_Input[i] ) { case '&': dst =+ "&amp;"; break; case '\'': dst =+ "&apos;"; break; case '"': dst =+ "&quot;"; break; case '<': dst =+ "&lt;"; break; case '>': dst =+ "&gt;"; break; default: dst =+ a_Input[i]; break; } } return dst(); } AString cWebAdmin::GetBaseURL( const AStringVector& a_URLSplit ) { AString BaseURL = "./"; if (a_URLSplit.size() > 1) { for (unsigned int i = 0; i < a_URLSplit.size(); i++) { BaseURL += "../"; } BaseURL += "webadmin/"; } return BaseURL; } int cWebAdmin::GetMemoryUsage(void) { LOGWARNING("%s: This function is obsolete, use cRoot::GetPhysicalRAMUsage() or cRoot::GetVirtualRAMUsage() instead", __FUNCTION__); return cRoot::GetPhysicalRAMUsage(); } void cWebAdmin::OnRequestBegun(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) { const AString & URL = a_Request.GetURL(); if ( (strncmp(URL.c_str(), "/webadmin", 9) == 0) || (strncmp(URL.c_str(), "/~webadmin", 10) == 0) ) { a_Request.SetUserData(new cWebadminRequestData(a_Request)); return; } if (URL == "/") { // The root needs no body handler and is fully handled in the OnRequestFinished() call return; } // TODO: Handle other requests } void cWebAdmin::OnRequestBody(cHTTPConnection & a_Connection, cHTTPRequest & a_Request, const char * a_Data, int a_Size) { cRequestData * Data = (cRequestData *)(a_Request.GetUserData()); if (Data == NULL) { return; } Data->OnBody(a_Data, a_Size); } void cWebAdmin::OnRequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) { const AString & URL = a_Request.GetURL(); if ( (strncmp(URL.c_str(), "/webadmin", 9) == 0) || (strncmp(URL.c_str(), "/~webadmin", 10) == 0) ) { HandleWebadminRequest(a_Connection, a_Request); } else if (URL == "/") { // The root needs no body handler and is fully handled in the OnRequestFinished() call HandleRootRequest(a_Connection, a_Request); } else { // TODO: Handle other requests } // Delete any request data assigned to the request: cRequestData * Data = (cRequestData *)(a_Request.GetUserData()); delete Data; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cWebAdmin::cWebadminRequestData void cWebAdmin::cWebadminRequestData::OnBody(const char * a_Data, int a_Size) { m_Form.Parse(a_Data, a_Size); } <|endoftext|>
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. #include "mfem.hpp" #include "catch.hpp" #include <iostream> #include <cmath> using namespace mfem; /** * Utility function to generate IntegerationPoints, based on param ip * that are outside the unit interval. Results are placed in output * parameter arr. */ void GetRelatedIntegrationPoints(const IntegrationPoint& ip, int dim, Array<IntegrationPoint>& arr) { IntegrationPoint pt = ip; int idx = 0; switch (dim) { case 1: arr.SetSize(3); pt.x = ip.x; arr[idx++] = pt; pt.x = -ip.x; arr[idx++] = pt; pt.x = 1+ip.x; arr[idx++] = pt; break; case 2: arr.SetSize(7); pt.Set2( ip.x, ip.y); arr[idx++] = pt; pt.Set2( -ip.x, ip.y); arr[idx++] = pt; pt.Set2( ip.x, -ip.y); arr[idx++] = pt; pt.Set2( -ip.x, -ip.y); arr[idx++] = pt; pt.Set2(1+ip.x, ip.y); arr[idx++] = pt; pt.Set2( ip.x, 1+ip.y); arr[idx++] = pt; pt.Set2(1+ip.x, 1+ip.y); arr[idx++] = pt; break; case 3: arr.SetSize(15); pt.Set3( ip.x, ip.y, ip.z ); arr[idx++] = pt; pt.Set3( -ip.x, ip.y, ip.z ); arr[idx++] = pt; pt.Set3( ip.x, -ip.y, ip.z ); arr[idx++] = pt; pt.Set3( -ip.x, -ip.y, ip.z ); arr[idx++] = pt; pt.Set3( ip.x, ip.y, -ip.z ); arr[idx++] = pt; pt.Set3( -ip.x, ip.y, -ip.z ); arr[idx++] = pt; pt.Set3( ip.x, -ip.y, -ip.z ); arr[idx++] = pt; pt.Set3( -ip.x, -ip.y, -ip.z ); arr[idx++] = pt; pt.Set3(1+ip.x, ip.y, ip.z ); arr[idx++] = pt; pt.Set3( ip.x, 1+ip.y, ip.z ); arr[idx++] = pt; pt.Set3(1+ip.x, 1+ip.y, ip.z ); arr[idx++] = pt; pt.Set3( ip.x, ip.y, 1+ip.z ); arr[idx++] = pt; pt.Set3(1+ip.x, ip.y, 1+ip.z ); arr[idx++] = pt; pt.Set3( ip.x, 1+ip.y, 1+ip.z ); arr[idx++] = pt; pt.Set3(1+ip.x, 1+ip.y, 1+ip.z ); arr[idx++] = pt; break; } } /** * Tests fe->CalcShape() over a grid of IntegrationPoints * of resolution res. Also tests at integration poins * that are outside the element. */ void TestCalcShape(FiniteElement* fe, int res) { int dim = fe->GetDim(); Vector weights( fe->GetDof() ); // Get a uniform grid or integration points RefinedGeometry* ref = GlobGeometryRefiner.Refine( fe->GetGeomType(), res); const IntegrationRule& intRule = ref->RefPts; int npoints = intRule.GetNPoints(); for (int i=0; i < npoints; ++i) { // Get the current integration point from intRule IntegrationPoint pt = intRule.IntPoint(i); // Get several variants of this integration point // some of which are inside the element and some are outside Array<IntegrationPoint> ipArr; GetRelatedIntegrationPoints( pt, dim, ipArr ); // For each such integration point check that the weights // from CalcShape() sum to one for (int j=0; j < ipArr.Size(); ++j) { IntegrationPoint& ip = ipArr[j]; fe->CalcShape(ip, weights); REQUIRE( weights.Sum() == Approx(1.) ); } } } TEST_CASE("CalcShape for several Lagrange FiniteElement instances", "[Lagrange1DFiniteElement]" "[BiLinear2DFiniteElement]" "[BiQuad2DFiniteElement]" "[LagrangeHexFiniteElement]") { int maxOrder = 5; int resolution = 10; SECTION("Lagrange1DFiniteElement") { for (int order =1; order <= maxOrder; ++order) { std::cout << "Testing Lagrange1DFiniteElement::CalcShape() " << "for order " << order << std::endl; Lagrange1DFiniteElement fe(order); TestCalcShape(&fe, resolution); } } SECTION("BiLinear2DFiniteElement") { std::cout << "Testing BiLinear2DFiniteElement::CalcShape()" << std::endl; BiLinear2DFiniteElement fe; TestCalcShape(&fe, resolution); } SECTION("BiQuad2DFiniteElement") { std::cout << "Testing BiQuad2DFiniteElement::CalcShape()" << std::endl; BiQuad2DFiniteElement fe; TestCalcShape(&fe, resolution); } SECTION("LagrangeHexFiniteElement") { std::cout << "Testing LagrangeHexFiniteElement::CalcShape() " << "for order 2" << std::endl; // Comments for LagrangeHexFiniteElement state // that only degree 2 is functional for this class LagrangeHexFiniteElement fe(2); TestCalcShape(&fe, resolution); } } TEST_CASE("CalcShape for several H1 FiniteElement instances", "[H1_SegmentElement]" "[H1_QuadrilateralElement]" "[H1_HexahedronElement]") { int maxOrder = 5; int resolution = 10; SECTION("H1_SegmentElement") { for (int order =1; order <= maxOrder; ++order) { std::cout << "Testing H1_SegmentElement::CalcShape() " << "for order " << order << std::endl; H1_SegmentElement fe(order); TestCalcShape(&fe, resolution); } } SECTION("H1_QuadrilateralElement") { for (int order =1; order <= maxOrder; ++order) { std::cout << "Testing H1_QuadrilateralElement::CalcShape() " << "for order " << order << std::endl; H1_QuadrilateralElement fe(order); TestCalcShape(&fe, resolution); } } SECTION("H1_HexahedronElement") { for (int order =1; order <= maxOrder; ++order) { std::cout << "Testing H1_HexahedronElement::CalcShape() " << "for order " << order << std::endl; H1_HexahedronElement fe(order); TestCalcShape(&fe, resolution); } } } <commit_msg>Adding more element types to test_calcshape<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. #include "mfem.hpp" #include "catch.hpp" #include <iostream> #include <cmath> using namespace mfem; /** * Utility function to generate IntegerationPoints, based on param ip * that are outside the unit interval. Results are placed in output * parameter arr. */ void GetRelatedIntegrationPoints(const IntegrationPoint& ip, int dim, Array<IntegrationPoint>& arr) { IntegrationPoint pt = ip; int idx = 0; switch (dim) { case 1: arr.SetSize(3); pt.x = ip.x; arr[idx++] = pt; pt.x = -ip.x; arr[idx++] = pt; pt.x = 1+ip.x; arr[idx++] = pt; break; case 2: arr.SetSize(7); pt.Set2( ip.x, ip.y); arr[idx++] = pt; pt.Set2( -ip.x, ip.y); arr[idx++] = pt; pt.Set2( ip.x, -ip.y); arr[idx++] = pt; pt.Set2( -ip.x, -ip.y); arr[idx++] = pt; pt.Set2(1+ip.x, ip.y); arr[idx++] = pt; pt.Set2( ip.x, 1+ip.y); arr[idx++] = pt; pt.Set2(1+ip.x, 1+ip.y); arr[idx++] = pt; break; case 3: arr.SetSize(15); pt.Set3( ip.x, ip.y, ip.z ); arr[idx++] = pt; pt.Set3( -ip.x, ip.y, ip.z ); arr[idx++] = pt; pt.Set3( ip.x, -ip.y, ip.z ); arr[idx++] = pt; pt.Set3( -ip.x, -ip.y, ip.z ); arr[idx++] = pt; pt.Set3( ip.x, ip.y, -ip.z ); arr[idx++] = pt; pt.Set3( -ip.x, ip.y, -ip.z ); arr[idx++] = pt; pt.Set3( ip.x, -ip.y, -ip.z ); arr[idx++] = pt; pt.Set3( -ip.x, -ip.y, -ip.z ); arr[idx++] = pt; pt.Set3(1+ip.x, ip.y, ip.z ); arr[idx++] = pt; pt.Set3( ip.x, 1+ip.y, ip.z ); arr[idx++] = pt; pt.Set3(1+ip.x, 1+ip.y, ip.z ); arr[idx++] = pt; pt.Set3( ip.x, ip.y, 1+ip.z ); arr[idx++] = pt; pt.Set3(1+ip.x, ip.y, 1+ip.z ); arr[idx++] = pt; pt.Set3( ip.x, 1+ip.y, 1+ip.z ); arr[idx++] = pt; pt.Set3(1+ip.x, 1+ip.y, 1+ip.z ); arr[idx++] = pt; break; } } /** * Tests fe->CalcShape() over a grid of IntegrationPoints * of resolution res. Also tests at integration poins * that are outside the element. */ void TestCalcShape(FiniteElement* fe, int res) { int dim = fe->GetDim(); Vector weights( fe->GetDof() ); // Get a uniform grid or integration points RefinedGeometry* ref = GlobGeometryRefiner.Refine( fe->GetGeomType(), res); const IntegrationRule& intRule = ref->RefPts; int npoints = intRule.GetNPoints(); for (int i=0; i < npoints; ++i) { // Get the current integration point from intRule IntegrationPoint pt = intRule.IntPoint(i); // Get several variants of this integration point // some of which are inside the element and some are outside Array<IntegrationPoint> ipArr; GetRelatedIntegrationPoints( pt, dim, ipArr ); // For each such integration point check that the weights // from CalcShape() sum to one for (int j=0; j < ipArr.Size(); ++j) { IntegrationPoint& ip = ipArr[j]; fe->CalcShape(ip, weights); REQUIRE( weights.Sum() == Approx(1.) ); } } } TEST_CASE("CalcShape for several Lagrange FiniteElement instances", "[Lagrange1DFiniteElement]" "[BiLinear2DFiniteElement]" "[BiQuad2DFiniteElement]" "[LagrangeHexFiniteElement]") { int maxOrder = 5; int resolution = 10; SECTION("Lagrange1DFiniteElement") { for (int order =1; order <= maxOrder; ++order) { std::cout << "Testing Lagrange1DFiniteElement::CalcShape() " << "for order " << order << std::endl; Lagrange1DFiniteElement fe(order); TestCalcShape(&fe, resolution); } } SECTION("BiLinear2DFiniteElement") { std::cout << "Testing BiLinear2DFiniteElement::CalcShape()" << std::endl; BiLinear2DFiniteElement fe; TestCalcShape(&fe, resolution); } SECTION("BiQuad2DFiniteElement") { std::cout << "Testing BiQuad2DFiniteElement::CalcShape()" << std::endl; BiQuad2DFiniteElement fe; TestCalcShape(&fe, resolution); } SECTION("LagrangeHexFiniteElement") { std::cout << "Testing LagrangeHexFiniteElement::CalcShape() " << "for order 2" << std::endl; // Comments for LagrangeHexFiniteElement state // that only degree 2 is functional for this class LagrangeHexFiniteElement fe(2); TestCalcShape(&fe, resolution); } } TEST_CASE("CalcShape for several H1 FiniteElement instances", "[H1_SegmentElement]" "[H1_TriangleElement]" "[H1_QuadrilateralElement]" "[H1_TetrahedronElement]" "[H1_HexahedronElement]" "[H1_WedgeElement]") { int maxOrder = 5; int resolution = 10; SECTION("H1_SegmentElement") { for (int order =1; order <= maxOrder; ++order) { std::cout << "Testing H1_SegmentElement::CalcShape() " << "for order " << order << std::endl; H1_SegmentElement fe(order); TestCalcShape(&fe, resolution); } } SECTION("H1_TriangleElement") { for (int order =1; order <= maxOrder; ++order) { std::cout << "Testing H1_TriangleElement::CalcShape() " << "for order " << order << std::endl; H1_TriangleElement fe(order); TestCalcShape(&fe, resolution); } } SECTION("H1_QuadrilateralElement") { for (int order =1; order <= maxOrder; ++order) { std::cout << "Testing H1_QuadrilateralElement::CalcShape() " << "for order " << order << std::endl; H1_QuadrilateralElement fe(order); TestCalcShape(&fe, resolution); } } SECTION("H1_TetrahedronElement") { for (int order =1; order <= maxOrder; ++order) { std::cout << "Testing H1_TetrahedronElement::CalcShape() " << "for order " << order << std::endl; H1_TetrahedronElement fe(order); TestCalcShape(&fe, resolution); } } SECTION("H1_HexahedronElement") { for (int order =1; order <= maxOrder; ++order) { std::cout << "Testing H1_HexahedronElement::CalcShape() " << "for order " << order << std::endl; H1_HexahedronElement fe(order); TestCalcShape(&fe, resolution); } } SECTION("H1_WedgeElement") { for (int order =1; order <= maxOrder; ++order) { std::cout << "Testing H1_WedgeElement::CalcShape() " << "for order " << order << std::endl; H1_WedgeElement fe(order); TestCalcShape(&fe, resolution); } } } <|endoftext|>
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "catch.hpp" #include "mfem.hpp" #include <fstream> #include <iostream> #include "../../../fem/libceed/ceed.hpp" using namespace mfem; namespace ceed_test { double coeff_function(const Vector &x) { return 1 + x[0]*x[0]; } void test_assembly_level(Mesh &&mesh, int order, const CeedCoeff coeff_type, const int pb, const AssemblyLevel assembly) { mesh.EnsureNodes(); int dim = mesh.Dimension(); H1_FECollection fec(order, dim); FiniteElementSpace fespace(&mesh, &fec); BilinearForm k_test(&fespace); BilinearForm k_ref(&fespace); GridFunction gf(&fespace); FunctionCoefficient f_coeff(coeff_function); Coefficient *coeff = nullptr; switch (coeff_type) { case CeedCoeff::Const: coeff = new ConstantCoefficient(1.0); break; case CeedCoeff::Grid: gf.ProjectCoefficient(f_coeff); coeff = new GridFunctionCoefficient(&gf); break; case CeedCoeff::Quad: coeff = &f_coeff; break; default: mfem_error("Unexpected coefficient type."); break; } if (pb==0) // Mass { k_ref.AddDomainIntegrator(new MassIntegrator(*coeff)); k_test.AddDomainIntegrator(new MassIntegrator(*coeff)); } else if (pb==2) // Diffusion { k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff)); k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff)); } k_ref.Assemble(); k_ref.Finalize(); k_test.SetAssemblyLevel(assembly); k_test.Assemble(); GridFunction x(&fespace), y_ref(&fespace), y_test(&fespace); x.Randomize(1); k_ref.Mult(x,y_ref); k_test.Mult(x,y_test); y_test -= y_ref; REQUIRE(y_test.Norml2() < 1.e-12); } TEST_CASE("CEED", "[CEED]") { Device device("ceed-cpu"); SECTION("Continuous Galerkin") { const bool dg = false; SECTION("2D") { for (CeedCoeff coeff_type : {CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad}) { for (AssemblyLevel assembly : {AssemblyLevel::PARTIAL}) { for (int pb : {0, 2}) { for (int order : {2, 3, 4}) { test_assembly_level(Mesh("../../data/inline-quad.mesh", 1, 1), order, coeff_type, pb, assembly); // test_assembly_level(Mesh("../../data/periodic-hexagon.mesh", 1, 1), // order, coeff_type, pb, assembly); test_assembly_level(Mesh("../../data/star-q3.mesh", 1, 1), order, coeff_type, pb, assembly); } } } } } SECTION("3D") { for (CeedCoeff coeff_type : {CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad}) { for (AssemblyLevel assembly : {AssemblyLevel::PARTIAL}) { for (int pb : {0, 2}) { int order = 2; test_assembly_level(Mesh("../../data/inline-hex.mesh", 1, 1), order, coeff_type, pb, assembly); test_assembly_level(Mesh("../../data/fichera-q3.mesh", 1, 1), order, coeff_type, pb, assembly); } } } } SECTION("AMR 2D") { for (CeedCoeff coeff_type : {CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad}) { for (AssemblyLevel assembly : {AssemblyLevel::PARTIAL}) { for (int pb : {0, 2}) { for (int order : {2, 3, 4}) { test_assembly_level(Mesh("../../data/amr-quad.mesh", 1, 1), order, coeff_type, 0, assembly); } } } } } SECTION("AMR 3D") { for (CeedCoeff coeff_type : {CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad}) { for (AssemblyLevel assembly : {AssemblyLevel::PARTIAL}) { for (int pb : {0, 2}) { int order = 2; test_assembly_level(Mesh("../../data/fichera-amr.mesh", 1, 1), order, coeff_type, 0, assembly); } } } } } } // test case } // namespace ceed_test <commit_msg>Remove test_ceed<commit_after><|endoftext|>
<commit_before>// bslstl_referencewrapper.t.cpp -*-C++-*- #include <bslstl_referencewrapper.h> #include <bsls_bsltestutil.h> #include <iostream> #include <stdio.h> #include <stdlib.h> // ============================================================================ // TEST PLAN // ---------------------------------------------------------------------------- // Overview // -------- // The component under test is fully specified by the standard, verifiable by // inspection. Therefore, testing only exercises basic uses to ensure template // specializations may be instantiated successfully. // // ---------------------------------------------------------------------------- // TESTING INSTANTIATIONS AND BASIC FUNCTIONALITY // [ 1] reference_wrapper(T&); // [ 1] reference_wrapper(const reference_wrapper<T>&) // [ 1] reference_wrapper<T>& operator=(reference_wrapper<T>&); // [ 1] operator T&() const; // [ 1] T& get() const; // [ 1] reference_wrapper<T> cref(const T&) // [ 1] reference_wrapper<T> cref(reference_wrapper<T>) // [ 1] reference_wrapper<T> ref(T&) // [ 1] reference_wrapper<T> ref(reference_wrapper<T>) // ---------------------------------------------------------------------------- // [ 1] BASIC TESTS // [ 2] USAGE EXAMPLE // ============================================================================ // STANDARD BSL ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool condition, const char *message, int line) { if (condition) { printf("Error " __FILE__ "(%d): %s (failed)\n", line, message); if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace // ============================================================================ // STANDARD BSL TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLS_BSLTESTUTIL_ASSERT #define ASSERTV BSLS_BSLTESTUTIL_ASSERTV #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 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 // ============================================================================ // GLOBAL TEST VALUES // ---------------------------------------------------------------------------- static bool verbose; static bool veryVerbose; static bool veryVeryVerbose; static bool veryVeryVeryVerbose; // ============================================================================ // GLOBAL TYPEDEFS/CONSTANTS FOR TESTING // ---------------------------------------------------------------------------- // ============================================================================ // TEST FACILITIES // ---------------------------------------------------------------------------- struct dummy {}; void use(dummy&) {} void const_use(const dummy&) {} // these functions are used solely to verify that a 'reference_wrapper' can // be passed to a function expecting an actual reference. // ============================================================================ // USAGE EXAMPLE CLASSES AND FUNCTIONS // ---------------------------------------------------------------------------- namespace TEST_CASE_USAGE { ///Usage ///----- // This section illustrates intended use of this component. // ///Example 1: Sorted References /// - - - - - - - - - - - - - - // Let us suppose that we wish to handle objects that will be passed to a // comparison function expecting references to the objects. Let us suppose // further that these objects are large enough that we would not wish to move // them around bodily as they are sorted. Note that plausible examples of uses // for this component are limited in freestanding C++98. // // First, let us define the large-object type: //.. struct Canary { int d_values[1000]; explicit Canary(int values); }; //.. Canary::Canary(int values) { for (int i = 0; i < 1000; ++i) { d_values[i] = values; } } //.. // Next, we define the comparison function: //.. bool operator<(Canary const& a, Canary const& b) { return a.d_values[0] < b.d_values[0]; } //.. // Finally, we define a generic function to sort two items: //.. template <typename T> void sortTwoItems(T& a, T& b) { if (b < a) { T tmp(a); a = b; b = tmp; } } //.. } // close namespace TEST_CASE_USAGE // ============================================================================ // 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 2: { // -------------------------------------------------------------------- // USAGE EXAMPLE // Extracted from bslstl_referencewrapper.h // // Concerns: //: 1 The example in the header builds and runs as claimed. // // Plan: //: 1 Reformat the comment to runnable code, as prescribed. // // Testing: // USAGE EXAMPLE // // -------------------------------------------------------------------- if (verbose) { printf("\nUSAGE EXAMPLE" "\n=============\n"); } using namespace TEST_CASE_USAGE; //.. // We can call 'sortTwoItems' on wrappers representing 'Canary' objects // without need to move actual, large 'Canary' objects about. In the // call to 'sortTwoItems()', below, the 'operator=' used in it is that // of 'bsl::reference_wrapper<Canary>', but the 'operator<' used is the // one declared for 'Canary&' arguments. All of the conversions needed // are applied implicitly. //.. Canary two(2); Canary one(1); bsl::reference_wrapper<Canary> canaryA = bsl::ref(two); bsl::reference_wrapper<Canary> canaryB = bsl::ref(one); sortTwoItems(canaryA, canaryB); ASSERT(&canaryA.get() == &one); ASSERT(&canaryB.get() == &two); //.. } break; case 1: { // -------------------------------------------------------------------- // BASIC TESTS // Create objects each possible way, verify they have the right // contents and can be used in the standard ways. // // Concerns: //: 1 Template functions defined are only checked by the compiler when //: called, so all templates must be instantiated here. //: //: 2 The various functions' argument must be copied into the object //: correctly. //: //: 3 The accessors must reproduce the various functions' argument //: values. // // Plan: //: 1 Define a dummy type (C-1..3) //: 2 Wrap the dummy type using each available method (C-1..3) //: 3 Use the wrappers' explicit and implicit accessors (C-1..3) // // Testing: // reference_wrapper(T&); // reference_wrapper(consts reference_wrapper<T>&) // reference_wrapper<T>& operator=(reference_wrapper<T>&); // operator T&() const; // T& get() const; // reference_wrapper<T> cref(const T&) // reference_wrapper<T> cref(reference_wrapper<T>) // reference_wrapper<T> ref(T&) // reference_wrapper<T> ref(reference_wrapper<T>) // -------------------------------------------------------------------- if (verbose) { printf("\nBASIC TESTS" "\n===========\n"); } dummy a; const dummy b = {}; bsl::reference_wrapper<dummy> rwa(a); bsl::reference_wrapper<const dummy> rwca(a); bsl::reference_wrapper<const dummy> rwcb(b); bsl::reference_wrapper<dummy> copyrwa(rwa); bsl::reference_wrapper<const dummy> copyrwca(rwca); bsl::reference_wrapper<const dummy> copyrwcb(rwcb); copyrwa = a; copyrwca = a; copyrwcb = b; copyrwa = rwa; copyrwca = rwca; copyrwcb = rwcb; dummy& rax = rwa; const dummy& rcax = rwca; const dummy& rcbx = rwcb; dummy& ray = bsl::ref(a); const dummy& rcay = bsl::cref(a); const dummy& rcby = bsl::cref(b); bsl::reference_wrapper<dummy> copyrwaz(bsl::ref(rwa)); bsl::reference_wrapper<const dummy> copyrwcaz(bsl::ref(rwca)); bsl::reference_wrapper<const dummy> copyrwcbz(bsl::ref(rwcb)); bsl::reference_wrapper<const dummy> copyrwcazb(bsl::cref(rwca)); bsl::reference_wrapper<const dummy> copyrwcbzc(bsl::cref(rwcb)); use(rwa); const_use(rwca); const_use(rwcb); dummy c; bsl::reference_wrapper<dummy> assrwaz(bsl::ref(rwa)); assrwaz = a; assrwaz = c; assrwaz = rwa; bsl::reference_wrapper<const dummy> assrwcaz(bsl::ref(rwca)); assrwcaz = b; assrwcaz = c; assrwcaz = rwca; assrwcaz = rwcb; ASSERT(&copyrwa.get() == &a); ASSERT(&copyrwca.get() == &a); ASSERT(&copyrwcb.get() == &b); ASSERT(&copyrwaz.get() == &a); ASSERT(&copyrwcaz.get() == &a); ASSERT(&copyrwcbz.get() == &b); (void)rax; (void)rcax; (void)rcbx; (void)ray; (void)rcay; (void)rcby; (void)copyrwcazb; (void)copyrwcbzc; } 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 2013 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>typos<commit_after>// bslstl_referencewrapper.t.cpp -*-C++-*- #include <bslstl_referencewrapper.h> #include <bsls_bsltestutil.h> #include <iostream> #include <stdio.h> #include <stdlib.h> // ============================================================================ // TEST PLAN // ---------------------------------------------------------------------------- // Overview // -------- // The component under test is fully specified by the standard, verifiable by // inspection. Therefore, testing only exercises basic uses to ensure template // specializations may be instantiated successfully. // // ---------------------------------------------------------------------------- // TESTING INSTANTIATIONS AND BASIC FUNCTIONALITY // [ 1] reference_wrapper(T&); // [ 1] reference_wrapper(const reference_wrapper<T>&) // [ 1] reference_wrapper<T>& operator=(reference_wrapper<T>&) // [ 1] operator T&() const; // [ 1] T& get() const; // [ 1] reference_wrapper<T> cref(const T&) // [ 1] reference_wrapper<T> cref(reference_wrapper<T>) // [ 1] reference_wrapper<T> ref(T&) // [ 1] reference_wrapper<T> ref(reference_wrapper<T>) // ---------------------------------------------------------------------------- // [ 1] BASIC TESTS // [ 2] USAGE EXAMPLE // ============================================================================ // STANDARD BSL ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool condition, const char *message, int line) { if (condition) { printf("Error " __FILE__ "(%d): %s (failed)\n", line, message); if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace // ============================================================================ // STANDARD BSL TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLS_BSLTESTUTIL_ASSERT #define ASSERTV BSLS_BSLTESTUTIL_ASSERTV #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 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 // ============================================================================ // GLOBAL TEST VALUES // ---------------------------------------------------------------------------- static bool verbose; static bool veryVerbose; static bool veryVeryVerbose; static bool veryVeryVeryVerbose; // ============================================================================ // GLOBAL TYPEDEFS/CONSTANTS FOR TESTING // ---------------------------------------------------------------------------- // ============================================================================ // TEST FACILITIES // ---------------------------------------------------------------------------- struct dummy {}; void use(dummy&) {} void const_use(const dummy&) {} // these functions are used solely to verify that a 'reference_wrapper' can // be passed to a function expecting an actual reference. // ============================================================================ // USAGE EXAMPLE CLASSES AND FUNCTIONS // ---------------------------------------------------------------------------- namespace TEST_CASE_USAGE { ///Usage ///----- // This section illustrates intended use of this component. // ///Example 1: Sorted References /// - - - - - - - - - - - - - - // Let us suppose that we wish to handle objects that will be passed to a // comparison function expecting references to the objects. Let us suppose // further that these objects are large enough that we would not wish to move // them around bodily as they are sorted. Note that plausible examples of uses // for this component are limited in freestanding C++98. // // First, let us define the large-object type: //.. struct Canary { int d_values[1000]; explicit Canary(int values); }; //.. Canary::Canary(int values) { for (int i = 0; i < 1000; ++i) { d_values[i] = values; } } //.. // Next, we define the comparison function: //.. bool operator<(Canary const& a, Canary const& b) { return a.d_values[0] < b.d_values[0]; } //.. // Finally, we define a generic function to sort two items: //.. template <typename T> void sortTwoItems(T& a, T& b) { if (b < a) { T tmp(a); a = b; b = tmp; } } //.. } // close namespace TEST_CASE_USAGE // ============================================================================ // 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 2: { // -------------------------------------------------------------------- // USAGE EXAMPLE // Extracted from bslstl_referencewrapper.h // // Concerns: //: 1 The example in the header builds and runs as claimed. // // Plan: //: 1 Reformat the comment to runnable code, as prescribed. // // Testing: // USAGE EXAMPLE // // -------------------------------------------------------------------- if (verbose) { printf("\nUSAGE EXAMPLE" "\n=============\n"); } using namespace TEST_CASE_USAGE; //.. // We can call 'sortTwoItems' on wrappers representing 'Canary' objects // without need to move actual, large 'Canary' objects about. In the // call to 'sortTwoItems()', below, the 'operator=' used in it is that // of 'bsl::reference_wrapper<Canary>', but the 'operator<' used is the // one declared for 'Canary&' arguments. All of the conversions needed // are applied implicitly. //.. Canary two(2); Canary one(1); bsl::reference_wrapper<Canary> canaryA = bsl::ref(two); bsl::reference_wrapper<Canary> canaryB = bsl::ref(one); sortTwoItems(canaryA, canaryB); ASSERT(&canaryA.get() == &one); ASSERT(&canaryB.get() == &two); //.. } break; case 1: { // -------------------------------------------------------------------- // BASIC TESTS // Create objects each possible way, verify they have the right // contents and can be used in the standard ways. // // Concerns: //: 1 Template functions defined are only checked by the compiler when //: called, so all templates must be instantiated here. //: //: 2 The various functions' argument must be copied into the object //: correctly. //: //: 3 The accessors must reproduce the various functions' argument //: values. // // Plan: //: 1 Define a dummy type (C-1..3) //: 2 Wrap the dummy type using each available method (C-1..3) //: 3 Use the wrappers' explicit and implicit accessors (C-1..3) // // Testing: // reference_wrapper(T&) // reference_wrapper(const reference_wrapper<T>&) // reference_wrapper<T>& operator=(reference_wrapper<T>&) // operator T&() const // T& get() const // reference_wrapper<T> cref(const T&) // reference_wrapper<T> cref(reference_wrapper<T>) // reference_wrapper<T> ref(T&) // reference_wrapper<T> ref(reference_wrapper<T>) // -------------------------------------------------------------------- if (verbose) { printf("\nBASIC TESTS" "\n===========\n"); } dummy a; const dummy b = {}; bsl::reference_wrapper<dummy> rwa(a); bsl::reference_wrapper<const dummy> rwca(a); bsl::reference_wrapper<const dummy> rwcb(b); bsl::reference_wrapper<dummy> copyrwa(rwa); bsl::reference_wrapper<const dummy> copyrwca(rwca); bsl::reference_wrapper<const dummy> copyrwcb(rwcb); copyrwa = a; copyrwca = a; copyrwcb = b; copyrwa = rwa; copyrwca = rwca; copyrwcb = rwcb; dummy& rax = rwa; const dummy& rcax = rwca; const dummy& rcbx = rwcb; dummy& ray = bsl::ref(a); const dummy& rcay = bsl::cref(a); const dummy& rcby = bsl::cref(b); bsl::reference_wrapper<dummy> copyrwaz(bsl::ref(rwa)); bsl::reference_wrapper<const dummy> copyrwcaz(bsl::ref(rwca)); bsl::reference_wrapper<const dummy> copyrwcbz(bsl::ref(rwcb)); bsl::reference_wrapper<const dummy> copyrwcazb(bsl::cref(rwca)); bsl::reference_wrapper<const dummy> copyrwcbzc(bsl::cref(rwcb)); use(rwa); const_use(rwca); const_use(rwcb); dummy c; bsl::reference_wrapper<dummy> assrwaz(bsl::ref(rwa)); assrwaz = a; assrwaz = c; assrwaz = rwa; bsl::reference_wrapper<const dummy> assrwcaz(bsl::ref(rwca)); assrwcaz = b; assrwcaz = c; assrwcaz = rwca; assrwcaz = rwcb; ASSERT(&copyrwa.get() == &a); ASSERT(&copyrwca.get() == &a); ASSERT(&copyrwcb.get() == &b); ASSERT(&copyrwaz.get() == &a); ASSERT(&copyrwcaz.get() == &a); ASSERT(&copyrwcbz.get() == &b); (void)rax; (void)rcax; (void)rcbx; (void)ray; (void)rcay; (void)rcby; (void)copyrwcazb; (void)copyrwcbzc; } 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 2013 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>/* * The main source of the Beng proxy server. * * author: Max Kellermann <mk@cm4all.com> */ #include "tpool.h" #include "direct.h" #include "lb_instance.hxx" #include "lb_setup.hxx" #include "lb_connection.hxx" #include "tcp_stock.hxx" #include "tcp_balancer.hxx" #include "hstock.hxx" #include "stock.hxx" #include "failure.hxx" #include "bulldog.h" #include "balancer.hxx" #include "pipe_stock.hxx" #include "log-glue.h" #include "lb_config.hxx" #include "lb_hmonitor.hxx" #include "ssl_init.hxx" #include "child_manager.hxx" #include "thread_pool.hxx" #include "fb_pool.hxx" #include "capabilities.hxx" #include "isolate.hxx" #include "util/Error.hxx" #include <daemon/log.h> #include <daemon/daemonize.h> #include <assert.h> #include <unistd.h> #include <sys/signal.h> #include <sys/wait.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <pthread.h> #ifdef __linux #include <sys/prctl.h> #ifndef PR_SET_NO_NEW_PRIVS #define PR_SET_NO_NEW_PRIVS 38 #endif #endif #include <event.h> static constexpr cap_value_t cap_keep_list[1] = { /* keep the NET_RAW capability to be able to to use the socket option IP_TRANSPARENT */ CAP_NET_RAW, }; static constexpr struct timeval launch_worker_now = { 0, 10000, }; static constexpr struct timeval launch_worker_delayed = { 10, 0, }; static bool is_watchdog; static pid_t worker_pid; static struct event launch_worker_event; static void worker_callback(int status, void *ctx) { struct lb_instance *instance = (struct lb_instance *)ctx; int exit_status = WEXITSTATUS(status); if (WIFSIGNALED(status)) fprintf(stderr, "worker %d died from signal %d%s\n", worker_pid, WTERMSIG(status), WCOREDUMP(status) ? " (core dumped)" : ""); else if (exit_status == 0) fprintf(stderr, "worker %d exited with success\n", worker_pid); else fprintf(stderr, "worker %d exited with status %d\n", worker_pid, exit_status); worker_pid = 0; if (!instance->should_exit) evtimer_add(&launch_worker_event, &launch_worker_delayed); } static void launch_worker_callback(int fd gcc_unused, short event gcc_unused, void *ctx) { assert(is_watchdog); assert(worker_pid <= 0); struct lb_instance *instance = (struct lb_instance *)ctx; /* in libevent 2.0.16, it is necessary to re-add all EV_SIGNAL events after forking; this bug is not present in 1.4.13 and 2.0.19 */ deinit_signals(instance); children_event_del(); worker_pid = fork(); if (worker_pid < 0) { fprintf(stderr, "Failed to fork: %s\n", strerror(errno)); init_signals(instance); children_event_add(); evtimer_add(&launch_worker_event, &launch_worker_delayed); return; } if (worker_pid == 0) { event_reinit(instance->event_base); init_signals(instance); children_init(); all_listeners_event_add(instance); enable_all_controls(instance); /* run monitors only in the worker process */ lb_hmonitor_enable(); return; } init_signals(instance); children_event_add(); child_register(worker_pid, "worker", worker_callback, instance); } static void shutdown_callback(void *ctx) { struct lb_instance *instance = (struct lb_instance *)ctx; if (instance->should_exit) return; instance->should_exit = true; deinit_signals(instance); thread_pool_stop(); if (is_watchdog && worker_pid > 0) kill(worker_pid, SIGTERM); children_shutdown(); thread_pool_join(); thread_pool_deinit(); if (is_watchdog) evtimer_del(&launch_worker_event); deinit_all_controls(instance); while (!instance->connections.empty()) lb_connection_close(&instance->connections.front()); deinit_all_listeners(instance); lb_hmonitor_deinit(); pool_commit(); if (instance->tcp_stock != nullptr) hstock_free(instance->tcp_stock); if (instance->balancer != nullptr) balancer_free(instance->balancer); if (instance->pipe_stock != nullptr) stock_free(instance->pipe_stock); fb_pool_disable(); pool_commit(); } static void reload_event_callback(int fd gcc_unused, short event gcc_unused, void *ctx) { struct lb_instance *instance = (struct lb_instance *)ctx; daemonize_reopen_logfile(); unsigned n_ssl_sessions = instance->FlushSSLSessionCache(LONG_MAX); daemon_log(3, "flushed %u SSL sessions\n", n_ssl_sessions); fb_pool_compress(); } void init_signals(struct lb_instance *instance) { signal(SIGPIPE, SIG_IGN); shutdown_listener_init(&instance->shutdown_listener, shutdown_callback, instance); event_set(&instance->sighup_event, SIGHUP, EV_SIGNAL|EV_PERSIST, reload_event_callback, instance); event_add(&instance->sighup_event, nullptr); } void deinit_signals(struct lb_instance *instance) { shutdown_listener_deinit(&instance->shutdown_listener); event_del(&instance->sighup_event); } int main(int argc, char **argv) { Error error2; int ret; int gcc_unused ref; struct lb_instance instance; #ifdef HAVE_OLD_GTHREAD /* deprecated in GLib 2.32 */ g_thread_init(nullptr); #endif instance.pool = pool_new_libc(nullptr, "global"); tpool_init(instance.pool); /* configuration */ parse_cmdline(&instance.cmdline, instance.pool, argc, argv); GError *error = nullptr; instance.config = lb_config_load(instance.pool, instance.cmdline.config_path, &error); if (instance.config == nullptr) { fprintf(stderr, "%s\n", error->message); g_error_free(error); return EXIT_FAILURE; } if (instance.cmdline.check) return EXIT_SUCCESS; /* initialize */ lb_hmonitor_init(instance.pool); ssl_global_init(); direct_global_init(); instance.event_base = event_init(); fb_pool_init(true); init_signals(&instance); /* reduce glibc's thread cancellation overhead */ pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, nullptr); children_init(); instance.balancer = balancer_new(*instance.pool); instance.tcp_stock = tcp_stock_new(instance.pool, instance.cmdline.tcp_stock_limit); instance.tcp_balancer = tcp_balancer_new(instance.pool, instance.tcp_stock, instance.balancer); instance.pipe_stock = pipe_stock_new(instance.pool); failure_init(); bulldog_init(instance.cmdline.bulldog_path); if (!init_all_controls(&instance, &error)) { fprintf(stderr, "%s\n", error->message); g_error_free(error); return EXIT_FAILURE; } if (!init_all_listeners(instance, error2)) { deinit_all_controls(&instance); fprintf(stderr, "%s\n", error2.GetMessage()); return EXIT_FAILURE; } /* daemonize */ ret = daemonize(); if (ret < 0) exit(2); /* launch the access logger */ if (!log_global_init(instance.cmdline.access_logger)) return EXIT_FAILURE; /* daemonize II */ if (daemon_user_defined(&instance.cmdline.user)) capabilities_pre_setuid(); if (daemon_user_set(&instance.cmdline.user) < 0) return EXIT_FAILURE; isolate_from_filesystem(); if (daemon_user_defined(&instance.cmdline.user)) capabilities_post_setuid(cap_keep_list, G_N_ELEMENTS(cap_keep_list)); #ifdef __linux prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); #endif /* main loop */ if (instance.cmdline.watchdog) { /* watchdog */ all_listeners_event_del(&instance); is_watchdog = true; evtimer_set(&launch_worker_event, launch_worker_callback, &instance); evtimer_add(&launch_worker_event, &launch_worker_now); } else { /* this is already the worker process: enable monitors here */ lb_hmonitor_enable(); } event_dispatch(); /* cleanup */ children_shutdown(); log_global_deinit(); bulldog_deinit(); failure_deinit(); deinit_all_listeners(&instance); deinit_all_controls(&instance); fb_pool_deinit(); event_base_free(instance.event_base); tpool_deinit(); delete instance.config; ref = pool_unref(instance.pool); assert(ref == 0); pool_commit(); pool_recycler_clear(); ssl_global_deinit(); daemonize_cleanup(); direct_global_deinit(); } <commit_msg>lb_main: make variables more local<commit_after>/* * The main source of the Beng proxy server. * * author: Max Kellermann <mk@cm4all.com> */ #include "tpool.h" #include "direct.h" #include "lb_instance.hxx" #include "lb_setup.hxx" #include "lb_connection.hxx" #include "tcp_stock.hxx" #include "tcp_balancer.hxx" #include "hstock.hxx" #include "stock.hxx" #include "failure.hxx" #include "bulldog.h" #include "balancer.hxx" #include "pipe_stock.hxx" #include "log-glue.h" #include "lb_config.hxx" #include "lb_hmonitor.hxx" #include "ssl_init.hxx" #include "child_manager.hxx" #include "thread_pool.hxx" #include "fb_pool.hxx" #include "capabilities.hxx" #include "isolate.hxx" #include "util/Error.hxx" #include <daemon/log.h> #include <daemon/daemonize.h> #include <assert.h> #include <unistd.h> #include <sys/signal.h> #include <sys/wait.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <pthread.h> #ifdef __linux #include <sys/prctl.h> #ifndef PR_SET_NO_NEW_PRIVS #define PR_SET_NO_NEW_PRIVS 38 #endif #endif #include <event.h> static constexpr cap_value_t cap_keep_list[1] = { /* keep the NET_RAW capability to be able to to use the socket option IP_TRANSPARENT */ CAP_NET_RAW, }; static constexpr struct timeval launch_worker_now = { 0, 10000, }; static constexpr struct timeval launch_worker_delayed = { 10, 0, }; static bool is_watchdog; static pid_t worker_pid; static struct event launch_worker_event; static void worker_callback(int status, void *ctx) { struct lb_instance *instance = (struct lb_instance *)ctx; int exit_status = WEXITSTATUS(status); if (WIFSIGNALED(status)) fprintf(stderr, "worker %d died from signal %d%s\n", worker_pid, WTERMSIG(status), WCOREDUMP(status) ? " (core dumped)" : ""); else if (exit_status == 0) fprintf(stderr, "worker %d exited with success\n", worker_pid); else fprintf(stderr, "worker %d exited with status %d\n", worker_pid, exit_status); worker_pid = 0; if (!instance->should_exit) evtimer_add(&launch_worker_event, &launch_worker_delayed); } static void launch_worker_callback(int fd gcc_unused, short event gcc_unused, void *ctx) { assert(is_watchdog); assert(worker_pid <= 0); struct lb_instance *instance = (struct lb_instance *)ctx; /* in libevent 2.0.16, it is necessary to re-add all EV_SIGNAL events after forking; this bug is not present in 1.4.13 and 2.0.19 */ deinit_signals(instance); children_event_del(); worker_pid = fork(); if (worker_pid < 0) { fprintf(stderr, "Failed to fork: %s\n", strerror(errno)); init_signals(instance); children_event_add(); evtimer_add(&launch_worker_event, &launch_worker_delayed); return; } if (worker_pid == 0) { event_reinit(instance->event_base); init_signals(instance); children_init(); all_listeners_event_add(instance); enable_all_controls(instance); /* run monitors only in the worker process */ lb_hmonitor_enable(); return; } init_signals(instance); children_event_add(); child_register(worker_pid, "worker", worker_callback, instance); } static void shutdown_callback(void *ctx) { struct lb_instance *instance = (struct lb_instance *)ctx; if (instance->should_exit) return; instance->should_exit = true; deinit_signals(instance); thread_pool_stop(); if (is_watchdog && worker_pid > 0) kill(worker_pid, SIGTERM); children_shutdown(); thread_pool_join(); thread_pool_deinit(); if (is_watchdog) evtimer_del(&launch_worker_event); deinit_all_controls(instance); while (!instance->connections.empty()) lb_connection_close(&instance->connections.front()); deinit_all_listeners(instance); lb_hmonitor_deinit(); pool_commit(); if (instance->tcp_stock != nullptr) hstock_free(instance->tcp_stock); if (instance->balancer != nullptr) balancer_free(instance->balancer); if (instance->pipe_stock != nullptr) stock_free(instance->pipe_stock); fb_pool_disable(); pool_commit(); } static void reload_event_callback(int fd gcc_unused, short event gcc_unused, void *ctx) { struct lb_instance *instance = (struct lb_instance *)ctx; daemonize_reopen_logfile(); unsigned n_ssl_sessions = instance->FlushSSLSessionCache(LONG_MAX); daemon_log(3, "flushed %u SSL sessions\n", n_ssl_sessions); fb_pool_compress(); } void init_signals(struct lb_instance *instance) { signal(SIGPIPE, SIG_IGN); shutdown_listener_init(&instance->shutdown_listener, shutdown_callback, instance); event_set(&instance->sighup_event, SIGHUP, EV_SIGNAL|EV_PERSIST, reload_event_callback, instance); event_add(&instance->sighup_event, nullptr); } void deinit_signals(struct lb_instance *instance) { shutdown_listener_deinit(&instance->shutdown_listener); event_del(&instance->sighup_event); } int main(int argc, char **argv) { struct lb_instance instance; #ifdef HAVE_OLD_GTHREAD /* deprecated in GLib 2.32 */ g_thread_init(nullptr); #endif instance.pool = pool_new_libc(nullptr, "global"); tpool_init(instance.pool); /* configuration */ parse_cmdline(&instance.cmdline, instance.pool, argc, argv); GError *error = nullptr; instance.config = lb_config_load(instance.pool, instance.cmdline.config_path, &error); if (instance.config == nullptr) { fprintf(stderr, "%s\n", error->message); g_error_free(error); return EXIT_FAILURE; } if (instance.cmdline.check) return EXIT_SUCCESS; /* initialize */ lb_hmonitor_init(instance.pool); ssl_global_init(); direct_global_init(); instance.event_base = event_init(); fb_pool_init(true); init_signals(&instance); /* reduce glibc's thread cancellation overhead */ pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, nullptr); children_init(); instance.balancer = balancer_new(*instance.pool); instance.tcp_stock = tcp_stock_new(instance.pool, instance.cmdline.tcp_stock_limit); instance.tcp_balancer = tcp_balancer_new(instance.pool, instance.tcp_stock, instance.balancer); instance.pipe_stock = pipe_stock_new(instance.pool); failure_init(); bulldog_init(instance.cmdline.bulldog_path); if (!init_all_controls(&instance, &error)) { fprintf(stderr, "%s\n", error->message); g_error_free(error); return EXIT_FAILURE; } { Error error2; if (!init_all_listeners(instance, error2)) { deinit_all_controls(&instance); fprintf(stderr, "%s\n", error2.GetMessage()); return EXIT_FAILURE; } } /* daemonize */ if (daemonize() < 0) exit(2); /* launch the access logger */ if (!log_global_init(instance.cmdline.access_logger)) return EXIT_FAILURE; /* daemonize II */ if (daemon_user_defined(&instance.cmdline.user)) capabilities_pre_setuid(); if (daemon_user_set(&instance.cmdline.user) < 0) return EXIT_FAILURE; isolate_from_filesystem(); if (daemon_user_defined(&instance.cmdline.user)) capabilities_post_setuid(cap_keep_list, G_N_ELEMENTS(cap_keep_list)); #ifdef __linux prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); #endif /* main loop */ if (instance.cmdline.watchdog) { /* watchdog */ all_listeners_event_del(&instance); is_watchdog = true; evtimer_set(&launch_worker_event, launch_worker_callback, &instance); evtimer_add(&launch_worker_event, &launch_worker_now); } else { /* this is already the worker process: enable monitors here */ lb_hmonitor_enable(); } event_dispatch(); /* cleanup */ children_shutdown(); log_global_deinit(); bulldog_deinit(); failure_deinit(); deinit_all_listeners(&instance); deinit_all_controls(&instance); fb_pool_deinit(); event_base_free(instance.event_base); tpool_deinit(); delete instance.config; gcc_unused int ref = pool_unref(instance.pool); assert(ref == 0); pool_commit(); pool_recycler_clear(); ssl_global_deinit(); daemonize_cleanup(); direct_global_deinit(); } <|endoftext|>
<commit_before>#include <mtp/metadata/Metadata.h> #ifdef HAVE_TAGLIB # include <fileref.h> # include <tag.h> #endif namespace mtp { #ifdef HAVE_TAGLIB MetadataPtr Metadata::Read(const std::string & path) { TagLib::FileRef f(path.c_str()); auto tag = f.tag(); if (f.isNull() || !tag) return nullptr; auto meta = std::make_shared<Metadata>(); meta->Title = tag->title().to8Bit(true); meta->Artist = tag->artist().to8Bit(true); meta->Album = tag->album().to8Bit(true); meta->Genre = tag->genre().to8Bit(true); meta->Year = tag->year(); meta->Track = tag->track(); return meta; } #else MetadataPtr Metadata::Read(const std::string & path) { return nullptr; } #endif } <commit_msg>prefer album() ALBUMARTIST, ALBUM ARTIST or MUSICBRAINZ_ALBUMARTIST<commit_after>#include <mtp/metadata/Metadata.h> #ifdef HAVE_TAGLIB # include <fileref.h> # include <tag.h> # include <tpropertymap.h> #endif namespace mtp { #ifdef HAVE_TAGLIB MetadataPtr Metadata::Read(const std::string & path) { TagLib::FileRef f(path.c_str()); auto tag = f.tag(); if (f.isNull() || !tag) return nullptr; auto meta = std::make_shared<Metadata>(); auto artist = tag->artist(); const auto & props = tag->properties(); auto album_it = props.find("ALBUMARTIST"); if (album_it == props.end()) album_it = props.find("ALBUM ARTIST"); if (album_it == props.end()) album_it = props.find("MUSICBRAINZ_ALBUMARTIST"); if (album_it != props.end()) artist = album_it->second.toString(); meta->Title = tag->title().to8Bit(true); meta->Artist = artist.to8Bit(true); meta->Album = tag->album().to8Bit(true); meta->Genre = tag->genre().to8Bit(true); meta->Year = tag->year(); meta->Track = tag->track(); return meta; } #else MetadataPtr Metadata::Read(const std::string & path) { return nullptr; } #endif } <|endoftext|>
<commit_before>// // Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // UnfoldShortCircuitToIf is an AST traverser to convert short-circuiting operators to if-else statements. // The results are assigned to s# temporaries, which are used by the main translator instead of // the original expression. // #include "compiler/translator/UnfoldShortCircuitToIf.h" #include "compiler/translator/InfoSink.h" #include "compiler/translator/IntermNode.h" namespace { // Traverser that unfolds one short-circuiting operation at a time. class UnfoldShortCircuitTraverser : public TIntermTraverser { public: UnfoldShortCircuitTraverser(); void traverse(TIntermNode *node); bool visitBinary(Visit visit, TIntermBinary *node) override; bool visitAggregate(Visit visit, TIntermAggregate *node) override; bool visitSelection(Visit visit, TIntermSelection *node) override; void nextIteration(); bool foundShortCircuit() const { return mFoundShortCircuit; } protected: int mTemporaryIndex; // Marked to true once an operation that needs to be unfolded has been found. // After that, no more unfolding is performed on that traversal. bool mFoundShortCircuit; struct ParentBlock { ParentBlock(TIntermAggregate *_node, TIntermSequence::size_type _pos) : node(_node), pos(_pos) { } TIntermAggregate *node; TIntermSequence::size_type pos; }; std::vector<ParentBlock> mParentBlockStack; TIntermSymbol *createTempSymbol(const TType &type); TIntermAggregate *createTempInitDeclaration(const TType &type, TIntermTyped *initializer); TIntermBinary *createTempAssignment(const TType &type, TIntermTyped *rightNode); }; UnfoldShortCircuitTraverser::UnfoldShortCircuitTraverser() : TIntermTraverser(true, true, true), mTemporaryIndex(0), mFoundShortCircuit(false) { } TIntermSymbol *UnfoldShortCircuitTraverser::createTempSymbol(const TType &type) { // Each traversal uses at most one temporary variable, so the index stays the same within a single traversal. TInfoSinkBase symbolNameOut; symbolNameOut << "s" << mTemporaryIndex; TString symbolName = symbolNameOut.c_str(); TIntermSymbol *node = new TIntermSymbol(0, symbolName, type); node->setInternal(true); return node; } TIntermAggregate *UnfoldShortCircuitTraverser::createTempInitDeclaration(const TType &type, TIntermTyped *initializer) { ASSERT(initializer != nullptr); TIntermSymbol *tempSymbol = createTempSymbol(type); TIntermAggregate *tempDeclaration = new TIntermAggregate(EOpDeclaration); TIntermBinary *tempInit = new TIntermBinary(EOpInitialize); tempInit->setLeft(tempSymbol); tempInit->setRight(initializer); tempInit->setType(type); tempDeclaration->getSequence()->push_back(tempInit); return tempDeclaration; } TIntermBinary *UnfoldShortCircuitTraverser::createTempAssignment(const TType &type, TIntermTyped *rightNode) { ASSERT(rightNode != nullptr); TIntermSymbol *tempSymbol = createTempSymbol(type); TIntermBinary *assignment = new TIntermBinary(EOpAssign); assignment->setLeft(tempSymbol); assignment->setRight(rightNode); assignment->setType(type); return assignment; } bool UnfoldShortCircuitTraverser::visitBinary(Visit visit, TIntermBinary *node) { if (mFoundShortCircuit) return false; // If our right node doesn't have side effects, we know we don't need to unfold this // expression: there will be no short-circuiting side effects to avoid // (note: unfolding doesn't depend on the left node -- it will always be evaluated) if (!node->getRight()->hasSideEffects()) { return true; } switch (node->getOp()) { case EOpLogicalOr: mFoundShortCircuit = true; // "x || y" is equivalent to "x ? true : y", which unfolds to "bool s; if(x) s = true; else s = y;", // and then further simplifies down to "bool s = x; if(!s) s = y;". { TIntermSequence insertions; TType boolType(EbtBool, EbpUndefined, EvqTemporary); insertions.push_back(createTempInitDeclaration(boolType, node->getLeft())); TIntermAggregate *assignRightBlock = new TIntermAggregate(EOpSequence); assignRightBlock->getSequence()->push_back(createTempAssignment(boolType, node->getRight())); TIntermUnary *notTempSymbol = new TIntermUnary(EOpLogicalNot, boolType); notTempSymbol->setOperand(createTempSymbol(boolType)); TIntermSelection *ifNode = new TIntermSelection(notTempSymbol, assignRightBlock, nullptr); insertions.push_back(ifNode); NodeInsertMultipleEntry insert(mParentBlockStack.back().node, mParentBlockStack.back().pos, insertions); mInsertions.push_back(insert); NodeUpdateEntry replaceVariable(getParentNode(), node, createTempSymbol(boolType), false); mReplacements.push_back(replaceVariable); } return false; case EOpLogicalAnd: mFoundShortCircuit = true; // "x && y" is equivalent to "x ? y : false", which unfolds to "bool s; if(x) s = y; else s = false;", // and then further simplifies down to "bool s = x; if(s) s = y;". { TIntermSequence insertions; TType boolType(EbtBool, EbpUndefined, EvqTemporary); insertions.push_back(createTempInitDeclaration(boolType, node->getLeft())); TIntermAggregate *assignRightBlock = new TIntermAggregate(EOpSequence); assignRightBlock->getSequence()->push_back(createTempAssignment(boolType, node->getRight())); TIntermSelection *ifNode = new TIntermSelection(createTempSymbol(boolType), assignRightBlock, nullptr); insertions.push_back(ifNode); NodeInsertMultipleEntry insert(mParentBlockStack.back().node, mParentBlockStack.back().pos, insertions); mInsertions.push_back(insert); NodeUpdateEntry replaceVariable(getParentNode(), node, createTempSymbol(boolType), false); mReplacements.push_back(replaceVariable); } return false; default: return true; } } bool UnfoldShortCircuitTraverser::visitSelection(Visit visit, TIntermSelection *node) { if (mFoundShortCircuit) return false; // Unfold "b ? x : y" into "type s; if(b) s = x; else s = y;" if (visit == PreVisit && node->usesTernaryOperator()) { mFoundShortCircuit = true; TIntermSequence insertions; TIntermSymbol *tempSymbol = createTempSymbol(node->getType()); TIntermAggregate *tempDeclaration = new TIntermAggregate(EOpDeclaration); tempDeclaration->getSequence()->push_back(tempSymbol); insertions.push_back(tempDeclaration); TIntermAggregate *trueBlock = new TIntermAggregate(EOpSequence); TIntermBinary *trueAssignment = createTempAssignment(node->getType(), node->getTrueBlock()->getAsTyped()); trueBlock->getSequence()->push_back(trueAssignment); TIntermAggregate *falseBlock = new TIntermAggregate(EOpSequence); TIntermBinary *falseAssignment = createTempAssignment(node->getType(), node->getFalseBlock()->getAsTyped()); falseBlock->getSequence()->push_back(falseAssignment); TIntermSelection *ifNode = new TIntermSelection(node->getCondition()->getAsTyped(), trueBlock, falseBlock); insertions.push_back(ifNode); NodeInsertMultipleEntry insert(mParentBlockStack.back().node, mParentBlockStack.back().pos, insertions); mInsertions.push_back(insert); TIntermSymbol *ternaryResult = createTempSymbol(node->getType()); NodeUpdateEntry replaceVariable(getParentNode(), node, ternaryResult, false); mReplacements.push_back(replaceVariable); return false; } return true; } bool UnfoldShortCircuitTraverser::visitAggregate(Visit visit, TIntermAggregate *node) { if (node->getOp() == EOpSequence) { if (visit == PreVisit) { mParentBlockStack.push_back(ParentBlock(node, 0)); } else if (visit == InVisit) { ++mParentBlockStack.back().pos; } else { ASSERT(visit == PostVisit); mParentBlockStack.pop_back(); } } return true; } void UnfoldShortCircuitTraverser::nextIteration() { mFoundShortCircuit = false; mTemporaryIndex++; mReplacements.clear(); mMultiReplacements.clear(); mInsertions.clear(); } } // namespace void UnfoldShortCircuitToIf(TIntermNode *root) { UnfoldShortCircuitTraverser traverser; // Unfold one operator at a time, and reset the traverser between iterations. do { traverser.nextIteration(); root->traverse(&traverser); if (traverser.foundShortCircuit()) traverser.updateTree(); } while (traverser.foundShortCircuit()); } <commit_msg>Unfold sequence operator when operations inside need unfolding<commit_after>// // Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // UnfoldShortCircuitToIf is an AST traverser to convert short-circuiting operators to if-else statements. // The results are assigned to s# temporaries, which are used by the main translator instead of // the original expression. // #include "compiler/translator/UnfoldShortCircuitToIf.h" #include "compiler/translator/InfoSink.h" #include "compiler/translator/IntermNode.h" namespace { // Traverser that unfolds one short-circuiting operation at a time. class UnfoldShortCircuitTraverser : public TIntermTraverser { public: UnfoldShortCircuitTraverser(); void traverse(TIntermNode *node); bool visitBinary(Visit visit, TIntermBinary *node) override; bool visitAggregate(Visit visit, TIntermAggregate *node) override; bool visitSelection(Visit visit, TIntermSelection *node) override; void nextIteration(); bool foundShortCircuit() const { return mFoundShortCircuit; } protected: int mTemporaryIndex; // Marked to true once an operation that needs to be unfolded has been found. // After that, no more unfolding is performed on that traversal. bool mFoundShortCircuit; struct ParentBlock { ParentBlock(TIntermAggregate *_node, TIntermSequence::size_type _pos) : node(_node), pos(_pos) { } TIntermAggregate *node; TIntermSequence::size_type pos; }; std::vector<ParentBlock> mParentBlockStack; TIntermSymbol *createTempSymbol(const TType &type); TIntermAggregate *createTempInitDeclaration(const TType &type, TIntermTyped *initializer); TIntermBinary *createTempAssignment(const TType &type, TIntermTyped *rightNode); }; UnfoldShortCircuitTraverser::UnfoldShortCircuitTraverser() : TIntermTraverser(true, true, true), mTemporaryIndex(0), mFoundShortCircuit(false) { } TIntermSymbol *UnfoldShortCircuitTraverser::createTempSymbol(const TType &type) { // Each traversal uses at most one temporary variable, so the index stays the same within a single traversal. TInfoSinkBase symbolNameOut; symbolNameOut << "s" << mTemporaryIndex; TString symbolName = symbolNameOut.c_str(); TIntermSymbol *node = new TIntermSymbol(0, symbolName, type); node->setInternal(true); return node; } TIntermAggregate *UnfoldShortCircuitTraverser::createTempInitDeclaration(const TType &type, TIntermTyped *initializer) { ASSERT(initializer != nullptr); TIntermSymbol *tempSymbol = createTempSymbol(type); TIntermAggregate *tempDeclaration = new TIntermAggregate(EOpDeclaration); TIntermBinary *tempInit = new TIntermBinary(EOpInitialize); tempInit->setLeft(tempSymbol); tempInit->setRight(initializer); tempInit->setType(type); tempDeclaration->getSequence()->push_back(tempInit); return tempDeclaration; } TIntermBinary *UnfoldShortCircuitTraverser::createTempAssignment(const TType &type, TIntermTyped *rightNode) { ASSERT(rightNode != nullptr); TIntermSymbol *tempSymbol = createTempSymbol(type); TIntermBinary *assignment = new TIntermBinary(EOpAssign); assignment->setLeft(tempSymbol); assignment->setRight(rightNode); assignment->setType(type); return assignment; } bool UnfoldShortCircuitTraverser::visitBinary(Visit visit, TIntermBinary *node) { if (mFoundShortCircuit) return false; // If our right node doesn't have side effects, we know we don't need to unfold this // expression: there will be no short-circuiting side effects to avoid // (note: unfolding doesn't depend on the left node -- it will always be evaluated) if (!node->getRight()->hasSideEffects()) { return true; } switch (node->getOp()) { case EOpLogicalOr: mFoundShortCircuit = true; // "x || y" is equivalent to "x ? true : y", which unfolds to "bool s; if(x) s = true; else s = y;", // and then further simplifies down to "bool s = x; if(!s) s = y;". { TIntermSequence insertions; TType boolType(EbtBool, EbpUndefined, EvqTemporary); insertions.push_back(createTempInitDeclaration(boolType, node->getLeft())); TIntermAggregate *assignRightBlock = new TIntermAggregate(EOpSequence); assignRightBlock->getSequence()->push_back(createTempAssignment(boolType, node->getRight())); TIntermUnary *notTempSymbol = new TIntermUnary(EOpLogicalNot, boolType); notTempSymbol->setOperand(createTempSymbol(boolType)); TIntermSelection *ifNode = new TIntermSelection(notTempSymbol, assignRightBlock, nullptr); insertions.push_back(ifNode); NodeInsertMultipleEntry insert(mParentBlockStack.back().node, mParentBlockStack.back().pos, insertions); mInsertions.push_back(insert); NodeUpdateEntry replaceVariable(getParentNode(), node, createTempSymbol(boolType), false); mReplacements.push_back(replaceVariable); } return false; case EOpLogicalAnd: mFoundShortCircuit = true; // "x && y" is equivalent to "x ? y : false", which unfolds to "bool s; if(x) s = y; else s = false;", // and then further simplifies down to "bool s = x; if(s) s = y;". { TIntermSequence insertions; TType boolType(EbtBool, EbpUndefined, EvqTemporary); insertions.push_back(createTempInitDeclaration(boolType, node->getLeft())); TIntermAggregate *assignRightBlock = new TIntermAggregate(EOpSequence); assignRightBlock->getSequence()->push_back(createTempAssignment(boolType, node->getRight())); TIntermSelection *ifNode = new TIntermSelection(createTempSymbol(boolType), assignRightBlock, nullptr); insertions.push_back(ifNode); NodeInsertMultipleEntry insert(mParentBlockStack.back().node, mParentBlockStack.back().pos, insertions); mInsertions.push_back(insert); NodeUpdateEntry replaceVariable(getParentNode(), node, createTempSymbol(boolType), false); mReplacements.push_back(replaceVariable); } return false; default: return true; } } bool UnfoldShortCircuitTraverser::visitSelection(Visit visit, TIntermSelection *node) { if (mFoundShortCircuit) return false; // Unfold "b ? x : y" into "type s; if(b) s = x; else s = y;" if (visit == PreVisit && node->usesTernaryOperator()) { mFoundShortCircuit = true; TIntermSequence insertions; TIntermSymbol *tempSymbol = createTempSymbol(node->getType()); TIntermAggregate *tempDeclaration = new TIntermAggregate(EOpDeclaration); tempDeclaration->getSequence()->push_back(tempSymbol); insertions.push_back(tempDeclaration); TIntermAggregate *trueBlock = new TIntermAggregate(EOpSequence); TIntermBinary *trueAssignment = createTempAssignment(node->getType(), node->getTrueBlock()->getAsTyped()); trueBlock->getSequence()->push_back(trueAssignment); TIntermAggregate *falseBlock = new TIntermAggregate(EOpSequence); TIntermBinary *falseAssignment = createTempAssignment(node->getType(), node->getFalseBlock()->getAsTyped()); falseBlock->getSequence()->push_back(falseAssignment); TIntermSelection *ifNode = new TIntermSelection(node->getCondition()->getAsTyped(), trueBlock, falseBlock); insertions.push_back(ifNode); NodeInsertMultipleEntry insert(mParentBlockStack.back().node, mParentBlockStack.back().pos, insertions); mInsertions.push_back(insert); TIntermSymbol *ternaryResult = createTempSymbol(node->getType()); NodeUpdateEntry replaceVariable(getParentNode(), node, ternaryResult, false); mReplacements.push_back(replaceVariable); return false; } return true; } bool UnfoldShortCircuitTraverser::visitAggregate(Visit visit, TIntermAggregate *node) { if (visit == PreVisit && mFoundShortCircuit) return false; // No need to traverse further if (node->getOp() == EOpSequence) { if (visit == PreVisit) { mParentBlockStack.push_back(ParentBlock(node, 0)); } else if (visit == InVisit) { ++mParentBlockStack.back().pos; } else { ASSERT(visit == PostVisit); mParentBlockStack.pop_back(); } } else if (node->getOp() == EOpComma) { ASSERT(visit != PreVisit || !mFoundShortCircuit); if (visit == PostVisit && mFoundShortCircuit) { // We can be sure that we arrived here because there was a short-circuiting operator // inside the sequence operator since we only start traversing the sequence operator in // case a short-circuiting operator has not been found so far. // We need to unfold the sequence (comma) operator, otherwise the evaluation order of // statements would be messed up by unfolded operations inside. // Don't do any other unfolding on this round of traversal. mReplacements.clear(); mMultiReplacements.clear(); mInsertions.clear(); TIntermSequence insertions; TIntermSequence *seq = node->getSequence(); TIntermSequence::size_type i = 0; ASSERT(!seq->empty()); while (i < seq->size() - 1) { TIntermTyped *child = (*seq)[i]->getAsTyped(); insertions.push_back(child); ++i; } NodeInsertMultipleEntry insert(mParentBlockStack.back().node, mParentBlockStack.back().pos, insertions); mInsertions.push_back(insert); NodeUpdateEntry replaceVariable(getParentNode(), node, (*seq)[i], false); mReplacements.push_back(replaceVariable); } } return true; } void UnfoldShortCircuitTraverser::nextIteration() { mFoundShortCircuit = false; mTemporaryIndex++; mReplacements.clear(); mMultiReplacements.clear(); mInsertions.clear(); } } // namespace void UnfoldShortCircuitToIf(TIntermNode *root) { UnfoldShortCircuitTraverser traverser; // Unfold one operator at a time, and reset the traverser between iterations. do { traverser.nextIteration(); root->traverse(&traverser); if (traverser.foundShortCircuit()) traverser.updateTree(); } while (traverser.foundShortCircuit()); } <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_debug.h" #include "classad_merge.h" #include "startd_cron_job.h" #include "named_classad.h" #include "named_classad_list.h" #include "startd_named_classad.h" #include "startd_named_classad_list.h" StartdNamedClassAdList::StartdNamedClassAdList( void ) : NamedClassAdList( ) { } // virtual method so that NamedClassAdList can create a new StartdNamedClassAd if needed. // NamedClassAd * StartdNamedClassAdList::New( const char * name, ClassAd * ad) { StartdNamedClassAd * sad = NULL; const char * pdot = strchr(name, '.'); if (pdot) { // tj: its a bit of a hack, but for now, we look for an existing named ad // that matches the new ad's basename (i.e. everthing before the first '.') // then we ask the existing ad to create a new ad that shares it's job object. // this works because the CronJob will always register the basename in this list. // std::string pre(name); pre[pdot-name] = 0; NamedClassAd * nad = Find(pre.c_str()); sad = dynamic_cast<StartdNamedClassAd*>(nad); if (sad) { sad = sad->NewPeer(name, ad); } } ASSERT(sad); return sad; } int StartdNamedClassAdList::DeleteJob( StartdCronJob * job ) { bool no_match = 1; std::list<NamedClassAd *>::iterator iter = m_ads.begin(); while (iter != m_ads.end()) { NamedClassAd * nad = *iter; StartdNamedClassAd *sad = dynamic_cast<StartdNamedClassAd *>(nad); if ( sad && sad->IsJob (job) ) { no_match = 0; iter = m_ads.erase(iter); delete nad; } else { ++iter; } } // No match found; done return no_match; } int StartdNamedClassAdList::ClearJob ( StartdCronJob * job ) { bool no_match = 1; std::list<NamedClassAd *>::iterator iter = m_ads.begin(); while (iter != m_ads.end()) { NamedClassAd * nad = *iter; StartdNamedClassAd *sad = dynamic_cast<StartdNamedClassAd *>(nad); if ( sad && sad->IsJob (job) ) { no_match = 0; if ( ! strcmp(sad->GetName(), job->GetName()) ) { sad->ReplaceAd(NULL); ++iter; } else { iter = m_ads.erase(iter); delete nad; } } else { ++iter; } } // No match found; done return no_match; } bool StartdNamedClassAdList::Register( StartdNamedClassAd *ad ) { NamedClassAd *nad = dynamic_cast<NamedClassAd *>(ad); return NamedClassAdList::Register( nad ); } int StartdNamedClassAdList::Publish( ClassAd *merged_ad, unsigned r_id, const char * r_id_str ) { std::list<NamedClassAd *>::iterator iter; for( iter = m_ads.begin(); iter != m_ads.end(); iter++ ) { NamedClassAd *nad = *iter; StartdNamedClassAd *sad = dynamic_cast<StartdNamedClassAd*>(nad); ASSERT( sad ); if( sad->isResourceMonitor() ) { continue; } const char * match_attr = NULL; if ( sad->InSlotList(r_id) && sad->ShouldMergeInto(merged_ad, &match_attr) ) { ClassAd *ad = nad->GetAd( ); if ( NULL != ad ) { dprintf( D_FULLDEBUG, "Publishing ClassAd '%s' to %s [%s matches]\n", nad->GetName(), r_id_str, match_attr ? match_attr : "InSlotList" ); sad->MergeInto(merged_ad); } } else if (match_attr) { dprintf( D_FULLDEBUG, "Rejecting ClassAd '%s' for %s [%s does not match]\n", nad->GetName(), r_id_str, match_attr ); } } // // Because each (this) slot may have more than one custom resource of a // given type (e.g., two GPUs), we need to aggregate, rather than merge, // the resource-specific ads produce by the resource monitor. We assume // -- and once we fix #6489, will be able to enforce -- that monitors // for different resources will not have the same attribute names, so // we only need single accumulator ad (and don't have to split the // monitor ads by resource type). // ClassAd accumulator; // dprintf( D_FULLDEBUG, "Generating usage for %s...\n", r_id_str ); for( iter = m_ads.begin(); iter != m_ads.end(); iter++ ) { NamedClassAd *nad = *iter; StartdNamedClassAd *sad = dynamic_cast<StartdNamedClassAd*>(nad); ASSERT( sad ); if(! sad->isResourceMonitor()) { continue; } const char * match_attr = NULL; // dprintf( D_FULLDEBUG, "... adding %s...\n", sad->GetName() ); if( sad->InSlotList( r_id ) && sad->ShouldMergeInto( merged_ad, & match_attr ) ) { sad->AggregateInto( & accumulator ); } } // dprintf( D_FULLDEBUG, "... done generating usage report for %s.\n", r_id_str ); #if 0 classad::Value v, w; double usmpu = -1, smu = -1; accumulator.EvaluateAttr( "UptimeSQUIDsMemoryPeakUsage", v ) && v.IsNumber( usmpu ); accumulator.EvaluateAttr( "SQUIDsMemoryUsage", w ) && w.IsNumber( smu ); dprintf( D_FULLDEBUG, "%s UptimeSQUIDsMemoryPeakUsage = %.2f SQUIDsMemoryUsage = %.2f\n", r_id_str, usmpu, smu ); #endif // We don't filter out the (raw) Uptime* metrics here, because the // starter needs them to compute the (per-job) *Usage metrics. Instead, // we filter them out in Resource::do_update(). StartdNamedClassAd::Merge( merged_ad, & accumulator ); return 0; } void StartdNamedClassAdList::reset_monitors( unsigned r_id, ClassAd * forWhom ) { std::list<NamedClassAd *>::iterator iter; for( iter = m_ads.begin(); iter != m_ads.end(); iter++ ) { NamedClassAd *nad = *iter; StartdNamedClassAd *sad = dynamic_cast<StartdNamedClassAd*>(nad); ASSERT( sad ); if(! sad->isResourceMonitor()) { continue; } const char * match_attr = NULL; if( sad->InSlotList( r_id ) && sad->ShouldMergeInto( forWhom, & match_attr ) ) { sad->reset_monitor(); } } } void StartdNamedClassAdList::unset_monitors( unsigned r_id, ClassAd * forWhom ) { std::list<NamedClassAd *>::iterator iter; for( iter = m_ads.begin(); iter != m_ads.end(); iter++ ) { NamedClassAd *nad = *iter; StartdNamedClassAd *sad = dynamic_cast<StartdNamedClassAd*>(nad); ASSERT( sad ); if(! sad->isResourceMonitor()) { continue; } const char * match_attr = NULL; if( sad->InSlotList( r_id ) && sad->ShouldMergeInto( forWhom, & match_attr ) ) { sad->unset_monitor(); } } } <commit_msg>Don't dynamic_cast when we should static_cast #6992<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_debug.h" #include "classad_merge.h" #include "startd_cron_job.h" #include "named_classad.h" #include "named_classad_list.h" #include "startd_named_classad.h" #include "startd_named_classad_list.h" StartdNamedClassAdList::StartdNamedClassAdList( void ) : NamedClassAdList( ) { } // virtual method so that NamedClassAdList can create a new StartdNamedClassAd if needed. // NamedClassAd * StartdNamedClassAdList::New( const char * name, ClassAd * ad) { StartdNamedClassAd * sad = NULL; const char * pdot = strchr(name, '.'); if (pdot) { // tj: its a bit of a hack, but for now, we look for an existing named ad // that matches the new ad's basename (i.e. everthing before the first '.') // then we ask the existing ad to create a new ad that shares it's job object. // this works because the CronJob will always register the basename in this list. // std::string pre(name); pre[pdot-name] = 0; NamedClassAd * nad = Find(pre.c_str()); sad = dynamic_cast<StartdNamedClassAd*>(nad); if (sad) { sad = sad->NewPeer(name, ad); } } ASSERT(sad); return sad; } int StartdNamedClassAdList::DeleteJob( StartdCronJob * job ) { bool no_match = 1; std::list<NamedClassAd *>::iterator iter = m_ads.begin(); while (iter != m_ads.end()) { NamedClassAd * nad = *iter; StartdNamedClassAd *sad = dynamic_cast<StartdNamedClassAd *>(nad); if ( sad && sad->IsJob (job) ) { no_match = 0; iter = m_ads.erase(iter); delete nad; } else { ++iter; } } // No match found; done return no_match; } int StartdNamedClassAdList::ClearJob ( StartdCronJob * job ) { bool no_match = 1; std::list<NamedClassAd *>::iterator iter = m_ads.begin(); while (iter != m_ads.end()) { NamedClassAd * nad = *iter; StartdNamedClassAd *sad = dynamic_cast<StartdNamedClassAd *>(nad); if ( sad && sad->IsJob (job) ) { no_match = 0; if ( ! strcmp(sad->GetName(), job->GetName()) ) { sad->ReplaceAd(NULL); ++iter; } else { iter = m_ads.erase(iter); delete nad; } } else { ++iter; } } // No match found; done return no_match; } bool StartdNamedClassAdList::Register( StartdNamedClassAd *ad ) { NamedClassAd *nad = static_cast<NamedClassAd *>(ad); return NamedClassAdList::Register( nad ); } int StartdNamedClassAdList::Publish( ClassAd *merged_ad, unsigned r_id, const char * r_id_str ) { std::list<NamedClassAd *>::iterator iter; for( iter = m_ads.begin(); iter != m_ads.end(); iter++ ) { NamedClassAd *nad = *iter; StartdNamedClassAd *sad = dynamic_cast<StartdNamedClassAd*>(nad); ASSERT( sad ); if( sad->isResourceMonitor() ) { continue; } const char * match_attr = NULL; if ( sad->InSlotList(r_id) && sad->ShouldMergeInto(merged_ad, &match_attr) ) { ClassAd *ad = nad->GetAd( ); if ( NULL != ad ) { dprintf( D_FULLDEBUG, "Publishing ClassAd '%s' to %s [%s matches]\n", nad->GetName(), r_id_str, match_attr ? match_attr : "InSlotList" ); sad->MergeInto(merged_ad); } } else if (match_attr) { dprintf( D_FULLDEBUG, "Rejecting ClassAd '%s' for %s [%s does not match]\n", nad->GetName(), r_id_str, match_attr ); } } // // Because each (this) slot may have more than one custom resource of a // given type (e.g., two GPUs), we need to aggregate, rather than merge, // the resource-specific ads produce by the resource monitor. We assume // -- and once we fix #6489, will be able to enforce -- that monitors // for different resources will not have the same attribute names, so // we only need single accumulator ad (and don't have to split the // monitor ads by resource type). // ClassAd accumulator; // dprintf( D_FULLDEBUG, "Generating usage for %s...\n", r_id_str ); for( iter = m_ads.begin(); iter != m_ads.end(); iter++ ) { NamedClassAd *nad = *iter; StartdNamedClassAd *sad = dynamic_cast<StartdNamedClassAd*>(nad); ASSERT( sad ); if(! sad->isResourceMonitor()) { continue; } const char * match_attr = NULL; // dprintf( D_FULLDEBUG, "... adding %s...\n", sad->GetName() ); if( sad->InSlotList( r_id ) && sad->ShouldMergeInto( merged_ad, & match_attr ) ) { sad->AggregateInto( & accumulator ); } } // dprintf( D_FULLDEBUG, "... done generating usage report for %s.\n", r_id_str ); #if 0 classad::Value v, w; double usmpu = -1, smu = -1; accumulator.EvaluateAttr( "UptimeSQUIDsMemoryPeakUsage", v ) && v.IsNumber( usmpu ); accumulator.EvaluateAttr( "SQUIDsMemoryUsage", w ) && w.IsNumber( smu ); dprintf( D_FULLDEBUG, "%s UptimeSQUIDsMemoryPeakUsage = %.2f SQUIDsMemoryUsage = %.2f\n", r_id_str, usmpu, smu ); #endif // We don't filter out the (raw) Uptime* metrics here, because the // starter needs them to compute the (per-job) *Usage metrics. Instead, // we filter them out in Resource::do_update(). StartdNamedClassAd::Merge( merged_ad, & accumulator ); return 0; } void StartdNamedClassAdList::reset_monitors( unsigned r_id, ClassAd * forWhom ) { std::list<NamedClassAd *>::iterator iter; for( iter = m_ads.begin(); iter != m_ads.end(); iter++ ) { NamedClassAd *nad = *iter; StartdNamedClassAd *sad = dynamic_cast<StartdNamedClassAd*>(nad); ASSERT( sad ); if(! sad->isResourceMonitor()) { continue; } const char * match_attr = NULL; if( sad->InSlotList( r_id ) && sad->ShouldMergeInto( forWhom, & match_attr ) ) { sad->reset_monitor(); } } } void StartdNamedClassAdList::unset_monitors( unsigned r_id, ClassAd * forWhom ) { std::list<NamedClassAd *>::iterator iter; for( iter = m_ads.begin(); iter != m_ads.end(); iter++ ) { NamedClassAd *nad = *iter; StartdNamedClassAd *sad = dynamic_cast<StartdNamedClassAd*>(nad); ASSERT( sad ); if(! sad->isResourceMonitor()) { continue; } const char * match_attr = NULL; if( sad->InSlotList( r_id ) && sad->ShouldMergeInto( forWhom, & match_attr ) ) { sad->unset_monitor(); } } } <|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 "base/safe_strerror_posix.h" #include <errno.h> #include <stdio.h> #include <string.h> #if defined(__GLIBC__) && defined(__GNUC__) // GCC will complain about the unused second wrap function unless we tell it // that we meant for them to be potentially unused, which is exactly what this // attribute is for. #define POSSIBLY_UNUSED __attribute__((unused)) #else #define POSSIBLY_UNUSED #endif #if defined(__GLIBC__) // glibc has two strerror_r functions: a historical GNU-specific one that // returns type char *, and a POSIX.1-2001 compliant one available since 2.3.4 // that returns int. This wraps the GNU-specific one. static void POSSIBLY_UNUSED wrap_posix_strerror_r( char *(*strerror_r_ptr)(int, char *, size_t), int err, char *buf, size_t len) { // GNU version. char *rc = (*strerror_r_ptr)(err, buf, len); if (rc != buf) { // glibc did not use buf and returned a static string instead. Copy it // into buf. buf[0] = '\0'; strncat(buf, rc, len - 1); } // The GNU version never fails. Unknown errors get an "unknown error" message. // The result is always null terminated. } #endif // __GLIBC__ // Wrapper for strerror_r functions that implement the POSIX interface. POSIX // does not define the behaviour for some of the edge cases, so we wrap it to // guarantee that they are handled. This is compiled on all POSIX platforms, but // it will only be used on Linux if the POSIX strerror_r implementation is // being used (see below). static void POSSIBLY_UNUSED wrap_posix_strerror_r( int (*strerror_r_ptr)(int, char *, size_t), int err, char *buf, size_t len) { int old_errno = errno; // Have to cast since otherwise we get an error if this is the GNU version // (but in such a scenario this function is never called). Sadly we can't use // C++-style casts because the appropriate one is reinterpret_cast but it's // considered illegal to reinterpret_cast a type to itself, so we get an // error in the opposite case. int result = (*strerror_r_ptr)(err, buf, len); if (result == 0) { // POSIX is vague about whether the string will be terminated, although // it indirectly implies that typically ERANGE will be returned, instead // of truncating the string. We play it safe by always terminating the // string explicitly. buf[len - 1] = '\0'; } else { // Error. POSIX is vague about whether the return value is itself a system // error code or something else. On Linux currently it is -1 and errno is // set. On BSD-derived systems it is a system error and errno is unchanged. // We try and detect which case it is so as to put as much useful info as // we can into our message. int strerror_error; // The error encountered in strerror int new_errno = errno; if (new_errno != old_errno) { // errno was changed, so probably the return value is just -1 or something // else that doesn't provide any info, and errno is the error. strerror_error = new_errno; } else { // Either the error from strerror_r was the same as the previous value, or // errno wasn't used. Assume the latter. strerror_error = result; } // snprintf truncates and always null-terminates. snprintf(buf, len, "Error %d while retrieving error %d", strerror_error, err); } errno = old_errno; } void safe_strerror_r(int err, char *buf, size_t len) { if (buf == NULL || len <= 0) { return; } // If using glibc (i.e., Linux), the compiler will automatically select the // appropriate overloaded function based on the function type of strerror_r. // The other one will be elided from the translation unit since both are // static. wrap_posix_strerror_r(&strerror_r, err, buf, len); } std::string safe_strerror(int err) { const int buffer_size = 256; char buf[buffer_size]; safe_strerror_r(err, buf, sizeof(buf)); return std::string(buf); } <commit_msg>NaCl base bringup.<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 "build/build_config.h" #include "base/safe_strerror_posix.h" #include <errno.h> #include <stdio.h> #include <string.h> #define USE_HISTORICAL_STRERRO_R (defined(__GLIBC__) || defined(OS_NACL)) #if USE_HISTORICAL_STRERRO_R && defined(__GNUC__) // GCC will complain about the unused second wrap function unless we tell it // that we meant for them to be potentially unused, which is exactly what this // attribute is for. #define POSSIBLY_UNUSED __attribute__((unused)) #else #define POSSIBLY_UNUSED #endif #if USE_HISTORICAL_STRERRO_R // glibc has two strerror_r functions: a historical GNU-specific one that // returns type char *, and a POSIX.1-2001 compliant one available since 2.3.4 // that returns int. This wraps the GNU-specific one. static void POSSIBLY_UNUSED wrap_posix_strerror_r( char *(*strerror_r_ptr)(int, char *, size_t), int err, char *buf, size_t len) { // GNU version. char *rc = (*strerror_r_ptr)(err, buf, len); if (rc != buf) { // glibc did not use buf and returned a static string instead. Copy it // into buf. buf[0] = '\0'; strncat(buf, rc, len - 1); } // The GNU version never fails. Unknown errors get an "unknown error" message. // The result is always null terminated. } #endif // USE_HISTORICAL_STRERRO_R // Wrapper for strerror_r functions that implement the POSIX interface. POSIX // does not define the behaviour for some of the edge cases, so we wrap it to // guarantee that they are handled. This is compiled on all POSIX platforms, but // it will only be used on Linux if the POSIX strerror_r implementation is // being used (see below). static void POSSIBLY_UNUSED wrap_posix_strerror_r( int (*strerror_r_ptr)(int, char *, size_t), int err, char *buf, size_t len) { int old_errno = errno; // Have to cast since otherwise we get an error if this is the GNU version // (but in such a scenario this function is never called). Sadly we can't use // C++-style casts because the appropriate one is reinterpret_cast but it's // considered illegal to reinterpret_cast a type to itself, so we get an // error in the opposite case. int result = (*strerror_r_ptr)(err, buf, len); if (result == 0) { // POSIX is vague about whether the string will be terminated, although // it indirectly implies that typically ERANGE will be returned, instead // of truncating the string. We play it safe by always terminating the // string explicitly. buf[len - 1] = '\0'; } else { // Error. POSIX is vague about whether the return value is itself a system // error code or something else. On Linux currently it is -1 and errno is // set. On BSD-derived systems it is a system error and errno is unchanged. // We try and detect which case it is so as to put as much useful info as // we can into our message. int strerror_error; // The error encountered in strerror int new_errno = errno; if (new_errno != old_errno) { // errno was changed, so probably the return value is just -1 or something // else that doesn't provide any info, and errno is the error. strerror_error = new_errno; } else { // Either the error from strerror_r was the same as the previous value, or // errno wasn't used. Assume the latter. strerror_error = result; } // snprintf truncates and always null-terminates. snprintf(buf, len, "Error %d while retrieving error %d", strerror_error, err); } errno = old_errno; } void safe_strerror_r(int err, char *buf, size_t len) { if (buf == NULL || len <= 0) { return; } // If using glibc (i.e., Linux), the compiler will automatically select the // appropriate overloaded function based on the function type of strerror_r. // The other one will be elided from the translation unit since both are // static. wrap_posix_strerror_r(&strerror_r, err, buf, len); } std::string safe_strerror(int err) { const int buffer_size = 256; char buf[buffer_size]; safe_strerror_r(err, buf, sizeof(buf)); return std::string(buf); } <|endoftext|>
<commit_before>// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2012 Esteban Tovagliari. // // 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. // // Has to be first, to avoid redifinition warnings. #include "bind_auto_release_ptr.h" #include "renderer/modeling/scene/assembly.h" #include "renderer/modeling/scene/assemblyinstance.h" #include "bind_typed_entity_containers.hpp" #include "dict2dict.hpp" namespace bpy = boost::python; using namespace foundation; using namespace renderer; namespace detail { auto_release_ptr<Assembly> create_assembly( const std::string& name) { return AssemblyFactory::create( name.c_str(), ParamArray()); } auto_release_ptr<Assembly> create_assembly_with_params( const std::string& name, const bpy::dict& params) { return AssemblyFactory::create( name.c_str(), bpy_dict_to_param_array( params)); } auto_release_ptr<AssemblyInstance> create_assembly_instance( const std::string& name, const bpy::dict& params, const Assembly *assembly) { return AssemblyInstanceFactory::create( name.c_str(), bpy_dict_to_param_array( params), *assembly); } TransformSequence& assembly_instance_get_transform_sequence( AssemblyInstance *instance) { return instance->transform_sequence(); } } // detail void bind_assembly() { bpy::class_<Assembly, auto_release_ptr<Assembly>, bpy::bases<Entity>, boost::noncopyable>( "Assembly", bpy::no_init) .def( "__init__", bpy::make_constructor( detail::create_assembly)) .def( "__init__", bpy::make_constructor( detail::create_assembly_with_params)) .def( "colors", &Assembly::colors, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "textures", &Assembly::textures, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "texture_instances", &Assembly::texture_instances, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "bsdfs", &Assembly::bsdfs, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "edfs", &Assembly::edfs, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "surface_shaders", &Assembly::surface_shaders, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "materials", &Assembly::materials, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "lights", &Assembly::lights, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "objects", &Assembly::objects, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "object_instances", &Assembly::object_instances, bpy::return_value_policy<bpy::reference_existing_object>()) ; bind_typed_entity_map<Assembly>( "AssemblyContainer"); bpy::class_<AssemblyInstance, auto_release_ptr<AssemblyInstance>, bpy::bases<Entity>, boost::noncopyable>( "AssemblyInstance", bpy::no_init) .def( "__init__", bpy::make_constructor( detail::create_assembly_instance)) .def( "get_assembly", &AssemblyInstance::get_assembly, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "get_assembly_uid", &AssemblyInstance::get_assembly_uid) .def( "transform_sequence", detail::assembly_instance_get_transform_sequence, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "compute_parent_bbox", &AssemblyInstance::compute_parent_bbox) ; bind_typed_entity_map<AssemblyInstance>( "AssemblyInstanceContainer"); } <commit_msg>sync appleseed.py with master.<commit_after>// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2012 Esteban Tovagliari. // // 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. // // Has to be first, to avoid redifinition warnings. #include "bind_auto_release_ptr.h" #include "renderer/modeling/scene/assembly.h" #include "renderer/modeling/scene/assemblyinstance.h" #include "bind_typed_entity_containers.hpp" #include "dict2dict.hpp" namespace bpy = boost::python; using namespace foundation; using namespace renderer; namespace detail { auto_release_ptr<Assembly> create_assembly( const std::string& name) { return AssemblyFactory::create( name.c_str(), ParamArray()); } auto_release_ptr<Assembly> create_assembly_with_params( const std::string& name, const bpy::dict& params) { return AssemblyFactory::create( name.c_str(), bpy_dict_to_param_array( params)); } auto_release_ptr<AssemblyInstance> create_assembly_instance( const std::string& name, const bpy::dict& params, const Assembly *assembly) { return AssemblyInstanceFactory::create( name.c_str(), bpy_dict_to_param_array( params), *assembly); } TransformSequence& assembly_instance_get_transform_sequence( AssemblyInstance *instance) { return instance->transform_sequence(); } } // detail void bind_assembly() { bpy::class_<Assembly, auto_release_ptr<Assembly>, bpy::bases<Entity>, boost::noncopyable>( "Assembly", bpy::no_init) .def( "__init__", bpy::make_constructor( detail::create_assembly)) .def( "__init__", bpy::make_constructor( detail::create_assembly_with_params)) .def( "colors", &Assembly::colors, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "textures", &Assembly::textures, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "texture_instances", &Assembly::texture_instances, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "bsdfs", &Assembly::bsdfs, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "edfs", &Assembly::edfs, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "surface_shaders", &Assembly::surface_shaders, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "materials", &Assembly::materials, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "lights", &Assembly::lights, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "objects", &Assembly::objects, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "object_instances", &Assembly::object_instances, bpy::return_value_policy<bpy::reference_existing_object>()) ; bind_typed_entity_map<Assembly>( "AssemblyContainer"); bpy::class_<AssemblyInstance, auto_release_ptr<AssemblyInstance>, bpy::bases<Entity>, boost::noncopyable>( "AssemblyInstance", bpy::no_init) .def( "__init__", bpy::make_constructor( detail::create_assembly_instance)) .def( "get_assembly", &AssemblyInstance::get_assembly, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "transform_sequence", detail::assembly_instance_get_transform_sequence, bpy::return_value_policy<bpy::reference_existing_object>()) .def( "compute_parent_bbox", &AssemblyInstance::compute_parent_bbox) ; bind_typed_entity_map<AssemblyInstance>( "AssemblyInstanceContainer"); } <|endoftext|>
<commit_before>// $Id$ // Author: Sergey Linev 28/12/2013 /************************************************************************* * Copyright (C) 1995-2013, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TFastCgi.h" #include "TThread.h" #include "TUrl.h" #include "THttpServer.h" #include <string.h> #ifdef WIN32 #include <io.h> #else #include <unistd.h> #endif //////////////////////////////////////////////////////////////////////////////// class TFastCgiCallArg : public THttpCallArg { protected: void CheckWSPageContent(THttpWSHandler *) override { std::string search = "JSROOT.connectWebWindow({"; std::string replace = search + "socket_kind:\"longpoll\","; ReplaceAllinContent(search, replace, true); } public: TFastCgiCallArg() = default; /** All FastCGI requests should be immediately replied to get slot for next */ Bool_t CanPostpone() const override { return kFALSE; } }; //////////////////////////////////////////////////////////////////////////////// #ifndef HTTP_WITHOUT_FASTCGI #include "fcgiapp.h" #include <stdlib.h> void FCGX_ROOT_send_file(FCGX_Request *request, const char *fname) { std::string buf = THttpServer::ReadFileContent(fname); if (buf.empty()) { FCGX_FPrintF(request->out, "Status: 404 Not Found\r\n" "Content-Length: 0\r\n" // Always set Content-Length "Connection: close\r\n\r\n"); } else { FCGX_FPrintF(request->out, "Status: 200 OK\r\n" "Content-Type: %s\r\n" "Content-Length: %d\r\n" // Always set Content-Length "\r\n", THttpServer::GetMimeType(fname), (int) buf.length()); FCGX_PutStr(buf.c_str(), buf.length(), request->out); } } void process_request(TFastCgi *engine, FCGX_Request *request) { int count = 0; count++; // simple static request counter const char *inp_path = FCGX_GetParam("PATH_INFO", request->envp); if (!inp_path) inp_path = FCGX_GetParam("SCRIPT_FILENAME", request->envp); const char *inp_query = FCGX_GetParam("QUERY_STRING", request->envp); const char *inp_method = FCGX_GetParam("REQUEST_METHOD", request->envp); const char *inp_length = FCGX_GetParam("CONTENT_LENGTH", request->envp); auto arg = std::make_shared<TFastCgiCallArg>(); if (inp_path) arg->SetPathAndFileName(inp_path); if (inp_query) arg->SetQuery(inp_query); if (inp_method) arg->SetMethod(inp_method); if (engine->GetTopName()) arg->SetTopName(engine->GetTopName()); int len = 0; if (inp_length) len = strtol(inp_length, nullptr, 10); if (len > 0) { std::string buf; buf.resize(len); int nread = FCGX_GetStr((char *)buf.data(), len, request->in); if (nread == len) arg->SetPostData(std::move(buf)); } TString header; for (char **envp = request->envp; *envp != nullptr; envp++) { TString entry = *envp; for (Int_t n = 0; n < entry.Length(); n++) if (entry[n] == '=') { entry[n] = ':'; break; } header.Append(entry); header.Append("\r\n"); } arg->SetRequestHeader(header); TString username = arg->GetRequestHeader("REMOTE_USER"); if ((username.Length() > 0) && (arg->GetRequestHeader("AUTH_TYPE").Length() > 0)) arg->SetUserName(username); if (engine->IsDebugMode()) { FCGX_FPrintF(request->out, "Status: 200 OK\r\n" "Content-type: text/html\r\n" "\r\n" "<title>FastCGI echo</title>" "<h1>FastCGI echo</h1>\n"); FCGX_FPrintF(request->out, "Request %d:<br/>\n<pre>\n", count); FCGX_FPrintF(request->out, " Method : %s\n", arg->GetMethod()); FCGX_FPrintF(request->out, " PathName : %s\n", arg->GetPathName()); FCGX_FPrintF(request->out, " FileName : %s\n", arg->GetFileName()); FCGX_FPrintF(request->out, " Query : %s\n", arg->GetQuery()); FCGX_FPrintF(request->out, " PostData : %ld\n", arg->GetPostDataLength()); FCGX_FPrintF(request->out, "</pre><p>\n"); FCGX_FPrintF(request->out, "Environment:<br/>\n<pre>\n"); for (char **envp = request->envp; *envp != nullptr; envp++) FCGX_FPrintF(request->out, " %s\n", *envp); FCGX_FPrintF(request->out, "</pre><p>\n"); return; } TString fname; if (engine->GetServer()->IsFileRequested(inp_path, fname)) { FCGX_ROOT_send_file(request, fname.Data()); return; } if (!engine->GetServer()->ExecuteHttp(arg) || arg->Is404()) { std::string hdr = arg->FillHttpHeader("Status:"); FCGX_FPrintF(request->out, hdr.c_str()); } else if (arg->IsFile()) { FCGX_ROOT_send_file(request, (const char *)arg->GetContent()); } else { // TODO: check in request header that gzip encoding is supported if (arg->GetZipping() != THttpCallArg::kNoZip) arg->CompressWithGzip(); std::string hdr = arg->FillHttpHeader("Status:"); FCGX_FPrintF(request->out, hdr.c_str()); FCGX_PutStr((const char *)arg->GetContent(), (int)arg->GetContentLength(), request->out); } } void run_multi_threads(TFastCgi *engine, Int_t nthrds) { std::condition_variable cond; ///<! condition used to wait for processing std::mutex m; std::unique_ptr<FCGX_Request> arg; int nwaiting = 0; auto worker_func = [engine, &cond, &m, &arg, &nwaiting]() { while (!engine->IsTerminating()) { std::unique_ptr<FCGX_Request> request; { std::unique_lock<std::mutex> lk(m); nwaiting++; cond.wait(lk); nwaiting--; std::swap(arg, request); } if (request) { process_request(engine, request.get()); FCGX_Finish_r(request.get()); } } }; // start N workers std::vector<std::thread> workers; for (int n=0; n< nthrds; ++n) workers.emplace_back(worker_func); while (!engine->IsTerminating()) { auto request = std::make_unique<FCGX_Request>(); FCGX_InitRequest(request.get(), engine->GetSocket(), 0); int rc = FCGX_Accept_r(request.get()); if (rc != 0) continue; { std::lock_guard<std::mutex> lk(m); if (nwaiting > 0) std::swap(request, arg); } printf("Waiting %d\n", nwaiting); if (!request) { // notify thread to process request cond.notify_one(); } else { // process request ourselfs process_request(engine, request.get()); FCGX_Finish_r(request.get()); } } // ensure that all threads are waked up cond.notify_all(); // join all workers for (auto & thrd : workers) thrd.join(); } // simple run function to process all requests in same thread void run_single_thread(TFastCgi *engine) { FCGX_Request request; FCGX_InitRequest(&request, engine->GetSocket(), 0); while (!engine->IsTerminating()) { int rc = FCGX_Accept_r(&request); if (rc != 0) continue; process_request(engine, &request); FCGX_Finish_r(&request); } } #endif ////////////////////////////////////////////////////////////////////////// // // // TFastCgi // // // // http engine implementation, based on fastcgi package // // Allows to redirect http requests from normal web server like // // Apache or lighttpd // // // // Configuration example for lighttpd // // // // server.modules += ( "mod_fastcgi" ) // // fastcgi.server = ( // // "/remote_scripts/" => // // (( "host" => "192.168.1.11", // // "port" => 9000, // // "check-local" => "disable", // // "docroot" => "/" // // )) // // ) // // // // When creating THttpServer, one should specify: // // // // THttpServer* serv = new THttpServer("fastcgi:9000"); // // // // In this case, requests to lighttpd server will be // // redirected to ROOT session. Like: // // http://lighttpdhost/remote_scripts/root.cgi/ // // // // Following additional options can be specified // // top=foldername - name of top folder, seen in the browser // // thrds=N - run N worker threads to process requests, default 0 // // debug=1 - run fastcgi server in debug mode // // Example: // // serv->CreateEngine("fastcgi:9000?top=fastcgiserver"); // // // // // ////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// normal constructor TFastCgi::TFastCgi() : THttpEngine("fastcgi", "fastcgi interface to webserver") { } //////////////////////////////////////////////////////////////////////////////// /// destructor TFastCgi::~TFastCgi() { fTerminating = kTRUE; // running thread will stopped if (fThrd) fThrd->join(); if (fSocket > 0) { // close opened socket close(fSocket); fSocket = 0; } } //////////////////////////////////////////////////////////////////////////////// /// initializes fastcgi variables and start thread, /// which will process incoming http requests Bool_t TFastCgi::Create(const char *args) { #ifndef HTTP_WITHOUT_FASTCGI FCGX_Init(); TString sport = ":9000"; Int_t nthrds = 10; if ((args != 0) && (strlen(args) > 0)) { // first extract port number sport = ":"; while ((*args != 0) && (*args >= '0') && (*args <= '9')) sport.Append(*args++); // than search for extra parameters while ((*args != 0) && (*args != '?')) args++; if (*args == '?') { TUrl url(TString::Format("http://localhost/folder%s", args)); if (url.IsValid()) { url.ParseOptions(); if (url.GetValueFromOptions("debug") != 0) fDebugMode = kTRUE; if (url.HasOption("thrds")) nthrds = url.GetIntValueFromOptions("thrds"); const char *top = url.GetValueFromOptions("top"); if (top != 0) fTopName = top; } } } Info("Create", "Starting FastCGI server on port %s", sport.Data() + 1); fSocket = FCGX_OpenSocket(sport.Data(), 10); if (!fSocket) return kFALSE; if (nthrds > 0) fThrd = std::make_unique<std::thread>(run_multi_threads, this, nthrds); else fThrd = std::make_unique<std::thread>(run_single_thread, this); return kTRUE; #else (void) args; Error("Create", "ROOT compiled without fastcgi support"); return kFALSE; #endif } <commit_msg>[http] let postpone FastCGI request<commit_after>// $Id$ // Author: Sergey Linev 28/12/2013 /************************************************************************* * Copyright (C) 1995-2013, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TFastCgi.h" #include "TThread.h" #include "TUrl.h" #include "THttpServer.h" #include <string.h> #ifdef WIN32 #include <io.h> #else #include <unistd.h> #endif //////////////////////////////////////////////////////////////////////////////// class TFastCgiCallArg : public THttpCallArg { bool fCanPostpone{false}; protected: void CheckWSPageContent(THttpWSHandler *) override { std::string search = "JSROOT.connectWebWindow({"; std::string replace = search + "socket_kind:\"longpoll\","; ReplaceAllinContent(search, replace, true); } public: TFastCgiCallArg(bool can_postpone) : THttpCallArg(), fCanPostpone(can_postpone) {}; /** All FastCGI requests should be immediately replied to get slot for next */ Bool_t CanPostpone() const override { return fCanPostpone; } }; //////////////////////////////////////////////////////////////////////////////// #ifndef HTTP_WITHOUT_FASTCGI #include "fcgiapp.h" #include <stdlib.h> void FCGX_ROOT_send_file(FCGX_Request *request, const char *fname) { std::string buf = THttpServer::ReadFileContent(fname); if (buf.empty()) { FCGX_FPrintF(request->out, "Status: 404 Not Found\r\n" "Content-Length: 0\r\n" // Always set Content-Length "Connection: close\r\n\r\n"); } else { FCGX_FPrintF(request->out, "Status: 200 OK\r\n" "Content-Type: %s\r\n" "Content-Length: %d\r\n" // Always set Content-Length "\r\n", THttpServer::GetMimeType(fname), (int) buf.length()); FCGX_PutStr(buf.c_str(), buf.length(), request->out); } } void process_request(TFastCgi *engine, FCGX_Request *request, bool can_postpone) { int count = 0; count++; // simple static request counter const char *inp_path = FCGX_GetParam("PATH_INFO", request->envp); if (!inp_path) inp_path = FCGX_GetParam("SCRIPT_FILENAME", request->envp); const char *inp_query = FCGX_GetParam("QUERY_STRING", request->envp); const char *inp_method = FCGX_GetParam("REQUEST_METHOD", request->envp); const char *inp_length = FCGX_GetParam("CONTENT_LENGTH", request->envp); auto arg = std::make_shared<TFastCgiCallArg>(can_postpone); if (inp_path) arg->SetPathAndFileName(inp_path); if (inp_query) arg->SetQuery(inp_query); if (inp_method) arg->SetMethod(inp_method); if (engine->GetTopName()) arg->SetTopName(engine->GetTopName()); int len = 0; if (inp_length) len = strtol(inp_length, nullptr, 10); if (len > 0) { std::string buf; buf.resize(len); int nread = FCGX_GetStr((char *)buf.data(), len, request->in); if (nread == len) arg->SetPostData(std::move(buf)); } TString header; for (char **envp = request->envp; *envp != nullptr; envp++) { TString entry = *envp; for (Int_t n = 0; n < entry.Length(); n++) if (entry[n] == '=') { entry[n] = ':'; break; } header.Append(entry); header.Append("\r\n"); } arg->SetRequestHeader(header); TString username = arg->GetRequestHeader("REMOTE_USER"); if ((username.Length() > 0) && (arg->GetRequestHeader("AUTH_TYPE").Length() > 0)) arg->SetUserName(username); if (engine->IsDebugMode()) { FCGX_FPrintF(request->out, "Status: 200 OK\r\n" "Content-type: text/html\r\n" "\r\n" "<title>FastCGI echo</title>" "<h1>FastCGI echo</h1>\n"); FCGX_FPrintF(request->out, "Request %d:<br/>\n<pre>\n", count); FCGX_FPrintF(request->out, " Method : %s\n", arg->GetMethod()); FCGX_FPrintF(request->out, " PathName : %s\n", arg->GetPathName()); FCGX_FPrintF(request->out, " FileName : %s\n", arg->GetFileName()); FCGX_FPrintF(request->out, " Query : %s\n", arg->GetQuery()); FCGX_FPrintF(request->out, " PostData : %ld\n", arg->GetPostDataLength()); FCGX_FPrintF(request->out, "</pre><p>\n"); FCGX_FPrintF(request->out, "Environment:<br/>\n<pre>\n"); for (char **envp = request->envp; *envp != nullptr; envp++) FCGX_FPrintF(request->out, " %s\n", *envp); FCGX_FPrintF(request->out, "</pre><p>\n"); return; } TString fname; if (engine->GetServer()->IsFileRequested(inp_path, fname)) { FCGX_ROOT_send_file(request, fname.Data()); return; } if (!engine->GetServer()->ExecuteHttp(arg) || arg->Is404()) { std::string hdr = arg->FillHttpHeader("Status:"); FCGX_FPrintF(request->out, hdr.c_str()); } else if (arg->IsFile()) { FCGX_ROOT_send_file(request, (const char *)arg->GetContent()); } else { // TODO: check in request header that gzip encoding is supported if (arg->GetZipping() != THttpCallArg::kNoZip) arg->CompressWithGzip(); std::string hdr = arg->FillHttpHeader("Status:"); FCGX_FPrintF(request->out, hdr.c_str()); FCGX_PutStr((const char *)arg->GetContent(), (int)arg->GetContentLength(), request->out); } } void run_multi_threads(TFastCgi *engine, Int_t nthrds) { std::condition_variable cond; ///<! condition used to wait for processing std::mutex m; std::unique_ptr<FCGX_Request> arg; int nwaiting = 0; auto worker_func = [engine, &cond, &m, &arg, &nwaiting]() { while (!engine->IsTerminating()) { std::unique_ptr<FCGX_Request> request; bool can_postpone = false; { std::unique_lock<std::mutex> lk(m); nwaiting++; cond.wait(lk); nwaiting--; can_postpone = (nwaiting > 5); std::swap(arg, request); } if (request) { process_request(engine, request.get(), can_postpone); FCGX_Finish_r(request.get()); } } }; // start N workers std::vector<std::thread> workers; for (int n=0; n< nthrds; ++n) workers.emplace_back(worker_func); while (!engine->IsTerminating()) { auto request = std::make_unique<FCGX_Request>(); FCGX_InitRequest(request.get(), engine->GetSocket(), 0); int rc = FCGX_Accept_r(request.get()); if (rc != 0) continue; { std::lock_guard<std::mutex> lk(m); if (nwaiting > 0) std::swap(request, arg); } if (!request) { // notify thread to process request cond.notify_one(); } else { // process request ourselfs process_request(engine, request.get(), false); FCGX_Finish_r(request.get()); } } // ensure that all threads are waked up cond.notify_all(); // join all workers for (auto & thrd : workers) thrd.join(); } // simple run function to process all requests in same thread void run_single_thread(TFastCgi *engine) { FCGX_Request request; FCGX_InitRequest(&request, engine->GetSocket(), 0); while (!engine->IsTerminating()) { int rc = FCGX_Accept_r(&request); if (rc != 0) continue; process_request(engine, &request, false); FCGX_Finish_r(&request); } } #endif ////////////////////////////////////////////////////////////////////////// // // // TFastCgi // // // // http engine implementation, based on fastcgi package // // Allows to redirect http requests from normal web server like // // Apache or lighttpd // // // // Configuration example for lighttpd // // // // server.modules += ( "mod_fastcgi" ) // // fastcgi.server = ( // // "/remote_scripts/" => // // (( "host" => "192.168.1.11", // // "port" => 9000, // // "check-local" => "disable", // // "docroot" => "/" // // )) // // ) // // // // When creating THttpServer, one should specify: // // // // THttpServer* serv = new THttpServer("fastcgi:9000"); // // // // In this case, requests to lighttpd server will be // // redirected to ROOT session. Like: // // http://lighttpdhost/remote_scripts/root.cgi/ // // // // Following additional options can be specified // // top=foldername - name of top folder, seen in the browser // // thrds=N - run N worker threads to process requests, default 10 // // debug=1 - run fastcgi server in debug mode // // Example: // // serv->CreateEngine("fastcgi:9000?top=fastcgiserver"); // // // // // ////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// normal constructor TFastCgi::TFastCgi() : THttpEngine("fastcgi", "fastcgi interface to webserver") { } //////////////////////////////////////////////////////////////////////////////// /// destructor TFastCgi::~TFastCgi() { fTerminating = kTRUE; // running thread will stopped if (fThrd) fThrd->join(); if (fSocket > 0) { // close opened socket close(fSocket); fSocket = 0; } } //////////////////////////////////////////////////////////////////////////////// /// initializes fastcgi variables and start thread, /// which will process incoming http requests Bool_t TFastCgi::Create(const char *args) { #ifndef HTTP_WITHOUT_FASTCGI FCGX_Init(); TString sport = ":9000"; Int_t nthrds = 10; if ((args != 0) && (strlen(args) > 0)) { // first extract port number sport = ":"; while ((*args != 0) && (*args >= '0') && (*args <= '9')) sport.Append(*args++); // than search for extra parameters while ((*args != 0) && (*args != '?')) args++; if (*args == '?') { TUrl url(TString::Format("http://localhost/folder%s", args)); if (url.IsValid()) { url.ParseOptions(); if (url.GetValueFromOptions("debug") != 0) fDebugMode = kTRUE; if (url.HasOption("thrds")) nthrds = url.GetIntValueFromOptions("thrds"); const char *top = url.GetValueFromOptions("top"); if (top != 0) fTopName = top; } } } Info("Create", "Starting FastCGI server on port %s", sport.Data() + 1); fSocket = FCGX_OpenSocket(sport.Data(), 10); if (!fSocket) return kFALSE; if (nthrds > 0) fThrd = std::make_unique<std::thread>(run_multi_threads, this, nthrds); else fThrd = std::make_unique<std::thread>(run_single_thread, this); return kTRUE; #else (void) args; Error("Create", "ROOT compiled without fastcgi support"); return kFALSE; #endif } <|endoftext|>
<commit_before>#include "FlowControllerFactory.hpp" #include "FlowControllerImpl.hpp" #include <fastdds/dds/log/Log.hpp> namespace eprosima { namespace fastdds { namespace rtps { const char* const pure_sync_flow_controller_name = "PureSyncFlowController"; const char* const sync_flow_controller_name = "SyncFlowController"; const char* const async_flow_controller_name = "AsyncFlowController"; #ifdef FASTDDS_STATISTICS const char* const async_statistics_flow_controller_name = "AsyncStatisticsFlowController"; #endif // ifndef FASTDDS_STATISTICS void FlowControllerFactory::init( fastrtps::rtps::RTPSParticipantImpl* participant) { participant_ = participant; // Create default flow controllers. // PureSyncFlowController -> used by volatile besteffort writers. flow_controllers_.insert({pure_sync_flow_controller_name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerPureSyncPublishMode, FlowControllerFifoSchedule>(participant_, nullptr))}); // SyncFlowController -> used by rest of besteffort writers. flow_controllers_.insert({sync_flow_controller_name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerSyncPublishMode, FlowControllerFifoSchedule>(participant_, nullptr))}); // AsyncFlowController flow_controllers_.insert({async_flow_controller_name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerAsyncPublishMode, FlowControllerFifoSchedule>(participant_, nullptr))}); #ifdef FASTDDS_STATISTICS flow_controllers_.insert({async_statistics_flow_controller_name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerAsyncPublishMode, FlowControllerFifoSchedule>(participant_, nullptr))}); #endif // ifndef FASTDDS_STATISTICS } void FlowControllerFactory::register_flow_controller ( const FlowControllerDescriptor& flow_controller_descr) { if (flow_controllers_.end() != flow_controllers_.find(flow_controller_descr.name)) { logError(RTPS_PARTICIPANT, "Error registering FlowController " << flow_controller_descr.name << ". Already registered"); return; } if (0 < flow_controller_descr.max_bytes_per_period) { switch (flow_controller_descr.scheduler) { case FlowControllerSchedulerPolicy::FIFO: flow_controllers_.insert({flow_controller_descr.name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerLimitedAsyncPublishMode, FlowControllerFifoSchedule>(participant_, &flow_controller_descr))}); break; case FlowControllerSchedulerPolicy::ROUND_ROBIN: flow_controllers_.insert({flow_controller_descr.name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerLimitedAsyncPublishMode, FlowControllerRoundRobinSchedule>(participant_, &flow_controller_descr))}); break; case FlowControllerSchedulerPolicy::HIGH_PRIORITY: flow_controllers_.insert({flow_controller_descr.name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerLimitedAsyncPublishMode, FlowControllerHighPrioritySchedule>(participant_, &flow_controller_descr))}); break; case FlowControllerSchedulerPolicy::PRIORITY_WITH_RESERVATION: flow_controllers_.insert({flow_controller_descr.name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerLimitedAsyncPublishMode, FlowControllerPriorityWithReservationSchedule>(participant_, &flow_controller_descr))}); break; default: assert(false); } } else { switch (flow_controller_descr.scheduler) { case FlowControllerSchedulerPolicy::FIFO: flow_controllers_.insert({flow_controller_descr.name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerAsyncPublishMode, FlowControllerFifoSchedule>(participant_, &flow_controller_descr))}); break; case FlowControllerSchedulerPolicy::ROUND_ROBIN: flow_controllers_.insert({flow_controller_descr.name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerAsyncPublishMode, FlowControllerRoundRobinSchedule>(participant_, &flow_controller_descr))}); break; case FlowControllerSchedulerPolicy::HIGH_PRIORITY: flow_controllers_.insert({flow_controller_descr.name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerAsyncPublishMode, FlowControllerHighPrioritySchedule>(participant_, &flow_controller_descr))}); break; case FlowControllerSchedulerPolicy::PRIORITY_WITH_RESERVATION: flow_controllers_.insert({flow_controller_descr.name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerAsyncPublishMode, FlowControllerPriorityWithReservationSchedule>(participant_, &flow_controller_descr))}); break; default: assert(false); } } } /*! * Get a FlowController given its name. * * @param flow_controller_name Name of the interested FlowController. * @return Pointer to the FlowController. nullptr if no registered FlowController with that name. */ FlowController* FlowControllerFactory::retrieve_flow_controller( const std::string& flow_controller_name, const fastrtps::rtps::WriterAttributes& writer_attributes) { FlowController* returned_flow = nullptr; // Detect it has to be returned a default flow_controller. if (0 == flow_controller_name.compare(FASTDDS_FLOW_CONTROLLER_DEFAULT)) { if (fastrtps::rtps::SYNCHRONOUS_WRITER == writer_attributes.mode) { if (fastrtps::rtps::BEST_EFFORT == writer_attributes.endpoint.reliabilityKind) { returned_flow = flow_controllers_[pure_sync_flow_controller_name].get(); } else { returned_flow = flow_controllers_[sync_flow_controller_name].get(); } } else { returned_flow = flow_controllers_[async_flow_controller_name].get(); } } #ifdef FASTDDS_STATISTICS else if (0 == flow_controller_name.compare(FASTDDS_STATISTICS_FLOW_CONTROLLER_DEFAULT)) { assert(fastrtps::rtps::ASYNCHRONOUS_WRITER == writer_attributes.mode); returned_flow = flow_controllers_[async_statistics_flow_controller_name].get(); } #endif // ifdef FASTDDS_STATISTICS else { auto it = flow_controllers_.find(flow_controller_name); if (flow_controllers_.end() != it) { returned_flow = it->second.get(); } } if (nullptr != returned_flow) { returned_flow->init(); } else { logError(RTPS_PARTICIPANT, "Cannot find FlowController " << flow_controller_name << "."); } return returned_flow; } } // namespace rtps } // namespace fastdds } // namespace eprosima <commit_msg>Fix build on old compilers (#2220)<commit_after>#include "FlowControllerFactory.hpp" #include "FlowControllerImpl.hpp" #include <fastdds/dds/log/Log.hpp> namespace eprosima { namespace fastdds { namespace rtps { const char* const pure_sync_flow_controller_name = "PureSyncFlowController"; const char* const sync_flow_controller_name = "SyncFlowController"; const char* const async_flow_controller_name = "AsyncFlowController"; #ifdef FASTDDS_STATISTICS const char* const async_statistics_flow_controller_name = "AsyncStatisticsFlowController"; #endif // ifndef FASTDDS_STATISTICS void FlowControllerFactory::init( fastrtps::rtps::RTPSParticipantImpl* participant) { participant_ = participant; // Create default flow controllers. // PureSyncFlowController -> used by volatile besteffort writers. flow_controllers_.insert(std::make_pair<std::string, std::unique_ptr<FlowController>>( pure_sync_flow_controller_name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerPureSyncPublishMode, FlowControllerFifoSchedule>(participant_, nullptr)))); // SyncFlowController -> used by rest of besteffort writers. flow_controllers_.insert(std::make_pair<std::string, std::unique_ptr<FlowController>>( sync_flow_controller_name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerSyncPublishMode, FlowControllerFifoSchedule>(participant_, nullptr)))); // AsyncFlowController flow_controllers_.insert(std::make_pair<std::string, std::unique_ptr<FlowController>>( async_flow_controller_name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerAsyncPublishMode, FlowControllerFifoSchedule>(participant_, nullptr)))); #ifdef FASTDDS_STATISTICS flow_controllers_.insert({async_statistics_flow_controller_name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerAsyncPublishMode, FlowControllerFifoSchedule>(participant_, nullptr))}); #endif // ifndef FASTDDS_STATISTICS } void FlowControllerFactory::register_flow_controller ( const FlowControllerDescriptor& flow_controller_descr) { if (flow_controllers_.end() != flow_controllers_.find(flow_controller_descr.name)) { logError(RTPS_PARTICIPANT, "Error registering FlowController " << flow_controller_descr.name << ". Already registered"); return; } if (0 < flow_controller_descr.max_bytes_per_period) { switch (flow_controller_descr.scheduler) { case FlowControllerSchedulerPolicy::FIFO: flow_controllers_.insert({flow_controller_descr.name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerLimitedAsyncPublishMode, FlowControllerFifoSchedule>(participant_, &flow_controller_descr))}); break; case FlowControllerSchedulerPolicy::ROUND_ROBIN: flow_controllers_.insert({flow_controller_descr.name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerLimitedAsyncPublishMode, FlowControllerRoundRobinSchedule>(participant_, &flow_controller_descr))}); break; case FlowControllerSchedulerPolicy::HIGH_PRIORITY: flow_controllers_.insert({flow_controller_descr.name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerLimitedAsyncPublishMode, FlowControllerHighPrioritySchedule>(participant_, &flow_controller_descr))}); break; case FlowControllerSchedulerPolicy::PRIORITY_WITH_RESERVATION: flow_controllers_.insert({flow_controller_descr.name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerLimitedAsyncPublishMode, FlowControllerPriorityWithReservationSchedule>(participant_, &flow_controller_descr))}); break; default: assert(false); } } else { switch (flow_controller_descr.scheduler) { case FlowControllerSchedulerPolicy::FIFO: flow_controllers_.insert({flow_controller_descr.name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerAsyncPublishMode, FlowControllerFifoSchedule>(participant_, &flow_controller_descr))}); break; case FlowControllerSchedulerPolicy::ROUND_ROBIN: flow_controllers_.insert({flow_controller_descr.name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerAsyncPublishMode, FlowControllerRoundRobinSchedule>(participant_, &flow_controller_descr))}); break; case FlowControllerSchedulerPolicy::HIGH_PRIORITY: flow_controllers_.insert({flow_controller_descr.name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerAsyncPublishMode, FlowControllerHighPrioritySchedule>(participant_, &flow_controller_descr))}); break; case FlowControllerSchedulerPolicy::PRIORITY_WITH_RESERVATION: flow_controllers_.insert({flow_controller_descr.name, std::unique_ptr<FlowController>( new FlowControllerImpl<FlowControllerAsyncPublishMode, FlowControllerPriorityWithReservationSchedule>(participant_, &flow_controller_descr))}); break; default: assert(false); } } } /*! * Get a FlowController given its name. * * @param flow_controller_name Name of the interested FlowController. * @return Pointer to the FlowController. nullptr if no registered FlowController with that name. */ FlowController* FlowControllerFactory::retrieve_flow_controller( const std::string& flow_controller_name, const fastrtps::rtps::WriterAttributes& writer_attributes) { FlowController* returned_flow = nullptr; // Detect it has to be returned a default flow_controller. if (0 == flow_controller_name.compare(FASTDDS_FLOW_CONTROLLER_DEFAULT)) { if (fastrtps::rtps::SYNCHRONOUS_WRITER == writer_attributes.mode) { if (fastrtps::rtps::BEST_EFFORT == writer_attributes.endpoint.reliabilityKind) { returned_flow = flow_controllers_[pure_sync_flow_controller_name].get(); } else { returned_flow = flow_controllers_[sync_flow_controller_name].get(); } } else { returned_flow = flow_controllers_[async_flow_controller_name].get(); } } #ifdef FASTDDS_STATISTICS else if (0 == flow_controller_name.compare(FASTDDS_STATISTICS_FLOW_CONTROLLER_DEFAULT)) { assert(fastrtps::rtps::ASYNCHRONOUS_WRITER == writer_attributes.mode); returned_flow = flow_controllers_[async_statistics_flow_controller_name].get(); } #endif // ifdef FASTDDS_STATISTICS else { auto it = flow_controllers_.find(flow_controller_name); if (flow_controllers_.end() != it) { returned_flow = it->second.get(); } } if (nullptr != returned_flow) { returned_flow->init(); } else { logError(RTPS_PARTICIPANT, "Cannot find FlowController " << flow_controller_name << "."); } return returned_flow; } } // namespace rtps } // namespace fastdds } // namespace eprosima <|endoftext|>
<commit_before>/* Copyright 2017 R. Thomas * Copyright 2017 Quarkslab * * 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 "LIEF/config.h" #include "LIEF/logging.hpp" #include "LIEF/logging++.hpp" #include <map> #if defined(LIEF_LOGGING_SUPPORT) INITIALIZE_EASYLOGGINGPP #endif static LIEF::Logger logger; namespace LIEF { const char* logging_config = R"config( * GLOBAL: FORMAT = "%msg" ENABLED = true TO_STANDARD_OUTPUT = true TO_FILE = false PERFORMANCE_TRACKING = true * DEBUG: FORMAT = "%func %msg" Enabled = true )config"; const char* logging_config_disabled = R"config( * GLOBAL: FORMAT = "%msg" ENABLED = false TO_STANDARD_OUTPUT = false TO_FILE = false PERFORMANCE_TRACKING = false * DEBUG: FORMAT = "%func %msg" Enabled = false )config"; Logger::~Logger(void) = default; const char* to_string(LOGGING_LEVEL e) { const std::map<LOGGING_LEVEL, const char*> enumStrings { { LOGGING_LEVEL::LOG_GLOBAL, "GLOBAL" }, { LOGGING_LEVEL::LOG_TRACE, "TRACE" }, { LOGGING_LEVEL::LOG_DEBUG, "DEBUG" }, { LOGGING_LEVEL::LOG_FATAL, "FATAL" }, { LOGGING_LEVEL::LOG_ERROR, "ERROR" }, { LOGGING_LEVEL::LOG_WARNING, "WARNING" }, { LOGGING_LEVEL::LOG_INFO, "INFO" }, { LOGGING_LEVEL::LOG_VERBOSE, "VERBOSE" }, { LOGGING_LEVEL::LOG_UNKNOWN, "UNKNOWN" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "UNDEFINED" : it->second; } Logger::Logger(void) { #if defined(LIEF_LOGGING_SUPPORT) (void)el::Loggers::getLogger("default"); this->enable(); this->disable(); #endif } void Logger::disable(void) { #if defined(LIEF_LOGGING_SUPPORT) el::Loggers::setLoggingLevel(el::Level::Unknown); el::Configurations conf; conf.setToDefault(); conf.parseFromText(logging_config_disabled); el::Loggers::reconfigureAllLoggers(conf); #endif } void Logger::enable(void) { #if defined(LIEF_LOGGING_SUPPORT) el::Configurations conf; conf.setToDefault(); conf.parseFromText(logging_config); el::Loggers::setDefaultConfigurations(conf, true); el::Loggers::addFlag(el::LoggingFlag::HierarchicalLogging); el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput); el::Loggers::addFlag(el::LoggingFlag::ImmediateFlush); el::Loggers::addFlag(el::LoggingFlag::CreateLoggerAutomatically); el::Loggers::setLoggingLevel(el::Level::Fatal); #endif } void Logger::set_verbose_level(uint32_t level) { #if defined(LIEF_LOGGING_SUPPORT) Logger::enable(); el::Loggers::setVerboseLevel(level); #endif } void Logger::set_level(LOGGING_LEVEL level) { #if defined(LIEF_LOGGING_SUPPORT) Logger::enable(); el::Loggers::setLoggingLevel(static_cast<el::Level>(level)); if (level == LOGGING_LEVEL::LOG_DEBUG) { set_verbose_level(VDEBUG); } #endif } } <commit_msg>Disable abort() on fatal log<commit_after>/* Copyright 2017 R. Thomas * Copyright 2017 Quarkslab * * 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 "LIEF/config.h" #include "LIEF/logging.hpp" #include "LIEF/logging++.hpp" #include <map> #if defined(LIEF_LOGGING_SUPPORT) INITIALIZE_EASYLOGGINGPP #endif static LIEF::Logger logger; namespace LIEF { const char* logging_config = R"config( * GLOBAL: FORMAT = "%msg" ENABLED = true TO_STANDARD_OUTPUT = true TO_FILE = false PERFORMANCE_TRACKING = true * DEBUG: FORMAT = "%func %msg" Enabled = true )config"; const char* logging_config_disabled = R"config( * GLOBAL: FORMAT = "%msg" ENABLED = false TO_STANDARD_OUTPUT = false TO_FILE = false PERFORMANCE_TRACKING = false * DEBUG: FORMAT = "%func %msg" Enabled = false )config"; Logger::~Logger(void) = default; const char* to_string(LOGGING_LEVEL e) { const std::map<LOGGING_LEVEL, const char*> enumStrings { { LOGGING_LEVEL::LOG_GLOBAL, "GLOBAL" }, { LOGGING_LEVEL::LOG_TRACE, "TRACE" }, { LOGGING_LEVEL::LOG_DEBUG, "DEBUG" }, { LOGGING_LEVEL::LOG_FATAL, "FATAL" }, { LOGGING_LEVEL::LOG_ERROR, "ERROR" }, { LOGGING_LEVEL::LOG_WARNING, "WARNING" }, { LOGGING_LEVEL::LOG_INFO, "INFO" }, { LOGGING_LEVEL::LOG_VERBOSE, "VERBOSE" }, { LOGGING_LEVEL::LOG_UNKNOWN, "UNKNOWN" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "UNDEFINED" : it->second; } Logger::Logger(void) { #if defined(LIEF_LOGGING_SUPPORT) (void)el::Loggers::getLogger("default"); this->enable(); this->disable(); #endif } void Logger::disable(void) { #if defined(LIEF_LOGGING_SUPPORT) el::Loggers::setLoggingLevel(el::Level::Unknown); el::Configurations conf; conf.setToDefault(); conf.parseFromText(logging_config_disabled); el::Loggers::reconfigureAllLoggers(conf); #endif } void Logger::enable(void) { #if defined(LIEF_LOGGING_SUPPORT) el::Configurations conf; conf.setToDefault(); conf.parseFromText(logging_config); el::Loggers::setDefaultConfigurations(conf, true); el::Loggers::addFlag(el::LoggingFlag::HierarchicalLogging); el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput); el::Loggers::addFlag(el::LoggingFlag::ImmediateFlush); el::Loggers::addFlag(el::LoggingFlag::CreateLoggerAutomatically); el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog); el::Loggers::setLoggingLevel(el::Level::Fatal); #endif } void Logger::set_verbose_level(uint32_t level) { #if defined(LIEF_LOGGING_SUPPORT) Logger::enable(); el::Loggers::setVerboseLevel(level); #endif } void Logger::set_level(LOGGING_LEVEL level) { #if defined(LIEF_LOGGING_SUPPORT) Logger::enable(); el::Loggers::setLoggingLevel(static_cast<el::Level>(level)); if (level == LOGGING_LEVEL::LOG_DEBUG) { set_verbose_level(VDEBUG); } #endif } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: CustomAnimationDialog.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: kz $ $Date: 2008-04-02 09:44:26 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SD_CUSTOMANIMATIONDIALOG_HXX #define _SD_CUSTOMANIMATIONDIALOG_HXX #ifndef _SD_CUSTOMANIMATIONEFFECT_HXX #include "CustomAnimationEffect.hxx" #endif #ifndef _SD_CUSTOMANIMATIONPRESET_HXX #include "CustomAnimationPreset.hxx" #endif #ifndef _SV_TABDLG_HXX #include <vcl/tabdlg.hxx> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif class TabControl; class OKButton; class CancelButton; class HelpButton; namespace sd { // -------------------------------------------------------------------- // property handles const sal_Int32 nHandleSound = 0; const sal_Int32 nHandleHasAfterEffect = 1; const sal_Int32 nHandleIterateType = 2; const sal_Int32 nHandleIterateInterval = 3; const sal_Int32 nHandleStart = 4; const sal_Int32 nHandleBegin = 5; const sal_Int32 nHandleDuration = 6; const sal_Int32 nHandleRepeat = 7; const sal_Int32 nHandleRewind = 8; const sal_Int32 nHandleEnd = 9; const sal_Int32 nHandleAfterEffectOnNextEffect = 10; const sal_Int32 nHandleDimColor = 11; const sal_Int32 nHandleMaxParaDepth = 12; const sal_Int32 nHandlePresetId = 13; const sal_Int32 nHandleProperty1Type = 14; const sal_Int32 nHandleProperty1Value = 15; const sal_Int32 nHandleProperty2Type = 16; const sal_Int32 nHandleProperty2Value = 17; const sal_Int32 nHandleAccelerate = 18; const sal_Int32 nHandleDecelerate = 19; const sal_Int32 nHandleAutoReverse = 20; const sal_Int32 nHandleTrigger = 21; const sal_Int32 nHandleHasText = 22; const sal_Int32 nHandleTextGrouping = 23; const sal_Int32 nHandleAnimateForm = 24; const sal_Int32 nHandleTextGroupingAuto = 25; const sal_Int32 nHandleTextReverse = 26; const sal_Int32 nHandleCurrentPage = 27; const sal_Int32 nHandleSoundURL = 28; const sal_Int32 nHandleSoundVolumne = 29; const sal_Int32 nHandleSoundEndAfterSlide = 30; const sal_Int32 nHandleCommand = 31; const sal_Int32 nHandleHasVisibleShape = 32; const sal_Int32 nPropertyTypeNone = 0; const sal_Int32 nPropertyTypeDirection = 1; const sal_Int32 nPropertyTypeSpokes = 2; const sal_Int32 nPropertyTypeFirstColor = 3; const sal_Int32 nPropertyTypeSecondColor = 4; const sal_Int32 nPropertyTypeZoom = 5; const sal_Int32 nPropertyTypeFillColor = 6; const sal_Int32 nPropertyTypeColorStyle = 7; const sal_Int32 nPropertyTypeFont = 8; const sal_Int32 nPropertyTypeCharHeight = 9; const sal_Int32 nPropertyTypeCharColor = 10; const sal_Int32 nPropertyTypeCharHeightStyle = 11; const sal_Int32 nPropertyTypeCharDecoration = 12; const sal_Int32 nPropertyTypeLineColor = 13; const sal_Int32 nPropertyTypeRotate = 14; const sal_Int32 nPropertyTypeColor = 15; const sal_Int32 nPropertyTypeAccelerate = 16; const sal_Int32 nPropertyTypeDecelerate = 17; const sal_Int32 nPropertyTypeAutoReverse = 18; const sal_Int32 nPropertyTypeTransparency = 19; const sal_Int32 nPropertyTypeFontStyle = 20; const sal_Int32 nPropertyTypeScale = 21; // -------------------------------------------------------------------- class PropertySubControl { public: PropertySubControl( sal_Int32 nType ) : mnType( nType ) {} virtual ~PropertySubControl(); virtual ::com::sun::star::uno::Any getValue() = 0; virtual void setValue( const ::com::sun::star::uno::Any& rValue, const rtl::OUString& rPresetId ) = 0; virtual Control* getControl() = 0; static PropertySubControl* create( sal_Int32 nType, ::Window* pParent, const ::com::sun::star::uno::Any& rValue, const rtl::OUString& rPresetId, const Link& rModifyHdl ); sal_Int32 getControlType() const { return mnType; } protected: sal_Int32 mnType; }; // -------------------------------------------------------------------- class PropertyControl : public ListBox { public: PropertyControl( Window* pParent, const ResId& rResId ); ~PropertyControl(); void setSubControl( PropertySubControl* pSubControl ); PropertySubControl* getSubControl() const { return mpSubControl; } virtual void Resize(); private: PropertySubControl* mpSubControl; }; // -------------------------------------------------------------------- class CustomAnimationDurationTabPage; class CustomAnimationEffectTabPage; class CustomAnimationTextAnimTabPage; class STLPropertySet; class CustomAnimationDialog : public TabDialog { public: CustomAnimationDialog( Window* pParent, STLPropertySet* pSet, USHORT nPage = 0 ); ~CustomAnimationDialog(); STLPropertySet* getDefaultSet() { return mpSet; } STLPropertySet* getResultSet(); static STLPropertySet* createDefaultSet(); private: STLPropertySet* mpSet; STLPropertySet* mpResultSet; CustomAnimationEffectPtr mpEffect; TabControl* mpTabControl; OKButton* mpOKButton; CancelButton* mpCancelButton; HelpButton* mpHelpButton; CustomAnimationDurationTabPage* mpDurationTabPage; CustomAnimationEffectTabPage* mpEffectTabPage; CustomAnimationTextAnimTabPage* mpTextAnimTabPage; }; } #endif // _SD_CUSTOMANIMATIONDIALOG_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.6.298); FILE MERGED 2008/04/01 15:34:10 thb 1.6.298.3: #i85898# Stripping all external header guards 2008/04/01 12:38:36 thb 1.6.298.2: #i85898# Stripping all external header guards 2008/03/31 13:56:55 rt 1.6.298.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: CustomAnimationDialog.hxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SD_CUSTOMANIMATIONDIALOG_HXX #define _SD_CUSTOMANIMATIONDIALOG_HXX #include "CustomAnimationEffect.hxx" #include "CustomAnimationPreset.hxx" #include <vcl/tabdlg.hxx> #include <vcl/lstbox.hxx> class TabControl; class OKButton; class CancelButton; class HelpButton; namespace sd { // -------------------------------------------------------------------- // property handles const sal_Int32 nHandleSound = 0; const sal_Int32 nHandleHasAfterEffect = 1; const sal_Int32 nHandleIterateType = 2; const sal_Int32 nHandleIterateInterval = 3; const sal_Int32 nHandleStart = 4; const sal_Int32 nHandleBegin = 5; const sal_Int32 nHandleDuration = 6; const sal_Int32 nHandleRepeat = 7; const sal_Int32 nHandleRewind = 8; const sal_Int32 nHandleEnd = 9; const sal_Int32 nHandleAfterEffectOnNextEffect = 10; const sal_Int32 nHandleDimColor = 11; const sal_Int32 nHandleMaxParaDepth = 12; const sal_Int32 nHandlePresetId = 13; const sal_Int32 nHandleProperty1Type = 14; const sal_Int32 nHandleProperty1Value = 15; const sal_Int32 nHandleProperty2Type = 16; const sal_Int32 nHandleProperty2Value = 17; const sal_Int32 nHandleAccelerate = 18; const sal_Int32 nHandleDecelerate = 19; const sal_Int32 nHandleAutoReverse = 20; const sal_Int32 nHandleTrigger = 21; const sal_Int32 nHandleHasText = 22; const sal_Int32 nHandleTextGrouping = 23; const sal_Int32 nHandleAnimateForm = 24; const sal_Int32 nHandleTextGroupingAuto = 25; const sal_Int32 nHandleTextReverse = 26; const sal_Int32 nHandleCurrentPage = 27; const sal_Int32 nHandleSoundURL = 28; const sal_Int32 nHandleSoundVolumne = 29; const sal_Int32 nHandleSoundEndAfterSlide = 30; const sal_Int32 nHandleCommand = 31; const sal_Int32 nHandleHasVisibleShape = 32; const sal_Int32 nPropertyTypeNone = 0; const sal_Int32 nPropertyTypeDirection = 1; const sal_Int32 nPropertyTypeSpokes = 2; const sal_Int32 nPropertyTypeFirstColor = 3; const sal_Int32 nPropertyTypeSecondColor = 4; const sal_Int32 nPropertyTypeZoom = 5; const sal_Int32 nPropertyTypeFillColor = 6; const sal_Int32 nPropertyTypeColorStyle = 7; const sal_Int32 nPropertyTypeFont = 8; const sal_Int32 nPropertyTypeCharHeight = 9; const sal_Int32 nPropertyTypeCharColor = 10; const sal_Int32 nPropertyTypeCharHeightStyle = 11; const sal_Int32 nPropertyTypeCharDecoration = 12; const sal_Int32 nPropertyTypeLineColor = 13; const sal_Int32 nPropertyTypeRotate = 14; const sal_Int32 nPropertyTypeColor = 15; const sal_Int32 nPropertyTypeAccelerate = 16; const sal_Int32 nPropertyTypeDecelerate = 17; const sal_Int32 nPropertyTypeAutoReverse = 18; const sal_Int32 nPropertyTypeTransparency = 19; const sal_Int32 nPropertyTypeFontStyle = 20; const sal_Int32 nPropertyTypeScale = 21; // -------------------------------------------------------------------- class PropertySubControl { public: PropertySubControl( sal_Int32 nType ) : mnType( nType ) {} virtual ~PropertySubControl(); virtual ::com::sun::star::uno::Any getValue() = 0; virtual void setValue( const ::com::sun::star::uno::Any& rValue, const rtl::OUString& rPresetId ) = 0; virtual Control* getControl() = 0; static PropertySubControl* create( sal_Int32 nType, ::Window* pParent, const ::com::sun::star::uno::Any& rValue, const rtl::OUString& rPresetId, const Link& rModifyHdl ); sal_Int32 getControlType() const { return mnType; } protected: sal_Int32 mnType; }; // -------------------------------------------------------------------- class PropertyControl : public ListBox { public: PropertyControl( Window* pParent, const ResId& rResId ); ~PropertyControl(); void setSubControl( PropertySubControl* pSubControl ); PropertySubControl* getSubControl() const { return mpSubControl; } virtual void Resize(); private: PropertySubControl* mpSubControl; }; // -------------------------------------------------------------------- class CustomAnimationDurationTabPage; class CustomAnimationEffectTabPage; class CustomAnimationTextAnimTabPage; class STLPropertySet; class CustomAnimationDialog : public TabDialog { public: CustomAnimationDialog( Window* pParent, STLPropertySet* pSet, USHORT nPage = 0 ); ~CustomAnimationDialog(); STLPropertySet* getDefaultSet() { return mpSet; } STLPropertySet* getResultSet(); static STLPropertySet* createDefaultSet(); private: STLPropertySet* mpSet; STLPropertySet* mpResultSet; CustomAnimationEffectPtr mpEffect; TabControl* mpTabControl; OKButton* mpOKButton; CancelButton* mpCancelButton; HelpButton* mpHelpButton; CustomAnimationDurationTabPage* mpDurationTabPage; CustomAnimationEffectTabPage* mpEffectTabPage; CustomAnimationTextAnimTabPage* mpTextAnimTabPage; }; } #endif // _SD_CUSTOMANIMATIONDIALOG_HXX <|endoftext|>
<commit_before>#include "demoloop.h" #include "graphics/3d_primitives.h" #include "graphics/mesh.h" #include "helpers.h" #include <array> #include <glm/gtx/rotate_vector.hpp> using namespace std; using namespace demoloop; float t = 0; const float CYCLE_LENGTH = 10; const float size = 3; Vertex plane(const float u, const float v) { return { (u - 0.5f) * size, (v - 0.5f) * size, 0, 1 - u, 1 - v, 255, 255, 255, 255 }; } Vertex flatMobius(float s, float t) { float u = s - 0.5; float v = 2 * DEMOLOOP_M_PI * -t; float x, y, z; float a = size / 2; x = cosf(v) * (a + u * cosf(v / 2)); y = sinf(v) * (a + u * cosf(v / 2)); z = u * sinf( v / 2 ); return { x, y, z, s, (1 - t) * 3 }; } Vertex volumetricMobius(float s, float v) { float u = s * DEMOLOOP_M_PI; float t = v * 2 * DEMOLOOP_M_PI; u = u * 2; float phi = u / 2; float major = size / 2, a = 0.125, b = 0.65; float x, y, z; x = a * cosf( t ) * cosf( phi ) - b * sinf( t ) * sinf( phi ); z = a * cosf( t ) * sinf( phi ) + b * sinf( t ) * cosf( phi ); y = ( major + x ) * sinf( u ); x = ( major + x ) * cosf( u ); return { x, y, z, s, 1 - v }; } Vertex parametricSphere(float s, float t) { float u = t * DEMOLOOP_M_PI; float v = s * DEMOLOOP_M_PI * 2; // v *= 3.0/4.0; float radius = size / 2; float x = -radius * sinf(u) * sinf(v); float y = -radius * cosf(u); float z = radius * sinf(u) * cosf(v); return { x, y, z, 1 - s, 1 - t }; } template < typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type > T mix(T const& a, T const& b, const float& ratio) { return a * (1.0f - ratio) + b * ratio; } glm::vec3 computeNormal(const Vertex &a, const Vertex &b, const Vertex &c) { glm::vec3 v1(a.x, a.y, a.z); glm::vec3 v2(b.x, b.y, b.z); glm::vec3 v3(c.x, c.y, c.z); return normalize(cross(v2 - v1, v3 - v1)); } Vertex mix(const Vertex& a, const Vertex& b, const float& ratio) { const float x = mix<float>(a.x, b.x, ratio); const float y = mix<float>(a.y, b.y, ratio); const float z = mix<float>(a.z, b.z, ratio); const float s = mix<float>(a.s, b.s, ratio); const float t = mix<float>(a.t, b.t, ratio); const uint8_t red = mix<uint8_t>(a.r, b.r, ratio); const uint8_t green = mix<uint8_t>(a.g, b.g, ratio); const uint8_t blue = mix<uint8_t>(a.b, b.b, ratio); const uint8_t alpha = mix<uint8_t>(a.a, b.a, ratio); return {x, y, z, s, t, red, green, blue, alpha}; } const array<function<Vertex(float, float)>, 2> surfaces = {{ plane, parametricSphere//, volumetricMobius, flatMobius }}; const uint32_t stacks = 30, slices = 30; const uint32_t numVertices = (slices + 1) * (stacks + 1); const uint32_t numIndices = slices * stacks * 6; class Loop055 : public Demoloop { public: Loop055() : Demoloop(150, 150, 150) { // glEnable(GL_CULL_FACE); texture = loadTexture("uv_texture.jpg"); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT); } ~Loop055() { } void Update(float dt) { t += dt; const float cycle = fmod(t, CYCLE_LENGTH); const float cycle_ratio = cycle / CYCLE_LENGTH; const float mod_ratio = powf(sinf(cycle_ratio * DEMOLOOP_M_PI), 2); const uint32_t surfaceIndex = fmod(floor(t / CYCLE_LENGTH), surfaces.size()); const uint32_t sliceCount = slices + 1; uint32_t index = 0; for (uint32_t i = 0; i <= stacks; ++i) { const float v = static_cast<float>(i) / stacks; for (uint32_t j = 0; j <= slices; ++j) { const float u = static_cast<float>(j) / slices; // vertices[index] = parametricSphere(u, v); // vertices[index] = mix(plane(u, v), parametricSphere(u, v), mod_ratio); vertices[index] = mix( surfaces[surfaceIndex](u, v), surfaces[(surfaceIndex + 1) % surfaces.size()](u, v), cycle_ratio ); normals[index] = glm::vec3(0, 0, 0); index++; } } index = 0; for (uint32_t i = 0; i < stacks; ++i) { for (uint32_t j = 0; j < slices; ++j) { const uint32_t a = i * sliceCount + j; const uint32_t b = i * sliceCount + j + 1; const uint32_t c = ( i + 1 ) * sliceCount + j + 1; const uint32_t d = ( i + 1 ) * sliceCount + j; // faces one and two indices[index++] = a; indices[index++] = b; indices[index++] = d; glm::vec3 faceNormal1 = computeNormal(vertices[a], vertices[b], vertices[d]); normals[a] = glm::normalize(normals[a] + faceNormal1); normals[b] = glm::normalize(normals[b] + faceNormal1); normals[c] = glm::normalize(normals[c] + faceNormal1); indices[index++] = b; indices[index++] = c; indices[index++] = d; glm::vec3 faceNormal2 = computeNormal(vertices[b], vertices[c], vertices[d]); normals[b] = glm::normalize(normals[b] + faceNormal2); normals[c] = glm::normalize(normals[c] + faceNormal2); normals[d] = glm::normalize(normals[d] + faceNormal2); } } // const glm::vec3 eye = glm::rotate(glm::vec3(0, 0, 10), static_cast<float>(cycle_ratio * DEMOLOOP_M_PI * 2), glm::vec3(0, 1, 0)); const glm::vec3 eye = glm::vec3(0, 0, 10); const glm::vec3 target = {0, 0, 0}; const glm::vec3 up = {0, 1, 0}; glm::mat4 camera = glm::lookAt(eye, target, up); GL::TempTransform t1(gl); t1.get() = camera; GL::TempProjection p1(gl); p1.get() = glm::perspective((float)DEMOLOOP_M_PI / 4.0f, (float)width / (float)height, 0.1f, 100.0f); gl.bufferVertices(&vertices[0], numVertices); glVertexAttribPointer(ATTRIB_POS, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, x)); glVertexAttribPointer(ATTRIB_TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, s)); glVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, r)); // uint32_t normalsLocation = shader.getAttribLocation("v_normal"); // glBindBuffer(GL_ARRAY_BUFFER, normalsBuffer); // glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(glm::vec3), &normals[0].x, GL_DYNAMIC_DRAW); // glVertexAttribPointer(normalsLocation, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), 0); gl.bufferIndices(&indices[0], numIndices); // gl.useVertexAttribArrays(ATTRIBFLAG_POS | ATTRIBFLAG_COLOR | ATTRIBFLAG_TEXCOORD | (1u << normalsLocation)); gl.useVertexAttribArrays(ATTRIBFLAG_POS | ATTRIBFLAG_COLOR | ATTRIBFLAG_TEXCOORD); { glm::mat4 m; m = glm::translate(m, {2.5, -0.5, 0}); m = glm::scale(m, {1.5, 1.5, 1.5}); m = glm::rotate(m, cycle_ratio * (float)DEMOLOOP_M_PI * 2, glm::vec3(0, 1, 0)); gl.prepareDraw(m); gl.drawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_INT, 0); } { glm::mat4 m; m = glm::translate(m, {-2.5, -0.5, 0}); m = glm::scale(m, {1.5, 1.5, 1.5}); m = glm::rotate(m, cycle_ratio * (float)DEMOLOOP_M_PI * 2, glm::vec3(0, 1, 0)); m = glm::rotate(m, (float)DEMOLOOP_M_PI, glm::vec3(0, 1, 0)); gl.prepareDraw(m); gl.drawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_INT, 0); } } private: GLuint texture; Vertex vertices[numVertices]; glm::vec3 normals[numVertices]; uint32_t indices[numIndices]; }; int main(int, char**){ Loop055 test; test.Run(); return 0; } <commit_msg>loop 055<commit_after>#include "demoloop.h" #include "graphics/3d_primitives.h" #include "graphics/shader.h" #include "helpers.h" #include <array> #include <glm/gtx/rotate_vector.hpp> using namespace std; using namespace demoloop; float t = 0; const float CYCLE_LENGTH = 10; const float size = 3; float cubicEaseInOut(float t,float b , float c, float d) { t/=d/2; if (t < 1) return c/2*t*t*t + b; t-=2; return c/2*(t*t*t + 2) + b; } Vertex parametricPlane(const float u, const float v) { return { (u - 0.5f) * size, (v - 0.5f) * size, 0, 1 - u, 1 - v, 255, 255, 255, 255 }; } Vertex flatMobius(float s, float t) { float u = s - 0.5; float v = 2 * DEMOLOOP_M_PI * -t; float x, y, z; float a = size / 2 / 2; x = cosf(v) * (a + u * cosf(v / 2)); y = sinf(v) * (a + u * cosf(v / 2)); z = u * sinf( v / 2 ); return { x, y, z, 1 - s, (1 - t) * 1 }; } Vertex volumetricMobius(float s, float v) { float u = s * DEMOLOOP_M_PI; float t = v * 2 * DEMOLOOP_M_PI; u = u * 2; float phi = u / 2; float major = size / 2, a = 0.125, b = 0.65; float x, y, z; x = a * cosf( t ) * cosf( phi ) - b * sinf( t ) * sinf( phi ); z = a * cosf( t ) * sinf( phi ) + b * sinf( t ) * cosf( phi ); y = ( major + x ) * sinf( u ); x = ( major + x ) * cosf( u ); return { x, y, z, 1 - s, 1 - v }; } Vertex parametricSphere(float s, float t) { float u = t * DEMOLOOP_M_PI; float v = s * DEMOLOOP_M_PI * 2; // v *= 3.0/4.0; float radius = size / 2; float x = -radius * sinf(u) * sinf(v); float y = -radius * cosf(u); float z = radius * sinf(u) * cosf(v); return { x, y, z, 1 - s, 1 - t }; } template < typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type > constexpr T mix(T const& a, T const& b, const float& ratio) { return a * (1.0f - ratio) + b * ratio; } glm::vec3 computeNormal(const Vertex &a, const Vertex &b, const Vertex &c) { glm::vec3 v1(a.x, a.y, a.z); glm::vec3 v2(b.x, b.y, b.z); glm::vec3 v3(c.x, c.y, c.z); return normalize(cross(v2 - v1, v3 - v1)); } Vertex mix(const Vertex& a, const Vertex& b, const float& ratio) { const float x = mix<float>(a.x, b.x, ratio); const float y = mix<float>(a.y, b.y, ratio); const float z = mix<float>(a.z, b.z, ratio); const float s = mix<float>(a.s, b.s, ratio); const float t = mix<float>(a.t, b.t, ratio); const uint8_t red = mix<uint8_t>(a.r, b.r, ratio); const uint8_t green = mix<uint8_t>(a.g, b.g, ratio); const uint8_t blue = mix<uint8_t>(a.b, b.b, ratio); const uint8_t alpha = mix<uint8_t>(a.a, b.a, ratio); return {x, y, z, s, t, red, green, blue, alpha}; } const array<function<Vertex(float, float)>, 3> surfaces = {{ parametricPlane, parametricSphere, flatMobius }}; const static std::string shaderCode = R"===( #ifdef VERTEX vec4 position(mat4 transform_proj, mat4 m, vec4 v_coord) { mat4 mvp = transform_proj * m; return mvp * v_coord; } #endif #ifdef PIXEL vec4 effect(vec4 globalColor, Image texture, vec2 st, vec2 screen_coords) { vec2 q = abs(fract(st) - 0.5); float d = fract((q.x + q.y) * 5.0); if (gl_FrontFacing) { return vec4(vec3(1, 0.2, 0.75) * d, 1.0); } else { return vec4(vec3(0.2, 0.75, 1) * d, 1.0); } } #endif )==="; const uint32_t stacks = 30, slices = 30; const uint32_t numVertices = (slices + 1) * (stacks + 1); const uint32_t numIndices = slices * stacks * 6; class Loop055 : public Demoloop { public: Loop055() : Demoloop(150, 150, 150), shader({shaderCode, shaderCode}) { // glEnable(GL_CULL_FACE); texture = loadTexture("uv_texture.jpg"); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT); } ~Loop055() { } void Update(float dt) { t += dt; const float cycle = fmod(t, CYCLE_LENGTH); const float cycle_ratio = cycle / CYCLE_LENGTH; // const float mod_ratio = powf(sinf(cycle_ratio * DEMOLOOP_M_PI), 2); const uint32_t surfaceIndex = fmod(floor(t / CYCLE_LENGTH), surfaces.size()); const uint32_t sliceCount = slices + 1; uint32_t index = 0; for (uint32_t i = 0; i <= stacks; ++i) { const float v = static_cast<float>(i) / stacks; for (uint32_t j = 0; j <= slices; ++j) { const float u = static_cast<float>(j) / slices; // vertices[index] = volumetricMobius(u, v); // vertices[index] = mix(plane(u, v), flatMobius(u, v), mod_ratio); vertices[index] = mix( surfaces[surfaceIndex](u, v), surfaces[(surfaceIndex + 1) % surfaces.size()](u, v), cubicEaseInOut(cycle_ratio, 0, 1, 1) ); normals[index] = glm::vec3(0, 0, 0); index++; } } index = 0; for (uint32_t i = 0; i < stacks; ++i) { for (uint32_t j = 0; j < slices; ++j) { const uint32_t a = i * sliceCount + j; const uint32_t b = i * sliceCount + j + 1; const uint32_t c = ( i + 1 ) * sliceCount + j + 1; const uint32_t d = ( i + 1 ) * sliceCount + j; // faces one and two indices[index++] = a; indices[index++] = b; indices[index++] = d; glm::vec3 faceNormal1 = computeNormal(vertices[a], vertices[b], vertices[d]); normals[a] = glm::normalize(normals[a] + faceNormal1); normals[b] = glm::normalize(normals[b] + faceNormal1); normals[c] = glm::normalize(normals[c] + faceNormal1); indices[index++] = b; indices[index++] = c; indices[index++] = d; glm::vec3 faceNormal2 = computeNormal(vertices[b], vertices[c], vertices[d]); normals[b] = glm::normalize(normals[b] + faceNormal2); normals[c] = glm::normalize(normals[c] + faceNormal2); normals[d] = glm::normalize(normals[d] + faceNormal2); } } // const glm::vec3 eye = glm::rotate(glm::vec3(0, 0, 10), static_cast<float>(cycle_ratio * DEMOLOOP_M_PI * 2), glm::vec3(0, 1, 0)); const glm::vec3 eye = glm::vec3(0, 0, 10); const glm::vec3 target = {0, 0, 0}; const glm::vec3 up = {0, 1, 0}; glm::mat4 camera = glm::lookAt(eye, target, up); GL::TempTransform t1(gl); t1.get() = camera; GL::TempProjection p1(gl); p1.get() = glm::perspective((float)DEMOLOOP_M_PI / 4.0f, (float)width / (float)height, 0.1f, 100.0f); shader.attach(); gl.bufferVertices(&vertices[0], numVertices); glVertexAttribPointer(ATTRIB_POS, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, x)); glVertexAttribPointer(ATTRIB_TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, s)); glVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, r)); // uint32_t normalsLocation = shader.getAttribLocation("v_normal"); // glBindBuffer(GL_ARRAY_BUFFER, normalsBuffer); // glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(glm::vec3), &normals[0].x, GL_DYNAMIC_DRAW); // glVertexAttribPointer(normalsLocation, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), 0); gl.bufferIndices(&indices[0], numIndices); // gl.useVertexAttribArrays(ATTRIBFLAG_POS | ATTRIBFLAG_COLOR | ATTRIBFLAG_TEXCOORD | (1u << normalsLocation)); gl.useVertexAttribArrays(ATTRIBFLAG_POS | ATTRIBFLAG_COLOR | ATTRIBFLAG_TEXCOORD); { glm::mat4 m; m = glm::translate(m, {2.5, 0, 0}); m = glm::scale(m, {1.5, 1.5, 1.5}); m = glm::rotate(m, cycle_ratio * (float)DEMOLOOP_M_PI * 2, glm::vec3(0, 1, 0)); gl.prepareDraw(m); gl.drawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_INT, 0); } { glm::mat4 m; m = glm::translate(m, {-2.5, 0, 0}); m = glm::scale(m, {1.5, 1.5, 1.5}); m = glm::rotate(m, cycle_ratio * (float)DEMOLOOP_M_PI * 2, glm::vec3(0, 1, 0)); m = glm::rotate(m, (float)DEMOLOOP_M_PI, glm::vec3(0, 1, 0)); gl.prepareDraw(m); gl.drawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_INT, 0); } shader.detach(); } private: GLuint texture; Shader shader; Vertex vertices[numVertices]; glm::vec3 normals[numVertices]; uint32_t indices[numIndices]; }; int main(int, char**){ Loop055 test; test.Run(); return 0; } <|endoftext|>
<commit_before>/* dtkComposerNodeMetaScalarArray.cpp --- * * Author: tkloczko * Copyright (C) 2011 - Thibaud Kloczko, Inria. * Created: Fri Jul 13 16:06:48 2012 (+0200) * Version: $Id$ * Last-Updated: Wed Oct 17 11:36:54 2012 (+0200) * By: Julien Wintz * Update #: 16 */ /* Commentary: * */ /* Change log: * */ #include "dtkComposerNodeMetaScalarArray.h" #include <dtkComposer/dtkComposerTransmitterEmitter.h> #include <dtkContainer/dtkAbstractContainerWrapper.h> #include <dtkContainer/dtkContainerVector.h> #include <dtkLog/dtkLog> // ///////////////////////////////////////////////////////////////// // dtkComposerNodeMetaScalarArrayPrivate interface // ///////////////////////////////////////////////////////////////// class dtkComposerNodeMetaScalarArrayPrivate { public: dtkComposerTransmitterEmitterVector<dtkContainerVector<qreal> > emitter_arrays; }; // ///////////////////////////////////////////////////////////////// // dtkComposerNodeMetaScalarArray implementation // ///////////////////////////////////////////////////////////////// dtkComposerNodeMetaScalarArray::dtkComposerNodeMetaScalarArray(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeMetaScalarArrayPrivate) { this->appendEmitter(&d->emitter_arrays); } dtkComposerNodeMetaScalarArray::~dtkComposerNodeMetaScalarArray(void) { delete d; d = NULL; } QString dtkComposerNodeMetaScalarArray::outputLabelHint(int port) { switch(port) { case 0: return "arrays"; break; default: break; } return "port"; } void dtkComposerNodeMetaScalarArray::run(void) { dtkContainerVector<dtkContainerVector<qreal> > arrays; d->emitter_arrays.setData(&arrays); } <commit_msg>Fixed bug in MetaScalarArray node.<commit_after>/* dtkComposerNodeMetaScalarArray.cpp --- * * Author: tkloczko * Copyright (C) 2011 - Thibaud Kloczko, Inria. * Created: Fri Jul 13 16:06:48 2012 (+0200) * Version: $Id$ * Last-Updated: Tue Oct 23 20:52:18 2012 (+0200) * By: Régis Duvigneau * Update #: 19 */ /* Commentary: * */ /* Change log: * */ #include "dtkComposerNodeMetaScalarArray.h" #include <dtkComposer/dtkComposerTransmitterEmitter.h> #include <dtkContainer/dtkAbstractContainerWrapper.h> #include <dtkContainer/dtkContainerVector.h> #include <dtkLog/dtkLog> // ///////////////////////////////////////////////////////////////// // dtkComposerNodeMetaScalarArrayPrivate interface // ///////////////////////////////////////////////////////////////// class dtkComposerNodeMetaScalarArrayPrivate { public: dtkComposerTransmitterEmitterVector<dtkContainerVector<qreal> > emitter_arrays; dtkContainerVector< dtkContainerVector<qreal> > *arrays; }; // ///////////////////////////////////////////////////////////////// // dtkComposerNodeMetaScalarArray implementation // ///////////////////////////////////////////////////////////////// dtkComposerNodeMetaScalarArray::dtkComposerNodeMetaScalarArray(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeMetaScalarArrayPrivate) { d->arrays = new dtkContainerVector< dtkContainerVector<qreal> >(); d->emitter_arrays.setData(d->arrays); this->appendEmitter(&d->emitter_arrays); } dtkComposerNodeMetaScalarArray::~dtkComposerNodeMetaScalarArray(void) { delete d; d = NULL; } QString dtkComposerNodeMetaScalarArray::outputLabelHint(int port) { switch(port) { case 0: return "arrays"; break; default: break; } return "port"; } void dtkComposerNodeMetaScalarArray::run(void) { } <|endoftext|>
<commit_before>//! Copyright (c) 2014 ASMlover. 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 ofconditions 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 materialsprovided with the //! distribution. //! //! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS //! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT //! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS //! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE //! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, //! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; //! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER //! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT //! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN //! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE //! POSSIBILITY OF SUCH DAMAGE. #include "global.h" #include "logical.h" #define CARDVALUE_SMALL_KING (13) #define CARDVALUE_BIG_KING (14) #define CARDVALUE_2POINT (12) Logical::Logical(std::vector<uint8_t>& cards) : cards_(cards) { } Logical::~Logical(void) { } bool Logical::PlayAnyCard(std::vector<uint8_t>& out_cards) { if (!CardsAnalysis()) return false; out_cards.clear(); return PlayAnySingle(out_cards) || PlayAnyPair(out_cards) || PlayAnyThree(out_cards) || PlayAnyThreeWithSingle(out_cards) || PlayAnyThreeWithPair(out_cards) || PlayAnyBomb(out_cards) || PlayRocket(out_cards); } bool Logical::PlayCard(CardType type, std::vector<uint8_t>& out_cards) { return true; } bool Logical::CardsAnalysis(void) { if (cards_.empty()) return false; // card value => cards std::map<uint8_t, std::vector<Card> > src_cards; Card c; int n = static_cast<int>(cards_.size()); for (int i = 0; i < n; ++i) { c.card = cards_[i]; c.value = CardValue(cards_[i]); src_cards[c.value].push_back(c); } std::map<uint8_t, std::vector<Card> >::iterator it; for (it = src_cards.begin(); it != src_cards.end(); ++it) { switch (it->second.size()) { case 1: single_.push_back(it->second[0]); break; case 2: if (CARDVALUE_SMALL_KING == it->second[0].value && CARDVALUE_BIG_KING == it->second[1].value) { rocket_.push_back(it->second[0]); rocket_.push_back(it->second[1]); } else { pair_.push_back(it->second[0]); pair_.push_back(it->second[1]); } break; case 3: three_.push_back(it->second[0]); three_.push_back(it->second[1]); three_.push_back(it->second[2]); break; case 4: bomb_.push_back(it->second[0]); bomb_.push_back(it->second[1]); bomb_.push_back(it->second[2]); bomb_.push_back(it->second[3]); break; default: return false; } } return true; } bool Logical::IsContinued(const Card* cards, int count, int step) { for (int i = 0; i < count - step; i += step) { if (cards[i].value + 1 != cards[i + step].value) return false; } return true; } bool Logical::PlayAnySingle(std::vector<uint8_t>& out_cards) { if (single_.empty()) return false; out_cards.push_back(single_[0].card); return true; } bool Logical::PlayAnyPair(std::vector<uint8_t>& out_cards) { if (pair_.size() < 2) return false; out_cards.push_back(pair_[0].card); out_cards.push_back(pair_[1].card); return true; } bool Logical::PlayAnyThree(std::vector<uint8_t>& out_cards) { if (three_.size() < 3) return false; out_cards.push_back(three_[0].card); out_cards.push_back(three_[1].card); out_cards.push_back(three_[2].card); return true; } bool Logical::PlayAnyThreeWithSingle(std::vector<uint8_t>& out_cards) { if (single_.empty() || three_.size() < 3) return false; out_cards.push_back(three_[0].card); out_cards.push_back(three_[1].card); out_cards.push_back(three_[2].card); out_cards.push_back(single_[0].card); return true; } bool Logical::PlayAnyThreeWithPair(std::vector<uint8_t>& out_cards) { if (pair_.size() < 2 || three_.size() < 3) return false; out_cards.push_back(three_[0].card); out_cards.push_back(three_[1].card); out_cards.push_back(three_[2].card); out_cards.push_back(pair_[0].card); out_cards.push_back(pair_[1].card); return true; } bool Logical::PlayAnyBomb(std::vector<uint8_t>& out_cards) { if (bomb_.size() < 4) return false; out_cards.push_back(bomb_[0].card); out_cards.push_back(bomb_[1].card); out_cards.push_back(bomb_[2].card); out_cards.push_back(bomb_[3].card); return true; } bool Logical::PlayRocket(std::vector<uint8_t>& out_cards) { if (rocket_.size() < 2) return false; out_cards.push_back(rocket_[0].card); out_cards.push_back(rocket_[1].card); return true; } bool Logical::PlaySingle( uint8_t value, std::vector<uint8_t>& out_cards) { int n = static_cast<int>(single_.size()); for (int i = 0; i < n; ++i) { if (single_[i].value > value) { out_cards.push_back(single_[i].card); return true; } } return false; } bool Logical::PlayPair( uint8_t value, std::vector<uint8_t>& out_cards) { int n = static_cast<int>(pair_.size()); for (int i = 0; i < n; i += 2) { if (pair_[i].value > value && (i + 1 < n)) { out_cards.push_back(pair_[i].card); out_cards.push_back(pair_[i + 1].card); return true; } } return false; } bool Logical::PlayThree( uint8_t value, std::vector<uint8_t>& out_cards) { int n = static_cast<int>(three_.size()); for (int i = 0; i < n; i += 3) { if (three_[i].value > value && (i + 2 < n)) { out_cards.push_back(three_[i].card); out_cards.push_back(three_[i + 1].card); out_cards.push_back(three_[i + 2].card); return true; } } return false; } bool Logical::PlayThreeWithSingle( uint8_t value, std::vector<uint8_t>& out_cards) { if (single_.empty() || !PlayThree(value, out_cards)) return false; out_cards.push_back(single_[0].card); return true; } bool Logical::PlayThreeWithPair( uint8_t value, std::vector<uint8_t>& out_cards) { if (pair_.size() < 2 || !PlayThree(value, out_cards)) return false; out_cards.push_back(pair_[0].card); out_cards.push_back(pair_[1].card); return true; } bool Logical::PlayBomb( uint8_t value, std::vector<uint8_t>& out_cards) { int n = static_cast<int>(bomb_.size()); for (int i = 0; i < n; i += 4) { if (bomb_[i].value > value && (i + 3 < n)) { out_cards.push_back(bomb_[i].card); out_cards.push_back(bomb_[i + 1].card); out_cards.push_back(bomb_[i + 2].card); out_cards.push_back(bomb_[i + 3].card); return true; } } return false; } bool Logical::PlayFourWithTwoSingle( uint8_t value, std::vector<uint8_t>& out_cards) { if (single_.size() < 2 || !PlayBomb(value, out_cards)) return false; out_cards.push_back(single_[0].card); out_cards.push_back(single_[1].card); return true; } bool Logical::PlayFourWithTwoPair( uint8_t value, std::vector<uint8_t>& out_cards) { if (pair_.size() < 4 || !PlayBomb(value, out_cards)) return false; out_cards.push_back(pair_[0].card); out_cards.push_back(pair_[1].card); out_cards.push_back(pair_[2].card); out_cards.push_back(pair_[3].card); return true; } bool Logical::PlayStraightSingle(int num, uint8_t value, std::vector<uint8_t>& out_cards) { int n = static_cast<int>(single_.size()); if (n < num) return false; for (int i = n - 1; i >= 0; --i) { if (single_[i].value > value && i >= (num - 1)) { if (IsContinued(&single_[i - num + 1], num)) { for (int j = i - num + 1; j < num; ++j) out_cards.push_back(single_[j].card); return true; } } } return false; } bool Logical::PlayStraightPair(int num, uint8_t value, std::vector<uint8_t>& out_cards) { return false; } bool Logical::PlayStraightThree(int num, uint8_t value, std::vector<uint8_t>& out_cards) { return false; } bool Logical::PlayAirplaneWithSingle(int num, uint8_t value, std::vector<uint8_t>& out_cards) { return false; } bool Logical::PlayAirplaneWithPair(int num, uint8_t value, std::vector<uint8_t>& out_cards) { return false; } <commit_msg>add the AI about playing<commit_after>//! Copyright (c) 2014 ASMlover. 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 ofconditions 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 materialsprovided with the //! distribution. //! //! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS //! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT //! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS //! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE //! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, //! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; //! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER //! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT //! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN //! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE //! POSSIBILITY OF SUCH DAMAGE. #include "global.h" #include "logical.h" #define CARDVALUE_SMALL_KING (13) #define CARDVALUE_BIG_KING (14) #define CARDVALUE_2POINT (12) Logical::Logical(std::vector<uint8_t>& cards) : cards_(cards) { } Logical::~Logical(void) { } bool Logical::PlayAnyCard(std::vector<uint8_t>& out_cards) { if (!CardsAnalysis()) return false; out_cards.clear(); return PlayAnySingle(out_cards) || PlayAnyPair(out_cards) || PlayAnyThree(out_cards) || PlayAnyThreeWithSingle(out_cards) || PlayAnyThreeWithPair(out_cards) || PlayAnyBomb(out_cards) || PlayRocket(out_cards); } bool Logical::PlayCard(CardType type, std::vector<uint8_t>& out_cards) { return true; } bool Logical::CardsAnalysis(void) { if (cards_.empty()) return false; // card value => cards std::map<uint8_t, std::vector<Card> > src_cards; Card c; int n = static_cast<int>(cards_.size()); for (int i = 0; i < n; ++i) { c.card = cards_[i]; c.value = CardValue(cards_[i]); src_cards[c.value].push_back(c); } std::map<uint8_t, std::vector<Card> >::iterator it; for (it = src_cards.begin(); it != src_cards.end(); ++it) { switch (it->second.size()) { case 1: single_.push_back(it->second[0]); break; case 2: if (CARDVALUE_SMALL_KING == it->second[0].value && CARDVALUE_BIG_KING == it->second[1].value) { rocket_.push_back(it->second[0]); rocket_.push_back(it->second[1]); } else { pair_.push_back(it->second[0]); pair_.push_back(it->second[1]); } break; case 3: three_.push_back(it->second[0]); three_.push_back(it->second[1]); three_.push_back(it->second[2]); break; case 4: bomb_.push_back(it->second[0]); bomb_.push_back(it->second[1]); bomb_.push_back(it->second[2]); bomb_.push_back(it->second[3]); break; default: return false; } } return true; } bool Logical::IsContinued(const Card* cards, int count, int step) { for (int i = 0; i < count - step; i += step) { if (cards[i].value + 1 != cards[i + step].value) return false; } return true; } bool Logical::PlayAnySingle(std::vector<uint8_t>& out_cards) { if (single_.empty()) return false; out_cards.push_back(single_[0].card); return true; } bool Logical::PlayAnyPair(std::vector<uint8_t>& out_cards) { if (pair_.size() < 2) return false; out_cards.push_back(pair_[0].card); out_cards.push_back(pair_[1].card); return true; } bool Logical::PlayAnyThree(std::vector<uint8_t>& out_cards) { if (three_.size() < 3) return false; out_cards.push_back(three_[0].card); out_cards.push_back(three_[1].card); out_cards.push_back(three_[2].card); return true; } bool Logical::PlayAnyThreeWithSingle(std::vector<uint8_t>& out_cards) { if (single_.empty() || three_.size() < 3) return false; out_cards.push_back(three_[0].card); out_cards.push_back(three_[1].card); out_cards.push_back(three_[2].card); out_cards.push_back(single_[0].card); return true; } bool Logical::PlayAnyThreeWithPair(std::vector<uint8_t>& out_cards) { if (pair_.size() < 2 || three_.size() < 3) return false; out_cards.push_back(three_[0].card); out_cards.push_back(three_[1].card); out_cards.push_back(three_[2].card); out_cards.push_back(pair_[0].card); out_cards.push_back(pair_[1].card); return true; } bool Logical::PlayAnyBomb(std::vector<uint8_t>& out_cards) { if (bomb_.size() < 4) return false; out_cards.push_back(bomb_[0].card); out_cards.push_back(bomb_[1].card); out_cards.push_back(bomb_[2].card); out_cards.push_back(bomb_[3].card); return true; } bool Logical::PlayRocket(std::vector<uint8_t>& out_cards) { if (rocket_.size() < 2) return false; out_cards.push_back(rocket_[0].card); out_cards.push_back(rocket_[1].card); return true; } bool Logical::PlaySingle( uint8_t value, std::vector<uint8_t>& out_cards) { int n = static_cast<int>(single_.size()); for (int i = 0; i < n; ++i) { if (single_[i].value > value) { out_cards.push_back(single_[i].card); return true; } } return false; } bool Logical::PlayPair( uint8_t value, std::vector<uint8_t>& out_cards) { int n = static_cast<int>(pair_.size()); for (int i = 0; i < n; i += 2) { if (pair_[i].value > value && (i + 1 < n)) { out_cards.push_back(pair_[i].card); out_cards.push_back(pair_[i + 1].card); return true; } } return false; } bool Logical::PlayThree( uint8_t value, std::vector<uint8_t>& out_cards) { int n = static_cast<int>(three_.size()); for (int i = 0; i < n; i += 3) { if (three_[i].value > value && (i + 2 < n)) { out_cards.push_back(three_[i].card); out_cards.push_back(three_[i + 1].card); out_cards.push_back(three_[i + 2].card); return true; } } return false; } bool Logical::PlayThreeWithSingle( uint8_t value, std::vector<uint8_t>& out_cards) { if (single_.empty() || !PlayThree(value, out_cards)) return false; out_cards.push_back(single_[0].card); return true; } bool Logical::PlayThreeWithPair( uint8_t value, std::vector<uint8_t>& out_cards) { if (pair_.size() < 2 || !PlayThree(value, out_cards)) return false; out_cards.push_back(pair_[0].card); out_cards.push_back(pair_[1].card); return true; } bool Logical::PlayBomb( uint8_t value, std::vector<uint8_t>& out_cards) { int n = static_cast<int>(bomb_.size()); for (int i = 0; i < n; i += 4) { if (bomb_[i].value > value && (i + 3 < n)) { out_cards.push_back(bomb_[i].card); out_cards.push_back(bomb_[i + 1].card); out_cards.push_back(bomb_[i + 2].card); out_cards.push_back(bomb_[i + 3].card); return true; } } return false; } bool Logical::PlayFourWithTwoSingle( uint8_t value, std::vector<uint8_t>& out_cards) { if (single_.size() < 2 || !PlayBomb(value, out_cards)) return false; out_cards.push_back(single_[0].card); out_cards.push_back(single_[1].card); return true; } bool Logical::PlayFourWithTwoPair( uint8_t value, std::vector<uint8_t>& out_cards) { if (pair_.size() < 4 || !PlayBomb(value, out_cards)) return false; out_cards.push_back(pair_[0].card); out_cards.push_back(pair_[1].card); out_cards.push_back(pair_[2].card); out_cards.push_back(pair_[3].card); return true; } bool Logical::PlayStraightSingle(int num, uint8_t value, std::vector<uint8_t>& out_cards) { int n = static_cast<int>(single_.size()); if (n < num) return false; for (int i = n - 1; i >= 0; --i) { if (single_[i].value > value && i >= (num - 1)) { if (IsContinued(&single_[i - num + 1], num)) { for (int j = i + 1 - num; j < num; ++j) out_cards.push_back(single_[j].card); return true; } } } return false; } bool Logical::PlayStraightPair(int num, uint8_t value, std::vector<uint8_t>& out_cards) { int n = static_cast<int>(pair_.size()); if (n < num * 2) return false; for (int i = n - 1; i >= 0; i -= 2) { if (pair_[i].value > value && ((i - 1) / 2 >= (num - 1))) { if (IsContinued(&pair_[i + 1 - num * 2], num * 2, 2)) { for (int j = i + 1 - num * 2; j < num * 2; ++j) out_cards.push_back(pair_[j].card); return true; } } } return false; } bool Logical::PlayStraightThree(int num, uint8_t value, std::vector<uint8_t>& out_cards) { int n = static_cast<int>(three_.size()); if (n < num * 3) return false; for (int i = n - 1; i >= 0; i -= 3) { if (three_[i].value > value && ((i - 1) / 3 >= (num - 1))) { if (IsContinued(&three_[i + 1 - num * 3], num * 3, 3)) { for (int j = i + 1 - num * 3; j < num * 3; ++j) out_cards.push_back(three_[j].card); return true; } } } return false; } bool Logical::PlayAirplaneWithSingle(int num, uint8_t value, std::vector<uint8_t>& out_cards) { if (single_.size() < 2 || !PlayStraightThree(num, value, out_cards)) return false; out_cards.push_back(single_[0].card); out_cards.push_back(single_[1].card); return true; } bool Logical::PlayAirplaneWithPair(int num, uint8_t value, std::vector<uint8_t>& out_cards) { if (pair_.size() < 4 || !PlayStraightThree(num, value, out_cards)) return false; out_cards.push_back(pair_[0].card); out_cards.push_back(pair_[1].card); out_cards.push_back(pair_[2].card); out_cards.push_back(pair_[3].card); return true; } <|endoftext|>
<commit_before>#ifdef STAN_OPENCL #include <stan/math/opencl/kernel_generator/type_str.hpp> #include <gtest/gtest.h> TEST(MathMatrixCL, type_str) { EXPECT_EQ(type_str<double>::name, "double"); EXPECT_EQ(type_str<int>::name, "int"); EXPECT_EQ(type_str<bool>::name, "bool"); } #endif <commit_msg>fixed type_str test<commit_after>#ifdef STAN_OPENCL #include <stan/math/opencl/kernel_generator/type_str.hpp> #include <gtest/gtest.h> TEST(MathMatrixCL, type_str) { EXPECT_EQ(type_str<double>(), "double"); EXPECT_EQ(type_str<int>(), "int"); EXPECT_EQ(type_str<bool>(), "bool"); } #endif <|endoftext|>
<commit_before>#include <stan/math/prim.hpp> #include <gtest/gtest.h> TEST(MathFunctions, apply_scalar_binary_copy_scalars) { int n = 1; Eigen::VectorXd lambda(1); lambda << 0.4; const auto& y1 = stan::math::apply_scalar_binary(n + 1, lambda, [&](const auto& c, const auto& d) { return stan::math::gamma_q(c, d); }); EXPECT_NO_THROW(stan::math::sum(y1)); const auto& y2 = stan::math::apply_scalar_binary(lambda, n + 1, [&](const auto& d, const auto& c) { return stan::math::gamma_q(c, d); }); EXPECT_NO_THROW(stan::math::sum(y2)); } <commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#include <stan/math/prim.hpp> #include <gtest/gtest.h> TEST(MathFunctions, apply_scalar_binary_copy_scalars) { int n = 1; Eigen::VectorXd lambda(1); lambda << 0.4; const auto& y1 = stan::math::apply_scalar_binary( n + 1, lambda, [&](const auto& c, const auto& d) { return stan::math::gamma_q(c, d); }); EXPECT_NO_THROW(stan::math::sum(y1)); const auto& y2 = stan::math::apply_scalar_binary( lambda, n + 1, [&](const auto& d, const auto& c) { return stan::math::gamma_q(c, d); }); EXPECT_NO_THROW(stan::math::sum(y2)); } <|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * Created on: Jan 2018 * Author: Norbert Podhorszki */ #include <chrono> #include <ios> //std::ios_base::failure #include <iostream> //std::cout #include <numeric> #include <stdexcept> //std::invalid_argument std::exception #include <thread> #include <utility> #include <vector> #include <string> #include <gtest/gtest.h> #include <adios2.h> static int numprocs, wrank; std::string engineName; // comes from command line struct RunParams { unsigned int npx_w; unsigned int npy_w; unsigned int npx_r; unsigned int npy_r; RunParams(unsigned int xw, unsigned int yw, unsigned int xr, unsigned int yr) : npx_w{xw}, npy_w{yw}, npx_r{xr}, npy_r{yr} {}; }; /* This function is executed by INSTANTIATE_TEST_CASE_P before main() and MPI_Init()!!! */ std::vector<RunParams> CreateRunParams() { std::vector<RunParams> params; // 2 process test params.push_back(RunParams(1, 1, 1, 1)); // 3 process tests params.push_back(RunParams(2, 1, 1, 1)); params.push_back(RunParams(1, 2, 1, 1)); params.push_back(RunParams(1, 1, 2, 1)); params.push_back(RunParams(1, 1, 1, 2)); return params; } class TestStagingMPMD : public ::testing::TestWithParam<RunParams> { public: TestStagingMPMD() = default; const std::string streamName = "TestStream"; int MainWriters(MPI_Comm comm, unsigned int npx, unsigned int npy, int steps, unsigned int sleeptime) { int rank, nproc; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &nproc); if (!rank) { std::cout << "There are " << nproc << "Writers" << std::endl; } unsigned int ndx = 5; unsigned int ndy = 6; unsigned int gndx = npx * ndx; unsigned int gndy = npy * ndy; unsigned int posx = rank % npx; unsigned int posy = rank / npx; unsigned int offsx = posx * ndx; unsigned int offsy = posy * ndy; std::vector<float> myArray(ndx * ndy); adios2::ADIOS adios(comm); adios2::IO &io = adios.DeclareIO("writer"); io.SetEngine(engineName); adios2::Variable<float> &varArray = io.DefineVariable<float>("myArray", {gndx, gndy}, {offsx, offsy}, {ndx, ndy}, adios2::ConstantDims); adios2::Engine &writer = io.Open(streamName, adios2::Mode::Write, comm); for (int step = 0; step < steps; ++step) { int idx = 0; for (int j = 0; j < ndy; ++j) { for (int i = 0; i < ndx; ++i) { myArray[idx] = rank + (step / 100.0f); ++idx; } } writer.BeginStep(adios2::StepMode::Append); writer.PutDeferred<float>(varArray, myArray.data()); writer.EndStep(); std::this_thread::sleep_for(std::chrono::milliseconds(sleeptime)); } writer.Close(); } int MainReaders(MPI_Comm comm, unsigned int npx, unsigned int npy, unsigned int sleeptime) { int rank, nproc; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &nproc); if (!rank) { std::cout << "There are " << nproc << "Readers" << std::endl; } adios2::ADIOS adios(comm); adios2::IO &io = adios.DeclareIO("reader"); io.SetEngine(engineName); adios2::Engine &reader = io.Open(streamName, adios2::Mode::Read, comm); unsigned int posx = rank % npx; unsigned int posy = rank / npx; int step = 0; adios2::Variable<float> *vMyArray = nullptr; std::vector<float> myArray; while (true) { adios2::StepStatus status = reader.BeginStep(adios2::StepMode::NextAvailable, 60.0f); if (status != adios2::StepStatus::OK) { break; } vMyArray = io.InquireVariable<float>("myArray"); if (vMyArray == nullptr) { throw std::ios_base::failure("Missing 'myArray' variable."); } // 2D decomposition of global array reading size_t gndx = vMyArray->m_Shape[0]; size_t gndy = vMyArray->m_Shape[1]; size_t ndx = gndx / npx; size_t ndy = gndy / npy; size_t offsx = ndx * posx; size_t offsy = ndy * posy; if (posx == npx - 1) { // right-most processes need to read all the rest of rows ndx = gndx - ndx * (npx - 1); } if (posy == npy - 1) { // bottom processes need to read all the rest of columns ndy = gndy - ndy * (npy - 1); } adios2::Dims count({ndx, ndy}); adios2::Dims start({offsx, offsy}); vMyArray->SetSelection({start, count}); size_t elementsSize = count[0] * count[1]; myArray.resize(elementsSize); reader.GetDeferred(*vMyArray, myArray.data()); reader.EndStep(); // checkData(myArray.data(), count, start, rank, step); ++step; } reader.Close(); } }; TEST_P(TestStagingMPMD, P) { RunParams p = GetParam(); std::cout << "test " << p.npx_w << "x" << p.npy_w << " writers " << p.npx_r << "x" << p.npy_r << " readers " << std::endl; int nwriters = p.npx_w * p.npy_w; int nreaders = p.npx_r * p.npy_r; if (nwriters + nreaders > numprocs) { if (!wrank) { std::cout << "skip test: writers+readers > available processors " << std::endl; } return; } int rank; MPI_Comm comm; unsigned int color; if (wrank < nwriters) { color = 0; // writers } else if (wrank < nwriters + nreaders) { color = 1; // readers } else { color = 2; // not participating in test } MPI_Comm_split(MPI_COMM_WORLD, color, wrank, &comm); MPI_Comm_rank(comm, &rank); if (color == 0) { std::cout << "Process wrank " << wrank << " rank " << rank << " calls MainWriters " << std::endl; MainWriters(comm, p.npx_w, p.npy_w, 10, 1); } else if (color == 1) { std::cout << "Process wrank " << wrank << " rank " << rank << " calls MainReaders " << std::endl; MainReaders(comm, p.npx_r, p.npy_r, 1); } std::cout << "Process wrank " << wrank << " rank " << rank << " enters MPI barrier..." << std::endl; MPI_Barrier(MPI_COMM_WORLD); } INSTANTIATE_TEST_CASE_P(NxM, TestStagingMPMD, ::testing::ValuesIn(CreateRunParams())); //****************************************************************************** // main //****************************************************************************** int main(int argc, char **argv) { MPI_Init(&argc, &argv); ::testing::InitGoogleTest(&argc, argv); MPI_Comm_rank(MPI_COMM_WORLD, &wrank); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); engineName = std::string(argv[1]); if (!wrank) { std::cout << "Test " << engineName << " engine with " << numprocs << " processes " << std::endl; } int result = RUN_ALL_TESTS(); MPI_Finalize(); return result; } <commit_msg>clang-format<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * Created on: Jan 2018 * Author: Norbert Podhorszki */ #include <chrono> #include <ios> //std::ios_base::failure #include <iostream> //std::cout #include <numeric> #include <stdexcept> //std::invalid_argument std::exception #include <string> #include <thread> #include <utility> #include <vector> #include <gtest/gtest.h> #include <adios2.h> static int numprocs, wrank; std::string engineName; // comes from command line struct RunParams { unsigned int npx_w; unsigned int npy_w; unsigned int npx_r; unsigned int npy_r; RunParams(unsigned int xw, unsigned int yw, unsigned int xr, unsigned int yr) : npx_w{xw}, npy_w{yw}, npx_r{xr}, npy_r{yr} {}; }; /* This function is executed by INSTANTIATE_TEST_CASE_P before main() and MPI_Init()!!! */ std::vector<RunParams> CreateRunParams() { std::vector<RunParams> params; // 2 process test params.push_back(RunParams(1, 1, 1, 1)); // 3 process tests params.push_back(RunParams(2, 1, 1, 1)); params.push_back(RunParams(1, 2, 1, 1)); params.push_back(RunParams(1, 1, 2, 1)); params.push_back(RunParams(1, 1, 1, 2)); return params; } class TestStagingMPMD : public ::testing::TestWithParam<RunParams> { public: TestStagingMPMD() = default; const std::string streamName = "TestStream"; int MainWriters(MPI_Comm comm, unsigned int npx, unsigned int npy, int steps, unsigned int sleeptime) { int rank, nproc; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &nproc); if (!rank) { std::cout << "There are " << nproc << "Writers" << std::endl; } unsigned int ndx = 5; unsigned int ndy = 6; unsigned int gndx = npx * ndx; unsigned int gndy = npy * ndy; unsigned int posx = rank % npx; unsigned int posy = rank / npx; unsigned int offsx = posx * ndx; unsigned int offsy = posy * ndy; std::vector<float> myArray(ndx * ndy); adios2::ADIOS adios(comm); adios2::IO &io = adios.DeclareIO("writer"); io.SetEngine(engineName); adios2::Variable<float> &varArray = io.DefineVariable<float>("myArray", {gndx, gndy}, {offsx, offsy}, {ndx, ndy}, adios2::ConstantDims); adios2::Engine &writer = io.Open(streamName, adios2::Mode::Write, comm); for (int step = 0; step < steps; ++step) { int idx = 0; for (int j = 0; j < ndy; ++j) { for (int i = 0; i < ndx; ++i) { myArray[idx] = rank + (step / 100.0f); ++idx; } } writer.BeginStep(adios2::StepMode::Append); writer.PutDeferred<float>(varArray, myArray.data()); writer.EndStep(); std::this_thread::sleep_for(std::chrono::milliseconds(sleeptime)); } writer.Close(); } int MainReaders(MPI_Comm comm, unsigned int npx, unsigned int npy, unsigned int sleeptime) { int rank, nproc; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &nproc); if (!rank) { std::cout << "There are " << nproc << "Readers" << std::endl; } adios2::ADIOS adios(comm); adios2::IO &io = adios.DeclareIO("reader"); io.SetEngine(engineName); adios2::Engine &reader = io.Open(streamName, adios2::Mode::Read, comm); unsigned int posx = rank % npx; unsigned int posy = rank / npx; int step = 0; adios2::Variable<float> *vMyArray = nullptr; std::vector<float> myArray; while (true) { adios2::StepStatus status = reader.BeginStep(adios2::StepMode::NextAvailable, 60.0f); if (status != adios2::StepStatus::OK) { break; } vMyArray = io.InquireVariable<float>("myArray"); if (vMyArray == nullptr) { throw std::ios_base::failure("Missing 'myArray' variable."); } // 2D decomposition of global array reading size_t gndx = vMyArray->m_Shape[0]; size_t gndy = vMyArray->m_Shape[1]; size_t ndx = gndx / npx; size_t ndy = gndy / npy; size_t offsx = ndx * posx; size_t offsy = ndy * posy; if (posx == npx - 1) { // right-most processes need to read all the rest of rows ndx = gndx - ndx * (npx - 1); } if (posy == npy - 1) { // bottom processes need to read all the rest of columns ndy = gndy - ndy * (npy - 1); } adios2::Dims count({ndx, ndy}); adios2::Dims start({offsx, offsy}); vMyArray->SetSelection({start, count}); size_t elementsSize = count[0] * count[1]; myArray.resize(elementsSize); reader.GetDeferred(*vMyArray, myArray.data()); reader.EndStep(); // checkData(myArray.data(), count, start, rank, step); ++step; } reader.Close(); } }; TEST_P(TestStagingMPMD, P) { RunParams p = GetParam(); std::cout << "test " << p.npx_w << "x" << p.npy_w << " writers " << p.npx_r << "x" << p.npy_r << " readers " << std::endl; int nwriters = p.npx_w * p.npy_w; int nreaders = p.npx_r * p.npy_r; if (nwriters + nreaders > numprocs) { if (!wrank) { std::cout << "skip test: writers+readers > available processors " << std::endl; } return; } int rank; MPI_Comm comm; unsigned int color; if (wrank < nwriters) { color = 0; // writers } else if (wrank < nwriters + nreaders) { color = 1; // readers } else { color = 2; // not participating in test } MPI_Comm_split(MPI_COMM_WORLD, color, wrank, &comm); MPI_Comm_rank(comm, &rank); if (color == 0) { std::cout << "Process wrank " << wrank << " rank " << rank << " calls MainWriters " << std::endl; MainWriters(comm, p.npx_w, p.npy_w, 10, 1); } else if (color == 1) { std::cout << "Process wrank " << wrank << " rank " << rank << " calls MainReaders " << std::endl; MainReaders(comm, p.npx_r, p.npy_r, 1); } std::cout << "Process wrank " << wrank << " rank " << rank << " enters MPI barrier..." << std::endl; MPI_Barrier(MPI_COMM_WORLD); } INSTANTIATE_TEST_CASE_P(NxM, TestStagingMPMD, ::testing::ValuesIn(CreateRunParams())); //****************************************************************************** // main //****************************************************************************** int main(int argc, char **argv) { MPI_Init(&argc, &argv); ::testing::InitGoogleTest(&argc, argv); MPI_Comm_rank(MPI_COMM_WORLD, &wrank); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); engineName = std::string(argv[1]); if (!wrank) { std::cout << "Test " << engineName << " engine with " << numprocs << " processes " << std::endl; } int result = RUN_ALL_TESTS(); MPI_Finalize(); return result; } <|endoftext|>
<commit_before>// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "stdafx.h" #include "CppUnitTest.h" #include "worker\Worker.h" #include "worker\WorkerContext.h" #include "TestWorkerContext.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace BatchEncoderCoreUnitTests { TEST_CLASS(CWorker_Tests) { public: TEST_METHOD(CWorker_Convert_Nothing) { config::CConfiguration m_Config; CTestWorkerContext ctx; Assert::IsTrue(ctx.bDone); Assert::IsNull(ctx.pConfig); ctx.bRunning = true; ctx.bDone = false; ctx.nTotalFiles = 0; ctx.nProcessedFiles = 0; ctx.nErrors = 0; ctx.nLastItemId = -1; ctx.nThreadCount = m_Config.m_Options.nThreadCount; ctx.pConfig = &m_Config; Assert::AreEqual(0, ctx.nThreadCount); Assert::IsNotNull(ctx.pConfig); worker::CWorker m_Worker; m_Worker.Convert(&ctx); Assert::IsFalse(ctx.bRunning); Assert::IsTrue(ctx.bDone); Assert::IsTrue(ctx.nTotalFiles == 0); Assert::IsTrue(ctx.nProcessedFiles == 0); Assert::IsTrue(ctx.nErrors == 0); Assert::IsTrue(ctx.nLastItemId == -1); Assert::AreEqual(0, ctx.nThreadCount); Assert::IsNull(ctx.pConfig); } }; } <commit_msg>Added Init helper function<commit_after>// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "stdafx.h" #include "CppUnitTest.h" #include "worker\Worker.h" #include "worker\WorkerContext.h" #include "TestWorkerContext.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace BatchEncoderCoreUnitTests { TEST_CLASS(CWorker_Tests) { void Init(worker::IWorkerContext& ctx) { ctx.bRunning = true; ctx.bDone = false; ctx.nTotalFiles = 0; ctx.nProcessedFiles = 0; ctx.nErrors = 0; ctx.nLastItemId = -1; } public: TEST_METHOD(CWorker_Convert_Nothing) { config::CConfiguration m_Config; CTestWorkerContext ctx; Assert::IsTrue(ctx.bDone); Assert::IsNull(ctx.pConfig); Init(ctx); ctx.nThreadCount = 1; ctx.pConfig = &m_Config; Assert::AreEqual(1, ctx.nThreadCount); Assert::IsNotNull(ctx.pConfig); worker::CWorker m_Worker; m_Worker.Convert(&ctx); Assert::IsFalse(ctx.bRunning); Assert::IsTrue(ctx.bDone); Assert::IsTrue(ctx.nTotalFiles == 0); Assert::IsTrue(ctx.nProcessedFiles == 0); Assert::IsTrue(ctx.nErrors == 0); Assert::IsTrue(ctx.nLastItemId == -1); Assert::AreEqual(1, ctx.nThreadCount); Assert::IsNull(ctx.pConfig); } }; } <|endoftext|>
<commit_before>#include <ctime> #include <iostream> #include <cstdlib> #include <iterator> #include <time_ordered_set.h> #include <Bucket.h> #include <ctime> int main(int argc, char *argv[]) { const size_t K = 1; { const size_t max_size=K*100000; auto tos =memseries::storage::TimeOrderedSet{ max_size }; auto m = memseries::Meas::empty(); auto start = clock(); for (size_t i = 0; i < max_size; i++) { m.id = 1; m.flag = 0xff; m.time = i; m.value = i; tos.append(m); } auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC; std::cout<<"TimeOrderedSet insert : "<<elapsed<<std::endl; start = clock(); auto reader = tos.as_array(); elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "TimeOrderedSet as_array: " << elapsed << std::endl; std::cout << "raded: " << reader.size() << std::endl; } { const size_t max_size=10000; const size_t max_count=K*10; auto tos =memseries::storage::Bucket{ max_size,max_count }; auto m = memseries::Meas::empty(); auto start = clock(); for (size_t i = 0; i < K*1000000; i++) { m.id = 1; m.flag = 0xff; m.time = i; m.value = i; tos.append(m); } auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC; std::cout<<"Bucket insert : "<<elapsed<<std::endl; } } <commit_msg>#include<commit_after>#include <ctime> #include <iostream> #include <cstdlib> #include <iterator> #include <time_ordered_set.h> #include <bucket.h> #include <ctime> int main(int argc, char *argv[]) { const size_t K = 1; { const size_t max_size=K*100000; auto tos =memseries::storage::TimeOrderedSet{ max_size }; auto m = memseries::Meas::empty(); auto start = clock(); for (size_t i = 0; i < max_size; i++) { m.id = 1; m.flag = 0xff; m.time = i; m.value = i; tos.append(m); } auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC; std::cout<<"TimeOrderedSet insert : "<<elapsed<<std::endl; start = clock(); auto reader = tos.as_array(); elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "TimeOrderedSet as_array: " << elapsed << std::endl; std::cout << "raded: " << reader.size() << std::endl; } { const size_t max_size=10000; const size_t max_count=K*10; auto tos =memseries::storage::Bucket{ max_size,max_count }; auto m = memseries::Meas::empty(); auto start = clock(); for (size_t i = 0; i < K*1000000; i++) { m.id = 1; m.flag = 0xff; m.time = i; m.value = i; tos.append(m); } auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC; std::cout<<"Bucket insert : "<<elapsed<<std::endl; } } <|endoftext|>
<commit_before>#include <iostream> #include <limits.h> #include <thread> #include <unistd.h> int main() { char name[_POSIX_HOST_NAME_MAX + 1]; gethostname(name, sizeof(name)); std::cout << "Host name: " << name << std::endl; unsigned int cores = std::thread::hardware_concurrency(); std::cout << "Total cores: " << cores << std::endl; return 0; } <commit_msg>Fix Windows build issues by removing posix only code.<commit_after>#include <iostream> #include <limits.h> #include <thread> int main() { unsigned int cores = std::thread::hardware_concurrency(); std::cout << "Total cores: " << cores << std::endl; return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/operators/softmax_with_cross_entropy_op.h" #include <paddle/function/TensorType.h> namespace paddle { namespace operators { class SoftmaxWithCrossEntropyOpMaker : public framework::OpProtoAndCheckerMaker { public: SoftmaxWithCrossEntropyOpMaker(framework::OpProto* proto, framework::OpAttrChecker* op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput("Logits", "(Tensor, default: Tensor<float>), The unscaled log probabilities " "which is a 2-D tensor with shape [N x K]. N is the batch_size, " "and K is the class number."); AddInput("Label", "(Tensor) The ground truth which is a 2-D tensor. If soft_label " "is set to false, Label is a Tensor<int64> with shape [N x 1]. If " "soft_label is set to true, Label is a Tensor<float/double> with " "shape [N x K]."); AddOutput( "Softmax", "(Tensor, default: Tensor<float>), A 2-D tensor with shape [N x K]. " "The outputs value of softmax activation by given the input batch, " "which will be used in backward calculation.") .AsIntermediate(); AddOutput("Loss", "(Tensor, default: Tensor<float>), A 2-D tensor. The cross " "entropy loss with shape [N x 1]."); AddAttr<bool>( "soft_label", "(bool, default: false), A flag to indicate whether to interpretate " "the given labels as soft labels.") .SetDefault(false); AddComment(R"DOC( Softmax With Cross Entropy Operator. Cross entropy loss with softmax is used as the output layer extensively. This operator computes the softmax normalized values for each row of the input tensor, after which cross-entropy loss is computed. This provides a more numerically stable gradient. Because this operator performs a softmax on logits internally, it expects unscaled logits. This operator should not be used with the output of softmax operator since that would produce incorrect results. When the attribute soft_label is set false, this operators expects mutually exclusive hard labels, each sample in a batch is in exactly one class with a probability of 1.0. Each sample in the batch will have a single label. The equation is as follows: 1) Hard label (one-hot label, so every sample has exactly one class) $$Loss_j = -\text{Logit}_{Label_j} + \log\left(\sum_{i=0}^{K}\exp(\text{Logit}_i)\right), j = 1,..., K$$ 2) Soft label (each sample can have a distribution over all classes) $$Loss_j = -\sum_{i=0}^{K}\text{Label}_i \left(\text{Logit}_i - \log\left(\sum_{i=0}^{K}\exp(\text{Logit}_i)\right)\right), j = 1,...,K$$ )DOC"); } }; class SoftmaxWithCrossEntropyOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("Logits"), "Input(Logits) should be not null."); PADDLE_ENFORCE(ctx->HasInput("Label"), "Input(Label) should be not null."); PADDLE_ENFORCE(ctx->HasOutput("Softmax"), "Output(Softmax) should be not null."); PADDLE_ENFORCE(ctx->HasOutput("Loss"), "Output(Loss) should be not null."); auto logits_dims = ctx->GetInputDim("Logits"); auto labels_dims = ctx->GetInputDim("Label"); PADDLE_ENFORCE_EQ( logits_dims.size(), 2UL, "The input of softmax_with_cross_entropy should be a 2-D tensor."); PADDLE_ENFORCE_EQ(labels_dims.size(), 2UL, "The labels should be a 2-D tensor."); if (ctx->Attrs().Get<bool>("soft_label")) { PADDLE_ENFORCE_EQ(logits_dims[1], labels_dims[1], "If Attr(soft_label) == true, the 2nd dimension of " "Input(X) and Input(Label) should be equal."); } else { PADDLE_ENFORCE_EQ(labels_dims[1], 1UL, "If Attr(soft_label) == false, the 2nd dimension of " "Input(Label) should be 1."); } ctx->SetOutputDim("Softmax", logits_dims); ctx->SetOutputDim("Loss", {logits_dims[0], 1}); ctx->ShareLoD("Logits", /*->*/ "Softmax"); ctx->ShareLoD("Logits", /*->*/ "Loss"); } protected: framework::OpKernelType GetKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( framework::ToDataType(ctx.Input<Tensor>("Logits")->type()), ctx.device_context()); } }; class SoftmaxWithCrossEntropyOpGrad : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Loss")), "Input(Loss@Grad) should not be null."); PADDLE_ENFORCE(ctx->HasInput("Softmax"), "Input(Softmax) should be not null."); PADDLE_ENFORCE(ctx->HasInput("Label"), "Input(Label) should be not null."); PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("Logits")), "Output(Logits@Grad) should be not null."); auto softmax_dims = ctx->GetInputDim("Softmax"); auto labels_dims = ctx->GetInputDim("Label"); PADDLE_ENFORCE_EQ(labels_dims.size(), 2UL, "The labels should be a 2-D tensor."); if (ctx->Attrs().Get<bool>("soft_label")) { PADDLE_ENFORCE_EQ(softmax_dims[1], labels_dims[1], "When Attr(soft_label) == true, the 2nd dimension of " "Input(X) and Input(Label) should be equal."); } else { PADDLE_ENFORCE_EQ(labels_dims[1], 1UL, "When Attr(soft_label) == false, the 2nd dimension of " "Input(Label) should be 1."); } ctx->SetOutputDim(framework::GradVarName("Logits"), ctx->GetInputDim("Softmax")); } protected: framework::OpKernelType GetKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( framework::ToDataType( ctx.Input<Tensor>(framework::GradVarName("Loss"))->type()), ctx.device_context()); } }; class SoftmaxGradMaker : public framework::SingleGradOpDescMaker { public: using framework::SingleGradOpDescMaker::SingleGradOpDescMaker; protected: std::unique_ptr<framework::OpDescBind> Apply() const override { auto* grad_op = new framework::OpDescBind(); grad_op->SetType("softmax_with_cross_entropy_grad"); grad_op->SetInput("Label", Input("Label")); grad_op->SetInput("Softmax", Output("Softmax")); grad_op->SetInput("Loss", Output("Loss")); grad_op->SetInput(framework::GradVarName("Softmax"), OutputGrad("Softmax")); grad_op->SetInput(framework::GradVarName("Loss"), OutputGrad("Loss")); grad_op->SetOutput(framework::GradVarName("Logits"), InputGrad("Logits")); grad_op->SetAttrMap(Attrs()); return std::unique_ptr<framework::OpDescBind>(grad_op); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(softmax_with_cross_entropy, ops::SoftmaxWithCrossEntropyOp, ops::SoftmaxWithCrossEntropyOpMaker, ops::SoftmaxGradMaker); REGISTER_OPERATOR(softmax_with_cross_entropy_grad, ops::SoftmaxWithCrossEntropyOpGrad); REGISTER_OP_CPU_KERNEL(softmax_with_cross_entropy, ops::SoftmaxWithCrossEntropyKernel<float>, ops::SoftmaxWithCrossEntropyKernel<double>); REGISTER_OP_CPU_KERNEL(softmax_with_cross_entropy_grad, ops::SoftmaxWithCrossEntropyGradKernel<float>, ops::SoftmaxWithCrossEntropyGradKernel<double>); <commit_msg>Make the new framework independent the old framework. (#6201)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/operators/softmax_with_cross_entropy_op.h" namespace paddle { namespace operators { class SoftmaxWithCrossEntropyOpMaker : public framework::OpProtoAndCheckerMaker { public: SoftmaxWithCrossEntropyOpMaker(framework::OpProto* proto, framework::OpAttrChecker* op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput("Logits", "(Tensor, default: Tensor<float>), The unscaled log probabilities " "which is a 2-D tensor with shape [N x K]. N is the batch_size, " "and K is the class number."); AddInput("Label", "(Tensor) The ground truth which is a 2-D tensor. If soft_label " "is set to false, Label is a Tensor<int64> with shape [N x 1]. If " "soft_label is set to true, Label is a Tensor<float/double> with " "shape [N x K]."); AddOutput( "Softmax", "(Tensor, default: Tensor<float>), A 2-D tensor with shape [N x K]. " "The outputs value of softmax activation by given the input batch, " "which will be used in backward calculation.") .AsIntermediate(); AddOutput("Loss", "(Tensor, default: Tensor<float>), A 2-D tensor. The cross " "entropy loss with shape [N x 1]."); AddAttr<bool>( "soft_label", "(bool, default: false), A flag to indicate whether to interpretate " "the given labels as soft labels.") .SetDefault(false); AddComment(R"DOC( Softmax With Cross Entropy Operator. Cross entropy loss with softmax is used as the output layer extensively. This operator computes the softmax normalized values for each row of the input tensor, after which cross-entropy loss is computed. This provides a more numerically stable gradient. Because this operator performs a softmax on logits internally, it expects unscaled logits. This operator should not be used with the output of softmax operator since that would produce incorrect results. When the attribute soft_label is set false, this operators expects mutually exclusive hard labels, each sample in a batch is in exactly one class with a probability of 1.0. Each sample in the batch will have a single label. The equation is as follows: 1) Hard label (one-hot label, so every sample has exactly one class) $$Loss_j = -\text{Logit}_{Label_j} + \log\left(\sum_{i=0}^{K}\exp(\text{Logit}_i)\right), j = 1,..., K$$ 2) Soft label (each sample can have a distribution over all classes) $$Loss_j = -\sum_{i=0}^{K}\text{Label}_i \left(\text{Logit}_i - \log\left(\sum_{i=0}^{K}\exp(\text{Logit}_i)\right)\right), j = 1,...,K$$ )DOC"); } }; class SoftmaxWithCrossEntropyOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("Logits"), "Input(Logits) should be not null."); PADDLE_ENFORCE(ctx->HasInput("Label"), "Input(Label) should be not null."); PADDLE_ENFORCE(ctx->HasOutput("Softmax"), "Output(Softmax) should be not null."); PADDLE_ENFORCE(ctx->HasOutput("Loss"), "Output(Loss) should be not null."); auto logits_dims = ctx->GetInputDim("Logits"); auto labels_dims = ctx->GetInputDim("Label"); PADDLE_ENFORCE_EQ( logits_dims.size(), 2UL, "The input of softmax_with_cross_entropy should be a 2-D tensor."); PADDLE_ENFORCE_EQ(labels_dims.size(), 2UL, "The labels should be a 2-D tensor."); if (ctx->Attrs().Get<bool>("soft_label")) { PADDLE_ENFORCE_EQ(logits_dims[1], labels_dims[1], "If Attr(soft_label) == true, the 2nd dimension of " "Input(X) and Input(Label) should be equal."); } else { PADDLE_ENFORCE_EQ(labels_dims[1], 1UL, "If Attr(soft_label) == false, the 2nd dimension of " "Input(Label) should be 1."); } ctx->SetOutputDim("Softmax", logits_dims); ctx->SetOutputDim("Loss", {logits_dims[0], 1}); ctx->ShareLoD("Logits", /*->*/ "Softmax"); ctx->ShareLoD("Logits", /*->*/ "Loss"); } protected: framework::OpKernelType GetKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( framework::ToDataType(ctx.Input<Tensor>("Logits")->type()), ctx.device_context()); } }; class SoftmaxWithCrossEntropyOpGrad : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Loss")), "Input(Loss@Grad) should not be null."); PADDLE_ENFORCE(ctx->HasInput("Softmax"), "Input(Softmax) should be not null."); PADDLE_ENFORCE(ctx->HasInput("Label"), "Input(Label) should be not null."); PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("Logits")), "Output(Logits@Grad) should be not null."); auto softmax_dims = ctx->GetInputDim("Softmax"); auto labels_dims = ctx->GetInputDim("Label"); PADDLE_ENFORCE_EQ(labels_dims.size(), 2UL, "The labels should be a 2-D tensor."); if (ctx->Attrs().Get<bool>("soft_label")) { PADDLE_ENFORCE_EQ(softmax_dims[1], labels_dims[1], "When Attr(soft_label) == true, the 2nd dimension of " "Input(X) and Input(Label) should be equal."); } else { PADDLE_ENFORCE_EQ(labels_dims[1], 1UL, "When Attr(soft_label) == false, the 2nd dimension of " "Input(Label) should be 1."); } ctx->SetOutputDim(framework::GradVarName("Logits"), ctx->GetInputDim("Softmax")); } protected: framework::OpKernelType GetKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( framework::ToDataType( ctx.Input<Tensor>(framework::GradVarName("Loss"))->type()), ctx.device_context()); } }; class SoftmaxGradMaker : public framework::SingleGradOpDescMaker { public: using framework::SingleGradOpDescMaker::SingleGradOpDescMaker; protected: std::unique_ptr<framework::OpDescBind> Apply() const override { auto* grad_op = new framework::OpDescBind(); grad_op->SetType("softmax_with_cross_entropy_grad"); grad_op->SetInput("Label", Input("Label")); grad_op->SetInput("Softmax", Output("Softmax")); grad_op->SetInput("Loss", Output("Loss")); grad_op->SetInput(framework::GradVarName("Softmax"), OutputGrad("Softmax")); grad_op->SetInput(framework::GradVarName("Loss"), OutputGrad("Loss")); grad_op->SetOutput(framework::GradVarName("Logits"), InputGrad("Logits")); grad_op->SetAttrMap(Attrs()); return std::unique_ptr<framework::OpDescBind>(grad_op); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(softmax_with_cross_entropy, ops::SoftmaxWithCrossEntropyOp, ops::SoftmaxWithCrossEntropyOpMaker, ops::SoftmaxGradMaker); REGISTER_OPERATOR(softmax_with_cross_entropy_grad, ops::SoftmaxWithCrossEntropyOpGrad); REGISTER_OP_CPU_KERNEL(softmax_with_cross_entropy, ops::SoftmaxWithCrossEntropyKernel<float>, ops::SoftmaxWithCrossEntropyKernel<double>); REGISTER_OP_CPU_KERNEL(softmax_with_cross_entropy_grad, ops::SoftmaxWithCrossEntropyGradKernel<float>, ops::SoftmaxWithCrossEntropyGradKernel<double>); <|endoftext|>
<commit_before>#include "player.hpp" namespace msrv { namespace player_foobar2000 { namespace { inline t_size clampIndex(int32_t index, t_size count, t_size fallback); class PlaylistQueryImpl : public PlaylistQuery { public: PlaylistQueryImpl( const PlaylistRef& plrefVal, const Range& rangeVal, TitleFormatVector columnsVal) : plref(plrefVal), range(rangeVal), columns(std::move(columnsVal)) { } PlaylistRef plref; Range range; TitleFormatVector columns; }; class AsyncAddCompleter : public process_locations_notify { public: AsyncAddCompleter( service_ptr_t<playlist_manager_v4> playlistManager, std::shared_ptr<PlaylistMapping> playlists, const PlaylistRef& plref, int32_t index) : playlistManager_(playlistManager), playlists_(playlists), plref_(plref), index_(index) { } boost::unique_future<void> getResult() { return result_.get_future(); } virtual void on_completion(const pfc::list_base_const_t<metadb_handle_ptr>& items) override { try { complete(items); } catch (std::exception& ex) { result_.set_exception(ex); return; } result_.set_value(); } virtual void on_aborted() override { result_.set_exception(InvalidRequestException("Operation aborted")); } private: void complete(const pfc::list_base_const_t<metadb_handle_ptr>& items) { auto playlist = playlists_->resolve(plref_); auto itemCount = playlistManager_->playlist_get_item_count(playlist); auto index = clampIndex(index_, itemCount, pfc_infinite); playlistManager_->playlist_insert_items(playlist, index, items, bit_array_false()); } service_ptr_t<playlist_manager_v4> playlistManager_; std::shared_ptr<PlaylistMapping> playlists_; PlaylistRef plref_; int32_t index_; boost::promise<void> result_; }; std::vector<t_size> createIndexesVector(t_size count) { std::vector<t_size> indexes; indexes.reserve(count); for (t_size i = 0; i < count; i++) indexes.push_back(i); return indexes; } inline t_size clampIndex(int32_t index, t_size count, t_size fallback) { return index >= 0 && static_cast<t_size>(index) < count ? index : fallback; } } std::vector<std::string> PlayerImpl::evaluatePlaylistColumns( t_size playlist, t_size item, const TitleFormatVector& compiledColumns, pfc::string8* buffer) { std::vector<std::string> result; result.reserve(compiledColumns.size()); for (auto& compiledColumn : compiledColumns) { playlistManager_->playlist_item_format_title( playlist, item, nullptr, *buffer, compiledColumn, nullptr, playback_control::display_level_basic); result.emplace_back(buffer->get_ptr(), buffer->get_length()); } return result; } std::vector<PlaylistInfo> PlayerImpl::getPlaylists() { playlists_->ensureInitialized(); auto count = playlistManager_->get_playlist_count(); auto current = playlistManager_->get_active_playlist(); std::vector<PlaylistInfo> playlists; playlists.reserve(count); pfc::string8 nameBuffer; for (t_size i = 0; i < count; i++) { PlaylistInfo info; info.id = playlists_->getId(i); info.index = i; info.isCurrent = i == current; info.itemCount = playlistManager_->playlist_get_item_count(i); if (playlistManager_->playlist_get_name(i, nameBuffer)) info.title.assign(nameBuffer.get_ptr(), nameBuffer.get_length()); info.totalTime = 0.0; playlists.emplace_back(std::move(info)); } return playlists; } std::vector<PlaylistItemInfo> PlayerImpl::getPlaylistItems(PlaylistQuery* queryPtr) { auto query = static_cast<PlaylistQueryImpl*>(queryPtr); auto playlist = playlists_->resolve(query->plref); auto start = static_cast<t_size>(query->range.offset); auto end = std::min( static_cast<t_size>(query->range.endOffset()), playlistManager_->playlist_get_item_count(playlist)); std::vector<PlaylistItemInfo> result; pfc::string8 buffer; for (t_size item = start; item < end; item++) result.emplace_back(evaluatePlaylistColumns(playlist, item, query->columns, &buffer)); return result; } void PlayerImpl::addPlaylist(int32_t index, const std::string& title) { playlists_->ensureInitialized(); playlistManager_->create_playlist( title.data(), title.length(), clampIndex(index, playlistManager_->get_playlist_count(), pfc_infinite)); } void PlayerImpl::removePlaylist(const PlaylistRef& playlist) { playlistManager_->remove_playlist_switch(playlists_->resolve(playlist)); } void PlayerImpl::movePlaylist(const PlaylistRef& playlist, int32_t index) { auto count = playlistManager_->get_playlist_count(); auto oldIndex = playlists_->resolve(playlist); auto newIndex = clampIndex(index, count, count - 1); if (newIndex == oldIndex) return; auto indexes = createIndexesVector(count); pfc::create_move_item_permutation(indexes.data(), count, oldIndex, newIndex); playlistManager_->reorder(indexes.data(), count); } void PlayerImpl::clearPlaylist(const PlaylistRef& playlist) { playlistManager_->playlist_clear(playlists_->resolve(playlist)); } void PlayerImpl::setCurrentPlaylist(const PlaylistRef& playlist) { playlistManager_->set_active_playlist(playlists_->resolve(playlist)); } void PlayerImpl::setPlaylistTitle(const PlaylistRef& playlist, const std::string& title) { playlistManager_->playlist_rename(playlists_->resolve(playlist), title.data(), title.length()); } boost::unique_future<void> PlayerImpl::addPlaylistItems( const PlaylistRef& plref, const std::vector<std::string>& items, int32_t targetIndex) { pfc::list_t<const char*> itemsList; itemsList.prealloc(items.size()); for (auto& item : items) itemsList.add_item(item.c_str()); service_ptr_t<AsyncAddCompleter> completer( new service_impl_t<AsyncAddCompleter>( playlistManager_, playlists_, plref, targetIndex)); incomingItemFilter_->process_locations_async( itemsList, playlist_incoming_item_filter_v2::op_flag_background, nullptr, nullptr, core_api::get_main_window(), completer); return completer->getResult(); } void PlayerImpl::copyPlaylistItems( const PlaylistRef& sourcePlaylist, const PlaylistRef& targetPlaylist, const std::vector<int32_t>& sourceItemIndexes, int32_t targetIndex) { } void PlayerImpl::movePlaylistItems( const PlaylistRef& sourcePlaylist, const PlaylistRef& targetPlaylist, const std::vector<int32_t>& sourceItemIndexes, int32_t targetIndex) { } void PlayerImpl::removePlaylistItems( const PlaylistRef& plref, const std::vector<int32_t>& itemIndexes) { auto playlist = playlists_->resolve(plref); auto count = playlistManager_->playlist_get_item_count(playlist); pfc::bit_array_flatIndexList items; for (auto index : itemIndexes) { if (index >= 0 && static_cast<t_size>(index) < count) items.add(index); } items.presort(); playlistManager_->playlist_remove_items(playlist, items); } void PlayerImpl::sortPlaylist( const PlaylistRef& plref, const std::string& expression, bool descending) { playlistManager_->playlist_sort_by_format(playlists_->resolve(plref), expression.c_str(), false); // TODO: descending sort } void PlayerImpl::sortPlaylistRandom(const PlaylistRef& plref) { playlistManager_->playlist_sort_by_format(playlists_->resolve(plref), nullptr, false); } PlaylistQueryPtr PlayerImpl::createPlaylistQuery( const PlaylistRef& playlist, const Range& range, const std::vector<std::string>& columns) { return std::make_unique<PlaylistQueryImpl>(playlist, range, compileColumns(columns)); } }} <commit_msg>player_foobar2000/player_playlists.cpp: create new playlist when last playlist is removed<commit_after>#include "player.hpp" namespace msrv { namespace player_foobar2000 { namespace { inline t_size clampIndex(int32_t index, t_size count, t_size fallback); class PlaylistQueryImpl : public PlaylistQuery { public: PlaylistQueryImpl( const PlaylistRef& plrefVal, const Range& rangeVal, TitleFormatVector columnsVal) : plref(plrefVal), range(rangeVal), columns(std::move(columnsVal)) { } PlaylistRef plref; Range range; TitleFormatVector columns; }; class AsyncAddCompleter : public process_locations_notify { public: AsyncAddCompleter( service_ptr_t<playlist_manager_v4> playlistManager, std::shared_ptr<PlaylistMapping> playlists, const PlaylistRef& plref, int32_t index) : playlistManager_(playlistManager), playlists_(playlists), plref_(plref), index_(index) { } boost::unique_future<void> getResult() { return result_.get_future(); } virtual void on_completion(const pfc::list_base_const_t<metadb_handle_ptr>& items) override { try { complete(items); } catch (std::exception& ex) { result_.set_exception(ex); return; } result_.set_value(); } virtual void on_aborted() override { result_.set_exception(InvalidRequestException("Operation aborted")); } private: void complete(const pfc::list_base_const_t<metadb_handle_ptr>& items) { auto playlist = playlists_->resolve(plref_); auto itemCount = playlistManager_->playlist_get_item_count(playlist); auto index = clampIndex(index_, itemCount, pfc_infinite); playlistManager_->playlist_insert_items(playlist, index, items, bit_array_false()); } service_ptr_t<playlist_manager_v4> playlistManager_; std::shared_ptr<PlaylistMapping> playlists_; PlaylistRef plref_; int32_t index_; boost::promise<void> result_; }; std::vector<t_size> createIndexesVector(t_size count) { std::vector<t_size> indexes; indexes.reserve(count); for (t_size i = 0; i < count; i++) indexes.push_back(i); return indexes; } inline t_size clampIndex(int32_t index, t_size count, t_size fallback) { return index >= 0 && static_cast<t_size>(index) < count ? index : fallback; } } std::vector<std::string> PlayerImpl::evaluatePlaylistColumns( t_size playlist, t_size item, const TitleFormatVector& compiledColumns, pfc::string8* buffer) { std::vector<std::string> result; result.reserve(compiledColumns.size()); for (auto& compiledColumn : compiledColumns) { playlistManager_->playlist_item_format_title( playlist, item, nullptr, *buffer, compiledColumn, nullptr, playback_control::display_level_basic); result.emplace_back(buffer->get_ptr(), buffer->get_length()); } return result; } std::vector<PlaylistInfo> PlayerImpl::getPlaylists() { playlists_->ensureInitialized(); auto count = playlistManager_->get_playlist_count(); auto current = playlistManager_->get_active_playlist(); std::vector<PlaylistInfo> playlists; playlists.reserve(count); pfc::string8 nameBuffer; for (t_size i = 0; i < count; i++) { PlaylistInfo info; info.id = playlists_->getId(i); info.index = i; info.isCurrent = i == current; info.itemCount = playlistManager_->playlist_get_item_count(i); if (playlistManager_->playlist_get_name(i, nameBuffer)) info.title.assign(nameBuffer.get_ptr(), nameBuffer.get_length()); info.totalTime = 0.0; playlists.emplace_back(std::move(info)); } return playlists; } std::vector<PlaylistItemInfo> PlayerImpl::getPlaylistItems(PlaylistQuery* queryPtr) { auto query = static_cast<PlaylistQueryImpl*>(queryPtr); auto playlist = playlists_->resolve(query->plref); auto start = static_cast<t_size>(query->range.offset); auto end = std::min( static_cast<t_size>(query->range.endOffset()), playlistManager_->playlist_get_item_count(playlist)); std::vector<PlaylistItemInfo> result; pfc::string8 buffer; for (t_size item = start; item < end; item++) result.emplace_back(evaluatePlaylistColumns(playlist, item, query->columns, &buffer)); return result; } void PlayerImpl::addPlaylist(int32_t index, const std::string& title) { playlists_->ensureInitialized(); playlistManager_->create_playlist( title.data(), title.length(), clampIndex(index, playlistManager_->get_playlist_count(), pfc_infinite)); } void PlayerImpl::removePlaylist(const PlaylistRef& playlist) { playlistManager_->remove_playlist_switch(playlists_->resolve(playlist)); if (playlistManager_->get_playlist_count() == 0) playlistManager_->create_playlist_autoname(); } void PlayerImpl::movePlaylist(const PlaylistRef& playlist, int32_t index) { auto count = playlistManager_->get_playlist_count(); auto oldIndex = playlists_->resolve(playlist); auto newIndex = clampIndex(index, count, count - 1); if (newIndex == oldIndex) return; auto indexes = createIndexesVector(count); pfc::create_move_item_permutation(indexes.data(), count, oldIndex, newIndex); playlistManager_->reorder(indexes.data(), count); } void PlayerImpl::clearPlaylist(const PlaylistRef& playlist) { playlistManager_->playlist_clear(playlists_->resolve(playlist)); } void PlayerImpl::setCurrentPlaylist(const PlaylistRef& playlist) { playlistManager_->set_active_playlist(playlists_->resolve(playlist)); } void PlayerImpl::setPlaylistTitle(const PlaylistRef& playlist, const std::string& title) { playlistManager_->playlist_rename(playlists_->resolve(playlist), title.data(), title.length()); } boost::unique_future<void> PlayerImpl::addPlaylistItems( const PlaylistRef& plref, const std::vector<std::string>& items, int32_t targetIndex) { pfc::list_t<const char*> itemsList; itemsList.prealloc(items.size()); for (auto& item : items) itemsList.add_item(item.c_str()); service_ptr_t<AsyncAddCompleter> completer( new service_impl_t<AsyncAddCompleter>( playlistManager_, playlists_, plref, targetIndex)); incomingItemFilter_->process_locations_async( itemsList, playlist_incoming_item_filter_v2::op_flag_background, nullptr, nullptr, core_api::get_main_window(), completer); return completer->getResult(); } void PlayerImpl::copyPlaylistItems( const PlaylistRef& sourcePlaylist, const PlaylistRef& targetPlaylist, const std::vector<int32_t>& sourceItemIndexes, int32_t targetIndex) { } void PlayerImpl::movePlaylistItems( const PlaylistRef& sourcePlaylist, const PlaylistRef& targetPlaylist, const std::vector<int32_t>& sourceItemIndexes, int32_t targetIndex) { } void PlayerImpl::removePlaylistItems( const PlaylistRef& plref, const std::vector<int32_t>& itemIndexes) { auto playlist = playlists_->resolve(plref); auto count = playlistManager_->playlist_get_item_count(playlist); pfc::bit_array_flatIndexList items; for (auto index : itemIndexes) { if (index >= 0 && static_cast<t_size>(index) < count) items.add(index); } items.presort(); playlistManager_->playlist_remove_items(playlist, items); } void PlayerImpl::sortPlaylist( const PlaylistRef& plref, const std::string& expression, bool descending) { playlistManager_->playlist_sort_by_format(playlists_->resolve(plref), expression.c_str(), false); // TODO: descending sort } void PlayerImpl::sortPlaylistRandom(const PlaylistRef& plref) { playlistManager_->playlist_sort_by_format(playlists_->resolve(plref), nullptr, false); } PlaylistQueryPtr PlayerImpl::createPlaylistQuery( const PlaylistRef& playlist, const Range& range, const std::vector<std::string>& columns) { return std::make_unique<PlaylistQueryImpl>(playlist, range, compileColumns(columns)); } }} <|endoftext|>
<commit_before>/* * * * * * Implements the people detection algorithm described here: * M. Munaro, F. Basso and E. Menegatti, * Tracking people within groups with RGB-D data, * In Proceedings of the International Conference on Intelligent Robots and Systems (IROS) 2012, Vilamoura (Portugal), 2012. */ #include <signal.h> #include <vector> #include <string> #include <ros/ros.h> #include <ros/package.h> #include <sensor_msgs/PointCloud2.h> #include <visualization_msgs/Marker.h> #include <visualization_msgs/MarkerArray.h> #include <tf/transform_listener.h> #include <tf/tf.h> #include <pcl_ros/impl/transforms.hpp> // PCL specific includes #include <pcl/conversions.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_cloud.h> #include <pcl/console/parse.h> #include <pcl/point_types.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/io/openni_grabber.h> #include <pcl/sample_consensus/sac_model_plane.h> #include <pcl/people/ground_based_people_detection_app.h> #include <pcl/common/time.h> #include <pcl/filters/crop_box.h> using namespace std; typedef pcl::PointXYZRGB PointT; typedef pcl::PointCloud<PointT> PointCloudT; //some custom functions #include "utils/file_io.h" #include "utils/viz_utils.h" #include "utils/pcl_utils.h" //some constants bool visualize = false; bool calibrate_plane = false; const std::string data_topic = "nav_kinect/depth_registered/points"; const std::string classifier_location = ros::package::getPath("pcl_perception") + "/classifier.yaml"; const std::string node_name = "segbot_people_detector"; //true if Ctrl-C is pressed bool g_caught_sigint=false; //refresh rate double ros_rate = 10.0; Eigen::VectorXf ground_coeffs; // Mutex: // boost::mutex cloud_mutex; bool new_cloud_available_flag = false; PointCloudT::Ptr cloud (new PointCloudT); PointCloudT::Ptr person_cloud (new PointCloudT); sensor_msgs::PointCloud2 person_cloud_ros; std::string sensor_frame_id; void sig_handler(int sig) { g_caught_sigint = true; ROS_INFO("caught sigint, init shutdown sequence..."); ros::shutdown(); exit(1); }; void cloud_cb (const sensor_msgs::PointCloud2ConstPtr& input) { sensor_frame_id = input.header.frame_id; cloud_mutex.lock (); //convert to PCL format pcl::fromROSMsg (*input, *cloud); //state that a new cloud is available new_cloud_available_flag = true; cloud_mutex.unlock (); } struct callback_args{ // structure used to pass arguments to the callback function PointCloudT::Ptr clicked_points_3d; pcl::visualization::PCLVisualizer::Ptr viewerPtr; }; int main (int argc, char** argv) { // Initialize ROS ros::init (argc, argv, "segbot_background_person_detector"); ros::NodeHandle nh; nh.param<bool>("background_person_detector/visualize", visualize, false); nh.param<double>("background_person_detector/rate", ros_rate, 10.0); string param_out_frame_id; nh.param<std::string>(std::string("background_person_detector/out_frame_id"), param_out_frame_id, "/map"); string param_topic; nh.param<std::string>(std::string("background_person_detector/rgbd_topic"), param_topic, data_topic); string param_classifier; nh.param<std::string>(std::string("background_person_detector/classifier_location"), param_classifier, ros::package::getPath("pcl_perception")+"/data/classifier.yaml"); string param_sensor_frame_id; nh.param<std::string>(std::string("background_person_detector/sensor_frame_id"), param_sensor_frame_id, //"/nav_kinect_rgb_optical_frame"); sensor_frame_id); //nh.getParam("background_person_detector/rgbd_topic", data_topic); //initialize marker publisher ros::Publisher marker_pub = nh.advertise<visualization_msgs::Marker>("segbot_pcl_person_detector/marker", 10); ros::Publisher pose_pub = nh.advertise<geometry_msgs::PoseStamped>("segbot_pcl_person_detector/human_poses", 10); ros::Publisher cloud_pub = nh.advertise<sensor_msgs::PointCloud2>("segbot_pcl_person_detector/human_clouds", 10); // Create a ROS subscriber for the input point cloud ros::Subscriber sub = nh.subscribe (param_topic, 1, cloud_cb); // Algorithm parameters: std::string svm_filename = param_classifier; float min_confidence = -1.5;//-1.9 float min_height = 1.3; float max_height = 2.3; float voxel_size = 0.06; Eigen::Matrix3f rgb_intrinsics_matrix; rgb_intrinsics_matrix << 525, 0.0, 319.5, 0.0, 525, 239.5, 0.0, 0.0, 1.0; // Kinect RGB camera intrinsics //register ctrl-c signal(SIGINT, sig_handler); //load ground plane coeffs ground_coeffs.resize(4); std::string ground_plane_file, path_to_package, path; if (false == ros::param::has("~ground_plane_file")) { ROS_ERROR("ground_plane_file parameter needs to be set"); ros::shutdown(); } else { ros::param::get("~ground_plane_file", ground_plane_file); } string plane_coefs_location = ros::package::getPath("pcl_perception")+"/data/"+ground_plane_file; ground_coeffs = load_vector_from_file(plane_coefs_location.c_str(),4); // Initialize new viewer: pcl::visualization::PCLVisualizer *viewer_display; // viewer initialization if (visualize){ viewer_display = new pcl::visualization::PCLVisualizer("People Viewer"); viewer_display->setCameraPosition(0,0,-2,0,-1,0,0); } // Create classifier for people detection: pcl::people::PersonClassifier<pcl::RGB> person_classifier; person_classifier.loadSVMFromFile(param_classifier); // load trained SVM // People detection app initialization: pcl::people::GroundBasedPeopleDetectionApp<PointT> people_detector; // people detection object people_detector.setVoxelSize(voxel_size); // set the voxel size people_detector.setIntrinsics(rgb_intrinsics_matrix); // set RGB camera intrinsic parameters people_detector.setClassifier(person_classifier); // set person classifier people_detector.setHeightLimits(min_height, max_height); // set person classifier // people_detector.setSensorPortraitOrientation(true); // set sensor orientation to vertical // For timing: static unsigned count = 0; static double last = pcl::getTime (); // int detection_count=0; bool set_ground = false; ros::Rate r(ros_rate); tf::TransformListener listener; tf::StampedTransform transform; // Main loop: while (!g_caught_sigint && ros::ok()) { //collect messages ros::spinOnce(); r.sleep(); if (new_cloud_available_flag && cloud_mutex.try_lock ()) // if a new cloud is available { new_cloud_available_flag = false; // Perform people detection on the new cloud: std::vector<pcl::people::PersonCluster<PointT> > clusters; // vector containing persons clusters std::vector<pcl::people::PersonCluster<PointT> > clusters_filtered; people_detector.setInputCloud(cloud); people_detector.setGround(ground_coeffs); people_detector.compute(clusters); // perform people detection ground_coeffs = people_detector.getGround(); // get updated floor coefficients // Draw cloud and people bounding boxes in the viewer: if (visualize){ viewer_display->removeAllPointClouds(); viewer_display->removeAllShapes(); pcl::visualization::PointCloudColorHandlerRGBField<PointT> rgb(cloud); viewer_display->addPointCloud<PointT> (cloud, rgb, "input_cloud"); } unsigned int k = 0; for(std::vector<pcl::people::PersonCluster<PointT> >::iterator it = clusters.begin(); it != clusters.end(); ++it) { if(it->getPersonConfidence() > min_confidence) // draw only people with confidence above a threshold { Eigen::Vector3f centroid_k = it->getCenter(); Eigen::Vector3f top_k = it->getTop(); Eigen::Vector3f bottom_k = it->getBottom(); //calculate the distance from the centroid of the cloud to the plane pcl::PointXYZ p_k; p_k.x=bottom_k(0);p_k.y=bottom_k(1);p_k.z=bottom_k(2); double dist_to_ground_bottom = pcl::pointToPlaneDistance(p_k,ground_coeffs); p_k.x=top_k(0);p_k.y=top_k(1);p_k.z=top_k(2); double dist_to_ground_top = pcl::pointToPlaneDistance(p_k,ground_coeffs); p_k.x=centroid_k(0);p_k.y=centroid_k(1);p_k.z=centroid_k(2); double dist_to_ground = pcl::pointToPlaneDistance(p_k,ground_coeffs); /*ROS_INFO("Cluter centroid: %f, %f, %f",centroid_k(0),centroid_k(1),centroid_k(2)); ROS_INFO("\tDistance to ground (top): %f",dist_to_ground_top); ROS_INFO("\tDistance to ground (centroid): %f",dist_to_ground); ROS_INFO("\tDistance to ground (bottom): %f",dist_to_ground_bottom); ROS_INFO("\tCluster height: %f",it->getHeight()); ROS_INFO("\tCluster points: %i",it->getNumberPoints()); ROS_INFO("\tDistance from sensor: %f",it->getDistance()); ROS_INFO("\tconfidence: %f",it->getPersonConfidence()); */ bool accept = true; if (it->getNumberPoints() < 250) //a person should have about 350 points +- 50 depending on distance from kinect accept = false; else if (it->getNumberPoints() > 600) //a person should have about 450 points +- 50 depending on distance from kinect accept = false; else if (it->getHeight() < 1.1) //nobody should be shorter than a meter and 10 cm accept = false; else if (it->getHeight() > 2.2) //or taller than 2.2 meters accept = false; if (dist_to_ground_bottom > 0.3) //or hovering more than 30 cm over the floor accept = false; if (accept){ // draw theoretical person bounding box in the PCL viewer: if (visualize) it->drawTBoundingBox(*viewer_display, k); //get just the person out of the whole cloud pcl_utils::applyBoxFilter(it->getMin(), it->getMax(),cloud,person_cloud); //publish person cloud pcl::toROSMsg(*person_cloud,person_cloud_ros); person_cloud_ros.header.frame_id = param_sensor_frame_id; cloud_pub.publish(person_cloud_ros); //transforms the pose into /map frame geometry_msgs::Pose pose_i; pose_i.position.x=centroid_k(0); pose_i.position.y=0.5; pose_i.position.z=centroid_k(2); pose_i.orientation = tf::createQuaternionMsgFromRollPitchYaw(0,0,-3.14/2); geometry_msgs::PoseStamped stampedPose; stampedPose.header.frame_id = param_sensor_frame_id; stampedPose.header.stamp = ros::Time(0); stampedPose.pose = pose_i; geometry_msgs::PoseStamped stampOut; listener.waitForTransform(param_sensor_frame_id, param_out_frame_id, ros::Time(0), ros::Duration(3.0)); listener.transformPose(param_out_frame_id, stampedPose, stampOut); //transform the human point cloud into presumably the /map frame of reference pcl_ros::transformPointCloud (param_out_frame_id, person_cloud_ros, person_cloud_ros, listener); //save to file for analysis ros::Time nowTime = ros::Time::now(); stringstream ss; ss << ros::package::getPath("pcl_perception") << "/data/human_kinect_" << nowTime.toNSec() << ".pcd"; pcl::io::savePCDFileASCII (ss.str(), *person_cloud); //save cloud in map frame of reference pcl::fromROSMsg(person_cloud_ros,*person_cloud); ss.str(std::string()); ss << ros::package::getPath("pcl_perception") << "/data/human_map_" << nowTime.toNSec() << ".pcd"; pcl::io::savePCDFileASCII (ss.str(), *person_cloud); stampOut.pose.position.z = 0.7; stampOut.header.stamp = nowTime; //publish the marker visualization_msgs::Marker marker_k = create_next_person_marker(it,param_out_frame_id,"segbot_pcl_person_detector",detection_count); marker_k.pose = stampOut.pose; marker_pub.publish(marker_k); //publish the pose stampOut.pose.position.z = 0.0; pose_pub.publish(stampOut); k++; detection_count++; } } } if (visualize){ viewer_display->spinOnce(); } cloud_mutex.unlock (); } } return 0; } <commit_msg>change the msg PointCloud2ConstPtr to -><commit_after>/* * * * * * Implements the people detection algorithm described here: * M. Munaro, F. Basso and E. Menegatti, * Tracking people within groups with RGB-D data, * In Proceedings of the International Conference on Intelligent Robots and Systems (IROS) 2012, Vilamoura (Portugal), 2012. */ #include <signal.h> #include <vector> #include <string> #include <ros/ros.h> #include <ros/package.h> #include <sensor_msgs/PointCloud2.h> #include <visualization_msgs/Marker.h> #include <visualization_msgs/MarkerArray.h> #include <tf/transform_listener.h> #include <tf/tf.h> #include <pcl_ros/impl/transforms.hpp> // PCL specific includes #include <pcl/conversions.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_cloud.h> #include <pcl/console/parse.h> #include <pcl/point_types.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/io/openni_grabber.h> #include <pcl/sample_consensus/sac_model_plane.h> #include <pcl/people/ground_based_people_detection_app.h> #include <pcl/common/time.h> #include <pcl/filters/crop_box.h> using namespace std; typedef pcl::PointXYZRGB PointT; typedef pcl::PointCloud<PointT> PointCloudT; //some custom functions #include "utils/file_io.h" #include "utils/viz_utils.h" #include "utils/pcl_utils.h" //some constants bool visualize = false; bool calibrate_plane = false; const std::string data_topic = "nav_kinect/depth_registered/points"; const std::string classifier_location = ros::package::getPath("pcl_perception") + "/classifier.yaml"; const std::string node_name = "segbot_people_detector"; //true if Ctrl-C is pressed bool g_caught_sigint=false; //refresh rate double ros_rate = 10.0; Eigen::VectorXf ground_coeffs; // Mutex: // boost::mutex cloud_mutex; bool new_cloud_available_flag = false; PointCloudT::Ptr cloud (new PointCloudT); PointCloudT::Ptr person_cloud (new PointCloudT); sensor_msgs::PointCloud2 person_cloud_ros; std::string sensor_frame_id; void sig_handler(int sig) { g_caught_sigint = true; ROS_INFO("caught sigint, init shutdown sequence..."); ros::shutdown(); exit(1); }; void cloud_cb (const sensor_msgs::PointCloud2ConstPtr& input) { sensor_frame_id = input->header.frame_id; cloud_mutex.lock (); //convert to PCL format pcl::fromROSMsg (*input, *cloud); //state that a new cloud is available new_cloud_available_flag = true; cloud_mutex.unlock (); } struct callback_args{ // structure used to pass arguments to the callback function PointCloudT::Ptr clicked_points_3d; pcl::visualization::PCLVisualizer::Ptr viewerPtr; }; int main (int argc, char** argv) { // Initialize ROS ros::init (argc, argv, "segbot_background_person_detector"); ros::NodeHandle nh; nh.param<bool>("background_person_detector/visualize", visualize, false); nh.param<double>("background_person_detector/rate", ros_rate, 10.0); string param_out_frame_id; nh.param<std::string>(std::string("background_person_detector/out_frame_id"), param_out_frame_id, "/map"); string param_topic; nh.param<std::string>(std::string("background_person_detector/rgbd_topic"), param_topic, data_topic); string param_classifier; nh.param<std::string>(std::string("background_person_detector/classifier_location"), param_classifier, ros::package::getPath("pcl_perception")+"/data/classifier.yaml"); string param_sensor_frame_id; nh.param<std::string>(std::string("background_person_detector/sensor_frame_id"), param_sensor_frame_id, //"/nav_kinect_rgb_optical_frame"); sensor_frame_id); //nh.getParam("background_person_detector/rgbd_topic", data_topic); //initialize marker publisher ros::Publisher marker_pub = nh.advertise<visualization_msgs::Marker>("segbot_pcl_person_detector/marker", 10); ros::Publisher pose_pub = nh.advertise<geometry_msgs::PoseStamped>("segbot_pcl_person_detector/human_poses", 10); ros::Publisher cloud_pub = nh.advertise<sensor_msgs::PointCloud2>("segbot_pcl_person_detector/human_clouds", 10); // Create a ROS subscriber for the input point cloud ros::Subscriber sub = nh.subscribe (param_topic, 1, cloud_cb); // Algorithm parameters: std::string svm_filename = param_classifier; float min_confidence = -1.5;//-1.9 float min_height = 1.3; float max_height = 2.3; float voxel_size = 0.06; Eigen::Matrix3f rgb_intrinsics_matrix; rgb_intrinsics_matrix << 525, 0.0, 319.5, 0.0, 525, 239.5, 0.0, 0.0, 1.0; // Kinect RGB camera intrinsics //register ctrl-c signal(SIGINT, sig_handler); //load ground plane coeffs ground_coeffs.resize(4); std::string ground_plane_file, path_to_package, path; if (false == ros::param::has("~ground_plane_file")) { ROS_ERROR("ground_plane_file parameter needs to be set"); ros::shutdown(); } else { ros::param::get("~ground_plane_file", ground_plane_file); } string plane_coefs_location = ros::package::getPath("pcl_perception")+"/data/"+ground_plane_file; ground_coeffs = load_vector_from_file(plane_coefs_location.c_str(),4); // Initialize new viewer: pcl::visualization::PCLVisualizer *viewer_display; // viewer initialization if (visualize){ viewer_display = new pcl::visualization::PCLVisualizer("People Viewer"); viewer_display->setCameraPosition(0,0,-2,0,-1,0,0); } // Create classifier for people detection: pcl::people::PersonClassifier<pcl::RGB> person_classifier; person_classifier.loadSVMFromFile(param_classifier); // load trained SVM // People detection app initialization: pcl::people::GroundBasedPeopleDetectionApp<PointT> people_detector; // people detection object people_detector.setVoxelSize(voxel_size); // set the voxel size people_detector.setIntrinsics(rgb_intrinsics_matrix); // set RGB camera intrinsic parameters people_detector.setClassifier(person_classifier); // set person classifier people_detector.setHeightLimits(min_height, max_height); // set person classifier // people_detector.setSensorPortraitOrientation(true); // set sensor orientation to vertical // For timing: static unsigned count = 0; static double last = pcl::getTime (); // int detection_count=0; bool set_ground = false; ros::Rate r(ros_rate); tf::TransformListener listener; tf::StampedTransform transform; // Main loop: while (!g_caught_sigint && ros::ok()) { //collect messages ros::spinOnce(); r.sleep(); if (new_cloud_available_flag && cloud_mutex.try_lock ()) // if a new cloud is available { new_cloud_available_flag = false; // Perform people detection on the new cloud: std::vector<pcl::people::PersonCluster<PointT> > clusters; // vector containing persons clusters std::vector<pcl::people::PersonCluster<PointT> > clusters_filtered; people_detector.setInputCloud(cloud); people_detector.setGround(ground_coeffs); people_detector.compute(clusters); // perform people detection ground_coeffs = people_detector.getGround(); // get updated floor coefficients // Draw cloud and people bounding boxes in the viewer: if (visualize){ viewer_display->removeAllPointClouds(); viewer_display->removeAllShapes(); pcl::visualization::PointCloudColorHandlerRGBField<PointT> rgb(cloud); viewer_display->addPointCloud<PointT> (cloud, rgb, "input_cloud"); } unsigned int k = 0; for(std::vector<pcl::people::PersonCluster<PointT> >::iterator it = clusters.begin(); it != clusters.end(); ++it) { if(it->getPersonConfidence() > min_confidence) // draw only people with confidence above a threshold { Eigen::Vector3f centroid_k = it->getCenter(); Eigen::Vector3f top_k = it->getTop(); Eigen::Vector3f bottom_k = it->getBottom(); //calculate the distance from the centroid of the cloud to the plane pcl::PointXYZ p_k; p_k.x=bottom_k(0);p_k.y=bottom_k(1);p_k.z=bottom_k(2); double dist_to_ground_bottom = pcl::pointToPlaneDistance(p_k,ground_coeffs); p_k.x=top_k(0);p_k.y=top_k(1);p_k.z=top_k(2); double dist_to_ground_top = pcl::pointToPlaneDistance(p_k,ground_coeffs); p_k.x=centroid_k(0);p_k.y=centroid_k(1);p_k.z=centroid_k(2); double dist_to_ground = pcl::pointToPlaneDistance(p_k,ground_coeffs); /*ROS_INFO("Cluter centroid: %f, %f, %f",centroid_k(0),centroid_k(1),centroid_k(2)); ROS_INFO("\tDistance to ground (top): %f",dist_to_ground_top); ROS_INFO("\tDistance to ground (centroid): %f",dist_to_ground); ROS_INFO("\tDistance to ground (bottom): %f",dist_to_ground_bottom); ROS_INFO("\tCluster height: %f",it->getHeight()); ROS_INFO("\tCluster points: %i",it->getNumberPoints()); ROS_INFO("\tDistance from sensor: %f",it->getDistance()); ROS_INFO("\tconfidence: %f",it->getPersonConfidence()); */ bool accept = true; if (it->getNumberPoints() < 250) //a person should have about 350 points +- 50 depending on distance from kinect accept = false; else if (it->getNumberPoints() > 600) //a person should have about 450 points +- 50 depending on distance from kinect accept = false; else if (it->getHeight() < 1.1) //nobody should be shorter than a meter and 10 cm accept = false; else if (it->getHeight() > 2.2) //or taller than 2.2 meters accept = false; if (dist_to_ground_bottom > 0.3) //or hovering more than 30 cm over the floor accept = false; if (accept){ // draw theoretical person bounding box in the PCL viewer: if (visualize) it->drawTBoundingBox(*viewer_display, k); //get just the person out of the whole cloud pcl_utils::applyBoxFilter(it->getMin(), it->getMax(),cloud,person_cloud); //publish person cloud pcl::toROSMsg(*person_cloud,person_cloud_ros); person_cloud_ros.header.frame_id = param_sensor_frame_id; cloud_pub.publish(person_cloud_ros); //transforms the pose into /map frame geometry_msgs::Pose pose_i; pose_i.position.x=centroid_k(0); pose_i.position.y=0.5; pose_i.position.z=centroid_k(2); pose_i.orientation = tf::createQuaternionMsgFromRollPitchYaw(0,0,-3.14/2); geometry_msgs::PoseStamped stampedPose; stampedPose.header.frame_id = param_sensor_frame_id; stampedPose.header.stamp = ros::Time(0); stampedPose.pose = pose_i; geometry_msgs::PoseStamped stampOut; listener.waitForTransform(param_sensor_frame_id, param_out_frame_id, ros::Time(0), ros::Duration(3.0)); listener.transformPose(param_out_frame_id, stampedPose, stampOut); //transform the human point cloud into presumably the /map frame of reference pcl_ros::transformPointCloud (param_out_frame_id, person_cloud_ros, person_cloud_ros, listener); //save to file for analysis ros::Time nowTime = ros::Time::now(); stringstream ss; ss << ros::package::getPath("pcl_perception") << "/data/human_kinect_" << nowTime.toNSec() << ".pcd"; pcl::io::savePCDFileASCII (ss.str(), *person_cloud); //save cloud in map frame of reference pcl::fromROSMsg(person_cloud_ros,*person_cloud); ss.str(std::string()); ss << ros::package::getPath("pcl_perception") << "/data/human_map_" << nowTime.toNSec() << ".pcd"; pcl::io::savePCDFileASCII (ss.str(), *person_cloud); stampOut.pose.position.z = 0.7; stampOut.header.stamp = nowTime; //publish the marker visualization_msgs::Marker marker_k = create_next_person_marker(it,param_out_frame_id,"segbot_pcl_person_detector",detection_count); marker_k.pose = stampOut.pose; marker_pub.publish(marker_k); //publish the pose stampOut.pose.position.z = 0.0; pose_pub.publish(stampOut); k++; detection_count++; } } } if (visualize){ viewer_display->spinOnce(); } cloud_mutex.unlock (); } } return 0; } <|endoftext|>
<commit_before>#include <matrix.hpp> #include <catch.hpp> #include <iostream> using namespace std; SCENARIO("matrix init", "[init]") { Matrix matrix; REQUIRE(matrix.rows() == 0); REQUIRE(matrix.columns() == 0); } SCENARIO("params init", "[init with params]") { int init = 5; Matrix matrix(init, init); REQUIRE(matrix.rows() == 5); REQUIRE(matrix.columns() == 5); } SCENARIO("copy", "[copy]") { int init = 2; Matrix m1(init, init); Matrix copy(m1); REQUIRE(copy.rows() == 2); REQUIRE(copy.columns() == 2); } SCENARIO("m+", "[m+]") { Matrix A(2, 2); Matrix B(2, 2); <commit_msg>Update init.cpp<commit_after>#include <matrix.hpp> #include <catch.hpp> #include <iostream> using namespace std; SCENARIO("matrix init", "[init]") { Matrix matrix; REQUIRE(matrix.rows() == 0); REQUIRE(matrix.columns() == 0); } SCENARIO("params init", "[init with params]") { int init = 5; Matrix matrix(init, init); REQUIRE(matrix.rows() == 5); REQUIRE(matrix.columns() == 5); } SCENARIO("copy", "[copy]") { int init = 2; Matrix m1(init, init); Matrix copy(m1); REQUIRE(copy.rows() == 2); <|endoftext|>
<commit_before>#include <BinaryTree.hpp> #include <catch.hpp> SCENARIO ("init", "[init]") { BinaryTree<int> obj; REQUIRE(obj.root_() == nullptr); } SCENARIO ("output to cout") { BinaryTree<int> tree; tree.insert_node(3); tree.writing("1.txt"); Binarytree <int> tree_1; tree_1.read("2.txt"); REQUIRE(tree.find_node(3, tree_1.root_())!= nullptr); } SCENARIO("insert", "[insert]") { BinaryTree<int> obj; obj.insert_node(3); REQUIRE(obj.find_node(3, obj.root_())->data == 3); } SCENARIO("find_node", "[find_node]") { BinaryTree<int> obj; obj.insert_node(2); REQUIRE(obj.find_node(2, obj.root_()) != nullptr); REQUIRE(obj.find_node(2, obj.root_())->data == 2); } SCENARIO("get root", "[get root]") { BinaryTree<int> obj; obj.insert_node(4); REQUIRE(obj.root_() != 0); } <commit_msg>Update init.cpp<commit_after>#include <BinaryTree.hpp> #include <catch.hpp> SCENARIO ("init", "[init]") { BinaryTree<int> obj; REQUIRE(obj.root_() == nullptr); } SCENARIO ("output to cout") { BinaryTree<int> tree; tree.insert_node(3); tree.writing("file1.txt"); BinaryTree <int> tree_1; tree_1.read("file2.txt"); REQUIRE(tree.find_node(3, tree_1.root_())!= nullptr); } SCENARIO("insert", "[insert]") { BinaryTree<int> obj; obj.insert_node(3); REQUIRE(obj.find_node(3, obj.root_())->data == 3); } SCENARIO("find_node", "[find_node]") { BinaryTree<int> obj; obj.insert_node(2); REQUIRE(obj.find_node(2, obj.root_()) != nullptr); REQUIRE(obj.find_node(2, obj.root_())->data == 2); } SCENARIO("get root", "[get root]") { BinaryTree<int> obj; obj.insert_node(4); REQUIRE(obj.root_() != 0); } <|endoftext|>
<commit_before>#include "BinaryTree.hpp" #include <catch.hpp> SCENARIO("default constructor") { Tree<int> node; REQUIRE(node.root_() == nullptr); } SCENARIO("insert") { Tree<int> tree; tree.insert(7); REQUIRE(tree.x_() == 7); REQUIRE(tree.left_() == nullptr); REQUIRE(tree.right_() == nullptr); } SCENARIO("search") { Tree<int> tree; bool a; tree.insert(7); a = tree.check_search(7); REQUIRE(a == true); } <commit_msg>Update init.cpp<commit_after>#include "BinaryTree.hpp" #include <catch.hpp> SCENARIO("default constructor") { Tree<int> node; REQUIRE(node.root_() == nullptr); } SCENARIO("insert") { Tree<int> tree; tree.insert(7); REQUIRE(tree.x_() == 7); REQUIRE(tree.left_() == nullptr); REQUIRE(tree.right_() == nullptr); } SCENARIO("search") { Tree<int> tree; bool a; tree.insert(7); a = tree.check_search(7); REQUIRE(a == true); } SCENARIO("size") { Tree<int> tree; int size = 0; tree.insert(7); size = tree.size(tree.root_()); REQUIRE(size == 1); } <|endoftext|>
<commit_before>#include "catch.hpp" #include <iostream> //#include "Database_Creator.hpp" #include "Database_Sorter.hpp" person readPerson(std::string const & file_name, size_t const index) { person result; std::ifstream file(file_name); for (size_t i = 0; i < index + 1; i++) { file >> result; } file.close(); return result; } bool isANotMoreThanB(person const & A, person const & B) { char * A_name = A.getName(); char * B_name = B.getName(); for (size_t i = 0; i < A.name_length; i++) { char A_char = A_name[i]; char B_char = (i < B.name_length) ? B_name[i] : ' '; if (letterI(A_name[i], i == 0) < letterI(B_name[i], i == 0)) { return true; } else { if (A_name[i] != B_name[i]) { return false; } } } delete []A_name; delete []B_name; return true; } SCENARIO("Sort", "[s]") { size_t n_persons = 200; //system("start www.cyberforum.ru/cpp-beginners/thread82643.html#post458604"); size_t RAM_amount = 1; std::string names_file_name = "F:\\1\\names.txt"; std::string surnames_file_name = "F:\\1\\surnames.txt"; std::string database_file_name = "8.txt"; std::string output_file_name = "F:\\1\\sorted_database.txt"; //Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons); Database_Sorter database_sorter1("8.txt", "1.txt", 1, "1\\"); //Database_Sorter database_sorter2("16.txt", "2", 4, "2\\"); //Database_Sorter database_sorter3("16.txt", "3", 17, "3\\"); size_t start = clock(); database_sorter1.sortDatabase(); //database_sorter2.sortDatabase(); //database_sorter3.sortDatabase(); size_t result = clock() - start; database_sorter1.closeDatabase(); //database_sorter2.closeDatabase(); //database_sorter3.closeDatabase(); std::cout << "Result " << result << std::endl; for (size_t i = 0; i < 100; i++) { size_t person1_i = rand() % n_persons; size_t person2_i = person1_i + rand() % (n_persons - person1_i); person person1 = readPerson("1.txt", person1_i); person person2 = readPerson("1.txt", person2_i); REQUIRE(isANotMoreThanB(person1, person2)); } } <commit_msg>Update init.cpp<commit_after>#include "catch.hpp" #include <iostream> //#include "Database_Creator.hpp" #include "Database_Sorter.hpp" person readPerson(std::string const & file_name, size_t const index) { person result; std::ifstream file(file_name); for (size_t i = 0; i < index + 1; i++) { file >> result; } file.close(); return result; } bool isANotMoreThanB(person const & A, person const & B) { char * A_name = A.getName(); char * B_name = B.getName(); for (size_t i = 0; i < A.name_length; i++) { char A_char = A_name[i]; char B_char = (i < B.name_length) ? B_name[i] : ' '; if (letterI(A_name[i], i == 0) < letterI(B_name[i], i == 0)) { return true; } else { if (A_name[i] != B_name[i]) { return false; } } } delete []A_name; delete []B_name; return true; } SCENARIO("Sort", "[s]") { size_t n_persons = 200; //system("start www.cyberforum.ru/cpp-beginners/thread82643.html#post458604"); size_t RAM_amount = 1; std::string names_file_name = "F:\\1\\names.txt"; std::string surnames_file_name = "F:\\1\\surnames.txt"; std::string database_file_name = "8.txt"; std::string output_file_name = "F:\\1\\sorted_database.txt"; //Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons); Database_Sorter database_sorter1("8.txt", "1.txt", 1, "1\\"); Database_Sorter database_sorter2("16.txt", "2.txt", 4, "2\\"); //Database_Sorter database_sorter3("16.txt", "3", 17, "3\\"); size_t start = clock(); database_sorter1.sortDatabase(); database_sorter2.sortDatabase(); //database_sorter3.sortDatabase(); size_t result = clock() - start; database_sorter1.closeDatabase(); database_sorter2.closeDatabase(); //database_sorter3.closeDatabase(); std::cout << "Result " << result << std::endl; for (size_t i = 0; i < 100; i++) { size_t person1_i = rand() % n_persons; size_t person2_i = person1_i + rand() % (n_persons - person1_i); person person1 = readPerson("1.txt", person1_i); person person2 = readPerson("1.txt", person2_i); REQUIRE(isANotMoreThanB(person1, person2)); } } <|endoftext|>
<commit_before>#include <rbt.h> #include <catch.hpp> SCENARIO ("init", "[init]") { RBT<int> tree; REQUIRE(tree.root_() == tree.nil_()); } SCENARIO("insert with search", "[ins+srch]") { RBT<int> tree; tree.insert(2); REQUIRE(tree.search(2) != 0); } SCENARIO("insert with search 2", "[ins+srch_2]") { RBT<int> tree; tree.insert(5); tree.insert(1); tree.insert(8); REQUIRE(tree._root() == tree.search(5)); REQUIRE(tree._color(5) == 1); REQUIRE(tree._color(1) == 0); REQUIRE(tree._color(8) == 0); REQUIRE(tree.search(5) != 0); REQUIRE(tree.search(1) != 0); REQUIRE(tree.search(8) != 0); } SCENARIO("insert with search 3", "[ins+srch_3]") { RBT<int> tree; tree.insert(6); tree.insert(4); tree.insert(2); tree.insert(10); tree.insert(1); REQUIRE(tree._root() == tree.search(4)); REQUIRE(tree._color(4) == 1); REQUIRE(tree._color(2) == 1); REQUIRE(tree._color(6) == 1); REQUIRE(tree._color(1) == 0); REQUIRE(tree._color(10) == 0); REQUIRE(tree.search(4) != 0); REQUIRE(tree.search(2) != 0); REQUIRE(tree.search(6) != 0); REQUIRE(tree.search(1) != 0); REQUIRE(tree.search(10) != 0); } SCENARIO ("insert with search 4", "[ins+srch_4]") { RBT<int> tree; tree.insert(10); tree.insert(1); tree.insert(6); tree.insert(19); tree.insert(7); tree.insert(3); tree.insert(8); REQUIRE(tree._root() == tree.search(6)); REQUIRE(tree._color(6) == 1); REQUIRE(tree._color(1) == 1); REQUIRE(tree._color(10) == 0); REQUIRE(tree._color(3) == 0); REQUIRE(tree._color(7) == 1); REQUIRE(tree._color(19) == 1); REQUIRE(tree._color(8) == 0); REQUIRE(tree.search(6) != 0); REQUIRE(tree.search(1) != 0); REQUIRE(tree.search(10) != 0); REQUIRE(tree.search(3) != 0); REQUIRE(tree.search(7) != 0); REQUIRE(tree.search(19) != 0); REQUIRE(tree.search(8) != 0); }<commit_msg>Create init.cpp<commit_after>#include <rbt.h> #include <catch.hpp> SCENARIO ("init", "[init]") { RBT<int> tree; REQUIRE(tree.root_() == tree.nil_()); } SCENARIO("insert with search", "[ins+srch]") { RBT<int> tree; tree.insert(2); REQUIRE(tree.search(2) != 0); } SCENARIO("insert with search ¹2", "[ins+srch_2]") { RBT<int> tree; tree.insert(5); tree.insert(1); tree.insert(8); REQUIRE(tree.root_() == tree.search(5)); REQUIRE(tree._color(5) == 1); REQUIRE(tree._color(1) == 0); REQUIRE(tree._color(8) == 0); REQUIRE(tree.search(5) != 0); REQUIRE(tree.search(1) != 0); REQUIRE(tree.search(8) != 0); } SCENARIO("insert with search ¹3", "[ins+srch_3]") { RBT<int> tree; tree.insert(6); tree.insert(4); tree.insert(2); tree.insert(10); tree.insert(1); REQUIRE(tree.root_() == tree.search(4)); REQUIRE(tree._color(4) == 1); REQUIRE(tree._color(2) == 1); REQUIRE(tree._color(6) == 1); REQUIRE(tree._color(1) == 0); REQUIRE(tree._color(10) == 0); REQUIRE(tree.search(4) != 0); REQUIRE(tree.search(2) != 0); REQUIRE(tree.search(6) != 0); REQUIRE(tree.search(1) != 0); REQUIRE(tree.search(10) != 0); } SCENARIO ("insert with search ¹4", "[ins+srch_4]") { RBT<int> tree; tree.insert(10); tree.insert(1); tree.insert(6); tree.insert(19); tree.insert(7); tree.insert(3); tree.insert(8); REQUIRE(tree.root_() == tree.search(6)); REQUIRE(tree._color(6) == 1); REQUIRE(tree._color(1) == 1); REQUIRE(tree._color(10) == 0); REQUIRE(tree._color(3) == 0); REQUIRE(tree._color(7) == 1); REQUIRE(tree._color(19) == 1); REQUIRE(tree._color(8) == 0); REQUIRE(tree.search(6) != 0); REQUIRE(tree.search(1) != 0); REQUIRE(tree.search(10) != 0); REQUIRE(tree.search(3) != 0); REQUIRE(tree.search(7) != 0); REQUIRE(tree.search(19) != 0); REQUIRE(tree.search(8) != 0); } <|endoftext|>
<commit_before>#include "YouBotGripperService.hpp" #include <youbot/YouBotManipulator.hpp> #include <stdio.h> #include <cassert> #include <youbot/ProtocolDefinitions.hpp> #include "YouBotHelpers.hpp" namespace YouBot { using namespace RTT; using namespace RTT::types; using namespace std; YouBotGripperService::YouBotGripperService(const string& name, TaskContext* parent) : YouBotService(name, parent), // Set the commands to zero depending on the number of joints m_calibrated(false) { // m_gripper_state.name.assign(1, ""); // m_gripper_state.name[0] = "gripper"; // m_gripper_state.position.assign(1, 0); // m_gripper_state.velocity.assign(0); // m_gripper_state.effort.assign(0); m_gripper_cmd_position.positions.resize(1, 0); this->addPort("gripper_cmd_position", gripper_cmd_position).doc("Command the gripper position"); this->addOperation("start",&YouBotGripperService::start,this); this->addOperation("update",&YouBotGripperService::update,this); this->addOperation("calibrate",&YouBotGripperService::calibrate,this); this->addOperation("stop",&YouBotGripperService::stop,this); this->addOperation("cleanup",&YouBotGripperService::cleanup,this); // this->addOperation("displayGripperStatus",&YouBotGripperService::displayGripperStatus,this, OwnThread); // Pre-allocate port memory for outputs // gripper_state.setDataSample(m_gripper_state); } YouBotGripperService::~YouBotGripperService() { } void YouBotGripperService::displayGripperStatus() { log(Warning) << "Not implemented." << endlog(); } bool YouBotGripperService::start() { return m_calibrated; } void YouBotGripperService::update() { // ros::Time time = ros::Time::now(); // The OODL gripper does not support this. // m_gripper->getData(m_tmp_gripper_state); // m_gripper_state.header.stamp = m_joint_states.header.stamp; // m_gripper_state.position[0] = m_tmp_gripper_state.barSpacing.value(); // gripper_state.write(m_gripper_state); // Update gripper setpoint if(gripper_cmd_position.read(m_gripper_cmd_position) == NewData) //setData has SLEEP_MILLISECOND :-( { m_tmp_gripper_cmd_position.barSpacing = m_gripper_cmd_position.positions[0] * si::meter; // check limits to prevent exceptions if( m_tmp_gripper_cmd_position.barSpacing < m_gripper_limits.min_position ) { m_tmp_gripper_cmd_position.barSpacing = m_gripper_limits.min_position; } //above limits: else if(m_tmp_gripper_cmd_position.barSpacing > m_gripper_limits.max_position) { m_tmp_gripper_cmd_position.barSpacing = m_gripper_limits.max_position; } m_gripper->setData(m_tmp_gripper_cmd_position); } // Check for errors: // checkForErrors(); } bool YouBotGripperService::calibrate() { log(Info) << "Calibrating YouBotGripperService" << endlog(); if(m_calibrated) { log(Info) << "Already calibrated." << endlog(); return m_calibrated; } try { YouBotManipulator* m_manipulator = new YouBotManipulator("/youbot-manipulator", OODL_YOUBOT_CONFIG_DIR); if(m_manipulator == NULL) { log(Error) << "Could not create the YouBotManipulator." << endlog(); return false; } // Gripper m_manipulator->calibrateGripper(); m_gripper = &(m_manipulator->getArmGripper()); // Determine gripper limits to prevent exceptions MaxTravelDistance _max_distance; BarSpacingOffset _spacing; quantity<length> max_distance; quantity<length> spacing; m_gripper->getConfigurationParameter(_max_distance, BAR_ONE); m_gripper->getConfigurationParameter(_spacing, BAR_ONE); _max_distance.getParameter(max_distance); _spacing.getParameter(spacing); m_gripper_limits.min_position = spacing; m_gripper_limits.max_position = max_distance + spacing; log(Info) << "Gripper calibration min_position: " << m_gripper_limits.min_position << " max_position: " << m_gripper_limits.max_position << endlog(); delete m_manipulator; } catch (std::exception& e) { log(Error) << e.what(); return false; } return (m_calibrated = true); } void YouBotGripperService::checkForErrors() { log(Warning) << "checkForErrors - Not implemented" << endlog(); } void YouBotGripperService::stop() { } void YouBotGripperService::cleanup() { m_calibrated = false; } } <commit_msg>Switching off 'exception' safety temporarily.<commit_after>#include "YouBotGripperService.hpp" #include <youbot/YouBotManipulator.hpp> #include <stdio.h> #include <cassert> #include <youbot/ProtocolDefinitions.hpp> #include "YouBotHelpers.hpp" namespace YouBot { using namespace RTT; using namespace RTT::types; using namespace std; YouBotGripperService::YouBotGripperService(const string& name, TaskContext* parent) : YouBotService(name, parent), // Set the commands to zero depending on the number of joints m_calibrated(false) { // m_gripper_state.name.assign(1, ""); // m_gripper_state.name[0] = "gripper"; // m_gripper_state.position.assign(1, 0); // m_gripper_state.velocity.assign(0); // m_gripper_state.effort.assign(0); m_gripper_cmd_position.positions.resize(1, 0); this->addPort("gripper_cmd_position", gripper_cmd_position).doc("Command the gripper position"); this->addOperation("start",&YouBotGripperService::start,this); this->addOperation("update",&YouBotGripperService::update,this); this->addOperation("calibrate",&YouBotGripperService::calibrate,this); this->addOperation("stop",&YouBotGripperService::stop,this); this->addOperation("cleanup",&YouBotGripperService::cleanup,this); // this->addOperation("displayGripperStatus",&YouBotGripperService::displayGripperStatus,this, OwnThread); // Pre-allocate port memory for outputs // gripper_state.setDataSample(m_gripper_state); } YouBotGripperService::~YouBotGripperService() { } void YouBotGripperService::displayGripperStatus() { log(Warning) << "Not implemented." << endlog(); } bool YouBotGripperService::start() { return m_calibrated; } void YouBotGripperService::update() { // ros::Time time = ros::Time::now(); // The OODL gripper does not support this. // m_gripper->getData(m_tmp_gripper_state); // m_gripper_state.header.stamp = m_joint_states.header.stamp; // m_gripper_state.position[0] = m_tmp_gripper_state.barSpacing.value(); // gripper_state.write(m_gripper_state); // Update gripper setpoint if(gripper_cmd_position.read(m_gripper_cmd_position) == NewData) //setData has SLEEP_MILLISECOND :-( { m_tmp_gripper_cmd_position.barSpacing = m_gripper_cmd_position.positions[0] * si::meter; // // check limits to prevent exceptions // if( m_tmp_gripper_cmd_position.barSpacing < m_gripper_limits.min_position ) // { // m_tmp_gripper_cmd_position.barSpacing = m_gripper_limits.min_position; // } // //above limits: // else if(m_tmp_gripper_cmd_position.barSpacing > m_gripper_limits.max_position) // { // m_tmp_gripper_cmd_position.barSpacing = m_gripper_limits.max_position; // } m_gripper->setData(m_tmp_gripper_cmd_position); } // Check for errors: // checkForErrors(); } bool YouBotGripperService::calibrate() { log(Info) << "Calibrating YouBotGripperService" << endlog(); if(m_calibrated) { log(Info) << "Already calibrated." << endlog(); return m_calibrated; } try { YouBotManipulator* m_manipulator = new YouBotManipulator("/youbot-manipulator", OODL_YOUBOT_CONFIG_DIR); if(m_manipulator == NULL) { log(Error) << "Could not create the YouBotManipulator." << endlog(); return false; } // Gripper m_manipulator->calibrateGripper(); m_gripper = &(m_manipulator->getArmGripper()); // Determine gripper limits to prevent exceptions MaxTravelDistance _max_distance; BarSpacingOffset _spacing; quantity<length> max_distance; quantity<length> spacing; m_gripper->getConfigurationParameter(_max_distance, BAR_ONE); m_gripper->getConfigurationParameter(_spacing, BAR_ONE); _max_distance.getParameter(max_distance); _spacing.getParameter(spacing); m_gripper_limits.min_position = spacing; m_gripper_limits.max_position = max_distance + spacing; log(Info) << "Gripper calibration min_position: " << m_gripper_limits.min_position << " max_position: " << m_gripper_limits.max_position << endlog(); delete m_manipulator; } catch (std::exception& e) { log(Error) << e.what(); return false; } return (m_calibrated = true); } void YouBotGripperService::checkForErrors() { log(Warning) << "checkForErrors - Not implemented" << endlog(); } void YouBotGripperService::stop() { } void YouBotGripperService::cleanup() { m_calibrated = false; } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtGui> #include <QtDebug> #include <private/qpaintengineex_p.h> #include <private/qpaintbuffer_p.h> class ReplayWidget : public QWidget { Q_OBJECT public: ReplayWidget(const QString &filename); void paintEvent(QPaintEvent *event); void resizeEvent(QResizeEvent *event); public slots: void updateRect(); public: QList<QRegion> updates; QPaintBuffer buffer; int currentFrame; int currentIteration; QTime timer; QList<uint> visibleUpdates; QList<uint> iterationTimes; QString filename; }; void ReplayWidget::updateRect() { if (!visibleUpdates.isEmpty()) update(updates.at(visibleUpdates.at(currentFrame))); } void ReplayWidget::paintEvent(QPaintEvent *) { QPainter p(this); // p.setClipRegion(frames.at(currentFrame).updateRegion); buffer.draw(&p, visibleUpdates.at(currentFrame)); ++currentFrame; if (currentFrame >= visibleUpdates.size()) { currentFrame = 0; ++currentIteration; if (currentIteration == 3) timer.start(); else if (currentIteration > 3) { iterationTimes << timer.elapsed(); timer.restart(); if (iterationTimes.size() >= 3) { qreal mean = 0; qreal stddev = 0; uint min = INT_MAX; for (int i = 0; i < iterationTimes.size(); ++i) { mean += iterationTimes.at(i); min = qMin(min, iterationTimes.at(i)); } mean /= qreal(iterationTimes.size()); for (int i = 0; i < iterationTimes.size(); ++i) { qreal delta = iterationTimes.at(i) - mean; stddev += delta * delta; } stddev = qSqrt(stddev / iterationTimes.size()); qSort(iterationTimes.begin(), iterationTimes.end()); uint median = iterationTimes.at(iterationTimes.size() / 2); stddev = 100 * stddev / mean; if (iterationTimes.size() >= 10 || stddev < 4) { printf("%s, iterations: %d, frames: %d, min(ms): %d, median(ms): %d, stddev: %f %%, max(fps): %f\n", qPrintable(filename), iterationTimes.size(), visibleUpdates.size(), min, median, stddev, 1000. * visibleUpdates.size() / min); deleteLater(); return; } } } } QTimer::singleShot(0, this, SLOT(updateRect())); } void ReplayWidget::resizeEvent(QResizeEvent *event) { visibleUpdates.clear(); QRect bounds = rect(); for (int i = 0; i < updates.size(); ++i) { if (updates.at(i).intersects(bounds)) visibleUpdates << i; } if (visibleUpdates.size() != updates.size()) printf("Warning: skipped %d frames due to limited resolution\n", updates.size() - visibleUpdates.size()); } ReplayWidget::ReplayWidget(const QString &filename_) : currentFrame(0) , currentIteration(0) , filename(filename_) { setWindowTitle(filename); QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { printf("Failed to load input file '%s'\n", qPrintable(filename_)); return; } QDataStream in(&file); char *data; uint size; in.readBytes(data, size); bool isTraceFile = size == 7 && qstrncmp(data, "qttrace", 7) == 0; delete [] data; if (!isTraceFile) { printf("File '%s' is not a trace file\n", qPrintable(filename_)); return; } in >> buffer >> updates; printf("Read paint buffer with %d frames\n", buffer.numFrames()); resize(buffer.boundingRect().size().toSize()); setAutoFillBackground(false); setAttribute(Qt::WA_NoSystemBackground); QTimer::singleShot(10, this, SLOT(updateRect())); } int main(int argc, char **argv) { QApplication app(argc, argv); if (argc <= 1 || qstrcmp(argv[1], "-h") == 0 || qstrcmp(argv[1], "--help") == 0) { printf("Replays a tracefile generated with '-graphicssystem trace'\n"); printf("Usage:\n > %s [traceFile]\n", argv[0]); return 1; } QFile file(argv[1]); if (!file.exists()) { printf("%s does not exist\n", argv[1]); return 1; } ReplayWidget *widget = new ReplayWidget(argv[1]); if (!widget->updates.isEmpty()) { widget->show(); return app.exec(); } } #include "main.moc" <commit_msg>Added --range and --single arguments to qttracereplay.<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtGui> #include <QtDebug> #include <private/qpaintengineex_p.h> #include <private/qpaintbuffer_p.h> class ReplayWidget : public QWidget { Q_OBJECT public: ReplayWidget(const QString &filename, int from, int to, bool single); void paintEvent(QPaintEvent *event); void resizeEvent(QResizeEvent *event); public slots: void updateRect(); public: QList<QRegion> updates; QPaintBuffer buffer; int currentFrame; int currentIteration; QTime timer; QList<uint> visibleUpdates; QList<uint> iterationTimes; QString filename; int from; int to; bool single; }; void ReplayWidget::updateRect() { if (!visibleUpdates.isEmpty()) update(updates.at(visibleUpdates.at(currentFrame))); } void ReplayWidget::paintEvent(QPaintEvent *) { QPainter p(this); // p.setClipRegion(frames.at(currentFrame).updateRegion); buffer.draw(&p, visibleUpdates.at(currentFrame)); ++currentFrame; if (currentFrame >= visibleUpdates.size()) { currentFrame = 0; ++currentIteration; if (single) { deleteLater(); return; } if (currentIteration == 3) timer.start(); else if (currentIteration > 3) { iterationTimes << timer.elapsed(); timer.restart(); if (iterationTimes.size() >= 3) { qreal mean = 0; qreal stddev = 0; uint min = INT_MAX; for (int i = 0; i < iterationTimes.size(); ++i) { mean += iterationTimes.at(i); min = qMin(min, iterationTimes.at(i)); } mean /= qreal(iterationTimes.size()); for (int i = 0; i < iterationTimes.size(); ++i) { qreal delta = iterationTimes.at(i) - mean; stddev += delta * delta; } stddev = qSqrt(stddev / iterationTimes.size()); qSort(iterationTimes.begin(), iterationTimes.end()); uint median = iterationTimes.at(iterationTimes.size() / 2); stddev = 100 * stddev / mean; if (iterationTimes.size() >= 10 || stddev < 4) { printf("%s, iterations: %d, frames: %d, min(ms): %d, median(ms): %d, stddev: %f %%, max(fps): %f\n", qPrintable(filename), iterationTimes.size(), visibleUpdates.size(), min, median, stddev, 1000. * visibleUpdates.size() / min); deleteLater(); return; } } } } QTimer::singleShot(0, this, SLOT(updateRect())); } void ReplayWidget::resizeEvent(QResizeEvent *event) { visibleUpdates.clear(); QRect bounds = rect(); int first = qMax(0, from); int last = qMin(unsigned(to), unsigned(updates.size())); for (int i = first; i < last; ++i) { if (updates.at(i).intersects(bounds)) visibleUpdates << i; } int range = last - first; if (visibleUpdates.size() != range) printf("Warning: skipped %d frames due to limited resolution\n", range - visibleUpdates.size()); } ReplayWidget::ReplayWidget(const QString &filename_, int from_, int to_, bool single_) : currentFrame(0) , currentIteration(0) , filename(filename_) , from(from_) , to(to_) , single(single_) { setWindowTitle(filename); QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { printf("Failed to load input file '%s'\n", qPrintable(filename_)); return; } QDataStream in(&file); char *data; uint size; in.readBytes(data, size); bool isTraceFile = size == 7 && qstrncmp(data, "qttrace", 7) == 0; delete [] data; if (!isTraceFile) { printf("File '%s' is not a trace file\n", qPrintable(filename_)); return; } in >> buffer >> updates; printf("Read paint buffer with %d frames\n", buffer.numFrames()); resize(buffer.boundingRect().size().toSize()); setAutoFillBackground(false); setAttribute(Qt::WA_NoSystemBackground); QTimer::singleShot(10, this, SLOT(updateRect())); } int main(int argc, char **argv) { QApplication app(argc, argv); if (argc <= 1 || qstrcmp(argv[1], "-h") == 0 || qstrcmp(argv[1], "--help") == 0) { printf("Replays a tracefile generated with '-graphicssystem trace'\n"); printf("Usage:\n > %s [OPTIONS] [traceFile]\n", argv[0]); printf("OPTIONS\n" " --range=from-to to specify a frame range.\n" " --singlerun to do only one run (without statistics)\n"); return 1; } QFile file(app.arguments().last()); if (!file.exists()) { printf("%s does not exist\n", qPrintable(app.arguments().last())); return 1; } bool single = false; int from = 0; int to = -1; for (int i = 1; i < app.arguments().size() - 1; ++i) { QString arg = app.arguments().at(i); if (arg.startsWith(QLatin1String("--range="))) { QString rest = arg.mid(8); QStringList components = rest.split(QLatin1Char('-')); bool ok1 = false; bool ok2 = false; int fromCandidate = 0; int toCandidate = 0; if (components.size() == 2) { fromCandidate = components.first().toInt(&ok1); toCandidate = components.last().toInt(&ok2); } if (ok1 && ok2) { from = fromCandidate; to = toCandidate; } else { printf("ERROR: malformed syntax in argument %s\n", qPrintable(arg)); } } else if (arg == QLatin1String("--singlerun")) { single = true; } else { printf("Unrecognized argument: %s\n", qPrintable(arg)); return 1; } } ReplayWidget *widget = new ReplayWidget(app.arguments().last(), from, to, single); if (!widget->updates.isEmpty()) { widget->show(); return app.exec(); } } #include "main.moc" <|endoftext|>
<commit_before>/* * Copyright 2006-2008 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 "testdriver_comparator.h" // used for Canonical XML #define LIBXML_C14N_ENABLED #define LIBXML_OUTPUT_ENABLED #include <libxml/c14n.h> #include <libxml/tree.h> #include <sstream> #include <iostream> #include <fstream> #include <cassert> #include <string.h> namespace zorba { /******************************************************************************* ********************************************************************************/ int canonicalizeAndCompare( const std::string& aComparisonMethod, const char* aRefFile, const char* aResultFile, const std::string& aRBKTBinDir) { xmlDocPtr lRefResult_ptr; xmlDocPtr lResult_ptr; LIBXML_TEST_VERSION int libxmlFlags = XML_PARSE_NOBLANKS; if (aComparisonMethod.compare("XML") == 0) { lRefResult_ptr = xmlReadFile(aRefFile, 0, 0); lResult_ptr = xmlReadFile(aResultFile, 0, 0); } else if (aComparisonMethod.compare("Text") == 0 || aComparisonMethod.compare("Fragment") == 0) { // prepend and append an artifical root tag as requested by the guidelines std::ostringstream lTmpRefResult; lTmpRefResult << "<root>"; std::ifstream lRefInStream(aRefFile); if (!lRefInStream.good()) { std::cout << "Failed to open ref file " << aRefFile << std::endl; return 8; } char buf[2048]; char buf2[2048]; char* bufp; char* bufp2; char* bufend = (buf + 2048); while (!lRefInStream.eof()) { memset(buf, 0, 2048); lRefInStream.read(buf, 2048); bufp = buf; bufp2 = buf2; // Skip xml declaration, if any if (!strncmp(bufp, "<?xml", 5)) { while (*bufp != '\n' && strncmp(bufp, "?>", 2)) { ++bufp; } if (*bufp == '?') bufp += 2; if (*bufp == '\r') ++bufp; if (*bufp == '\n') ++bufp; } // Convert \r\n to \n while (bufp != bufend && *bufp != '\0') { if (*bufp == '\r' && *(bufp+1) == '\n') ++bufp; *bufp2 = *bufp; ++bufp; ++bufp2; } if (*bufp == '\0') *bufp2 = *bufp; lTmpRefResult.write(buf2, bufp2 - buf2); } lTmpRefResult << "</root>"; lRefResult_ptr = xmlReadMemory(lTmpRefResult.str().c_str(), lTmpRefResult.str().size(), "ref_result.xml", 0, libxmlFlags); // prepend and append an artifical root tag as requested by the guidelines std::ostringstream lTmpResult; lTmpResult << "<root>"; std::ifstream lInStream(aResultFile); if (!lInStream.good()) { std::cout << "Failed to open result file " << aResultFile << std::endl; return 8; } while (!lInStream.eof()) { memset(buf, 0, 2048); lInStream.read(buf, 2048); lTmpResult.write(buf, lInStream.gcount()); } lTmpResult << "</root>"; lResult_ptr = xmlReadMemory(lTmpResult.str().c_str(), lTmpResult.str().size(), "result.xml", 0, libxmlFlags); } else if (aComparisonMethod.compare("Error") == 0 ) { std::cout << "an error was expected but we got a result" << std::endl; return 8; } else if (aComparisonMethod.compare("Inspect") == 0 ) { std::cout << "result must be inspected by humans." << std::endl; return 0; } else if (aComparisonMethod.compare("Ignore") == 0 ) { // safely return no error here return 0; } else { std::cout << "comparison method not supported: " << aComparisonMethod << std::endl; return 9; } if (lRefResult_ptr == NULL || lResult_ptr == NULL) { std::cerr << "couldn't read reference result or result file" << std::endl; return 8; } std::string lCanonicalRefFile = aRBKTBinDir + "/canonical_ref.xml"; std::string lCanonicalResFile = aRBKTBinDir + "/canonical_res.xml"; int lRefResultRes = xmlC14NDocSave(lRefResult_ptr, 0, 0, NULL, 0, lCanonicalRefFile.c_str(), 0); int lResultRes = xmlC14NDocSave(lResult_ptr, 0, 0, NULL, 0, lCanonicalResFile.c_str(), 0); xmlFreeDoc(lRefResult_ptr); xmlFreeDoc(lResult_ptr); if (lRefResultRes < 0) { std::cerr << "error canonicalizing reference result" << std::endl; return 10; } if (lResultRes < 0) { std::cerr << "error canonicalizing result" << std::endl; return 10; } // last, we have to diff the result int lLine, lCol, lPos; // where do the files differ std::string lRefLine, lResultLine; bool lRes = fileEquals(lCanonicalRefFile.c_str(), lCanonicalResFile.c_str(), lLine, lCol, lPos, lRefLine, lResultLine); if (!lRes) { std::cout << std::endl << "Actual and Reference canonical results are not identical" << std::endl << std::endl << "Actual Canonical Result: " << std::endl << std::endl; printFile(std::cout, lCanonicalResFile); std::cout << std::endl << std::endl; std::cout << "Reference Canonical Result: " << std::endl << std::endl; zorba::printFile(std::cout, lCanonicalRefFile); std::cout << std::endl << std::endl; std::cout << "See line " << lLine << ", col " << lCol << " of expected result. " << std::endl; std::cout << "Actual: <"; if( -1 != lPos ) printPart(std::cout, aResultFile, lPos, 15); else std::cout << lResultLine; std::cout << ">" << std::endl; std::cout << "Expected: <"; if( -1 != lPos ) printPart(std::cout, aRefFile, lPos, 15); else std::cout << lRefLine; std::cout << ">" << std::endl; return 8; } return 0; } /******************************************************************************* Return false if the files are not equal. aLine contains the line number in which the first difference occurs aCol contains the column number in which the first difference occurs aPos is the character number off the first difference in the file -1 is returned for aLine, aCol, and aPos if the files are equal ********************************************************************************/ bool fileEquals( const char* aRefFile, const char* aResFile, int& aLine, int& aCol, int& aPos, std::string& aRefLine, std::string& aResLine) { std::ifstream li(aRefFile); std::ifstream ri(aResFile); std::string lLine, rLine; if (!li.good()) { std::cout << "Failed to open ref file " << aRefFile << std::endl; return false; } if (!ri.good()) { std::cout << "Failed to open results file " << aResFile << std::endl; return false; } aLine = 1; aCol = 0; aPos = -1; while (! li.eof() ) { if ( ri.eof() ) { std::getline(li, lLine); if (li.peek() == -1) // ignore end-of-line in the ref result return true; else return false; } std::getline(li, lLine); std::getline(ri, rLine); while ( (aCol = lLine.compare(rLine)) != 0) { if (aLine == 1 && lLine == "<?xml version=\"1.0\" encoding=\"UTF-8\"?>") { ++aLine; std::getline(li, lLine); continue; } else { aRefLine = lLine; aResLine = rLine; return false; } } ++aLine; } if (! ri.eof() ) { std::getline(ri, rLine); if (ri.peek() == -1) // ignore end-of-line in the actual result { return true; } else { aResLine = rLine; return false; } } return true; } /******************************************************************************* Print parts of a file starting at aStartPos with the length of aLen ********************************************************************************/ void printPart(std::ostream& os, const std::string &aInFile, int aStartPos, int aLen) { char* buffer = new char [aLen]; try { std::ifstream lIn(aInFile.c_str()); lIn.seekg(aStartPos); #ifdef WIN32 int lCharsRead = lIn._Readsome_s (buffer, aLen, aLen); #else int lCharsRead = lIn.readsome (buffer, aLen); #endif os.write (buffer, lCharsRead); os.flush(); delete[] buffer; } catch (...) { delete[] buffer; } return; } /******************************************************************************* ********************************************************************************/ void printFile(std::ostream& os, const std::string &aInFile) { std::ifstream lInFileStream(aInFile.c_str()); assert(lInFileStream.good()); if(!lInFileStream.good()) { exit(1); } char buf[1024]; while (!lInFileStream.eof()) { lInFileStream.read(buf, 1024); os.write(buf, lInFileStream.gcount()); } os << std::endl; } } /* namespace zorba */ <commit_msg>Fixed a warning reported by Valgrind for canonicalizeAndCompare: "Conditional jump or move depends on uninitialised value(s)".<commit_after>/* * Copyright 2006-2008 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 "testdriver_comparator.h" // used for Canonical XML #define LIBXML_C14N_ENABLED #define LIBXML_OUTPUT_ENABLED #include <libxml/c14n.h> #include <libxml/tree.h> #include <sstream> #include <iostream> #include <fstream> #include <cassert> #include <string.h> namespace zorba { /******************************************************************************* ********************************************************************************/ int canonicalizeAndCompare( const std::string& aComparisonMethod, const char* aRefFile, const char* aResultFile, const std::string& aRBKTBinDir) { xmlDocPtr lRefResult_ptr; xmlDocPtr lResult_ptr; LIBXML_TEST_VERSION int libxmlFlags = XML_PARSE_NOBLANKS; if (aComparisonMethod.compare("XML") == 0) { lRefResult_ptr = xmlReadFile(aRefFile, 0, 0); lResult_ptr = xmlReadFile(aResultFile, 0, 0); } else if (aComparisonMethod.compare("Text") == 0 || aComparisonMethod.compare("Fragment") == 0) { // prepend and append an artifical root tag as requested by the guidelines std::ostringstream lTmpRefResult; lTmpRefResult << "<root>"; std::ifstream lRefInStream(aRefFile); if (!lRefInStream.good()) { std::cout << "Failed to open ref file " << aRefFile << std::endl; return 8; } char buf[2048]; char buf2[2048]; char* bufp; char* bufp2; char* bufend = (buf + 2048); while (!lRefInStream.eof()) { memset(buf, 0, 2048); memset(buf2, 0, 2048); lRefInStream.read(buf, 2048); bufp = buf; bufp2 = buf2; // Skip xml declaration, if any if (!strncmp(bufp, "<?xml", 5)) { while (*bufp != '\n' && strncmp(bufp, "?>", 2)) { ++bufp; } if (*bufp == '?') bufp += 2; if (*bufp == '\r') ++bufp; if (*bufp == '\n') ++bufp; } // Convert \r\n to \n while (bufp != bufend && *bufp != '\0') { if (*bufp == '\r' && *(bufp+1) == '\n') ++bufp; *bufp2 = *bufp; ++bufp; ++bufp2; } // if (*bufp == '\0') // *bufp2 = *bufp; lTmpRefResult.write(buf2, bufp2 - buf2); } lTmpRefResult << "</root>"; lRefResult_ptr = xmlReadMemory(lTmpRefResult.str().c_str(), lTmpRefResult.str().size(), "ref_result.xml", 0, libxmlFlags); // prepend and append an artifical root tag as requested by the guidelines std::ostringstream lTmpResult; lTmpResult << "<root>"; std::ifstream lInStream(aResultFile); if (!lInStream.good()) { std::cout << "Failed to open result file " << aResultFile << std::endl; return 8; } while (!lInStream.eof()) { memset(buf, 0, 2048); lInStream.read(buf, 2048); lTmpResult.write(buf, lInStream.gcount()); } lTmpResult << "</root>"; lResult_ptr = xmlReadMemory(lTmpResult.str().c_str(), lTmpResult.str().size(), "result.xml", 0, libxmlFlags); } else if (aComparisonMethod.compare("Error") == 0 ) { std::cout << "an error was expected but we got a result" << std::endl; return 8; } else if (aComparisonMethod.compare("Inspect") == 0 ) { std::cout << "result must be inspected by humans." << std::endl; return 0; } else if (aComparisonMethod.compare("Ignore") == 0 ) { // safely return no error here return 0; } else { std::cout << "comparison method not supported: " << aComparisonMethod << std::endl; return 9; } if (lRefResult_ptr == NULL || lResult_ptr == NULL) { std::cerr << "couldn't read reference result or result file" << std::endl; return 8; } std::string lCanonicalRefFile = aRBKTBinDir + "/canonical_ref.xml"; std::string lCanonicalResFile = aRBKTBinDir + "/canonical_res.xml"; int lRefResultRes = xmlC14NDocSave(lRefResult_ptr, 0, 0, NULL, 0, lCanonicalRefFile.c_str(), 0); int lResultRes = xmlC14NDocSave(lResult_ptr, 0, 0, NULL, 0, lCanonicalResFile.c_str(), 0); xmlFreeDoc(lRefResult_ptr); xmlFreeDoc(lResult_ptr); if (lRefResultRes < 0) { std::cerr << "error canonicalizing reference result" << std::endl; return 10; } if (lResultRes < 0) { std::cerr << "error canonicalizing result" << std::endl; return 10; } // last, we have to diff the result int lLine, lCol, lPos; // where do the files differ std::string lRefLine, lResultLine; bool lRes = fileEquals(lCanonicalRefFile.c_str(), lCanonicalResFile.c_str(), lLine, lCol, lPos, lRefLine, lResultLine); if (!lRes) { std::cout << std::endl << "Actual and Reference canonical results are not identical" << std::endl << std::endl << "Actual Canonical Result: " << std::endl << std::endl; printFile(std::cout, lCanonicalResFile); std::cout << std::endl << std::endl; std::cout << "Reference Canonical Result: " << std::endl << std::endl; zorba::printFile(std::cout, lCanonicalRefFile); std::cout << std::endl << std::endl; std::cout << "See line " << lLine << ", col " << lCol << " of expected result. " << std::endl; std::cout << "Actual: <"; if( -1 != lPos ) printPart(std::cout, aResultFile, lPos, 15); else std::cout << lResultLine; std::cout << ">" << std::endl; std::cout << "Expected: <"; if( -1 != lPos ) printPart(std::cout, aRefFile, lPos, 15); else std::cout << lRefLine; std::cout << ">" << std::endl; return 8; } return 0; } /******************************************************************************* Return false if the files are not equal. aLine contains the line number in which the first difference occurs aCol contains the column number in which the first difference occurs aPos is the character number off the first difference in the file -1 is returned for aLine, aCol, and aPos if the files are equal ********************************************************************************/ bool fileEquals( const char* aRefFile, const char* aResFile, int& aLine, int& aCol, int& aPos, std::string& aRefLine, std::string& aResLine) { std::ifstream li(aRefFile); std::ifstream ri(aResFile); std::string lLine, rLine; if (!li.good()) { std::cout << "Failed to open ref file " << aRefFile << std::endl; return false; } if (!ri.good()) { std::cout << "Failed to open results file " << aResFile << std::endl; return false; } aLine = 1; aCol = 0; aPos = -1; while (! li.eof() ) { if ( ri.eof() ) { std::getline(li, lLine); if (li.peek() == -1) // ignore end-of-line in the ref result return true; else return false; } std::getline(li, lLine); std::getline(ri, rLine); while ( (aCol = lLine.compare(rLine)) != 0) { if (aLine == 1 && lLine == "<?xml version=\"1.0\" encoding=\"UTF-8\"?>") { ++aLine; std::getline(li, lLine); continue; } else { aRefLine = lLine; aResLine = rLine; return false; } } ++aLine; } if (! ri.eof() ) { std::getline(ri, rLine); if (ri.peek() == -1) // ignore end-of-line in the actual result { return true; } else { aResLine = rLine; return false; } } return true; } /******************************************************************************* Print parts of a file starting at aStartPos with the length of aLen ********************************************************************************/ void printPart(std::ostream& os, const std::string &aInFile, int aStartPos, int aLen) { char* buffer = new char [aLen]; try { std::ifstream lIn(aInFile.c_str()); lIn.seekg(aStartPos); #ifdef WIN32 int lCharsRead = lIn._Readsome_s (buffer, aLen, aLen); #else int lCharsRead = lIn.readsome (buffer, aLen); #endif os.write (buffer, lCharsRead); os.flush(); delete[] buffer; } catch (...) { delete[] buffer; } return; } /******************************************************************************* ********************************************************************************/ void printFile(std::ostream& os, const std::string &aInFile) { std::ifstream lInFileStream(aInFile.c_str()); assert(lInFileStream.good()); if(!lInFileStream.good()) { exit(1); } char buf[1024]; while (!lInFileStream.eof()) { lInFileStream.read(buf, 1024); os.write(buf, lInFileStream.gcount()); } os << std::endl; } } /* namespace zorba */ <|endoftext|>
<commit_before>/******************************************************************************* * c7a/data/block_reader.hpp * * Part of Project c7a. * * Copyright (C) 2015 Timo Bingmann <tb@panthema.net> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_DATA_BLOCK_READER_HEADER #define C7A_DATA_BLOCK_READER_HEADER #include <c7a/common/config.hpp> #include <c7a/common/item_serializer_tools.hpp> #include <c7a/data/block.hpp> #include <c7a/data/serializer.hpp> #include <algorithm> #include <string> namespace c7a { namespace data { //! \addtogroup data Data Subsystem //! \{ /*! * BlockReader takes VirtualBlock objects from BlockSource and allows reading of * a) serializable Items or b) arbitray data from the Block sequence. It takes * care of fetching the next Block when the previous one underruns and also of * data items split between two Blocks. */ template <typename BlockSource> class BlockReader : public common::ItemReaderToolsBase<BlockReader<BlockSource> > { public: static const bool self_verify = common::g_self_verify; using Byte = unsigned char; using Block = typename BlockSource::Block; using BlockCPtr = std::shared_ptr<const Block>; //! Start reading a File explicit BlockReader(BlockSource&& source) : source_(std::move(source)) { } //! \name Reading (Generic) Items //! \{ //! Next() reads a complete item T template <typename T> T Next() { if (self_verify) { // for self-verification, T is prefixed with its hash code size_t code = Get<size_t>(); if (code != typeid(T).hash_code()) { throw std::runtime_error( "BlockReader::Next() attempted to retrieve item " "with different typeid!"); } } return Serializer<BlockReader, T>::deserialize(*this); } //! HasNext() returns true if at least one more byte is available. bool HasNext() { while (current_ == end_) { if (!NextBlock()) return false; } return true; } //! \} //! \name Cursor Reading Methods //! \{ //! Fetch a number of unstructured bytes from the current block, advancing //! the cursor. BlockReader & Read(void* outdata, size_t size) { Byte* cdata = reinterpret_cast<Byte*>(outdata); while (current_ + size > end_) { // partial copy of remainder of block size_t partial_size = end_ - current_; std::copy(current_, current_ + partial_size, cdata); cdata += partial_size; size -= partial_size; if (!NextBlock()) throw std::runtime_error("Data underflow in BlockReader."); } // copy rest from current block std::copy(current_, current_ + size, cdata); current_ += size; return *this; } //! Fetch a number of unstructured bytes from the buffer as std::string, //! advancing the cursor. std::string Read(size_t datalen) { std::string out(datalen, 0); Read(const_cast<char*>(out.data()), out.size()); return out; } //! Fetch a single byte from the current block, advancing the cursor. Byte GetByte() { // loop, since blocks can actually be empty. while (current_ == end_) { if (!NextBlock()) throw std::runtime_error("Data underflow in BlockReader."); } return *current_++; } //! Fetch a single item of the template type Type from the buffer, //! advancing the cursor. Be careful with implicit type conversions! template <typename Type> Type Get() { static_assert(std::is_pod<Type>::value, "You only want to Get() POD types as raw values."); Type ret; Read(&ret, sizeof(ret)); return ret; } //! \} protected: //! Instance of BlockSource. This is NOT a reference, as to enable embedding //! of FileBlockSource to compose classes into File::Reader. BlockSource source_; //! current read pointer into current block of file. const Byte* current_ = nullptr; //! pointer to end of current block. const Byte* end_ = nullptr; //! Call source_.NextBlock with appropriate parameters bool NextBlock() { return source_.NextBlock(&current_, &end_); } }; //! \} } // namespace data } // namespace c7a #endif // !C7A_DATA_BLOCK_READER_HEADER /******************************************************************************/ <commit_msg>Adding FileReader::ReadComplete() -> vector<T><commit_after>/******************************************************************************* * c7a/data/block_reader.hpp * * Part of Project c7a. * * Copyright (C) 2015 Timo Bingmann <tb@panthema.net> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_DATA_BLOCK_READER_HEADER #define C7A_DATA_BLOCK_READER_HEADER #include <c7a/common/config.hpp> #include <c7a/common/item_serializer_tools.hpp> #include <c7a/data/block.hpp> #include <c7a/data/serializer.hpp> #include <algorithm> #include <string> namespace c7a { namespace data { //! \addtogroup data Data Subsystem //! \{ /*! * BlockReader takes VirtualBlock objects from BlockSource and allows reading of * a) serializable Items or b) arbitray data from the Block sequence. It takes * care of fetching the next Block when the previous one underruns and also of * data items split between two Blocks. */ template <typename BlockSource> class BlockReader : public common::ItemReaderToolsBase<BlockReader<BlockSource> > { public: static const bool self_verify = common::g_self_verify; using Byte = unsigned char; using Block = typename BlockSource::Block; using BlockCPtr = std::shared_ptr<const Block>; //! Start reading a File explicit BlockReader(BlockSource&& source) : source_(std::move(source)) { } //! \name Reading (Generic) Items //! \{ //! Next() reads a complete item T template <typename T> T Next() { if (self_verify) { // for self-verification, T is prefixed with its hash code size_t code = Get<size_t>(); if (code != typeid(T).hash_code()) { throw std::runtime_error( "BlockReader::Next() attempted to retrieve item " "with different typeid!"); } } return Serializer<BlockReader, T>::deserialize(*this); } //! HasNext() returns true if at least one more byte is available. bool HasNext() { while (current_ == end_) { if (!NextBlock()) return false; } return true; } //! Return complete contents until empty as a std::vector<T>. Use this only //! if you are sure that it will fit into memory, -> only use it for tests. template <typename T> std::vector<T> ReadComplete() { std::vector<T> out; while (HasNext()) out.emplace_back(Next<T>()); return out; } //! \} //! \name Cursor Reading Methods //! \{ //! Fetch a number of unstructured bytes from the current block, advancing //! the cursor. BlockReader & Read(void* outdata, size_t size) { Byte* cdata = reinterpret_cast<Byte*>(outdata); while (current_ + size > end_) { // partial copy of remainder of block size_t partial_size = end_ - current_; std::copy(current_, current_ + partial_size, cdata); cdata += partial_size; size -= partial_size; if (!NextBlock()) throw std::runtime_error("Data underflow in BlockReader."); } // copy rest from current block std::copy(current_, current_ + size, cdata); current_ += size; return *this; } //! Fetch a number of unstructured bytes from the buffer as std::string, //! advancing the cursor. std::string Read(size_t datalen) { std::string out(datalen, 0); Read(const_cast<char*>(out.data()), out.size()); return out; } //! Fetch a single byte from the current block, advancing the cursor. Byte GetByte() { // loop, since blocks can actually be empty. while (current_ == end_) { if (!NextBlock()) throw std::runtime_error("Data underflow in BlockReader."); } return *current_++; } //! Fetch a single item of the template type Type from the buffer, //! advancing the cursor. Be careful with implicit type conversions! template <typename Type> Type Get() { static_assert(std::is_pod<Type>::value, "You only want to Get() POD types as raw values."); Type ret; Read(&ret, sizeof(ret)); return ret; } //! \} protected: //! Instance of BlockSource. This is NOT a reference, as to enable embedding //! of FileBlockSource to compose classes into File::Reader. BlockSource source_; //! current read pointer into current block of file. const Byte* current_ = nullptr; //! pointer to end of current block. const Byte* end_ = nullptr; //! Call source_.NextBlock with appropriate parameters bool NextBlock() { return source_.NextBlock(&current_, &end_); } }; //! \} } // namespace data } // namespace c7a #endif // !C7A_DATA_BLOCK_READER_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>// // Created by Bidbip on 10/8/2017. // #include "IntMap.h" using namespace std; static int FREE_KEY = 0; static int NO_VALUE = 0; static int INT_PHI = 0x9E3779B9; IntMap::IntMap() { i_size = 4; m_fillFactor = .75f; init(); } IntMap::IntMap(int size) { i_size = size; m_fillFactor = .75f; init(); } IntMap::IntMap(int size, float fillFactor) { i_size = size; m_fillFactor = fillFactor; init(); } void IntMap::init() { if (m_fillFactor <= 0 || m_fillFactor >= 1) { //errpr } if (i_size <= 0) { //error } int capacity = arraySize(i_size, m_fillFactor); m_mask = capacity -1; m_mask2 = capacity *2 -1; //m_data = new int[capacity*2]; m_data.resize(capacity*2); m_threshold = (int) (capacity * m_fillFactor); } int IntMap::get(int key) { int ptr = (phiMix(key) & m_mask) << 1; if (key == FREE_KEY) { return m_hasFreeKey ? m_freeValue : NO_VALUE; } int k = m_data[ptr]; if (k == FREE_KEY) { return NO_VALUE; } if (k == key) { return m_data[ptr + 1]; } while (true) { ptr = ptr + 2 & m_mask2; k = m_data[ptr]; if (k == FREE_KEY) { return NO_VALUE; } if (k == key) { return m_data[ptr + 1]; } } } bool IntMap::contains(int key) { return NO_VALUE != get(key); } bool IntMap::add(int key) { int x = put(key, 666); return NO_VALUE != x; } bool IntMap::mDelete(int key) { return NO_VALUE != remove(key); } bool IntMap::isEmpty() { return 0 == m_size; } void IntMap::intersect0(IntMap &m, vector<IntMap> &maps, vector<IntMap> &vmaps, IntStack &r) { vector<int> data = m.m_data; for (int k = 0; k < data.size(); k += 2) { bool found = true; int key = data[k]; if (FREE_KEY == key) { continue; } for (int i = 1; i < maps.size(); i++) { IntMap map = maps[i]; int value = map.get(key); if (NO_VALUE == value) { IntMap vmap = vmaps[i]; int vval = vmap.get(key); if (NO_VALUE == vval) { found = false; break; } } } if (found) { r.push(key); } } } IntStack IntMap::intersect(vector<IntMap> &maps, vector<IntMap> &vmaps) { IntStack *r = new IntStack(); intersect0(maps[0], maps, vmaps, *r); intersect0(vmaps[0], maps, vmaps, *r); return *r; } int IntMap::put(int key, int value) { if (key == FREE_KEY) { int ret = m_freeValue; if (!m_hasFreeKey) { ++m_size; } m_hasFreeKey = true; m_freeValue = value; return ret; } int ptr = (phiMix(key) & m_mask) << 1; int k = m_data[ptr]; if (k == FREE_KEY) { m_data[ptr] = key; m_data[ptr+1] = value; if (m_size >= m_threshold) { rehash(m_data.size() *2); } else { ++m_size; } return NO_VALUE; } else if (k == key) { int ret = m_data[ptr + 1]; m_data[ptr+1] = value; return ret; } while (true) { ptr = ptr + 2 & m_mask2; k = m_data[ptr]; if (k == FREE_KEY) { m_data[ptr] = key; m_data[ptr +1] = value; if (m_size >= m_threshold) { rehash(m_data.size()*2); } else { ++m_size; } return NO_VALUE; } else if (k == key) { int ret = m_data[ptr +1]; m_data[ptr + 1] = value; return ret; } } } int IntMap::remove(int key) { if (key == FREE_KEY) { if (!m_hasFreeKey) { return NO_VALUE; } m_hasFreeKey = false; --m_size; return m_freeValue; } int ptr = (phiMix(key) & m_mask) << 1; int k = m_data[ptr]; if (k == key) { int res = m_data[ptr + 1]; shiftKeys(ptr); --m_size; return res; } else if (k == FREE_KEY) { return NO_VALUE; } while (true) { ptr = ptr + 2 & m_mask2; k = m_data[ptr]; if (k == key) { int res = m_data[ptr + 1]; shiftKeys(ptr); --m_size; return res; } else if (k == FREE_KEY) { return NO_VALUE; } } } int IntMap::size() { return m_size; } int IntMap::shiftKeys(int pos) { int last, slot; int k; while (true) { last = pos; pos = pos + 2 & m_mask2; while (true) { k = m_data[pos]; if (k == FREE_KEY) { m_data[last] = FREE_KEY; return last; } slot = (phiMix(k) & m_mask) << 1; if (last <= pos ? last >= slot || slot > pos: last >= slot && slot > pos) { break; } pos = pos + 2 & m_mask2; } m_data[last] = k; m_data[last + 1] = m_data[pos +1]; } } void IntMap::rehash(int newCapacity) { m_threshold = (int) (newCapacity / 2 * m_fillFactor); m_mask = newCapacity / 2 - 1; m_mask2 = newCapacity - 1; int oldCapacity = m_data.size(); vector<int> oldData = m_data; m_data.resize(newCapacity); m_size = m_hasFreeKey ? 1 : 0; for (int i = 0; i < oldCapacity; i += 2) { int oldKey = oldData[i]; if (oldKey != FREE_KEY) { put(oldKey, oldData[i+1]); } } } long long IntMap::nextPowerOFTwo(long long x) { if (x == 0) { return 1; } x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return (x | x >> 32) + 1; } int IntMap::arraySize(int expected, float f) { //Fixed the build issue due to the bit size. needed static cast not old style long long s = max(static_cast<long long>(2), nextPowerOFTwo(static_cast<long long>(ceil(expected / f)))); if (s > 1 << 30) { cout << "error" << endl; return -1; } return static_cast<int> (s); } int IntMap::phiMix(int x) { int h = x * INT_PHI; return h ^ h >> 16; } string IntMap::toString() { string str; stringstream ss; ss << "{"; int l = m_data.size(); bool first = true; for (int i = 0; i < l; i += 2) { int v = m_data[i]; if (v != FREE_KEY) { if (!first) { ss << ","; } first = false; ss << (v - 1); } } ss << "}"; return ss.str(); } /* * IntMap Test0; IntMap Test1(10); IntMap Test2(4, .5f); Test2.put(10, 1); Test2.put(21, 2); Test2.put(31, 6); if (Test2.isEmpty()) { cout << "Empty" << endl; } cout << "size: "; cout << Test2.size() << endl; cout << Test2.toString() << endl; cout << Test2.get(21) << endl; Test2.put(21, 7); cout << Test2.get(21) << endl; if (Test2.contains(24)) { cout << "HAVE 24" << endl; } if (Test2.contains(10)) { cout << "HAVE 10" << endl; } if (Test2.add(22)) { cout << "added 22" << endl; } if (Test2.add(21)) { cout << "Added over 21" << endl; } cout << Test2.toString() << endl; cout << Test2.get(22) << endl; cout << Test2.get(21) << endl; cout << Test2.mDelete(22) << endl; cout << Test2.mDelete(43) << endl; Test1.put(10, 1); Test1.put(3, 54); Test1.put(22, 10); Test1.put(31, 2); vector<IntMap> i; i.push_back(Test1); vector<IntMap> j; j.push_back(Test2); IntStack list = Test2.intersect(i, j); cout << list.toString() << endl; * * * */<commit_msg>Update IntMap1.cpp<commit_after>// // Created by Bidbip on 10/8/2017. // #include "IntMap.h" using namespace std; static int FREE_KEY = 0; static int NO_VALUE = 0; static int INT_PHI = 0x9E3779B9; IntMap::IntMap() { i_size = 4; m_fillFactor = .75f; init(); } IntMap::IntMap(int size) { i_size = size; m_fillFactor = .75f; init(); } IntMap::IntMap(int size, float fillFactor) { i_size = size; m_fillFactor = fillFactor; init(); } void IntMap::init() { if (m_fillFactor <= 0 || m_fillFactor >= 1) { //errpr } if (i_size <= 0) { //error } int capacity = arraySize(i_size, m_fillFactor); m_mask = capacity -1; m_mask2 = capacity *2 -1; //m_data = new int[capacity*2]; m_data.resize(capacity*2); m_threshold = (int) (capacity * m_fillFactor); } int IntMap::get(int key) { int ptr = (phiMix(key) & m_mask) << 1; if (key == FREE_KEY) { return m_hasFreeKey ? m_freeValue : NO_VALUE; } int k = m_data[ptr]; if (k == FREE_KEY) { return NO_VALUE; } if (k == key) { return m_data[ptr + 1]; } while (true) { ptr = ptr + 2 & m_mask2; k = m_data[ptr]; if (k == FREE_KEY) { return NO_VALUE; } if (k == key) { return m_data[ptr + 1]; } } } bool IntMap::contains(int key) { return NO_VALUE != get(key); } bool IntMap::add(int key) { int x = put(key, 666); return NO_VALUE != x; } bool IntMap::mDelete(int key) { return NO_VALUE != remove(key); } bool IntMap::isEmpty() { return 0 == m_size; } void IntMap::intersect0(IntMap &m, vector<IntMap> &maps, vector<IntMap> &vmaps, IntStack &r) { vector<int> data = m.m_data; for (int k = 0; k < data.size(); k += 2) { bool found = true; int key = data[k]; if (FREE_KEY == key) { continue; } for (int i = 1; i < maps.size(); i++) { IntMap map = maps[i]; int value = map.get(key); if (NO_VALUE == value) { IntMap vmap = vmaps[i]; int vval = vmap.get(key); if (NO_VALUE == vval) { found = false; break; } } } if (found) { r.push(key); } } } IntStack IntMap::intersect(vector<IntMap> &maps, vector<IntMap> &vmaps) { IntStack *r = new IntStack(); intersect0(maps[0], maps, vmaps, *r); intersect0(vmaps[0], maps, vmaps, *r); return *r; } int IntMap::put(int key, int value) { if (key == FREE_KEY) { int ret = m_freeValue; if (!m_hasFreeKey) { ++m_size; } m_hasFreeKey = true; m_freeValue = value; return ret; } int ptr = (phiMix(key) & m_mask) << 1; int k = m_data[ptr]; if (k == FREE_KEY) { m_data[ptr] = key; m_data[ptr+1] = value; if (m_size >= m_threshold) { rehash(m_data.size() *2); } else { ++m_size; } return NO_VALUE; } else if (k == key) { int ret = m_data[ptr + 1]; m_data[ptr+1] = value; return ret; } while (true) { ptr = ptr + 2 & m_mask2; k = m_data[ptr]; if (k == FREE_KEY) { m_data[ptr] = key; m_data[ptr +1] = value; if (m_size >= m_threshold) { rehash(m_data.size()*2); } else { ++m_size; } return NO_VALUE; } else if (k == key) { int ret = m_data[ptr +1]; m_data[ptr + 1] = value; return ret; } } } int IntMap::remove(int key) { if (key == FREE_KEY) { if (!m_hasFreeKey) { return NO_VALUE; } m_hasFreeKey = false; --m_size; return m_freeValue; } int ptr = (phiMix(key) & m_mask) << 1; int k = m_data[ptr]; if (k == key) { int res = m_data[ptr + 1]; shiftKeys(ptr); --m_size; return res; } else if (k == FREE_KEY) { return NO_VALUE; } while (true) { ptr = ptr + 2 & m_mask2; k = m_data[ptr]; if (k == key) { int res = m_data[ptr + 1]; shiftKeys(ptr); --m_size; return res; } else if (k == FREE_KEY) { return NO_VALUE; } } } int IntMap::size() { return m_size; } int IntMap::shiftKeys(int pos) { int last, slot; int k; while (true) { last = pos; pos = pos + 2 & m_mask2; while (true) { k = m_data[pos]; if (k == FREE_KEY) { m_data[last] = FREE_KEY; return last; } slot = (phiMix(k) & m_mask) << 1; if (last <= pos ? last >= slot || slot > pos: last >= slot && slot > pos) { break; } pos = pos + 2 & m_mask2; } m_data[last] = k; m_data[last + 1] = m_data[pos +1]; } } void IntMap::rehash(int newCapacity) { m_threshold = (int) (newCapacity / 2 * m_fillFactor); m_mask = newCapacity / 2 - 1; m_mask2 = newCapacity - 1; int oldCapacity = m_data.size(); vector<int> oldData = m_data; m_data.resize(newCapacity); m_size = m_hasFreeKey ? 1 : 0; for (int i = 0; i < oldCapacity; i += 2) { int oldKey = oldData[i]; if (oldKey != FREE_KEY) { put(oldKey, oldData[i+1]); } } } long long IntMap::nextPowerOFTwo(long long x) { if (x == 0) { return 1; } x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return (x | x >> 32) + 1; } int IntMap::arraySize(int expected, float f) { //Fixed the build issue due to the bit size. needed static cast not old style long long s = max(static_cast<long long>(2), nextPowerOFTwo(static_cast<long long>(ceil(expected / f)))); if (s > 1 << 30) { cout << "error" << endl; return -1; } return static_cast<int> (s); } int IntMap::phiMix(int x) { int h = x * INT_PHI; return h ^ h >> 16; } string IntMap::toString() { string str; stringstream ss; ss << "{"; int l = m_data.size(); bool first = true; for (int i = 0; i < l; i += 2) { int v = m_data[i]; if (v != FREE_KEY) { if (!first) { ss << ","; } first = false; ss << (v - 1); } } ss << "}"; return ss.str(); } /* * IntMap Test0; IntMap Test1(10); IntMap Test2(4, .5f); Test2.put(10, 1); Test2.put(21, 2); Test2.put(31, 6); if (Test2.isEmpty()) { cout << "Empty" << endl; } cout << "size: "; cout << Test2.size() << endl; cout << Test2.toString() << endl; cout << Test2.get(21) << endl; Test2.put(21, 7); cout << Test2.get(21) << endl; if (Test2.contains(24)) { cout << "HAVE 24" << endl; } if (Test2.contains(10)) { cout << "HAVE 10" << endl; } if (Test2.add(22)) { cout << "added 22" << endl; } if (Test2.add(21)) { cout << "Added over 21" << endl; } cout << Test2.toString() << endl; cout << Test2.get(22) << endl; cout << Test2.get(21) << endl; cout << Test2.mDelete(22) << endl; cout << Test2.mDelete(43) << endl; Test1.put(10, 1); Test1.put(3, 54); Test1.put(22, 10); Test1.put(31, 2); vector<IntMap> i; i.push_back(Test1); vector<IntMap> j; j.push_back(Test2); IntStack list = Test2.intersect(i, j); cout << list.toString() << endl; * * * */end test/ <|endoftext|>
<commit_before>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <fstream> #include <string> #include "gflags/gflags.h" #include "google/protobuf/util/json_util.h" #include "tools/render/trace_program.h" enum InputFormat { INPUT_JSON, INPUT_QTR, }; namespace { InputFormat GuessInputFileFormat(const std::string& filename) { if (filename.find(".json") != std::string::npos) { return INPUT_JSON; } else { return INPUT_QTR; } } } // namespace // render_trace renders the specified trace file using an OpenGL-based viewer. int main(int argc, char* argv[]) { gflags::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); CHECK_GE(argc, 2) << "Specify file path"; auto trace = absl::make_unique<quic_trace::Trace>(); { std::string filename(argv[1]); std::ifstream f(filename); if (GuessInputFileFormat(filename) == INPUT_QTR) { trace->ParseFromIstream(&f); } else { std::istreambuf_iterator<char> it(f); std::istreambuf_iterator<char> end; auto status = google::protobuf::util::JsonStringToMessage( std::string(it, end), &*trace); if (!status.ok()) { LOG(FATAL) << "Failed to load '" << filename << "': " << status; } } } quic_trace::render::TraceProgram program; program.LoadTrace(std::move(trace)); program.Loop(); return 0; } <commit_msg>amend b6ba289bf6925fe2a3c667b5f927622737e70e01; switch is better<commit_after>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <fstream> #include <string> #include "gflags/gflags.h" #include "google/protobuf/util/json_util.h" #include "tools/render/trace_program.h" enum InputFormat { INPUT_JSON, INPUT_QTR, }; namespace { InputFormat GuessInputFileFormat(const std::string& filename) { if (filename.find(".json") != std::string::npos) { return INPUT_JSON; } else { return INPUT_QTR; } } } // namespace // render_trace renders the specified trace file using an OpenGL-based viewer. int main(int argc, char* argv[]) { gflags::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); CHECK_GE(argc, 2) << "Specify file path"; auto trace = absl::make_unique<quic_trace::Trace>(); { std::string filename(argv[1]); std::ifstream f(filename); switch (GuessInputFileFormat(filename)) { case INPUT_QTR: { trace->ParseFromIstream(&f); break; } case INPUT_JSON: { std::istreambuf_iterator<char> it(f); std::istreambuf_iterator<char> end; auto status = google::protobuf::util::JsonStringToMessage( std::string(it, end), &*trace); if (!status.ok()) { LOG(FATAL) << "Failed to load '" << filename << "': " << status; } break; } default: LOG(FATAL) << "Unexpected format"; } } quic_trace::render::TraceProgram program; program.LoadTrace(std::move(trace)); program.Loop(); return 0; } <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone 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 Street, Fifth Floor, Boston, MA 02110-1301 USA #include "global_id_generator.hpp" #include <cassert> #ifndef ATOMIC_I8_SUPPORT #include <pficommon/concurrent/lock.h> #endif namespace jubatus { namespace common { global_id_generator::global_id_generator(): is_standalone_(true), counter_(0) {} global_id_generator::global_id_generator(bool is_standalone): is_standalone_(is_standalone), counter_(0) {} global_id_generator::~global_id_generator() {} uint64_t global_id_generator::generate() { if(is_standalone_){ #ifdef ATOMIC_I8_SUPPORT return __sync_fetch_and_add(&counter_, 1); #else pfi::concurrent::scoped_lock lk(counter_mutex_); return ++counter_; #endif }else{ #ifdef HAVE_ZOOKEEPER_H // FIXME: to be implemented return ls_->create_id(path_); #else // never reaches here assert(is_standalone_); return 0; // dummy to remove warning #endif } } void global_id_generator::set_ls(cshared_ptr<lock_service>& ls, const std::string& path_prefix) { #ifdef HAVE_ZOOKEEPER_H path_ = path_prefix + "/id_generator"; ls_ = ls; ls_->create(path_); #endif } }} <commit_msg>check if server is standalone mode in set_ls (fix #149)<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone 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 Street, Fifth Floor, Boston, MA 02110-1301 USA #include "global_id_generator.hpp" #include <cassert> #ifndef ATOMIC_I8_SUPPORT #include <pficommon/concurrent/lock.h> #endif namespace jubatus { namespace common { global_id_generator::global_id_generator(): is_standalone_(true), counter_(0) {} global_id_generator::global_id_generator(bool is_standalone): is_standalone_(is_standalone), counter_(0) {} global_id_generator::~global_id_generator() {} uint64_t global_id_generator::generate() { if(is_standalone_){ #ifdef ATOMIC_I8_SUPPORT return __sync_fetch_and_add(&counter_, 1); #else pfi::concurrent::scoped_lock lk(counter_mutex_); return ++counter_; #endif }else{ #ifdef HAVE_ZOOKEEPER_H // FIXME: to be implemented return ls_->create_id(path_); #else // never reaches here assert(is_standalone_); return 0; // dummy to remove warning #endif } } void global_id_generator::set_ls(cshared_ptr<lock_service>& ls, const std::string& path_prefix) { #ifdef HAVE_ZOOKEEPER_H if (! is_standalone_) { path_ = path_prefix + "/id_generator"; ls_ = ls; ls_->create(path_); } #endif } }} <|endoftext|>
<commit_before>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2015 * * * * 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 "gtest/gtest.h" #include <ghoul/cmdparser/cmdparser> #include <ghoul/filesystem/filesystem> #include <ghoul/logging/logging> #include <ghoul/misc/dictionary.h> #include <ghoul/lua/ghoul_lua.h> #include <test_common.inl> //#include <test_spicemanager.inl> #include <test_scenegraphloader.inl> //#include <test_luaconversions.inl> //#include <test_powerscalecoordinates.inl> #include <openspace/engine/openspaceengine.h> #include <openspace/engine/configurationmanager.h> #include <openspace/util/constants.h> #include <openspace/util/factorymanager.h> #include <openspace/util/time.h> #include <iostream> using namespace ghoul::cmdparser; using namespace ghoul::filesystem; using namespace ghoul::logging; namespace { std::string _loggerCat = "OpenSpaceTest"; } int main(int argc, char** argv) { std::vector<std::string> args; std::string glVersion; openspace::OpenSpaceEngine::create(argc, argv, args, glVersion); //LogManager::initialize(LogManager::LogLevel::Debug); //LogMgr.addLog(new ConsoleLog); //FileSystem::initialize(); //std::string configurationFilePath = ""; //LDEBUG("Finding configuration"); //if (!openspace::OpenSpaceEngine::findConfiguration(configurationFilePath)) { // LFATAL("Could not find OpenSpace configuration file!"); // assert(false); //} ////LINFO("Configuration file found: " << FileSys.absolutePath(configurationFilePath)); //openspace::ConfigurationManager manager; //manager.loadFromFile(configurationFilePath); //openspace::FactoryManager::initialize(); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Fix OpenSpaceTest<commit_after>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2015 * * * * 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 "gtest/gtest.h" #include <ghoul/cmdparser/cmdparser> #include <ghoul/filesystem/filesystem> #include <ghoul/logging/logging> #include <ghoul/misc/dictionary.h> #include <ghoul/lua/ghoul_lua.h> #include <test_common.inl> //#include <test_spicemanager.inl> #include <test_scenegraphloader.inl> //#include <test_luaconversions.inl> //#include <test_powerscalecoordinates.inl> #include <openspace/engine/openspaceengine.h> #include <openspace/engine/configurationmanager.h> #include <openspace/util/constants.h> #include <openspace/util/factorymanager.h> #include <openspace/util/time.h> #include <iostream> using namespace ghoul::cmdparser; using namespace ghoul::filesystem; using namespace ghoul::logging; namespace { std::string _loggerCat = "OpenSpaceTest"; } int main(int argc, char** argv) { std::vector<std::string> args; openspace::OpenSpaceEngine::create(argc, argv, args); //LogManager::initialize(LogManager::LogLevel::Debug); //LogMgr.addLog(new ConsoleLog); //FileSystem::initialize(); //std::string configurationFilePath = ""; //LDEBUG("Finding configuration"); //if (!openspace::OpenSpaceEngine::findConfiguration(configurationFilePath)) { // LFATAL("Could not find OpenSpace configuration file!"); // assert(false); //} ////LINFO("Configuration file found: " << FileSys.absolutePath(configurationFilePath)); //openspace::ConfigurationManager manager; //manager.loadFromFile(configurationFilePath); //openspace::FactoryManager::initialize(); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include <boost/algorithm/string/find.hpp> #include <boost/filesystem.hpp> #include <regex> #include "androidmanager.h" #include "utilities/utils.h" #include <boost/phoenix/stl/algorithm/transformation.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/qi.hpp> namespace qi = boost::spirit::qi; namespace fs = boost::filesystem; const std::string AndroidManager::data_ota_package_dir_ = "/data/ota_package"; Json::Value AndroidManager::getInstalledPackages() const { using boost::phoenix::copy; using qi::_1; using qi::char_; std::string pm_output; Json::Value packages(Json::arrayValue); if (0 != Utils::shell("pm list packages --show-versioncode", &pm_output)) { return packages; } qi::rule<std::string::iterator, std::vector<char>()> char_seq = qi::lexeme[*(char_ - ' ')]; std::istringstream pv_lines(pm_output); for (std::string line; std::getline(pv_lines, line);) { std::string p, v; if (qi::parse(line.begin(), line.end(), ("package:" >> char_seq[copy(_1, std::back_inserter(p))] >> ' ' >> "versionCode:" >> char_seq[copy(_1, std::back_inserter(v))]))) { Json::Value package; package["name"] = p; package["version"] = v; packages.append(package); } } return packages; } Uptane::Target AndroidManager::getCurrent() const { std::string getprop_output; std::smatch hash_match; if (0 != Utils::shell("getprop ota.last_installed_package_file", &getprop_output) || !std::regex_search(getprop_output, hash_match, std::regex("\\.[[:xdigit:]]+"))) { return Uptane::Target::Unknown(); } const std::string installed_package_hash = hash_match[0].str().substr(1); std::vector<Uptane::Target> installed_versions; storage_->loadPrimaryInstalledVersions(&installed_versions, nullptr, nullptr); for (const auto& target : installed_versions) { if (target.sha256Hash() == installed_package_hash) { return target; } } return Uptane::Target::Unknown(); } data::InstallationResult AndroidManager::install(const Uptane::Target& target) const { LOG_INFO << "Begin Android package installation"; auto package_filename = (fs::path(data_ota_package_dir_) / target.filename()).string() + "." + target.sha256Hash(); std::ofstream package_file(package_filename.c_str()); if (!package_file.good()) { throw std::runtime_error(std::string("Error opening file ") + package_filename); } package_file << *storage_->openTargetFile(target); if (bootloader_ != nullptr) { bootloader_->rebootFlagSet(); } LOG_INFO << "Performing sync()"; sync(); return data::InstallationResult(data::ResultCode::Numeric::kNeedCompletion, "need reboot"); } data::InstallationResult AndroidManager::finalizeInstall(const Uptane::Target& target) const { std::string ota_package_file_path = GetOTAPackageFilePath(target.sha256Hash()); if (!ota_package_file_path.empty()) fs::remove(ota_package_file_path); std::string errorMessage{"n/a"}; if (installationAborted(&errorMessage)) { return data::InstallationResult(data::ResultCode::Numeric::kInstallFailed, errorMessage); } return data::InstallationResult(data::ResultCode::Numeric::kOk, "package installation successfully finalized"); } std::string AndroidManager::GetOTAPackageFilePath(const std::string& hash) { fs::directory_iterator entryItEnd, entryIt{fs::path(data_ota_package_dir_)}; for (; entryIt != entryItEnd; ++entryIt) { auto& entry_path = entryIt->path(); if (boost::filesystem::is_directory(*entryIt)) { continue; } auto ext = entry_path.extension().string(); ext = ext.substr(1); if (ext == hash) { return entry_path.string(); } } return std::string{}; } bool AndroidManager::installationAborted(std::string* errorMessage) const { std::string installation_log_file{"/cache/recovery/last_install"}; std::ifstream log(installation_log_file.c_str()); if (!log.good()) { throw std::runtime_error(std::string("Error opening file ") + installation_log_file); } for (std::string line; std::getline(log, line);) { if (boost::algorithm::find_first(line, "error:")) { int error_code = std::stoi(line.substr(6)); if (error_code != 0) { *errorMessage = std::string("Error code: ") + std::to_string(error_code); return true; } } } return false; } <commit_msg>Precise prop value parsing to find installed target hash<commit_after>#include <boost/algorithm/string/find.hpp> #include <boost/filesystem.hpp> #include <forward_list> #include "androidmanager.h" #include "utilities/utils.h" #include <boost/phoenix/stl/algorithm/transformation.hpp> #include <boost/spirit/include/phoenix_container.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/qi.hpp> namespace qi = boost::spirit::qi; namespace fs = boost::filesystem; const std::string AndroidManager::data_ota_package_dir_ = "/data/ota_package"; Json::Value AndroidManager::getInstalledPackages() const { using boost::phoenix::copy; using qi::_1; using qi::char_; std::string pm_output; Json::Value packages(Json::arrayValue); if (0 != Utils::shell("pm list packages --show-versioncode", &pm_output)) { return packages; } qi::rule<std::string::iterator, std::vector<char>()> char_seq = qi::lexeme[*(char_ - ' ')]; std::istringstream pv_lines(pm_output); for (std::string line; std::getline(pv_lines, line);) { std::string p, v; if (qi::parse(line.begin(), line.end(), ("package:" >> char_seq[copy(_1, std::back_inserter(p))] >> ' ' >> "versionCode:" >> char_seq[copy(_1, std::back_inserter(v))]))) { Json::Value package; package["name"] = p; package["version"] = v; packages.append(package); } } return packages; } Uptane::Target AndroidManager::getCurrent() const { using boost::phoenix::push_front; using boost::spirit::ascii::xdigit; using qi::_1; std::string getprop_output; if (0 == Utils::shell("getprop ota.last_installed_package_file", &getprop_output)) { std::forward_list<char> hash; qi::phrase_parse(getprop_output.crbegin(), getprop_output.crend(), *(xdigit[push_front(boost::phoenix::ref(hash), _1)]), boost::spirit::ascii::cntrl); std::vector<Uptane::Target> installed_versions; storage_->loadPrimaryInstalledVersions(&installed_versions, nullptr, nullptr); for (const auto& target : installed_versions) { if (std::equal(hash.cbegin(), hash.cend(), target.sha256Hash().cbegin())) { return target; } } } return Uptane::Target::Unknown(); } data::InstallationResult AndroidManager::install(const Uptane::Target& target) const { LOG_INFO << "Begin Android package installation"; auto package_filename = (fs::path(data_ota_package_dir_) / target.filename()).string() + "." + target.sha256Hash(); std::ofstream package_file(package_filename.c_str()); if (!package_file.good()) { throw std::runtime_error(std::string("Error opening file ") + package_filename); } package_file << *storage_->openTargetFile(target); if (bootloader_ != nullptr) { bootloader_->rebootFlagSet(); } LOG_INFO << "Performing sync()"; sync(); return data::InstallationResult(data::ResultCode::Numeric::kNeedCompletion, "need reboot"); } data::InstallationResult AndroidManager::finalizeInstall(const Uptane::Target& target) const { std::string ota_package_file_path = GetOTAPackageFilePath(target.sha256Hash()); if (!ota_package_file_path.empty()) fs::remove(ota_package_file_path); std::string errorMessage{"n/a"}; if (installationAborted(&errorMessage)) { return data::InstallationResult(data::ResultCode::Numeric::kInstallFailed, errorMessage); } return data::InstallationResult(data::ResultCode::Numeric::kOk, "package installation successfully finalized"); } std::string AndroidManager::GetOTAPackageFilePath(const std::string& hash) { fs::directory_iterator entryItEnd, entryIt{fs::path(data_ota_package_dir_)}; for (; entryIt != entryItEnd; ++entryIt) { auto& entry_path = entryIt->path(); if (boost::filesystem::is_directory(*entryIt)) { continue; } auto ext = entry_path.extension().string(); ext = ext.substr(1); if (ext == hash) { return entry_path.string(); } } return std::string{}; } bool AndroidManager::installationAborted(std::string* errorMessage) const { std::string installation_log_file{"/cache/recovery/last_install"}; std::ifstream log(installation_log_file.c_str()); if (!log.good()) { throw std::runtime_error(std::string("Error opening file ") + installation_log_file); } for (std::string line; std::getline(log, line);) { if (boost::algorithm::find_first(line, "error:")) { int error_code = std::stoi(line.substr(6)); if (error_code != 0) { *errorMessage = std::string("Error code: ") + std::to_string(error_code); return true; } } } return false; } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: VDataSeries.hxx,v $ * $Revision: 1.20 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _CHART2_VIEW_DATASERIES_HXX #define _CHART2_VIEW_DATASERIES_HXX #include "PropertyMapper.hxx" #include <vector> //for auto_ptr #include <memory> #include <com/sun/star/chart2/DataPointLabel.hpp> #include <com/sun/star/chart2/Symbol.hpp> #include <com/sun/star/chart2/StackingDirection.hpp> #include <com/sun/star/chart2/data/XLabeledDataSequence.hpp> #include <com/sun/star/chart2/XChartType.hpp> #include <com/sun/star/chart2/XDataSeries.hpp> #include <com/sun/star/drawing/HomogenMatrix.hpp> #include <com/sun/star/drawing/PolyPolygonShape3D.hpp> #include <com/sun/star/drawing/XShape.hpp> #include <com/sun/star/drawing/XShapes.hpp> #include <cppuhelper/weakref.hxx> //............................................................................. namespace chart { //............................................................................. //----------------------------------------------------------------------------- /** */ class VDataSequence { public: void init( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDataSequence >& xModel); bool is() const; void clear(); double getValue( sal_Int32 index ) const; sal_Int32 detectNumberFormatKey( sal_Int32 index ) const; sal_Int32 getLength() const; ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDataSequence > Model; mutable ::com::sun::star::uno::Sequence< double > Doubles; }; class VDataSeries { public: VDataSeries( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& xDataSeries ); virtual ~VDataSeries(); ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > getModel() const; void setCategoryXAxis(); void setParticle( const rtl::OUString& rSeriesParticle ); void setGlobalSeriesIndex( sal_Int32 nGlobalSeriesIndex ); void setDiagramReferenceSize( const ::com::sun::star::awt::Size & rDiagramRefSize ); sal_Int32 getTotalPointCount() const; double getX( sal_Int32 index ) const; double getY( sal_Int32 index ) const; double getY_Min( sal_Int32 index ) const; double getY_Max( sal_Int32 index ) const; double getY_First( sal_Int32 index ) const; double getY_Last( sal_Int32 index ) const; double getMinimumofAllDifferentYValues( sal_Int32 index ) const; double getMaximumofAllDifferentYValues( sal_Int32 index ) const; ::com::sun::star::uno::Sequence< double > getAllX() const; ::com::sun::star::uno::Sequence< double > getAllY() const; bool hasExplicitNumberFormat( sal_Int32 nPointIndex, bool bForPercentage ) const; sal_Int32 getExplicitNumberFormat( sal_Int32 nPointIndex, bool bForPercentage ) const; sal_Int32 detectNumberFormatKey( sal_Int32 nPointIndex ) const; sal_Int32 getLabelPlacement( sal_Int32 nPointIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType , sal_Int32 nDimensionCount, sal_Bool bSwapXAndY ) const; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > getPropertiesOfPoint( sal_Int32 index ) const; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > getPropertiesOfSeries() const; ::com::sun::star::chart2::Symbol* getSymbolProperties( sal_Int32 index ) const; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > getYErrorBarProperties( sal_Int32 index ) const; bool hasPointOwnColor( sal_Int32 index ) const; ::com::sun::star::chart2::StackingDirection getStackingDirection() const; sal_Int32 getAttachedAxisIndex() const; void setAttachedAxisIndex( sal_Int32 nAttachedAxisIndex ); void doSortByXValues(); void setConnectBars( sal_Bool bConnectBars ); sal_Bool getConnectBars() const; void setGroupBarsPerAxis( sal_Bool bGroupBarsPerAxis ); sal_Bool getGroupBarsPerAxis() const; void setStartingAngle( sal_Int32 nStartingAngle ); sal_Int32 getStartingAngle() const; //this is only temporarily here for area chart: ::com::sun::star::drawing::PolyPolygonShape3D m_aPolyPolygonShape3D; sal_Int32 m_nPolygonIndex; double m_fLogicMinX; double m_fLogicMaxX; // //this is here for deep stacking: double m_fLogicZPos;//from 0 to series count -1 // rtl::OUString getCID() const; rtl::OUString getSeriesParticle() const; rtl::OUString getPointCID_Stub() const; rtl::OUString getErrorBarsCID() const; rtl::OUString getLabelsCID() const; rtl::OUString getLabelCID_Stub() const; rtl::OUString getDataCurveCID( sal_Int32 nCurveIndex, bool bAverageLine ) const; ::com::sun::star::chart2::DataPointLabel* getDataPointLabelIfLabel( sal_Int32 index ) const; bool getTextLabelMultiPropertyLists( sal_Int32 index, tNameSequence*& pPropNames, tAnySequence*& pPropValues ) const; rtl::OUString getDataCurveEquationCID( sal_Int32 nCurveIndex ) const; bool isAttributedDataPoint( sal_Int32 index ) const; bool isVaryColorsByPoint() const; void releaseShapes(); private: //methods VDataSeries(); ::com::sun::star::chart2::DataPointLabel* getDataPointLabel( sal_Int32 index ) const; void adaptPointCache( sal_Int32 nNewPointIndex ) const; public: //member ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xGroupShape; ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xLabelsGroupShape; ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xErrorBarsGroupShape; //the following group shapes will be created as children of m_xGroupShape on demand //they can be used to assure that some parts of a series shape are always in front of others (e.g. symbols in front of lines) ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xFrontSubGroupShape; ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xBackSubGroupShape; private: //member ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > m_xDataSeries; ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XLabeledDataSequence > > m_aDataSequences; //all points given by the model data (here are not only the visible points meant) sal_Int32 m_nPointCount; VDataSequence m_aValues_X; VDataSequence m_aValues_Y; VDataSequence m_aValues_Z; VDataSequence m_aValues_Y_Min; VDataSequence m_aValues_Y_Max; VDataSequence m_aValues_Y_First; VDataSequence m_aValues_Y_Last; ::com::sun::star::uno::Sequence< sal_Int32 > m_aAttributedDataPointIndexList; ::com::sun::star::chart2::StackingDirection m_eStackingDirection; sal_Int32 m_nAxisIndex;//indicates wether this is attached to a main or secondary axis sal_Bool m_bConnectBars; sal_Bool m_bGroupBarsPerAxis; sal_Int32 m_nStartingAngle; rtl::OUString m_aSeriesParticle; rtl::OUString m_aCID; rtl::OUString m_aPointCID_Stub; rtl::OUString m_aLabelCID_Stub; sal_Int32 m_nGlobalSeriesIndex; //some cached values for data labels as they are very expensive mutable ::std::auto_ptr< ::com::sun::star::chart2::DataPointLabel > m_apLabel_Series; mutable ::std::auto_ptr< tNameSequence > m_apLabelPropNames_Series; mutable ::std::auto_ptr< tAnySequence > m_apLabelPropValues_Series; mutable ::std::auto_ptr< ::com::sun::star::chart2::Symbol > m_apSymbolProperties_Series; mutable ::std::auto_ptr< ::com::sun::star::chart2::DataPointLabel > m_apLabel_AttributedPoint; mutable ::std::auto_ptr< tNameSequence > m_apLabelPropNames_AttributedPoint; mutable ::std::auto_ptr< tAnySequence > m_apLabelPropValues_AttributedPoint; mutable ::std::auto_ptr< ::com::sun::star::chart2::Symbol > m_apSymbolProperties_AttributedPoint; mutable ::std::auto_ptr< ::com::sun::star::chart2::Symbol > m_apSymbolProperties_InvisibleSymbolForSelection; mutable sal_Int32 m_nCurrentAttributedPoint; ::com::sun::star::awt::Size m_aReferenceSize; // }; //............................................................................. } //namespace chart //............................................................................. #endif <commit_msg>INTEGRATION: CWS chart27 (1.20.28); FILE MERGED 2008/06/09 13:36:25 iha 1.20.28.1: #i72331 Wrong error indicator placement for standard deviation<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: VDataSeries.hxx,v $ * $Revision: 1.21 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _CHART2_VIEW_DATASERIES_HXX #define _CHART2_VIEW_DATASERIES_HXX #include "PropertyMapper.hxx" #include <vector> //for auto_ptr #include <memory> #include <com/sun/star/chart2/DataPointLabel.hpp> #include <com/sun/star/chart2/Symbol.hpp> #include <com/sun/star/chart2/StackingDirection.hpp> #include <com/sun/star/chart2/data/XLabeledDataSequence.hpp> #include <com/sun/star/chart2/XChartType.hpp> #include <com/sun/star/chart2/XDataSeries.hpp> #include <com/sun/star/drawing/HomogenMatrix.hpp> #include <com/sun/star/drawing/PolyPolygonShape3D.hpp> #include <com/sun/star/drawing/XShape.hpp> #include <com/sun/star/drawing/XShapes.hpp> #include <cppuhelper/weakref.hxx> //............................................................................. namespace chart { //............................................................................. //----------------------------------------------------------------------------- /** */ class VDataSequence { public: void init( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDataSequence >& xModel); bool is() const; void clear(); double getValue( sal_Int32 index ) const; sal_Int32 detectNumberFormatKey( sal_Int32 index ) const; sal_Int32 getLength() const; ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDataSequence > Model; mutable ::com::sun::star::uno::Sequence< double > Doubles; }; class VDataSeries { public: VDataSeries( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& xDataSeries ); virtual ~VDataSeries(); ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > getModel() const; void setCategoryXAxis(); void setParticle( const rtl::OUString& rSeriesParticle ); void setGlobalSeriesIndex( sal_Int32 nGlobalSeriesIndex ); void setDiagramReferenceSize( const ::com::sun::star::awt::Size & rDiagramRefSize ); sal_Int32 getTotalPointCount() const; double getX( sal_Int32 index ) const; double getY( sal_Int32 index ) const; double getY_Min( sal_Int32 index ) const; double getY_Max( sal_Int32 index ) const; double getY_First( sal_Int32 index ) const; double getY_Last( sal_Int32 index ) const; double getMinimumofAllDifferentYValues( sal_Int32 index ) const; double getMaximumofAllDifferentYValues( sal_Int32 index ) const; ::com::sun::star::uno::Sequence< double > getAllX() const; ::com::sun::star::uno::Sequence< double > getAllY() const; double getYMeanValue() const; bool hasExplicitNumberFormat( sal_Int32 nPointIndex, bool bForPercentage ) const; sal_Int32 getExplicitNumberFormat( sal_Int32 nPointIndex, bool bForPercentage ) const; sal_Int32 detectNumberFormatKey( sal_Int32 nPointIndex ) const; sal_Int32 getLabelPlacement( sal_Int32 nPointIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType , sal_Int32 nDimensionCount, sal_Bool bSwapXAndY ) const; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > getPropertiesOfPoint( sal_Int32 index ) const; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > getPropertiesOfSeries() const; ::com::sun::star::chart2::Symbol* getSymbolProperties( sal_Int32 index ) const; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > getYErrorBarProperties( sal_Int32 index ) const; bool hasPointOwnColor( sal_Int32 index ) const; ::com::sun::star::chart2::StackingDirection getStackingDirection() const; sal_Int32 getAttachedAxisIndex() const; void setAttachedAxisIndex( sal_Int32 nAttachedAxisIndex ); void doSortByXValues(); void setConnectBars( sal_Bool bConnectBars ); sal_Bool getConnectBars() const; void setGroupBarsPerAxis( sal_Bool bGroupBarsPerAxis ); sal_Bool getGroupBarsPerAxis() const; void setStartingAngle( sal_Int32 nStartingAngle ); sal_Int32 getStartingAngle() const; //this is only temporarily here for area chart: ::com::sun::star::drawing::PolyPolygonShape3D m_aPolyPolygonShape3D; sal_Int32 m_nPolygonIndex; double m_fLogicMinX; double m_fLogicMaxX; // //this is here for deep stacking: double m_fLogicZPos;//from 0 to series count -1 // rtl::OUString getCID() const; rtl::OUString getSeriesParticle() const; rtl::OUString getPointCID_Stub() const; rtl::OUString getErrorBarsCID() const; rtl::OUString getLabelsCID() const; rtl::OUString getLabelCID_Stub() const; rtl::OUString getDataCurveCID( sal_Int32 nCurveIndex, bool bAverageLine ) const; ::com::sun::star::chart2::DataPointLabel* getDataPointLabelIfLabel( sal_Int32 index ) const; bool getTextLabelMultiPropertyLists( sal_Int32 index, tNameSequence*& pPropNames, tAnySequence*& pPropValues ) const; rtl::OUString getDataCurveEquationCID( sal_Int32 nCurveIndex ) const; bool isAttributedDataPoint( sal_Int32 index ) const; bool isVaryColorsByPoint() const; void releaseShapes(); private: //methods VDataSeries(); ::com::sun::star::chart2::DataPointLabel* getDataPointLabel( sal_Int32 index ) const; void adaptPointCache( sal_Int32 nNewPointIndex ) const; public: //member ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xGroupShape; ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xLabelsGroupShape; ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xErrorBarsGroupShape; //the following group shapes will be created as children of m_xGroupShape on demand //they can be used to assure that some parts of a series shape are always in front of others (e.g. symbols in front of lines) ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xFrontSubGroupShape; ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xBackSubGroupShape; private: //member ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > m_xDataSeries; ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XLabeledDataSequence > > m_aDataSequences; //all points given by the model data (here are not only the visible points meant) sal_Int32 m_nPointCount; VDataSequence m_aValues_X; VDataSequence m_aValues_Y; VDataSequence m_aValues_Z; VDataSequence m_aValues_Y_Min; VDataSequence m_aValues_Y_Max; VDataSequence m_aValues_Y_First; VDataSequence m_aValues_Y_Last; mutable double m_fYMeanValue; ::com::sun::star::uno::Sequence< sal_Int32 > m_aAttributedDataPointIndexList; ::com::sun::star::chart2::StackingDirection m_eStackingDirection; sal_Int32 m_nAxisIndex;//indicates wether this is attached to a main or secondary axis sal_Bool m_bConnectBars; sal_Bool m_bGroupBarsPerAxis; sal_Int32 m_nStartingAngle; rtl::OUString m_aSeriesParticle; rtl::OUString m_aCID; rtl::OUString m_aPointCID_Stub; rtl::OUString m_aLabelCID_Stub; sal_Int32 m_nGlobalSeriesIndex; //some cached values for data labels as they are very expensive mutable ::std::auto_ptr< ::com::sun::star::chart2::DataPointLabel > m_apLabel_Series; mutable ::std::auto_ptr< tNameSequence > m_apLabelPropNames_Series; mutable ::std::auto_ptr< tAnySequence > m_apLabelPropValues_Series; mutable ::std::auto_ptr< ::com::sun::star::chart2::Symbol > m_apSymbolProperties_Series; mutable ::std::auto_ptr< ::com::sun::star::chart2::DataPointLabel > m_apLabel_AttributedPoint; mutable ::std::auto_ptr< tNameSequence > m_apLabelPropNames_AttributedPoint; mutable ::std::auto_ptr< tAnySequence > m_apLabelPropValues_AttributedPoint; mutable ::std::auto_ptr< ::com::sun::star::chart2::Symbol > m_apSymbolProperties_AttributedPoint; mutable ::std::auto_ptr< ::com::sun::star::chart2::Symbol > m_apSymbolProperties_InvisibleSymbolForSelection; mutable sal_Int32 m_nCurrentAttributedPoint; ::com::sun::star::awt::Size m_aReferenceSize; // }; //............................................................................. } //namespace chart //............................................................................. #endif <|endoftext|>
<commit_before>/* Copyright 2012 Ulrik Mikaelsson <ulrik.mikaelsson@gmail.com> 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 "client.hpp" #include <boost/assert.hpp> #include <iostream> #include <log4cplus/logger.h> #include <log4cplus/loggingmacros.h> #include "server.hpp" #include "../../lib/magneturi.h" #include "../../lib/random.h" const size_t MAX_ASSETS = 1024; const size_t MAX_CHUNK = 64*1024; using namespace std; namespace fs = boost::filesystem; using namespace bithorded; namespace bithorded { log4cplus::Logger clientLogger = log4cplus::Logger::getInstance("client"); } Client::Client( Server& server) : bithorde::Client(server.ioService(), server.name()), _server(server) { } size_t Client::serverAssets() const { size_t res = 0; for (auto iter = _assets.begin(); iter != _assets.end(); iter++) { if (*iter) res++; } return res; } void Client::describe(management::Info& tgt) const { tgt << '+' << clientAssets().size() << '-' << serverAssets() << ", incoming: " << stats->incomingBitrateCurrent << ", outgoing: " << stats->outgoingBitrateCurrent; } void Client::inspect(management::InfoList& tgt) const { tgt.append("incomingCurrent") << stats->incomingBitrateCurrent.autoScale() << ", " << stats->incomingMessagesCurrent.autoScale(); tgt.append("outgoingCurrent") << stats->outgoingBitrateCurrent.autoScale() << ", " << stats->outgoingMessagesCurrent.autoScale(); tgt.append("incomingTotal") << stats->incomingBytes.autoScale() << ", " << stats->incomingMessages.autoScale(); tgt.append("outgoingTotal") << stats->outgoingBytes.autoScale() << ", " << stats->outgoingMessages.autoScale(); tgt.append("assetResponseTime") << assetResponseTime; for (auto iter=clientAssets().begin(); iter != clientAssets().end(); iter++) { ostringstream name; name << '+' << iter->first; auto& node = tgt.append(name.str()); if (auto asset = iter->second->readAsset()) node << bithorde::Status_Name(asset->status) << ", " << asset->requestIds(); else node << "<stale>"; } for (size_t i=0; i < _assets.size(); i++) { if (auto& asset = _assets[i]) { ostringstream name; name << '-' << i; tgt.append(name.str(), *asset); } } } bool Client::requestsAsset(const BitHordeIds& ids) { for (auto iter=_assets.begin(); iter!=_assets.end(); iter++) { auto asset = *iter; if (asset) { BitHordeIds assetIds; if (asset->getIds(assetIds) && idsOverlap(assetIds, ids)) return true; } } return false; } void Client::onMessage(const bithorde::HandShake& msg) { bithorde::Client::onMessage(msg); LOG4CPLUS_INFO(clientLogger, "Connected: " << msg.name()); } void Client::onMessage(const bithorde::BindWrite& msg) { auto h = msg.handle(); if ((_assets.size() > h) && _assets[h]) { clearAsset(h); } if (msg.has_linkpath()) { fs::path path(msg.linkpath()); if (path.is_absolute()) { if (auto asset = _server.async_linkAsset(path)) { LOG4CPLUS_INFO(clientLogger, "Linking " << path); assignAsset(msg.handle(), asset); } else { LOG4CPLUS_ERROR(clientLogger, "Upload did not match any allowed assetStore: " << path); informAssetStatus(msg.handle(), bithorde::ERROR); } } else { LOG4CPLUS_ERROR(clientLogger, "Relative links not supported" << path); informAssetStatus(msg.handle(), bithorde::ERROR); } } else { if (auto asset = _server.prepareUpload(msg.size())) { LOG4CPLUS_INFO(clientLogger, "Ready for upload"); assignAsset(msg.handle(), asset); } else { informAssetStatus(msg.handle(), bithorde::NORESOURCES); } } } void Client::onMessage(bithorde::BindRead& msg) { auto h = msg.handle(); if ((_assets.size() > h) && _assets[h]) { clearAsset(h); } if (msg.ids_size() > 0) { // Trying to open LOG4CPLUS_INFO(clientLogger, peerName() << ':' << h << " requested: " << MagnetURI(msg)); if (!msg.has_uuid()) msg.set_uuid(rand64()); try { auto asset = _server.async_findAsset(msg); if (asset) assignAsset(h, asset); else informAssetStatus(h, bithorde::NOTFOUND); } catch (bithorded::BindError e) { informAssetStatus(h, e.status); } } else { // Trying to close informAssetStatus(h, bithorde::NOTFOUND); } } void Client::onMessage(const bithorde::Read::Request& msg) { IAsset::Ptr& asset = getAsset(msg.handle()); if (asset) { uint64_t offset = msg.offset(); size_t size = msg.size(); if (size > MAX_CHUNK) size = MAX_CHUNK; // Raw pointer to this should be fine here, since asset has ownership of this. (Through member Ptr client) auto onComplete = boost::bind(&Client::onReadResponse, this, msg, _1, _2, bithorde::Message::in(msg.timeout())); asset->async_read(offset, size, msg.timeout(), onComplete); } else { bithorde::Read::Response resp; resp.set_reqid(msg.reqid()); resp.set_status(bithorde::INVALID_HANDLE); sendMessage(bithorde::Connection::ReadResponse, resp); } } void Client::onMessage(const bithorde::DataSegment& msg) { IAsset::Ptr& asset_ = getAsset(msg.handle()); if (asset_) { bithorded::cache::CachedAsset::Ptr asset = dynamic_pointer_cast<bithorded::cache::CachedAsset>(asset_); if (asset) { asset->write(msg.offset(), msg.content()); } else { LOG4CPLUS_INFO(clientLogger, peerName() << ':' << msg.handle() << " is not an upload-asset"); } } else { LOG4CPLUS_INFO(clientLogger, peerName() << ':' << msg.handle() << " is not bound to any asset"); } return; } void Client::onReadResponse(const bithorde::Read::Request& req, int64_t offset, const std::string& data, bithorde::Message::Deadline t) { bithorde::Read::Response resp; resp.set_reqid(req.reqid()); if ((offset >= 0) && (data.size() > 0)) { resp.set_status(bithorde::SUCCESS); resp.set_offset(offset); resp.set_content(data); } else { resp.set_status(bithorde::NOTFOUND); } if (!sendMessage(bithorde::Connection::ReadResponse, resp, t)) { LOG4CPLUS_WARN(clientLogger, "Failed to write data chunk, (offset " << offset << ')'); } } void Client::informAssetStatus(bithorde::Asset::Handle h, bithorde::Status s) { bithorde::AssetStatus resp; resp.set_handle(h); resp.set_status(s); sendMessage(bithorde::Connection::AssetStatus, resp, bithorde::Message::NEVER, true); } void Client::informAssetStatusUpdate(bithorde::Asset::Handle h, const bithorded::IAsset::WeakPtr& asset_) { bithorde::AssetStatus resp; resp.set_handle(h); if (auto asset = asset_.lock()) { if (asset->status == bithorde::NONE) return; resp.set_status(asset->status); if (asset->status == bithorde::SUCCESS) { resp.set_availability(1000); resp.set_size(asset->size()); asset->getIds(*resp.mutable_ids()); } } else { resp.set_status(bithorde::NOTFOUND); } LOG4CPLUS_INFO(clientLogger, peerName() << ':' << h << " new state " << bithorde::Status_Name(resp.status()) << " (" << resp.ids() << ")"); sendMessage(bithorde::Connection::AssetStatus, resp); } void Client::assignAsset(bithorde::Asset::Handle handle_, const IAsset::Ptr& a) { size_t handle = handle_; if (handle >= _assets.size()) { if (handle >= MAX_ASSETS) { LOG4CPLUS_ERROR(clientLogger, peerName() << ": handle larger than allowed limit (" << handle << " > " << MAX_ASSETS << ")"); informAssetStatus(handle_, bithorde::Status::INVALID_HANDLE); return; } size_t new_size = _assets.size() + (handle - _assets.size() + 1) * 2; if (new_size > MAX_ASSETS) new_size = MAX_ASSETS; _assets.resize(new_size); } _assets[handle] = a; // Remember to inform peer about changes in asset-status. a->statusChange.connect(boost::bind(&Client::informAssetStatusUpdate, this, handle_, IAsset::WeakPtr(a))); if (a->status != bithorde::Status::NONE) { // We already have a valid status for the asset, so inform about it informAssetStatusUpdate(handle_, a); } } void Client::onDisconnected() { clearAssets(); bithorde::Client::onDisconnected(); } void Client::clearAssets() { for (size_t h=0; h < _assets.size(); h++) clearAsset(h); _assets.clear(); } void Client::clearAsset(bithorde::Asset::Handle handle_) { size_t handle = handle_; if (handle < _assets.size()) { if (auto& a=_assets[handle]) { a->statusChange.disconnect(boost::bind(&Client::informAssetStatusUpdate, this, handle_, IAsset::WeakPtr(a))); _assets[handle].reset(); } } LOG4CPLUS_INFO(clientLogger, peerName() << ':' << handle_ << " released"); } IAsset::Ptr& Client::getAsset(bithorde::Asset::Handle handle_) { size_t handle = handle_; if (handle < _assets.size()) return _assets.at(handle); else return ASSET_NONE; } <commit_msg>[bithorded/server/client]Check handle-mapping before sending asset-updates.<commit_after>/* Copyright 2012 Ulrik Mikaelsson <ulrik.mikaelsson@gmail.com> 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 "client.hpp" #include <boost/assert.hpp> #include <iostream> #include <log4cplus/logger.h> #include <log4cplus/loggingmacros.h> #include "server.hpp" #include "../../lib/magneturi.h" #include "../../lib/random.h" const size_t MAX_ASSETS = 1024; const size_t MAX_CHUNK = 64*1024; using namespace std; namespace fs = boost::filesystem; using namespace bithorded; namespace bithorded { log4cplus::Logger clientLogger = log4cplus::Logger::getInstance("client"); } Client::Client( Server& server) : bithorde::Client(server.ioService(), server.name()), _server(server) { } size_t Client::serverAssets() const { size_t res = 0; for (auto iter = _assets.begin(); iter != _assets.end(); iter++) { if (*iter) res++; } return res; } void Client::describe(management::Info& tgt) const { tgt << '+' << clientAssets().size() << '-' << serverAssets() << ", incoming: " << stats->incomingBitrateCurrent << ", outgoing: " << stats->outgoingBitrateCurrent; } void Client::inspect(management::InfoList& tgt) const { tgt.append("incomingCurrent") << stats->incomingBitrateCurrent.autoScale() << ", " << stats->incomingMessagesCurrent.autoScale(); tgt.append("outgoingCurrent") << stats->outgoingBitrateCurrent.autoScale() << ", " << stats->outgoingMessagesCurrent.autoScale(); tgt.append("incomingTotal") << stats->incomingBytes.autoScale() << ", " << stats->incomingMessages.autoScale(); tgt.append("outgoingTotal") << stats->outgoingBytes.autoScale() << ", " << stats->outgoingMessages.autoScale(); tgt.append("assetResponseTime") << assetResponseTime; for (auto iter=clientAssets().begin(); iter != clientAssets().end(); iter++) { ostringstream name; name << '+' << iter->first; auto& node = tgt.append(name.str()); if (auto asset = iter->second->readAsset()) node << bithorde::Status_Name(asset->status) << ", " << asset->requestIds(); else node << "<stale>"; } for (size_t i=0; i < _assets.size(); i++) { if (auto& asset = _assets[i]) { ostringstream name; name << '-' << i; tgt.append(name.str(), *asset); } } } bool Client::requestsAsset(const BitHordeIds& ids) { for (auto iter=_assets.begin(); iter!=_assets.end(); iter++) { auto asset = *iter; if (asset) { BitHordeIds assetIds; if (asset->getIds(assetIds) && idsOverlap(assetIds, ids)) return true; } } return false; } void Client::onMessage(const bithorde::HandShake& msg) { bithorde::Client::onMessage(msg); LOG4CPLUS_INFO(clientLogger, "Connected: " << msg.name()); } void Client::onMessage(const bithorde::BindWrite& msg) { auto h = msg.handle(); if ((_assets.size() > h) && _assets[h]) { clearAsset(h); } if (msg.has_linkpath()) { fs::path path(msg.linkpath()); if (path.is_absolute()) { if (auto asset = _server.async_linkAsset(path)) { LOG4CPLUS_INFO(clientLogger, "Linking " << path); assignAsset(msg.handle(), asset); } else { LOG4CPLUS_ERROR(clientLogger, "Upload did not match any allowed assetStore: " << path); informAssetStatus(msg.handle(), bithorde::ERROR); } } else { LOG4CPLUS_ERROR(clientLogger, "Relative links not supported" << path); informAssetStatus(msg.handle(), bithorde::ERROR); } } else { if (auto asset = _server.prepareUpload(msg.size())) { LOG4CPLUS_INFO(clientLogger, "Ready for upload"); assignAsset(msg.handle(), asset); } else { informAssetStatus(msg.handle(), bithorde::NORESOURCES); } } } void Client::onMessage(bithorde::BindRead& msg) { auto h = msg.handle(); if ((_assets.size() > h) && _assets[h]) { clearAsset(h); } if (msg.ids_size() > 0) { // Trying to open LOG4CPLUS_INFO(clientLogger, peerName() << ':' << h << " requested: " << MagnetURI(msg)); if (!msg.has_uuid()) msg.set_uuid(rand64()); try { auto asset = _server.async_findAsset(msg); if (asset) assignAsset(h, asset); else informAssetStatus(h, bithorde::NOTFOUND); } catch (bithorded::BindError e) { informAssetStatus(h, e.status); } } else { // Trying to close informAssetStatus(h, bithorde::NOTFOUND); } } void Client::onMessage(const bithorde::Read::Request& msg) { IAsset::Ptr& asset = getAsset(msg.handle()); if (asset) { uint64_t offset = msg.offset(); size_t size = msg.size(); if (size > MAX_CHUNK) size = MAX_CHUNK; // Raw pointer to this should be fine here, since asset has ownership of this. (Through member Ptr client) auto onComplete = boost::bind(&Client::onReadResponse, this, msg, _1, _2, bithorde::Message::in(msg.timeout())); asset->async_read(offset, size, msg.timeout(), onComplete); } else { bithorde::Read::Response resp; resp.set_reqid(msg.reqid()); resp.set_status(bithorde::INVALID_HANDLE); sendMessage(bithorde::Connection::ReadResponse, resp); } } void Client::onMessage(const bithorde::DataSegment& msg) { IAsset::Ptr& asset_ = getAsset(msg.handle()); if (asset_) { bithorded::cache::CachedAsset::Ptr asset = dynamic_pointer_cast<bithorded::cache::CachedAsset>(asset_); if (asset) { asset->write(msg.offset(), msg.content()); } else { LOG4CPLUS_INFO(clientLogger, peerName() << ':' << msg.handle() << " is not an upload-asset"); } } else { LOG4CPLUS_INFO(clientLogger, peerName() << ':' << msg.handle() << " is not bound to any asset"); } return; } void Client::onReadResponse(const bithorde::Read::Request& req, int64_t offset, const std::string& data, bithorde::Message::Deadline t) { bithorde::Read::Response resp; resp.set_reqid(req.reqid()); if ((offset >= 0) && (data.size() > 0)) { resp.set_status(bithorde::SUCCESS); resp.set_offset(offset); resp.set_content(data); } else { resp.set_status(bithorde::NOTFOUND); } if (!sendMessage(bithorde::Connection::ReadResponse, resp, t)) { LOG4CPLUS_WARN(clientLogger, "Failed to write data chunk, (offset " << offset << ')'); } } void Client::informAssetStatus(bithorde::Asset::Handle h, bithorde::Status s) { bithorde::AssetStatus resp; resp.set_handle(h); resp.set_status(s); sendMessage(bithorde::Connection::AssetStatus, resp, bithorde::Message::NEVER, true); } void Client::informAssetStatusUpdate(bithorde::Asset::Handle h, const bithorded::IAsset::WeakPtr& asset_) { auto asset = asset_.lock(); size_t asset_idx = h; if ((asset_idx >= _assets.size()) || (_assets[asset_idx] != asset)) return; bithorde::AssetStatus resp; resp.set_handle(h); if (asset) { if (asset->status == bithorde::NONE) return; resp.set_status(asset->status); if (asset->status == bithorde::SUCCESS) { resp.set_availability(1000); resp.set_size(asset->size()); asset->getIds(*resp.mutable_ids()); } } else { resp.set_status(bithorde::NOTFOUND); } LOG4CPLUS_INFO(clientLogger, peerName() << ':' << h << " new state " << bithorde::Status_Name(resp.status()) << " (" << resp.ids() << ")"); sendMessage(bithorde::Connection::AssetStatus, resp); } void Client::assignAsset(bithorde::Asset::Handle handle_, const IAsset::Ptr& a) { size_t handle = handle_; if (handle >= _assets.size()) { if (handle >= MAX_ASSETS) { LOG4CPLUS_ERROR(clientLogger, peerName() << ": handle larger than allowed limit (" << handle << " > " << MAX_ASSETS << ")"); informAssetStatus(handle_, bithorde::Status::INVALID_HANDLE); return; } size_t new_size = _assets.size() + (handle - _assets.size() + 1) * 2; if (new_size > MAX_ASSETS) new_size = MAX_ASSETS; _assets.resize(new_size); } _assets[handle] = a; // Remember to inform peer about changes in asset-status. a->statusChange.connect(boost::bind(&Client::informAssetStatusUpdate, this, handle_, IAsset::WeakPtr(a))); if (a->status != bithorde::Status::NONE) { // We already have a valid status for the asset, so inform about it informAssetStatusUpdate(handle_, a); } } void Client::onDisconnected() { clearAssets(); bithorde::Client::onDisconnected(); } void Client::clearAssets() { for (size_t h=0; h < _assets.size(); h++) clearAsset(h); _assets.clear(); } void Client::clearAsset(bithorde::Asset::Handle handle_) { size_t handle = handle_; if (handle < _assets.size()) { if (auto& a=_assets[handle]) { a->statusChange.disconnect(boost::bind(&Client::informAssetStatusUpdate, this, handle_, IAsset::WeakPtr(a))); _assets[handle].reset(); } } LOG4CPLUS_INFO(clientLogger, peerName() << ':' << handle_ << " released"); } IAsset::Ptr& Client::getAsset(bithorde::Asset::Handle handle_) { size_t handle = handle_; if (handle < _assets.size()) return _assets.at(handle); else return ASSET_NONE; } <|endoftext|>
<commit_before>#include "html_generator/tags.hpp" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(checking_empty_html) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); const auto &content = tags::menu(tags::p("Content")) + tags::footer(tags::p("Copyright")); tags::html(tags::head(tags::title("Title")) + tags::body(content)) .generate(erased_html_sink); BOOST_CHECK_EQUAL("<html><head><title>Title</title></" "head><body><menu><p>Content</p></" "menu><footer><p>Copyright</p></footer></body></html>", html_generated); } BOOST_AUTO_TEST_CASE(tags_link) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::link("https://", "google.com").generate(erased_html_sink); BOOST_CHECK_EQUAL( "<a href=\"https://google.com\" target=\"_blank\">google.com</a>", html_generated); } BOOST_AUTO_TEST_CASE(paragraph) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::p(tags::cl("someclass"), Si::html::text("Testing p tag")) .generate(erased_html_sink); BOOST_CHECK_EQUAL("<p class=\"someclass\">Testing p tag</p>", html_generated); } BOOST_AUTO_TEST_CASE(div_box) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::div(tags::cl(""), Si::html::text("Testing div tag")) .generate(erased_html_sink); BOOST_CHECK_EQUAL("<div class=\"\">Testing div tag</div>", html_generated); } BOOST_AUTO_TEST_CASE(span) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::span(tags::cl(""), Si::html::text("Testing span tag")) .generate(erased_html_sink); BOOST_CHECK_EQUAL("<span class=\"\">Testing span tag</span>", html_generated); } BOOST_AUTO_TEST_CASE(break_row) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::br(tags::cl("clear")).generate(erased_html_sink); BOOST_CHECK_EQUAL("<br class=\"clear\"/>", html_generated); } BOOST_AUTO_TEST_CASE(h1) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::h1(Si::html::text("Test heading")).generate(erased_html_sink); BOOST_CHECK_EQUAL("<h1>Test heading</h1>", html_generated); } BOOST_AUTO_TEST_CASE(h2) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::h2(Si::html::text("Test heading")).generate(erased_html_sink); BOOST_CHECK_EQUAL("<h2>Test heading</h2>", html_generated); } BOOST_AUTO_TEST_CASE(h3) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::h3(Si::html::text("Test heading")).generate(erased_html_sink); BOOST_CHECK_EQUAL("<h3>Test heading</h3>", html_generated); } BOOST_AUTO_TEST_CASE(h4) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::h4(Si::html::text("Test heading")).generate(erased_html_sink); BOOST_CHECK_EQUAL("<h4>Test heading</h4>", html_generated); } BOOST_AUTO_TEST_CASE(pre_tag) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::pre(Si::html::text("Test heading")).generate(erased_html_sink); BOOST_CHECK_EQUAL("<pre>Test heading</pre>", html_generated); } BOOST_AUTO_TEST_CASE(ul) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::ul(tags::li(Si::html::text("Test heading"))) .generate(erased_html_sink); BOOST_CHECK_EQUAL("<ul><li>Test heading</li></ul>", html_generated); }<commit_msg>fix for Visual C++<commit_after>#include "html_generator/tags.hpp" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(checking_empty_html) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); auto content = tags::menu(tags::p("Content")) + tags::footer(tags::p("Copyright")); tags::html(tags::head(tags::title("Title")) + tags::body(std::move(content))) .generate(erased_html_sink); BOOST_CHECK_EQUAL("<html><head><title>Title</title></" "head><body><menu><p>Content</p></" "menu><footer><p>Copyright</p></footer></body></html>", html_generated); } BOOST_AUTO_TEST_CASE(tags_link) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::link("https://", "google.com").generate(erased_html_sink); BOOST_CHECK_EQUAL( "<a href=\"https://google.com\" target=\"_blank\">google.com</a>", html_generated); } BOOST_AUTO_TEST_CASE(paragraph) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::p(tags::cl("someclass"), Si::html::text("Testing p tag")) .generate(erased_html_sink); BOOST_CHECK_EQUAL("<p class=\"someclass\">Testing p tag</p>", html_generated); } BOOST_AUTO_TEST_CASE(div_box) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::div(tags::cl(""), Si::html::text("Testing div tag")) .generate(erased_html_sink); BOOST_CHECK_EQUAL("<div class=\"\">Testing div tag</div>", html_generated); } BOOST_AUTO_TEST_CASE(span) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::span(tags::cl(""), Si::html::text("Testing span tag")) .generate(erased_html_sink); BOOST_CHECK_EQUAL("<span class=\"\">Testing span tag</span>", html_generated); } BOOST_AUTO_TEST_CASE(break_row) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::br(tags::cl("clear")).generate(erased_html_sink); BOOST_CHECK_EQUAL("<br class=\"clear\"/>", html_generated); } BOOST_AUTO_TEST_CASE(h1) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::h1(Si::html::text("Test heading")).generate(erased_html_sink); BOOST_CHECK_EQUAL("<h1>Test heading</h1>", html_generated); } BOOST_AUTO_TEST_CASE(h2) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::h2(Si::html::text("Test heading")).generate(erased_html_sink); BOOST_CHECK_EQUAL("<h2>Test heading</h2>", html_generated); } BOOST_AUTO_TEST_CASE(h3) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::h3(Si::html::text("Test heading")).generate(erased_html_sink); BOOST_CHECK_EQUAL("<h3>Test heading</h3>", html_generated); } BOOST_AUTO_TEST_CASE(h4) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::h4(Si::html::text("Test heading")).generate(erased_html_sink); BOOST_CHECK_EQUAL("<h4>Test heading</h4>", html_generated); } BOOST_AUTO_TEST_CASE(pre_tag) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::pre(Si::html::text("Test heading")).generate(erased_html_sink); BOOST_CHECK_EQUAL("<pre>Test heading</pre>", html_generated); } BOOST_AUTO_TEST_CASE(ul) { std::string html_generated; auto erased_html_sink = Si::Sink<char, Si::success>::erase( Si::make_container_sink(html_generated)); tags::ul(tags::li(Si::html::text("Test heading"))) .generate(erased_html_sink); BOOST_CHECK_EQUAL("<ul><li>Test heading</li></ul>", html_generated); }<|endoftext|>
<commit_before>#pragma once namespace autocxxpy { struct additional_init_default { //static void init(pybind11::module &m) template <class T> inline static void init(T&m) { } }; template <class tag> struct additional_init : additional_init_default {}; } <commit_msg>Delete additional_init.hpp<commit_after><|endoftext|>
<commit_before>#pragma once #include <functional> #include <string> #include <vector> #include <athena/DNAYaml.hpp> #include <athena/Global.hpp> #include <athena/Types.hpp> namespace hecl { namespace DNACVAR { enum class EType : atUint8 { Boolean, Signed, Unsigned, Real, Literal, Vec2f, Vec2d, Vec3f, Vec3d, Vec4f, Vec4d }; enum class EFlags { None = 0, System = (1 << 0), Game = (1 << 1), Editor = (1 << 2), Gui = (1 << 3), Cheat = (1 << 4), Hidden = (1 << 5), ReadOnly = (1 << 6), Archive = (1 << 7), InternalArchivable = (1 << 8), Modified = (1 << 9), ModifyRestart = (1 << 10), //!< If this bit is set, any modification will inform the user that a restart is required Color = (1 << 11), //!< If this bit is set, Vec3f and Vec4f will be displayed in the console with a colored square NoDeveloper = (1 << 12), //!< Not even developer mode can modify this Any = -1 }; ENABLE_BITWISE_ENUM(EFlags) class CVar : public athena::io::DNA<athena::Endian::Big> { public: AT_DECL_DNA String<-1> m_name; String<-1> m_value; }; struct CVarContainer : public athena::io::DNA<athena::Endian::Big> { AT_DECL_DNA Value<atUint32> magic = 'CVAR'; Value<atUint32> cvarCount; Vector<CVar, AT_DNA_COUNT(cvarCount)> cvars; }; } // namespace DNACVAR class CVarManager; class CVar : protected DNACVAR::CVar { friend class CVarManager; Delete _d; public: typedef std::function<void(CVar*)> ListenerFunc; using EType = DNACVAR::EType; using EFlags = DNACVAR::EFlags; CVar(std::string_view name, std::string_view value, std::string_view help, EFlags flags); CVar(std::string_view name, const atVec2f& value, std::string_view help, EFlags flags); CVar(std::string_view name, const atVec2d& value, std::string_view help, EFlags flags); CVar(std::string_view name, const atVec3f& value, std::string_view help, EFlags flags); CVar(std::string_view name, const atVec3d& value, std::string_view help, EFlags flags); CVar(std::string_view name, const atVec4f& value, std::string_view help, EFlags flags); CVar(std::string_view name, const atVec4d& value, std::string_view help, EFlags flags); CVar(std::string_view name, double value, std::string_view help, EFlags flags); CVar(std::string_view name, bool value, std::string_view help, EFlags flags); CVar(std::string_view name, int32_t value, std::string_view help, EFlags flags); CVar(std::string_view name, uint32_t value, std::string_view help, EFlags flags); std::string_view name() const { return m_name; } std::string_view rawHelp() const { return m_help; } std::string help() const; std::string value() const { return m_value; } atVec2f toVec2f(bool* isValid = nullptr) const; atVec2d toVec2d(bool* isValie = nullptr) const; atVec3f toVec3f(bool* isValid = nullptr) const; atVec3d toVec3d(bool* isValie = nullptr) const; atVec4f toVec4f(bool* isValid = nullptr) const; atVec4d toVec4d(bool* isValie = nullptr) const; double toReal(bool* isValid = nullptr) const; bool toBoolean(bool* isValid = nullptr) const; int32_t toSigned(bool* isValid = nullptr) const; uint32_t toUnsigned(bool* isValid = nullptr) const; std::wstring toWideLiteral(bool* isValid = nullptr) const; std::string toLiteral(bool* isValid = nullptr) const; bool fromVec2f(const atVec2f& val); bool fromVec2d(const atVec2d& val); bool fromVec3f(const atVec3f& val); bool fromVec3d(const atVec3d& val); bool fromVec4f(const atVec4f& val); bool fromVec4d(const atVec4d& val); bool fromReal(double val); bool fromBoolean(bool val); bool fromInteger(int32_t val); bool fromInteger(uint32_t val); bool fromLiteral(std::string_view val); bool fromLiteral(std::wstring_view val); bool fromLiteralToType(std::string_view val); bool fromLiteralToType(std::wstring_view val); bool isVec2f() const { return m_type == EType::Vec2f; } bool isVec2d() const { return m_type == EType::Vec2d; } bool isVec3f() const { return m_type == EType::Vec3f; } bool isVec3d() const { return m_type == EType::Vec3d; } bool isVec4f() const { return m_type == EType::Vec4f; } bool isVec4d() const { return m_type == EType::Vec4d; } bool isFloat() const { return m_type == EType::Real; } bool isBoolean() const { return m_type == EType::Boolean; } bool isInteger() const { return m_type == EType::Signed || m_type == EType::Unsigned; } bool isLiteral() const { return m_type == EType::Literal; } bool isModified() const; bool modificationRequiresRestart() const; bool isReadOnly() const; bool isCheat() const; bool isHidden() const; bool isArchive() const; bool isInternalArchivable() const; bool isNoDeveloper() const; bool isColor() const; bool wasDeserialized() const; bool hasDefaultValue() const; EType type() const { return m_type; } EFlags flags() const { return (m_unlocked ? m_oldFlags : m_flags); } /*! * \brief Unlocks the CVar for writing if it is ReadOnly. * <b>Handle with care!!!</b> if you use unlock(), make sure * you lock the cvar using lock() * \see lock */ void unlock(); /*! * \brief Locks the CVar to prevent writing if it is ReadOnly. * Unlike its partner function unlock, lock is harmless * \see unlock */ void lock(); void addListener(ListenerFunc func) { m_listeners.push_back(std::move(func)); } bool isValidInput(std::string_view input) const; bool isValidInput(std::wstring_view input) const; private: CVar(std::string_view name, std::string_view help, EType type) : m_help(help), m_type(type) { m_name = name; } void dispatch(); void clearModified(); void setModified(); std::string m_help; EType m_type; std::string m_defaultValue; EFlags m_flags = EFlags::None; EFlags m_oldFlags = EFlags::None; bool m_unlocked = false; bool m_wasDeserialized = false; std::vector<ListenerFunc> m_listeners; bool safeToModify(EType type) const; void init(EFlags flags, bool removeColor=true); }; class CVarUnlocker { CVar* m_cvar; public: CVarUnlocker(CVar* cvar) : m_cvar(cvar) { if (m_cvar) m_cvar->unlock(); } ~CVarUnlocker() { if (m_cvar) m_cvar->lock(); } }; } // namespace hecl <commit_msg>Add to/fromValue to simplify conversion<commit_after>#pragma once #include <functional> #include <string> #include <vector> #include <athena/DNAYaml.hpp> #include <athena/Global.hpp> #include <athena/Types.hpp> namespace hecl { namespace DNACVAR { enum class EType : atUint8 { Boolean, Signed, Unsigned, Real, Literal, Vec2f, Vec2d, Vec3f, Vec3d, Vec4f, Vec4d }; enum class EFlags { None = 0, System = (1 << 0), Game = (1 << 1), Editor = (1 << 2), Gui = (1 << 3), Cheat = (1 << 4), Hidden = (1 << 5), ReadOnly = (1 << 6), Archive = (1 << 7), InternalArchivable = (1 << 8), Modified = (1 << 9), ModifyRestart = (1 << 10), //!< If this bit is set, any modification will inform the user that a restart is required Color = (1 << 11), //!< If this bit is set, Vec3f and Vec4f will be displayed in the console with a colored square NoDeveloper = (1 << 12), //!< Not even developer mode can modify this Any = -1 }; ENABLE_BITWISE_ENUM(EFlags) class CVar : public athena::io::DNA<athena::Endian::Big> { public: AT_DECL_DNA String<-1> m_name; String<-1> m_value; }; struct CVarContainer : public athena::io::DNA<athena::Endian::Big> { AT_DECL_DNA Value<atUint32> magic = 'CVAR'; Value<atUint32> cvarCount; Vector<CVar, AT_DNA_COUNT(cvarCount)> cvars; }; } // namespace DNACVAR class CVarManager; class CVar : protected DNACVAR::CVar { friend class CVarManager; Delete _d; public: typedef std::function<void(CVar*)> ListenerFunc; using EType = DNACVAR::EType; using EFlags = DNACVAR::EFlags; CVar(std::string_view name, std::string_view value, std::string_view help, EFlags flags); CVar(std::string_view name, const atVec2f& value, std::string_view help, EFlags flags); CVar(std::string_view name, const atVec2d& value, std::string_view help, EFlags flags); CVar(std::string_view name, const atVec3f& value, std::string_view help, EFlags flags); CVar(std::string_view name, const atVec3d& value, std::string_view help, EFlags flags); CVar(std::string_view name, const atVec4f& value, std::string_view help, EFlags flags); CVar(std::string_view name, const atVec4d& value, std::string_view help, EFlags flags); CVar(std::string_view name, double value, std::string_view help, EFlags flags); CVar(std::string_view name, bool value, std::string_view help, EFlags flags); CVar(std::string_view name, int32_t value, std::string_view help, EFlags flags); CVar(std::string_view name, uint32_t value, std::string_view help, EFlags flags); std::string_view name() const { return m_name; } std::string_view rawHelp() const { return m_help; } std::string help() const; std::string value() const { return m_value; } template <typename T> bool toValue(T& value) const { return false; } atVec2f toVec2f(bool* isValid = nullptr) const; template<> bool toValue(atVec2f& value) const { bool isValid = false; value = toVec2f(&isValid); return isValid; } atVec2d toVec2d(bool* isValid = nullptr) const; template<> bool toValue(atVec2d& value) const { bool isValid = false; value = toVec2d(&isValid); return isValid; } atVec3f toVec3f(bool* isValid = nullptr) const; template<> bool toValue(atVec3f& value) const { bool isValid = false; value = toVec3f(&isValid); return isValid; } atVec3d toVec3d(bool* isValid = nullptr) const; template<> bool toValue(atVec3d& value) const { bool isValid = false; value = toVec3d(&isValid); return isValid; } atVec4f toVec4f(bool* isValid = nullptr) const; template<> bool toValue(atVec4f& value) const { bool isValid = false; value = toVec4f(&isValid); return isValid; } atVec4d toVec4d(bool* isValid = nullptr) const; template<> bool toValue(atVec4d& value) const { bool isValid = false; value = toVec4d(&isValid); return isValid; } double toReal(bool* isValid = nullptr) const; template<> bool toValue(double& value) const { bool isValid = false; value = toReal(&isValid); return isValid; } bool toBoolean(bool* isValid = nullptr) const; template<> bool toValue(bool& value) const { bool isValid = false; value = toBoolean(&isValid); return isValid; } int32_t toSigned(bool* isValid = nullptr) const; template<> bool toValue(int32_t& value) const { bool isValid = false; value = toSigned(&isValid); return isValid; } uint32_t toUnsigned(bool* isValid = nullptr) const; template<> bool toValue(uint32_t& value) const { bool isValid = false; value = toUnsigned(&isValid); return isValid; } std::wstring toWideLiteral(bool* isValid = nullptr) const; template<> bool toValue(std::wstring& value) const { bool isValid = false; value = toWideLiteral(&isValid); return isValid; } std::string toLiteral(bool* isValid = nullptr) const; template<> bool toValue(std::string& value) const { bool isValid = false; value = toLiteral(&isValid); return isValid; } template <typename T> bool fromValue(T value) {} bool fromVec2f(const atVec2f& val); template<> bool fromValue(const atVec2f& val) { return fromVec2f(val); } bool fromVec2d(const atVec2d& val); template<> bool fromValue(const atVec2d& val) { return fromVec2d(val); } bool fromVec3f(const atVec3f& val); template<> bool fromValue(const atVec3f& val) { return fromVec3f(val); } bool fromVec3d(const atVec3d& val); template<> bool fromValue(const atVec3d& val) { return fromVec3d(val); } bool fromVec4f(const atVec4f& val); template<> bool fromValue(const atVec4f& val) { return fromVec4f(val); } bool fromVec4d(const atVec4d& val); template<> bool fromValue(const atVec4d& val) { return fromVec4d(val); } bool fromReal(double val); template<> bool fromValue(float val) { return fromReal(val); } template<> bool fromValue(double val) { return fromReal(val); } bool fromBoolean(bool val); template<> bool fromValue(bool val) { return fromBoolean(val); } bool fromInteger(int32_t val); template<> bool fromValue(int32_t val) { return fromInteger(val); } bool fromInteger(uint32_t val); template<> bool fromValue(uint32_t val) { return fromInteger(val); } bool fromLiteral(std::string_view val); template<> bool fromValue(std::string_view val) { return fromLiteral(val); } bool fromLiteral(std::wstring_view val); template<> bool fromValue(std::wstring_view val) { return fromLiteral(val); } bool fromLiteralToType(std::string_view val); bool fromLiteralToType(std::wstring_view val); bool isVec2f() const { return m_type == EType::Vec2f; } bool isVec2d() const { return m_type == EType::Vec2d; } bool isVec3f() const { return m_type == EType::Vec3f; } bool isVec3d() const { return m_type == EType::Vec3d; } bool isVec4f() const { return m_type == EType::Vec4f; } bool isVec4d() const { return m_type == EType::Vec4d; } bool isFloat() const { return m_type == EType::Real; } bool isBoolean() const { return m_type == EType::Boolean; } bool isInteger() const { return m_type == EType::Signed || m_type == EType::Unsigned; } bool isLiteral() const { return m_type == EType::Literal; } bool isModified() const; bool modificationRequiresRestart() const; bool isReadOnly() const; bool isCheat() const; bool isHidden() const; bool isArchive() const; bool isInternalArchivable() const; bool isNoDeveloper() const; bool isColor() const; bool wasDeserialized() const; bool hasDefaultValue() const; EType type() const { return m_type; } EFlags flags() const { return (m_unlocked ? m_oldFlags : m_flags); } /*! * \brief Unlocks the CVar for writing if it is ReadOnly. * <b>Handle with care!!!</b> if you use unlock(), make sure * you lock the cvar using lock() * \see lock */ void unlock(); /*! * \brief Locks the CVar to prevent writing if it is ReadOnly. * Unlike its partner function unlock, lock is harmless * \see unlock */ void lock(); void addListener(ListenerFunc func) { m_listeners.push_back(std::move(func)); } bool isValidInput(std::string_view input) const; bool isValidInput(std::wstring_view input) const; private: CVar(std::string_view name, std::string_view help, EType type) : m_help(help), m_type(type) { m_name = name; } void dispatch(); void clearModified(); void setModified(); std::string m_help; EType m_type; std::string m_defaultValue; EFlags m_flags = EFlags::None; EFlags m_oldFlags = EFlags::None; bool m_unlocked = false; bool m_wasDeserialized = false; std::vector<ListenerFunc> m_listeners; bool safeToModify(EType type) const; void init(EFlags flags, bool removeColor=true); }; class CVarUnlocker { CVar* m_cvar; public: CVarUnlocker(CVar* cvar) : m_cvar(cvar) { if (m_cvar) m_cvar->unlock(); } ~CVarUnlocker() { if (m_cvar) m_cvar->lock(); } }; } // namespace hecl <|endoftext|>
<commit_before>#pragma once #include "../lubee/random.hpp" #include "../lubee/check_serialization.hpp" #include <gtest/gtest.h> #include <cereal/archives/json.hpp> #include <cereal/archives/binary.hpp> namespace spi { namespace test { class Random : public ::testing::Test { private: lubee::RandomMT _mt; public: Random(): _mt(lubee::RandomMT::Make<4>()) {} auto& mt() noexcept { return _mt; } }; #define USING(t) using t = typename TestFixture::t template <class T> class TestObj { public: using value_t = T; private: value_t _value; static int s_counter; public: TestObj(TestObj&&) = default; TestObj(const TestObj&) = delete; TestObj() noexcept { ++s_counter; } TestObj(const value_t& v) noexcept: _value(v) { ++s_counter; } ~TestObj() noexcept { --s_counter; } TestObj& operator = (const T& t) { _value = t; return *this; } value_t getValue() const noexcept { return _value; } bool operator == (const TestObj& m) const noexcept { return _value == m._value; } static void InitializeCounter() noexcept { s_counter = 0; } static bool CheckCounter(const int c) noexcept { return c == s_counter; } }; template <class T> int TestObj<T>::s_counter; template <class T> inline bool operator == (const T& t, const TestObj<T>& o) noexcept { return o == t; } // コンストラクタ・デストラクタが呼ばれる回数をチェックする機構の初期化 template <class T, ENABLE_IF(!std::is_trivial<T>{})> void InitializeCounter() { T::InitializeCounter(); } template <class T, ENABLE_IF(std::is_trivial<T>{})> void InitializeCounter() noexcept {} // コンストラクタ・デストラクタが呼ばれる回数をチェック template <class T, class V, ENABLE_IF(!std::is_trivial<T>{})> void CheckCounter(const V& v) { ASSERT_TRUE(T::CheckCounter(v)); } template <class T, class V, ENABLE_IF(std::is_trivial<T>{})> void CheckCounter(const V&) noexcept {} } } <commit_msg>余計なincludeを削除<commit_after>#pragma once #include "../lubee/random.hpp" #include "../lubee/check_serialization.hpp" namespace spi { namespace test { class Random : public ::testing::Test { private: lubee::RandomMT _mt; public: Random(): _mt(lubee::RandomMT::Make<4>()) {} auto& mt() noexcept { return _mt; } }; #define USING(t) using t = typename TestFixture::t template <class T> class TestObj { public: using value_t = T; private: value_t _value; static int s_counter; public: TestObj(TestObj&&) = default; TestObj(const TestObj&) = delete; TestObj() noexcept { ++s_counter; } TestObj(const value_t& v) noexcept: _value(v) { ++s_counter; } ~TestObj() noexcept { --s_counter; } TestObj& operator = (const T& t) { _value = t; return *this; } value_t getValue() const noexcept { return _value; } bool operator == (const TestObj& m) const noexcept { return _value == m._value; } static void InitializeCounter() noexcept { s_counter = 0; } static bool CheckCounter(const int c) noexcept { return c == s_counter; } }; template <class T> int TestObj<T>::s_counter; template <class T> inline bool operator == (const T& t, const TestObj<T>& o) noexcept { return o == t; } // コンストラクタ・デストラクタが呼ばれる回数をチェックする機構の初期化 template <class T, ENABLE_IF(!std::is_trivial<T>{})> void InitializeCounter() { T::InitializeCounter(); } template <class T, ENABLE_IF(std::is_trivial<T>{})> void InitializeCounter() noexcept {} // コンストラクタ・デストラクタが呼ばれる回数をチェック template <class T, class V, ENABLE_IF(!std::is_trivial<T>{})> void CheckCounter(const V& v) { ASSERT_TRUE(T::CheckCounter(v)); } template <class T, class V, ENABLE_IF(std::is_trivial<T>{})> void CheckCounter(const V&) noexcept {} } } <|endoftext|>
<commit_before>#include "message.h" Message::Message(zmq::socket_t& socket) { while (true) { zmq::message_t message; socket.recv(&message); std::string as_string((char*) message.data(), message.size()); frames_.push_back(as_string); // See if there are more int more = 0; size_t size = sizeof(more); socket.getsockopt(ZMQ_RCVMORE, &more, &size); if (!more) { return; } } } void Message::send(zmq::socket_t& socket) const { size_t count = frames_.size(); for (auto const &part : frames_) { zmq::message_t message(part.size()); memcpy(message.data(), part.data(), part.size()); // SNDMORE on all but the last frame (count will hit 0) socket.send(message, (--count ? ZMQ_SNDMORE : 0)); } } std::string Message::inspect() const { std::string result; for (auto frame : frames_) { result = result + " - \""+ frame + '"'; } return result; } const std::vector<std::string>& Message::frames() const { return frames_; } <commit_msg>Use the simpler message.more rather than getsockopt<commit_after>#include "message.h" Message::Message(zmq::socket_t& socket) { while (true) { zmq::message_t message; socket.recv(&message); std::string as_string((char*) message.data(), message.size()); frames_.push_back(as_string); // See if there are more messages (multipart) if (!message.more()) { return; } } } void Message::send(zmq::socket_t& socket) const { size_t count = frames_.size(); for (auto const &part : frames_) { zmq::message_t message(part.size()); memcpy(message.data(), part.data(), part.size()); // SNDMORE on all but the last frame (count will hit 0) socket.send(message, (--count ? ZMQ_SNDMORE : 0)); } } std::string Message::inspect() const { std::string result; for (auto frame : frames_) { result = result + " - \""+ frame + '"'; } return result; } const std::vector<std::string>& Message::frames() const { return frames_; } <|endoftext|>
<commit_before>#if !defined(SIP0X_LOGIC_UAS_HPP__) #define SIP0X_LOGIC_UAS_HPP__ //! //! Copyright 2014 Matteo Valdina //! //! 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 "utils/log/LoggerManager.hpp" #include "utils/log/Logger.hpp" #include "logic/TransportListener.hpp" #include "logic/UA.hpp" namespace sip0x { namespace Logic { using namespace sip0x::Utils::Log; //! //! \brief Models a SIP UAS (User Agent Server). //! //! \author Matteo Valdina //! class UAS : public TransactionListener, public UA { protected: TransactionLayer _transaction_layer; public: UAS(TransportLayer* transport, ApplicationDelegate* application_delegate, std::string domain, std::string useragent) : TransactionListener(), UA(application_delegate, domain, useragent), _transaction_layer(this, transport, true) { _logger = LoggerManager::get_logger("sip0x.Logic.UAS"); } virtual ~UAS(void) { } virtual void on_trying(Transaction* tran) override { std::shared_ptr<SIPRequest>& request = tran->request; switch (request->method) { case SIPMethod::SIPMETHOD_REGISTER: { process_REGISTER(tran); break; } } } virtual void on_processing(Transaction* tran) override { } virtual void on_completed(Transaction* tran) override { } virtual void on_terminated(Transaction* tran) override { } private: void process_REGISTER(Transaction* transaction) { // TODO: process and notify the Application of the register method. // Ask to the application layer if accept register from client bool accepted = _application_delegate->raise_cb_registrar_update(transaction->request); if (accepted) { // Create a valid response. std::shared_ptr<SIPResponse> response = create_RESPONSE_for(transaction->request.get(), 200, "OK"); _transaction_layer.process_response(response, false, transaction->opaque_data); } else { // Create an reject response } } std::shared_ptr<SIPResponse> create_RESPONSE_for(SIPRequest* request, int code, char const* phrase) { std::shared_ptr<SIPResponse> response = std::make_shared<SIPResponse>(); response->status_code = code; response->reason_phrase = phrase; response->version.major = 2; add_default_header_lines(response.get()); std::shared_ptr<SIPMessageHeaderCall_ID> callID = request->get_first<SIPMessageHeaderCall_ID>(); response->headers.push_back(callID); add_header_via(response.get(), "TCP", request->get_Via_branch().c_str()); add_header_cseq(response.get(), request->method, 1); return response; } }; } } #endif // SIP0X_LOGIC_UAS_HPP__ <commit_msg>Added content line in response.<commit_after>#if !defined(SIP0X_LOGIC_UAS_HPP__) #define SIP0X_LOGIC_UAS_HPP__ //! //! Copyright 2014 Matteo Valdina //! //! 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 "utils/log/LoggerManager.hpp" #include "utils/log/Logger.hpp" #include "logic/TransportListener.hpp" #include "logic/UA.hpp" namespace sip0x { namespace Logic { using namespace sip0x::Utils::Log; //! //! \brief Models a SIP UAS (User Agent Server). //! //! \author Matteo Valdina //! class UAS : public TransactionListener, public UA { protected: TransactionLayer _transaction_layer; public: UAS(TransportLayer* transport, ApplicationDelegate* application_delegate, std::string domain, std::string useragent) : TransactionListener(), UA(application_delegate, domain, useragent), _transaction_layer(this, transport, true) { _logger = LoggerManager::get_logger("sip0x.Logic.UAS"); } virtual ~UAS(void) { } virtual void on_trying(Transaction* tran) override { std::shared_ptr<SIPRequest>& request = tran->request; switch (request->method) { case SIPMethod::SIPMETHOD_REGISTER: { process_REGISTER(tran); break; } } } virtual void on_processing(Transaction* tran) override { } virtual void on_completed(Transaction* tran) override { } virtual void on_terminated(Transaction* tran) override { } private: void process_REGISTER(Transaction* transaction) { // TODO: process and notify the Application of the register method. // Ask to the application layer if accept register from client bool accepted = _application_delegate->raise_cb_registrar_update(transaction->request); if (accepted) { // Create a valid response. std::shared_ptr<SIPResponse> response = create_RESPONSE_for(transaction->request.get(), 200, "OK"); _transaction_layer.process_response(response, false, transaction->opaque_data); } else { // Create an reject response } } std::shared_ptr<SIPResponse> create_RESPONSE_for(SIPRequest* request, int code, char const* phrase) { std::shared_ptr<SIPResponse> response = std::make_shared<SIPResponse>(); response->status_code = code; response->reason_phrase = phrase; response->version.major = 2; add_default_header_lines(response.get()); std::shared_ptr<SIPMessageHeaderCall_ID> callID = request->get_first<SIPMessageHeaderCall_ID>(); response->headers.push_back(callID); add_header_via(response.get(), "TCP", request->get_Via_branch().c_str()); add_header_cseq(response.get(), request->method, 1); add_content(response.get(), nullptr, 0); return response; } }; } } #endif // SIP0X_LOGIC_UAS_HPP__ <|endoftext|>
<commit_before>#include <iostream> #include <set> #include <vector> #include <unordered_set> #include <algorithm> #include <chrono> #include <random> // based on std::set_symmetric_difference template<typename InputIterator1, typename InputIterator2, typename OutputIterator> OutputIterator set_symmetric_difference_with_duplicates(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result) { typename InputIterator1::value_type found_duplicate; while (first1 != last1 && first2 != last2) { if (*first1 < *first2) { *result = *first1; ++first1; ++result; } else if (*first2 < *first1) { *result = *first2; ++first2; ++result; } else { found_duplicate = *first1; do { ++first1; } while (first1 != last1 && *first1 == found_duplicate); do { ++first2; } while (first2 != last2 && *first2 == found_duplicate); } } return std::copy(first2, last2, std::copy(first1, last1, result)); } std::set<int> getUniqueNumbers(const int arr1[], const int arr1Size, const int arr2[], const int arr2Size) { std::set<int> set1 (arr1, arr1 + arr1Size); // O(n*log(n)) std::set<int> set2 (arr2, arr2 + arr2Size); // O(n*log(n)) std::set<int> uniqueNumbers; std::set_symmetric_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(uniqueNumbers, uniqueNumbers.end())); // O(n) return uniqueNumbers; } std::vector<int> getUniqueNumbersWithDuplicates1(const int arr1[], const int arr1Size, const int arr2[], const int arr2Size) { std::multiset<int> set1 (arr1, arr1 + arr1Size); // O(n*log(n)) std::multiset<int> set2 (arr2, arr2 + arr2Size); // O(n*log(n)) std::vector<int> uniqueNumbers; set_symmetric_difference_with_duplicates(set1.begin(), set1.end(), set2.begin(), set2.end(), std::back_inserter(uniqueNumbers)); // O(n) return uniqueNumbers; } std::multiset<int> getUniqueNumbersWithDuplicates2(const int arr1[], const int arr1Size, const int arr2[], const int arr2Size) { std::multiset<int> set1 (arr1, arr1 + arr1Size); // O(n*log(n)) std::multiset<int> set2 (arr2, arr2 + arr2Size); // O(n*log(n)) std::multiset<int> uniqueNumbers; set_symmetric_difference_with_duplicates(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(uniqueNumbers, uniqueNumbers.end())); // O(n) return uniqueNumbers; } std::unordered_multiset<int> getUniqueNumbersWithDuplicates3(const int arr1[], const int arr1Size, const int arr2[], const int arr2Size) { std::unordered_multiset<int> uniqueNumbers(arr1, arr1 + arr1Size); // O(n) std::unordered_multiset<int> tmpSet(arr2, arr2 + arr2Size); // O(n) for (auto it = tmpSet.begin(); it != tmpSet.end(); ) // O(n) { auto tmpSetRange = tmpSet.equal_range(*it); auto range = uniqueNumbers.equal_range(*it); if (range.first != range.second) // element is found { uniqueNumbers.erase(range.first, range.second); } else { uniqueNumbers.insert(tmpSetRange.first, tmpSetRange.second); } it = tmpSetRange.second; } return uniqueNumbers; } std::unordered_multiset<int> getUniqueNumbersWithDuplicates4(const int arr1[], const int arr1Size, const int arr2[], const int arr2Size) { std::unordered_multiset<int> set1(arr1, arr1 + arr1Size); // O(n) std::unordered_multiset<int> set2(arr2, arr2 + arr2Size); // O(n) std::unordered_multiset<int> uniqueNumbers; // look in set1 for (auto it = set1.begin(); it != set1.end(); ) // O(n) { auto set1Range = set1.equal_range(*it); if (set2.find(*it) == set2.end()) { uniqueNumbers.insert(set1Range.first, set1Range.second); } it = set1Range.second; } // look in set2 for (auto it = set2.begin(); it != set2.end(); ) // O(n) { auto set2Range = set2.equal_range(*it); if (set1.find(*it) == set1.end()) { uniqueNumbers.insert(set2Range.first, set2Range.second); } it = set2Range.second; } return uniqueNumbers; } int main() { //int arr1[] = {1, 3, 3, 3, 5}; //int arr2[] = {1, 2, 4, 5}; // { 1, 2, 2 }, {2, 3, 3} -> {1, 3, 3} //int arr1[] = {1, 2, 2}; //int arr2[] = {2, 3, 3}; //int arr1[] = {1, 2, 1, 2}; //int arr2[] = {2, 3, 3}; //int arr1Size = sizeof(arr1) / sizeof(arr1[0]); //int arr2Size = sizeof(arr2) / sizeof(arr2[0]); const int arr1Size = 1000000; const int arr2Size = 1000000; std::cout << "arr size: " << arr1Size << std::endl; int * arr1 = new int[arr1Size]; int * arr2 = new int[arr2Size]; std::default_random_engine randEng((std::random_device())()); //int randMax = std::numeric_limits<int>::max(); //int randMax = arr1Size / 10; int randMax = arr1Size; std::uniform_int_distribution<int> uniformDist(0, randMax); std::cout << "rand max: " << randMax << std::endl; for (int i = 0; i < arr1Size; ++i) arr1[i] = uniformDist(randEng); for (int i = 0; i < arr2Size; ++i) arr2[i] = uniformDist(randEng); // v1 - vector auto start = std::chrono::system_clock::now(); std::vector<int> uniqueNumbers1 = getUniqueNumbersWithDuplicates1(arr1, arr1Size, arr2, arr2Size); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start); std::cout << "v1 duration: " << duration.count() << std::endl; std::cout << "v1 final size: " << uniqueNumbers1.size() << std::endl; /* std::cout << "v1 result: " << std::endl; for (auto & i : uniqueNumbers) std::cout << i << " "; std::cout << std::endl << std::endl; */ // v2 - multiset start = std::chrono::system_clock::now(); std::multiset<int> uniqueNumbers2 = getUniqueNumbersWithDuplicates2(arr1, arr1Size, arr2, arr2Size); duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start); std::cout << "v2 duration: " << duration.count() << std::endl; std::cout << "v2 final size: " << uniqueNumbers2.size() << std::endl; /* std::cout << "v2 result: " << std::endl; for (auto & i : uniqueNumbers2) std::cout << i << " "; std::cout << std::endl << std::endl; */ // v3 - unordered_multiset, in-place removal, uses less memory, but spend time "erasing" start = std::chrono::system_clock::now(); std::unordered_multiset<int> uniqueNumbers3 = getUniqueNumbersWithDuplicates3(arr1, arr1Size, arr2, arr2Size); duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start); std::cout << "v3 duration: " << duration.count() << std::endl; std::cout << "v3 final size: " << uniqueNumbers3.size() << std::endl; /* std::cout << "v3 result: " << std::endl; for (auto & i : uniqueNumbers3) std::cout << i << " "; std::cout << std::endl << std::endl; */ // v4 - unordered_multiset, with 3rd resulting set, uses more memory, but no "erasing" time start = std::chrono::system_clock::now(); std::unordered_multiset<int> uniqueNumbers4 = getUniqueNumbersWithDuplicates4(arr1, arr1Size, arr2, arr2Size); duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start); std::cout << "v4 duration: " << duration.count() << std::endl; std::cout << "v4 final size: " << uniqueNumbers4.size() << std::endl; /* std::cout << "v4 result: " << std::endl; for (auto & i : uniqueNumbers4) std::cout << i << " "; std::cout << std::endl << std::endl; */ delete [] arr1; delete [] arr2; } <commit_msg>Replace tabs with spaces.<commit_after>#include <iostream> #include <set> #include <vector> #include <unordered_set> #include <algorithm> #include <chrono> #include <random> // based on std::set_symmetric_difference template<typename InputIterator1, typename InputIterator2, typename OutputIterator> OutputIterator set_symmetric_difference_with_duplicates(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result) { typename InputIterator1::value_type found_duplicate; while (first1 != last1 && first2 != last2) { if (*first1 < *first2) { *result = *first1; ++first1; ++result; } else if (*first2 < *first1) { *result = *first2; ++first2; ++result; } else { found_duplicate = *first1; do { ++first1; } while (first1 != last1 && *first1 == found_duplicate); do { ++first2; } while (first2 != last2 && *first2 == found_duplicate); } } return std::copy(first2, last2, std::copy(first1, last1, result)); } std::set<int> getUniqueNumbers(const int arr1[], const int arr1Size, const int arr2[], const int arr2Size) { std::set<int> set1 (arr1, arr1 + arr1Size); // O(n*log(n)) std::set<int> set2 (arr2, arr2 + arr2Size); // O(n*log(n)) std::set<int> uniqueNumbers; std::set_symmetric_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(uniqueNumbers, uniqueNumbers.end())); // O(n) return uniqueNumbers; } std::vector<int> getUniqueNumbersWithDuplicates1(const int arr1[], const int arr1Size, const int arr2[], const int arr2Size) { std::multiset<int> set1 (arr1, arr1 + arr1Size); // O(n*log(n)) std::multiset<int> set2 (arr2, arr2 + arr2Size); // O(n*log(n)) std::vector<int> uniqueNumbers; set_symmetric_difference_with_duplicates(set1.begin(), set1.end(), set2.begin(), set2.end(), std::back_inserter(uniqueNumbers)); // O(n) return uniqueNumbers; } std::multiset<int> getUniqueNumbersWithDuplicates2(const int arr1[], const int arr1Size, const int arr2[], const int arr2Size) { std::multiset<int> set1 (arr1, arr1 + arr1Size); // O(n*log(n)) std::multiset<int> set2 (arr2, arr2 + arr2Size); // O(n*log(n)) std::multiset<int> uniqueNumbers; set_symmetric_difference_with_duplicates(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(uniqueNumbers, uniqueNumbers.end())); // O(n) return uniqueNumbers; } std::unordered_multiset<int> getUniqueNumbersWithDuplicates3(const int arr1[], const int arr1Size, const int arr2[], const int arr2Size) { std::unordered_multiset<int> uniqueNumbers(arr1, arr1 + arr1Size); // O(n) std::unordered_multiset<int> tmpSet(arr2, arr2 + arr2Size); // O(n) for (auto it = tmpSet.begin(); it != tmpSet.end(); ) // O(n) { auto tmpSetRange = tmpSet.equal_range(*it); auto range = uniqueNumbers.equal_range(*it); if (range.first != range.second) // element is found { uniqueNumbers.erase(range.first, range.second); } else { uniqueNumbers.insert(tmpSetRange.first, tmpSetRange.second); } it = tmpSetRange.second; } return uniqueNumbers; } std::unordered_multiset<int> getUniqueNumbersWithDuplicates4(const int arr1[], const int arr1Size, const int arr2[], const int arr2Size) { std::unordered_multiset<int> set1(arr1, arr1 + arr1Size); // O(n) std::unordered_multiset<int> set2(arr2, arr2 + arr2Size); // O(n) std::unordered_multiset<int> uniqueNumbers; // look in set1 for (auto it = set1.begin(); it != set1.end(); ) // O(n) { auto set1Range = set1.equal_range(*it); if (set2.find(*it) == set2.end()) { uniqueNumbers.insert(set1Range.first, set1Range.second); } it = set1Range.second; } // look in set2 for (auto it = set2.begin(); it != set2.end(); ) // O(n) { auto set2Range = set2.equal_range(*it); if (set1.find(*it) == set1.end()) { uniqueNumbers.insert(set2Range.first, set2Range.second); } it = set2Range.second; } return uniqueNumbers; } int main() { //int arr1[] = {1, 3, 3, 3, 5}; //int arr2[] = {1, 2, 4, 5}; // { 1, 2, 2 }, {2, 3, 3} -> {1, 3, 3} //int arr1[] = {1, 2, 2}; //int arr2[] = {2, 3, 3}; //int arr1[] = {1, 2, 1, 2}; //int arr2[] = {2, 3, 3}; //int arr1Size = sizeof(arr1) / sizeof(arr1[0]); //int arr2Size = sizeof(arr2) / sizeof(arr2[0]); const int arr1Size = 1000000; const int arr2Size = 1000000; std::cout << "arr size: " << arr1Size << std::endl; int * arr1 = new int[arr1Size]; int * arr2 = new int[arr2Size]; std::default_random_engine randEng((std::random_device())()); //int randMax = std::numeric_limits<int>::max(); //int randMax = arr1Size / 10; int randMax = arr1Size; std::uniform_int_distribution<int> uniformDist(0, randMax); std::cout << "rand max: " << randMax << std::endl; for (int i = 0; i < arr1Size; ++i) arr1[i] = uniformDist(randEng); for (int i = 0; i < arr2Size; ++i) arr2[i] = uniformDist(randEng); // v1 - vector auto start = std::chrono::system_clock::now(); std::vector<int> uniqueNumbers1 = getUniqueNumbersWithDuplicates1(arr1, arr1Size, arr2, arr2Size); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start); std::cout << "v1 duration: " << duration.count() << std::endl; std::cout << "v1 final size: " << uniqueNumbers1.size() << std::endl; /* std::cout << "v1 result: " << std::endl; for (auto & i : uniqueNumbers) std::cout << i << " "; std::cout << std::endl << std::endl; */ // v2 - multiset start = std::chrono::system_clock::now(); std::multiset<int> uniqueNumbers2 = getUniqueNumbersWithDuplicates2(arr1, arr1Size, arr2, arr2Size); duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start); std::cout << "v2 duration: " << duration.count() << std::endl; std::cout << "v2 final size: " << uniqueNumbers2.size() << std::endl; /* std::cout << "v2 result: " << std::endl; for (auto & i : uniqueNumbers2) std::cout << i << " "; std::cout << std::endl << std::endl; */ // v3 - unordered_multiset, in-place removal, uses less memory, but spend time "erasing" start = std::chrono::system_clock::now(); std::unordered_multiset<int> uniqueNumbers3 = getUniqueNumbersWithDuplicates3(arr1, arr1Size, arr2, arr2Size); duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start); std::cout << "v3 duration: " << duration.count() << std::endl; std::cout << "v3 final size: " << uniqueNumbers3.size() << std::endl; /* std::cout << "v3 result: " << std::endl; for (auto & i : uniqueNumbers3) std::cout << i << " "; std::cout << std::endl << std::endl; */ // v4 - unordered_multiset, with 3rd resulting set, uses more memory, but no "erasing" time start = std::chrono::system_clock::now(); std::unordered_multiset<int> uniqueNumbers4 = getUniqueNumbersWithDuplicates4(arr1, arr1Size, arr2, arr2Size); duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start); std::cout << "v4 duration: " << duration.count() << std::endl; std::cout << "v4 final size: " << uniqueNumbers4.size() << std::endl; /* std::cout << "v4 result: " << std::endl; for (auto & i : uniqueNumbers4) std::cout << i << " "; std::cout << std::endl << std::endl; */ delete [] arr1; delete [] arr2; } <|endoftext|>
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * * Condor Software Copyright Notice * Copyright (C) 1990-2006, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * This source code is covered by the Condor Public License, which can * be found in the accompanying LICENSE.TXT file, or online at * www.condorproject.org. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS * FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT * HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON * MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS, * ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY * PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY * RIGHT. * ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ #include "condor_common.h" #include "condor_query.h" #include "condor_attributes.h" #include "condor_collector.h" #include "condor_config.h" #include "condor_network.h" #include "condor_io.h" #include "condor_parser.h" #include "condor_adtypes.h" #include "condor_debug.h" #include "internet.h" #include "daemon.h" #include "dc_collector.h" #define XDR_ASSERT(x) {if (!(x)) return Q_COMMUNICATION_ERROR;} char *new_strdup (const char *); // The order and number of the elements of the following arrays *are* // important. (They follow the structure of the enumerations supplied // in the header file condor_query.h) const char *ScheddStringKeywords [] = { ATTR_NAME }; const char *ScheddIntegerKeywords [] = { ATTR_NUM_USERS, ATTR_IDLE_JOBS, ATTR_RUNNING_JOBS }; const char *ScheddFloatKeywords [] = { "" // add null string to avoid compiler error }; const char *StartdStringKeywords [] = { ATTR_NAME, ATTR_MACHINE, ATTR_ARCH, ATTR_OPSYS }; const char *StartdIntegerKeywords [] = { ATTR_MEMORY, ATTR_DISK }; const char *StartdFloatKeywords [] = { "" // add null string to avoid compiler error }; // normal ctor CondorQuery:: CondorQuery (AdTypes qType) { queryType = qType; switch (qType) { case STARTD_AD: query.setNumStringCats (STARTD_STRING_THRESHOLD); query.setNumIntegerCats(STARTD_INT_THRESHOLD); query.setNumFloatCats (STARTD_FLOAT_THRESHOLD); query.setIntegerKwList ((char **)StartdIntegerKeywords); query.setStringKwList ((char **)StartdStringKeywords); query.setFloatKwList ((char **)StartdFloatKeywords); command = QUERY_STARTD_ADS; break; case STARTD_PVT_AD: query.setNumStringCats (STARTD_STRING_THRESHOLD); query.setNumIntegerCats(STARTD_INT_THRESHOLD); query.setNumFloatCats (STARTD_FLOAT_THRESHOLD); query.setIntegerKwList ((char **)StartdIntegerKeywords); query.setStringKwList ((char **)StartdStringKeywords); query.setFloatKwList ((char **)StartdFloatKeywords); command = QUERY_STARTD_PVT_ADS; break; #if WANT_QUILL case QUILL_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_QUILL_ADS; break; #endif /* WANT_QUILL */ case SCHEDD_AD: query.setNumStringCats (SCHEDD_STRING_THRESHOLD); query.setNumIntegerCats(SCHEDD_INT_THRESHOLD); query.setNumFloatCats (SCHEDD_FLOAT_THRESHOLD); query.setIntegerKwList ((char **)ScheddIntegerKeywords); query.setStringKwList ((char **)ScheddStringKeywords); query.setFloatKwList ((char **)ScheddFloatKeywords); command = QUERY_SCHEDD_ADS; break; case SUBMITTOR_AD: query.setNumStringCats (SCHEDD_STRING_THRESHOLD); query.setNumIntegerCats(SCHEDD_INT_THRESHOLD); query.setNumFloatCats (SCHEDD_FLOAT_THRESHOLD); query.setIntegerKwList ((char **)ScheddIntegerKeywords); query.setStringKwList ((char **)ScheddStringKeywords); query.setFloatKwList ((char **)ScheddFloatKeywords); command = QUERY_SUBMITTOR_ADS; break; case LICENSE_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_LICENSE_ADS; break; case MASTER_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_MASTER_ADS; break; case CKPT_SRVR_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_CKPT_SRVR_ADS; break; case COLLECTOR_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_COLLECTOR_ADS; break; case NEGOTIATOR_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_NEGOTIATOR_ADS; break; case HAD_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_HAD_ADS; break; case STORAGE_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_STORAGE_ADS; break; case CREDD_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_ANY_ADS; break; case ANY_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_ANY_ADS; break; default: command = -1; queryType = (AdTypes) -1; } } // copy ctor; makes deep copy CondorQuery:: CondorQuery (const CondorQuery &from) { } // dtor CondorQuery:: ~CondorQuery () { } // clear particular string category QueryResult CondorQuery:: clearStringConstraints (const int i) { return (QueryResult) query.clearString (i); } // clear particular integer category QueryResult CondorQuery:: clearIntegerConstraints (const int i) { return (QueryResult) query.clearInteger (i); } // clear particular float category QueryResult CondorQuery:: clearFloatConstraints (const int i) { return (QueryResult) query.clearFloat (i); } void CondorQuery:: clearORCustomConstraints (void) { query.clearCustomOR (); } void CondorQuery:: clearANDCustomConstraints (void) { query.clearCustomAND (); } // add a string constraint QueryResult CondorQuery:: addConstraint (const int cat, const char *value) { return (QueryResult) query.addString (cat, value); } // add an integer constraint QueryResult CondorQuery:: addConstraint (const int cat, const int value) { return (QueryResult) query.addInteger (cat, value); } // add a float constraint QueryResult CondorQuery:: addConstraint (const int cat, const float value) { return (QueryResult) query.addFloat (cat, value); } // add a custom constraint QueryResult CondorQuery:: addANDConstraint (const char *value) { return (QueryResult) query.addCustomAND (value); } // add a custom constraint QueryResult CondorQuery:: addORConstraint (const char *value) { return (QueryResult) query.addCustomOR (value); } // fetch all ads from the collector that satisfy the constraints QueryResult CondorQuery:: fetchAds (ClassAdList &adList, const char *poolName, CondorError* errstack) { Sock* sock; int more; QueryResult result; ClassAd queryAd, *ad; if ( !poolName ) { return Q_NO_COLLECTOR_HOST; } // contact collector Daemon my_collector( DT_COLLECTOR, poolName, NULL ); if( !my_collector.locate() ) { // We were passed a bogus poolName, abort gracefully return Q_NO_COLLECTOR_HOST; } // make the query ad result = (QueryResult) query.makeQuery (queryAd); if (result != Q_OK) return result; // fix types queryAd.SetMyTypeName (QUERY_ADTYPE); switch (queryType) { #if WANT_QUILL case QUILL_AD: queryAd.SetTargetTypeName (QUILL_ADTYPE); break; #endif /* WANT_QUILL */ case STARTD_AD: case STARTD_PVT_AD: queryAd.SetTargetTypeName (STARTD_ADTYPE); break; case SCHEDD_AD: case SUBMITTOR_AD: queryAd.SetTargetTypeName (SCHEDD_ADTYPE); break; case LICENSE_AD: queryAd.SetTargetTypeName (LICENSE_ADTYPE); break; case MASTER_AD: queryAd.SetTargetTypeName (MASTER_ADTYPE); break; case CKPT_SRVR_AD: queryAd.SetTargetTypeName (CKPT_SRVR_ADTYPE); break; case COLLECTOR_AD: queryAd.SetTargetTypeName (COLLECTOR_ADTYPE); break; case NEGOTIATOR_AD: queryAd.SetTargetTypeName (NEGOTIATOR_ADTYPE); break; case STORAGE_AD: queryAd.SetTargetTypeName (STORAGE_ADTYPE); break; case CREDD_AD: queryAd.SetTargetTypeName (CREDD_ADTYPE); break; case ANY_AD: queryAd.SetTargetTypeName (ANY_ADTYPE); break; default: return Q_INVALID_QUERY; } if( DebugFlags & D_HOSTNAME ) { dprintf( D_HOSTNAME, "Querying collector %s (%s) with classad:\n", my_collector.addr(), my_collector.fullHostname() ); queryAd.dPrint( D_HOSTNAME ); dprintf( D_HOSTNAME, " --- End of Query ClassAd ---\n" ); } if (!(sock = my_collector.startCommand(command, Stream::reli_sock, 0, errstack)) || !queryAd.put (*sock) || !sock->end_of_message()) { if (sock) { delete sock; } return Q_COMMUNICATION_ERROR; } // get result sock->decode (); more = 1; while (more) { if (!sock->code (more)) { sock->end_of_message(); delete sock; return Q_COMMUNICATION_ERROR; } if (more) { ad = new ClassAd; if( !ad->initFromStream(*sock) ) { sock->end_of_message(); delete ad; delete sock; return Q_COMMUNICATION_ERROR; } adList.Insert (ad); } } sock->end_of_message(); // finalize sock->close(); delete sock; return (Q_OK); } QueryResult CondorQuery:: getQueryAd (ClassAd &queryAd) { QueryResult result; result = (QueryResult) query.makeQuery (queryAd); if (result != Q_OK) return result; // fix types queryAd.SetMyTypeName (QUERY_ADTYPE); switch (queryType) { case STARTD_AD: case STARTD_PVT_AD: queryAd.SetTargetTypeName (STARTD_ADTYPE); break; case SCHEDD_AD: case SUBMITTOR_AD: queryAd.SetTargetTypeName (SCHEDD_ADTYPE); break; case LICENSE_AD: queryAd.SetTargetTypeName (LICENSE_ADTYPE); break; case MASTER_AD: queryAd.SetTargetTypeName (MASTER_ADTYPE); break; case CKPT_SRVR_AD: queryAd.SetTargetTypeName (CKPT_SRVR_ADTYPE); break; case COLLECTOR_AD: queryAd.SetTargetTypeName (COLLECTOR_ADTYPE); break; case NEGOTIATOR_AD: queryAd.SetTargetTypeName (NEGOTIATOR_ADTYPE); break; default: return Q_INVALID_QUERY; } return Q_OK; } QueryResult CondorQuery:: filterAds (ClassAdList &in, ClassAdList &out) { ClassAd queryAd, *candidate; QueryResult result; // make the query ad result = (QueryResult) query.makeQuery (queryAd); if (result != Q_OK) return result; in.Open(); while( (candidate = (ClassAd *) in.Next()) ) { // if a match occurs if ((*candidate) >= (queryAd)) out.Insert (candidate); } in.Close (); return Q_OK; } char *getStrQueryResult(QueryResult q) { switch (q) { case Q_OK: return "ok"; case Q_INVALID_CATEGORY: return "invalid category"; case Q_MEMORY_ERROR: return "memory error"; case Q_PARSE_ERROR: return "parse error"; case Q_COMMUNICATION_ERROR: return "communication error"; case Q_INVALID_QUERY: return "invalid query"; case Q_NO_COLLECTOR_HOST: return "can't find collector"; default: return "unknown error"; } } <commit_msg>remove warnings<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * * Condor Software Copyright Notice * Copyright (C) 1990-2006, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * This source code is covered by the Condor Public License, which can * be found in the accompanying LICENSE.TXT file, or online at * www.condorproject.org. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS * FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT * HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON * MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS, * ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY * PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY * RIGHT. * ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ #include "condor_common.h" #include "condor_query.h" #include "condor_attributes.h" #include "condor_collector.h" #include "condor_config.h" #include "condor_network.h" #include "condor_io.h" #include "condor_parser.h" #include "condor_adtypes.h" #include "condor_debug.h" #include "internet.h" #include "daemon.h" #include "dc_collector.h" #define XDR_ASSERT(x) {if (!(x)) return Q_COMMUNICATION_ERROR;} char *new_strdup (const char *); // The order and number of the elements of the following arrays *are* // important. (They follow the structure of the enumerations supplied // in the header file condor_query.h) const char *ScheddStringKeywords [] = { ATTR_NAME }; const char *ScheddIntegerKeywords [] = { ATTR_NUM_USERS, ATTR_IDLE_JOBS, ATTR_RUNNING_JOBS }; const char *ScheddFloatKeywords [] = { "" // add null string to avoid compiler error }; const char *StartdStringKeywords [] = { ATTR_NAME, ATTR_MACHINE, ATTR_ARCH, ATTR_OPSYS }; const char *StartdIntegerKeywords [] = { ATTR_MEMORY, ATTR_DISK }; const char *StartdFloatKeywords [] = { "" // add null string to avoid compiler error }; // normal ctor CondorQuery:: CondorQuery (AdTypes qType) { queryType = qType; switch (qType) { case STARTD_AD: query.setNumStringCats (STARTD_STRING_THRESHOLD); query.setNumIntegerCats(STARTD_INT_THRESHOLD); query.setNumFloatCats (STARTD_FLOAT_THRESHOLD); query.setIntegerKwList ((char **)StartdIntegerKeywords); query.setStringKwList ((char **)StartdStringKeywords); query.setFloatKwList ((char **)StartdFloatKeywords); command = QUERY_STARTD_ADS; break; case STARTD_PVT_AD: query.setNumStringCats (STARTD_STRING_THRESHOLD); query.setNumIntegerCats(STARTD_INT_THRESHOLD); query.setNumFloatCats (STARTD_FLOAT_THRESHOLD); query.setIntegerKwList ((char **)StartdIntegerKeywords); query.setStringKwList ((char **)StartdStringKeywords); query.setFloatKwList ((char **)StartdFloatKeywords); command = QUERY_STARTD_PVT_ADS; break; #if WANT_QUILL case QUILL_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_QUILL_ADS; break; #endif /* WANT_QUILL */ case SCHEDD_AD: query.setNumStringCats (SCHEDD_STRING_THRESHOLD); query.setNumIntegerCats(SCHEDD_INT_THRESHOLD); query.setNumFloatCats (SCHEDD_FLOAT_THRESHOLD); query.setIntegerKwList ((char **)ScheddIntegerKeywords); query.setStringKwList ((char **)ScheddStringKeywords); query.setFloatKwList ((char **)ScheddFloatKeywords); command = QUERY_SCHEDD_ADS; break; case SUBMITTOR_AD: query.setNumStringCats (SCHEDD_STRING_THRESHOLD); query.setNumIntegerCats(SCHEDD_INT_THRESHOLD); query.setNumFloatCats (SCHEDD_FLOAT_THRESHOLD); query.setIntegerKwList ((char **)ScheddIntegerKeywords); query.setStringKwList ((char **)ScheddStringKeywords); query.setFloatKwList ((char **)ScheddFloatKeywords); command = QUERY_SUBMITTOR_ADS; break; case LICENSE_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_LICENSE_ADS; break; case MASTER_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_MASTER_ADS; break; case CKPT_SRVR_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_CKPT_SRVR_ADS; break; case COLLECTOR_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_COLLECTOR_ADS; break; case NEGOTIATOR_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_NEGOTIATOR_ADS; break; case HAD_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_HAD_ADS; break; case STORAGE_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_STORAGE_ADS; break; case CREDD_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_ANY_ADS; break; case ANY_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_ANY_ADS; break; default: command = -1; queryType = (AdTypes) -1; } } // copy ctor; makes deep copy CondorQuery:: CondorQuery (const CondorQuery & /*from*/) { } // dtor CondorQuery:: ~CondorQuery () { } // clear particular string category QueryResult CondorQuery:: clearStringConstraints (const int i) { return (QueryResult) query.clearString (i); } // clear particular integer category QueryResult CondorQuery:: clearIntegerConstraints (const int i) { return (QueryResult) query.clearInteger (i); } // clear particular float category QueryResult CondorQuery:: clearFloatConstraints (const int i) { return (QueryResult) query.clearFloat (i); } void CondorQuery:: clearORCustomConstraints (void) { query.clearCustomOR (); } void CondorQuery:: clearANDCustomConstraints (void) { query.clearCustomAND (); } // add a string constraint QueryResult CondorQuery:: addConstraint (const int cat, const char *value) { return (QueryResult) query.addString (cat, value); } // add an integer constraint QueryResult CondorQuery:: addConstraint (const int cat, const int value) { return (QueryResult) query.addInteger (cat, value); } // add a float constraint QueryResult CondorQuery:: addConstraint (const int cat, const float value) { return (QueryResult) query.addFloat (cat, value); } // add a custom constraint QueryResult CondorQuery:: addANDConstraint (const char *value) { return (QueryResult) query.addCustomAND (value); } // add a custom constraint QueryResult CondorQuery:: addORConstraint (const char *value) { return (QueryResult) query.addCustomOR (value); } // fetch all ads from the collector that satisfy the constraints QueryResult CondorQuery:: fetchAds (ClassAdList &adList, const char *poolName, CondorError* errstack) { Sock* sock; int more; QueryResult result; ClassAd queryAd, *ad; if ( !poolName ) { return Q_NO_COLLECTOR_HOST; } // contact collector Daemon my_collector( DT_COLLECTOR, poolName, NULL ); if( !my_collector.locate() ) { // We were passed a bogus poolName, abort gracefully return Q_NO_COLLECTOR_HOST; } // make the query ad result = (QueryResult) query.makeQuery (queryAd); if (result != Q_OK) return result; // fix types queryAd.SetMyTypeName (QUERY_ADTYPE); switch (queryType) { #if WANT_QUILL case QUILL_AD: queryAd.SetTargetTypeName (QUILL_ADTYPE); break; #endif /* WANT_QUILL */ case STARTD_AD: case STARTD_PVT_AD: queryAd.SetTargetTypeName (STARTD_ADTYPE); break; case SCHEDD_AD: case SUBMITTOR_AD: queryAd.SetTargetTypeName (SCHEDD_ADTYPE); break; case LICENSE_AD: queryAd.SetTargetTypeName (LICENSE_ADTYPE); break; case MASTER_AD: queryAd.SetTargetTypeName (MASTER_ADTYPE); break; case CKPT_SRVR_AD: queryAd.SetTargetTypeName (CKPT_SRVR_ADTYPE); break; case COLLECTOR_AD: queryAd.SetTargetTypeName (COLLECTOR_ADTYPE); break; case NEGOTIATOR_AD: queryAd.SetTargetTypeName (NEGOTIATOR_ADTYPE); break; case STORAGE_AD: queryAd.SetTargetTypeName (STORAGE_ADTYPE); break; case CREDD_AD: queryAd.SetTargetTypeName (CREDD_ADTYPE); break; case ANY_AD: queryAd.SetTargetTypeName (ANY_ADTYPE); break; default: return Q_INVALID_QUERY; } if( DebugFlags & D_HOSTNAME ) { dprintf( D_HOSTNAME, "Querying collector %s (%s) with classad:\n", my_collector.addr(), my_collector.fullHostname() ); queryAd.dPrint( D_HOSTNAME ); dprintf( D_HOSTNAME, " --- End of Query ClassAd ---\n" ); } if (!(sock = my_collector.startCommand(command, Stream::reli_sock, 0, errstack)) || !queryAd.put (*sock) || !sock->end_of_message()) { if (sock) { delete sock; } return Q_COMMUNICATION_ERROR; } // get result sock->decode (); more = 1; while (more) { if (!sock->code (more)) { sock->end_of_message(); delete sock; return Q_COMMUNICATION_ERROR; } if (more) { ad = new ClassAd; if( !ad->initFromStream(*sock) ) { sock->end_of_message(); delete ad; delete sock; return Q_COMMUNICATION_ERROR; } adList.Insert (ad); } } sock->end_of_message(); // finalize sock->close(); delete sock; return (Q_OK); } QueryResult CondorQuery:: getQueryAd (ClassAd &queryAd) { QueryResult result; result = (QueryResult) query.makeQuery (queryAd); if (result != Q_OK) return result; // fix types queryAd.SetMyTypeName (QUERY_ADTYPE); switch (queryType) { case STARTD_AD: case STARTD_PVT_AD: queryAd.SetTargetTypeName (STARTD_ADTYPE); break; case SCHEDD_AD: case SUBMITTOR_AD: queryAd.SetTargetTypeName (SCHEDD_ADTYPE); break; case LICENSE_AD: queryAd.SetTargetTypeName (LICENSE_ADTYPE); break; case MASTER_AD: queryAd.SetTargetTypeName (MASTER_ADTYPE); break; case CKPT_SRVR_AD: queryAd.SetTargetTypeName (CKPT_SRVR_ADTYPE); break; case COLLECTOR_AD: queryAd.SetTargetTypeName (COLLECTOR_ADTYPE); break; case NEGOTIATOR_AD: queryAd.SetTargetTypeName (NEGOTIATOR_ADTYPE); break; default: return Q_INVALID_QUERY; } return Q_OK; } QueryResult CondorQuery:: filterAds (ClassAdList &in, ClassAdList &out) { ClassAd queryAd, *candidate; QueryResult result; // make the query ad result = (QueryResult) query.makeQuery (queryAd); if (result != Q_OK) return result; in.Open(); while( (candidate = (ClassAd *) in.Next()) ) { // if a match occurs if ((*candidate) >= (queryAd)) out.Insert (candidate); } in.Close (); return Q_OK; } char *getStrQueryResult(QueryResult q) { switch (q) { case Q_OK: return "ok"; case Q_INVALID_CATEGORY: return "invalid category"; case Q_MEMORY_ERROR: return "memory error"; case Q_PARSE_ERROR: return "parse error"; case Q_COMMUNICATION_ERROR: return "communication error"; case Q_INVALID_QUERY: return "invalid query"; case Q_NO_COLLECTOR_HOST: return "can't find collector"; default: return "unknown error"; } } <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "ipv6_addrinfo.h" #include "condor_netdb.h" #include "MyString.h" addrinfo get_default_hint() { addrinfo ret; memset(&ret, 0, sizeof(ret)); #ifndef WIN32 ret.ai_flags = AI_ADDRCONFIG; #endif ret.ai_flags |= AI_CANONNAME; ret.ai_socktype = SOCK_STREAM; ret.ai_protocol = IPPROTO_TCP; return ret; } // - m. // addrinfo_iterator has two features. // 1. it works as an iterator // 2. it works as a shared pointer // struct shared_context { shared_context() : count(0), head(NULL) {} int count; addrinfo* head; void add_ref() { count++; } void release() { count--; if (!count && head) { freeaddrinfo(head); delete this; } } }; addrinfo_iterator::addrinfo_iterator() : cxt_(NULL), current_(NULL) { } addrinfo_iterator::addrinfo_iterator(const addrinfo_iterator& rhs) : cxt_(rhs.cxt_), current_(NULL) { if (cxt_) cxt_->add_ref(); } addrinfo_iterator::addrinfo_iterator(addrinfo* res) : cxt_(new shared_context), current_(NULL) { cxt_->add_ref(); cxt_->head = res; } addrinfo_iterator::~addrinfo_iterator() { if (cxt_) { cxt_->release(); } } addrinfo_iterator& addrinfo_iterator::operator= (const addrinfo_iterator& rhs) { if (cxt_) cxt_->release(); cxt_ = rhs.cxt_; cxt_->add_ref(); current_ = NULL; return *this; } addrinfo* addrinfo_iterator::next() { if (!current_) current_ = cxt_->head; else if (!current_->ai_next) return NULL; else current_ = current_->ai_next; return current_; } void addrinfo_iterator::reset() { current_ = NULL; } bool find_any_ipv4(addrinfo_iterator& ai, sockaddr_in& sin) { while ( addrinfo* r = ai.next() ) if ( r->ai_family == AF_INET ) { memcpy(&sin, r->ai_addr, r->ai_addrlen); return true; } return false; } int ipv6_getaddrinfo(const char *node, const char *service, addrinfo_iterator& ai, const addrinfo& hint) { addrinfo* res = NULL; int e = getaddrinfo(node, service, &hint, &res ); if (e!=0) return e; ai = addrinfo_iterator(res); return 0; } /* addrinfo_iterator ipv6_getaddrinfo(const char *node, const char *service) { int e; addrinfo_iterator ret; e = ipv6_getaddrinfo(node, service, ret); return ret; } addrinfo_iterator ipv6_getaddrinfo2(const char *node, int port_no) { MyString port_str; port_str.sprintf("%d", port_no); return ipv6_getaddrinfo(node, port_str.Value()); } */ /* std::string ipv6_inet_ntop(int family, const void* addr) { std::string ret; ret.resize(IP_STRING_BUF_SIZE); // it will work with most STL implementation // however, it would not work with some non-standard STL implementation // that implements copy-on-write string. char* buf = const_cast<char*>(ret.c_str()); const char* result = inet_ntop(family, addr, buf, IP_STRING_BUF_SIZE); if (!result) return ""; // return empty string ret.resize( strlen(buf) ); return ret; } std::string ipv6_inet_ntop(struct sockaddr* sa) { if (sa->sa_family != AF_INET) { //dprintf( D_ALWAYS, "ipv6_inet_ntop() called with non-AF_INET sockaddr"); return ""; } struct sockaddr_in* sin = (struct sockaddr_in*)sa; return ipv6_inet_ntop(sin->sin_family, &sin->sin_addr); } */ <commit_msg>Fix #2554 - Only ask for IPv4 addresses if we're in IPv4 mode. Solves problem of using ::1 when we should be using 127.0.0.0.1<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "ipv6_addrinfo.h" #include "condor_netdb.h" #include "MyString.h" #include "condor_ipv6.h" addrinfo get_default_hint() { addrinfo ret; memset(&ret, 0, sizeof(ret)); #ifndef WIN32 ret.ai_flags = AI_ADDRCONFIG; #endif ret.ai_flags |= AI_CANONNAME; ret.ai_socktype = SOCK_STREAM; ret.ai_protocol = IPPROTO_TCP; if(_condor_is_ipv6_mode()) { ret.ai_family = AF_UNSPEC; } else { ret.ai_family = AF_INET; } return ret; } // - m. // addrinfo_iterator has two features. // 1. it works as an iterator // 2. it works as a shared pointer // struct shared_context { shared_context() : count(0), head(NULL) {} int count; addrinfo* head; void add_ref() { count++; } void release() { count--; if (!count && head) { freeaddrinfo(head); delete this; } } }; addrinfo_iterator::addrinfo_iterator() : cxt_(NULL), current_(NULL) { } addrinfo_iterator::addrinfo_iterator(const addrinfo_iterator& rhs) : cxt_(rhs.cxt_), current_(NULL) { if (cxt_) cxt_->add_ref(); } addrinfo_iterator::addrinfo_iterator(addrinfo* res) : cxt_(new shared_context), current_(NULL) { cxt_->add_ref(); cxt_->head = res; } addrinfo_iterator::~addrinfo_iterator() { if (cxt_) { cxt_->release(); } } addrinfo_iterator& addrinfo_iterator::operator= (const addrinfo_iterator& rhs) { if (cxt_) cxt_->release(); cxt_ = rhs.cxt_; cxt_->add_ref(); current_ = NULL; return *this; } addrinfo* addrinfo_iterator::next() { if (!current_) current_ = cxt_->head; else if (!current_->ai_next) return NULL; else current_ = current_->ai_next; return current_; } void addrinfo_iterator::reset() { current_ = NULL; } bool find_any_ipv4(addrinfo_iterator& ai, sockaddr_in& sin) { while ( addrinfo* r = ai.next() ) if ( r->ai_family == AF_INET ) { memcpy(&sin, r->ai_addr, r->ai_addrlen); return true; } return false; } int ipv6_getaddrinfo(const char *node, const char *service, addrinfo_iterator& ai, const addrinfo& hint) { addrinfo* res = NULL; int e = getaddrinfo(node, service, &hint, &res ); if (e!=0) return e; ai = addrinfo_iterator(res); return 0; } /* addrinfo_iterator ipv6_getaddrinfo(const char *node, const char *service) { int e; addrinfo_iterator ret; e = ipv6_getaddrinfo(node, service, ret); return ret; } addrinfo_iterator ipv6_getaddrinfo2(const char *node, int port_no) { MyString port_str; port_str.sprintf("%d", port_no); return ipv6_getaddrinfo(node, port_str.Value()); } */ /* std::string ipv6_inet_ntop(int family, const void* addr) { std::string ret; ret.resize(IP_STRING_BUF_SIZE); // it will work with most STL implementation // however, it would not work with some non-standard STL implementation // that implements copy-on-write string. char* buf = const_cast<char*>(ret.c_str()); const char* result = inet_ntop(family, addr, buf, IP_STRING_BUF_SIZE); if (!result) return ""; // return empty string ret.resize( strlen(buf) ); return ret; } std::string ipv6_inet_ntop(struct sockaddr* sa) { if (sa->sa_family != AF_INET) { //dprintf( D_ALWAYS, "ipv6_inet_ntop() called with non-AF_INET sockaddr"); return ""; } struct sockaddr_in* sin = (struct sockaddr_in*)sa; return ipv6_inet_ntop(sin->sin_family, &sin->sin_addr); } */ <|endoftext|>
<commit_before>#ifndef CONTAINERS_ARCHIVE_ARCHIVE_HPP_ #define CONTAINERS_ARCHIVE_ARCHIVE_HPP_ #include <stdint.h> #include "errors.hpp" #include "containers/intrusive_list.hpp" class uuid_t; struct fake_archive_exc_t { const char *what() const throw() { return "Writing to a tcp stream failed."; } }; class read_stream_t { public: read_stream_t() { } // Returns number of bytes read or 0 upon EOF, -1 upon error. virtual MUST_USE int64_t read(void *p, int64_t n) = 0; protected: virtual ~read_stream_t() { } private: DISABLE_COPYING(read_stream_t); }; // Deserialize functions return 0 upon success, a positive or negative error // code upon failure. -1 means there was an error on the socket, -2 means EOF on // the socket, -3 means a "range error", +1 means specific error info was // discarded, the error code got used as a boolean. enum archive_result_t { ARCHIVE_SUCCESS = 0, ARCHIVE_SOCK_ERROR = -1, ARCHIVE_SOCK_EOF = -2, ARCHIVE_RANGE_ERROR = -3, ARCHIVE_GENERIC_ERROR = 1, }; // We wrap things in this class for making friend declarations more // compilable under gcc-4.5. class archive_deserializer_t { private: template <class T> friend archive_result_t deserialize(read_stream_t *s, T *thing); template <class T> static MUST_USE archive_result_t deserialize(read_stream_t *s, T *thing) { return thing->rdb_deserialize(s); } archive_deserializer_t(); }; template <class T> MUST_USE archive_result_t deserialize(read_stream_t *s, T *thing) { return archive_deserializer_t::deserialize(s, thing); } // Returns the number of bytes written, or -1. Returns a // non-negative value less than n upon EOF. MUST_USE int64_t force_read(read_stream_t *s, void *p, int64_t n); class write_stream_t { public: write_stream_t() { } // Returns n, or -1 upon error. Blocks until all bytes are // written. virtual int64_t write(const void *p, int64_t n) = 0; protected: virtual ~write_stream_t() { } private: DISABLE_COPYING(write_stream_t); }; class write_buffer_t : public intrusive_list_node_t<write_buffer_t> { public: write_buffer_t() : size(0) { } static const int DATA_SIZE = 4096; int size; char data[DATA_SIZE]; private: DISABLE_COPYING(write_buffer_t); }; // A set of buffers in which an atomic message to be sent on a stream // gets built up. (This way we don't flush after the first four bytes // sent to a stream, or buffer things and then forget to manually // flush. This type can be extended to support holding references to // large buffers, to save copying.) Generally speaking, you serialize // to a write_message_t, and then flush that to a write_stream_t. class write_message_t { public: write_message_t() { } ~write_message_t(); void append(const void *p, int64_t n); intrusive_list_t<write_buffer_t> *unsafe_expose_buffers() { return &buffers_; } // This _could_ destroy the object yo. template <class T> write_message_t &operator<<(const T &x) { x.rdb_serialize(*this); return *this; } private: friend int send_write_message(write_stream_t *s, write_message_t *msg); intrusive_list_t<write_buffer_t> buffers_; DISABLE_COPYING(write_message_t); }; MUST_USE int send_message(write_stream_t *s, write_message_t *msg); #define ARCHIVE_PRIM_MAKE_WRITE_SERIALIZABLE(typ1, typ2) \ inline write_message_t &operator<<(write_message_t &msg, typ1 x) { \ union { \ typ2 v; \ char buf[sizeof(typ2)]; \ } u; \ u.v = x; \ msg.append(u.buf, sizeof(typ2)); \ return msg; \ } // Makes typ1 serializable, sending a typ2 over the wire. Has range // checking on the closed interval [lo, hi] when deserializing. #define ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE(typ1, typ2, lo, hi) \ ARCHIVE_PRIM_MAKE_WRITE_SERIALIZABLE(typ1, typ2); \ \ inline MUST_USE archive_result_t deserialize(read_stream_t *s, typ1 *x) { \ union { \ typ2 v; \ char buf[sizeof(typ2)]; \ } u; \ int64_t res = force_read(s, u.buf, sizeof(typ2)); \ if (res == -1) { \ return ARCHIVE_SOCK_ERROR; \ } \ if (res < int64_t(sizeof(typ2))) { \ return ARCHIVE_SOCK_EOF; \ } \ if (u.v < typ2(lo) || u.v > typ2(hi)) { \ return ARCHIVE_RANGE_ERROR; \ } \ *x = typ1(u.v); \ return ARCHIVE_SUCCESS; \ } // Designed for <stdint.h>'s u?int[0-9]+_t types, which are just sent // raw over the wire. #define ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(typ) \ ARCHIVE_PRIM_MAKE_WRITE_SERIALIZABLE(typ, typ); \ \ inline MUST_USE archive_result_t deserialize(read_stream_t *s, typ *x) { \ union { \ typ v; \ char buf[sizeof(typ)]; \ } u; \ int64_t res = force_read(s, u.buf, sizeof(typ)); \ if (res == -1) { \ return ARCHIVE_SOCK_ERROR; \ } \ if (res < int64_t(sizeof(typ))) { \ return ARCHIVE_SOCK_EOF; \ } \ *x = u.v; \ return ARCHIVE_SUCCESS; \ } ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(int8_t); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(uint8_t); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(int16_t); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(uint16_t); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(int32_t); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(uint32_t); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(int64_t); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(uint64_t); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(float); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(double); ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE(bool, int8_t, 0, 1); write_message_t &operator<<(write_message_t &msg, const uuid_t &uuid); MUST_USE archive_result_t deserialize(read_stream_t *s, uuid_t *uuid); #endif // CONTAINERS_ARCHIVE_ARCHIVE_HPP_ <commit_msg>Declared a method outside of the class so that old gcc's can find it.<commit_after>#ifndef CONTAINERS_ARCHIVE_ARCHIVE_HPP_ #define CONTAINERS_ARCHIVE_ARCHIVE_HPP_ #include <stdint.h> #include "errors.hpp" #include "containers/intrusive_list.hpp" class uuid_t; struct fake_archive_exc_t { const char *what() const throw() { return "Writing to a tcp stream failed."; } }; class read_stream_t { public: read_stream_t() { } // Returns number of bytes read or 0 upon EOF, -1 upon error. virtual MUST_USE int64_t read(void *p, int64_t n) = 0; protected: virtual ~read_stream_t() { } private: DISABLE_COPYING(read_stream_t); }; // Deserialize functions return 0 upon success, a positive or negative error // code upon failure. -1 means there was an error on the socket, -2 means EOF on // the socket, -3 means a "range error", +1 means specific error info was // discarded, the error code got used as a boolean. enum archive_result_t { ARCHIVE_SUCCESS = 0, ARCHIVE_SOCK_ERROR = -1, ARCHIVE_SOCK_EOF = -2, ARCHIVE_RANGE_ERROR = -3, ARCHIVE_GENERIC_ERROR = 1, }; // We wrap things in this class for making friend declarations more // compilable under gcc-4.5. class archive_deserializer_t { private: template <class T> friend archive_result_t deserialize(read_stream_t *s, T *thing); template <class T> static MUST_USE archive_result_t deserialize(read_stream_t *s, T *thing) { return thing->rdb_deserialize(s); } archive_deserializer_t(); }; template <class T> MUST_USE archive_result_t deserialize(read_stream_t *s, T *thing) { return archive_deserializer_t::deserialize(s, thing); } // Returns the number of bytes written, or -1. Returns a // non-negative value less than n upon EOF. MUST_USE int64_t force_read(read_stream_t *s, void *p, int64_t n); class write_stream_t { public: write_stream_t() { } // Returns n, or -1 upon error. Blocks until all bytes are // written. virtual int64_t write(const void *p, int64_t n) = 0; protected: virtual ~write_stream_t() { } private: DISABLE_COPYING(write_stream_t); }; class write_buffer_t : public intrusive_list_node_t<write_buffer_t> { public: write_buffer_t() : size(0) { } static const int DATA_SIZE = 4096; int size; char data[DATA_SIZE]; private: DISABLE_COPYING(write_buffer_t); }; // A set of buffers in which an atomic message to be sent on a stream // gets built up. (This way we don't flush after the first four bytes // sent to a stream, or buffer things and then forget to manually // flush. This type can be extended to support holding references to // large buffers, to save copying.) Generally speaking, you serialize // to a write_message_t, and then flush that to a write_stream_t. class write_message_t { public: write_message_t() { } ~write_message_t(); void append(const void *p, int64_t n); intrusive_list_t<write_buffer_t> *unsafe_expose_buffers() { return &buffers_; } // This _could_ destroy the object yo. template <class T> write_message_t &operator<<(const T &x) { x.rdb_serialize(*this); return *this; } private: friend int send_write_message(write_stream_t *s, write_message_t *msg); intrusive_list_t<write_buffer_t> buffers_; DISABLE_COPYING(write_message_t); }; // Hack for older versions of GCC, which seem to not find the declaration // it's outside of the write_message_t class. int send_write_message(write_stream_t *s, write_message_t *msg); MUST_USE int send_message(write_stream_t *s, write_message_t *msg); #define ARCHIVE_PRIM_MAKE_WRITE_SERIALIZABLE(typ1, typ2) \ inline write_message_t &operator<<(write_message_t &msg, typ1 x) { \ union { \ typ2 v; \ char buf[sizeof(typ2)]; \ } u; \ u.v = x; \ msg.append(u.buf, sizeof(typ2)); \ return msg; \ } // Makes typ1 serializable, sending a typ2 over the wire. Has range // checking on the closed interval [lo, hi] when deserializing. #define ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE(typ1, typ2, lo, hi) \ ARCHIVE_PRIM_MAKE_WRITE_SERIALIZABLE(typ1, typ2); \ \ inline MUST_USE archive_result_t deserialize(read_stream_t *s, typ1 *x) { \ union { \ typ2 v; \ char buf[sizeof(typ2)]; \ } u; \ int64_t res = force_read(s, u.buf, sizeof(typ2)); \ if (res == -1) { \ return ARCHIVE_SOCK_ERROR; \ } \ if (res < int64_t(sizeof(typ2))) { \ return ARCHIVE_SOCK_EOF; \ } \ if (u.v < typ2(lo) || u.v > typ2(hi)) { \ return ARCHIVE_RANGE_ERROR; \ } \ *x = typ1(u.v); \ return ARCHIVE_SUCCESS; \ } // Designed for <stdint.h>'s u?int[0-9]+_t types, which are just sent // raw over the wire. #define ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(typ) \ ARCHIVE_PRIM_MAKE_WRITE_SERIALIZABLE(typ, typ); \ \ inline MUST_USE archive_result_t deserialize(read_stream_t *s, typ *x) { \ union { \ typ v; \ char buf[sizeof(typ)]; \ } u; \ int64_t res = force_read(s, u.buf, sizeof(typ)); \ if (res == -1) { \ return ARCHIVE_SOCK_ERROR; \ } \ if (res < int64_t(sizeof(typ))) { \ return ARCHIVE_SOCK_EOF; \ } \ *x = u.v; \ return ARCHIVE_SUCCESS; \ } ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(int8_t); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(uint8_t); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(int16_t); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(uint16_t); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(int32_t); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(uint32_t); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(int64_t); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(uint64_t); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(float); ARCHIVE_PRIM_MAKE_RAW_SERIALIZABLE(double); ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE(bool, int8_t, 0, 1); write_message_t &operator<<(write_message_t &msg, const uuid_t &uuid); MUST_USE archive_result_t deserialize(read_stream_t *s, uuid_t *uuid); #endif // CONTAINERS_ARCHIVE_ARCHIVE_HPP_ <|endoftext|>
<commit_before>// -*- mode: c++; coding: utf-8 -*- /*! @file simulation.cpp @brief Implementation of Simulation class */ #include "simulation.hpp" #include <wtl/debug.hpp> #include <wtl/iostr.hpp> #include <wtl/getopt.hpp> #include <wtl/zfstream.hpp> #include <sfmt.hpp> #include <boost/asio.hpp> #include "individual.hpp" /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// // functions //! Symbols for the program options can be different from those in equations /*! @ingroup biol_param @return Program options description Command line option | Symbol | Variable ------------------- | --------- | ------------------------------------------ `-k,--patch_size` | \f$K_0\f$ | Simulation::INITIAL_PATCH_SIZE `--row,--col` | - | Simulation::NUM_COLS, Simulation::NUM_ROWS `-T,--time` | - | Simulation::ENTIRE_PERIOD `-I,--interval` | - | Simulation::OBSERVATION_CYCLE */ boost::program_options::options_description Simulation::opt_description() {HERE; namespace po = boost::program_options; po::options_description description("Simulation"); description.add_options() ("help,h", po::value<bool>()->default_value(false)->implicit_value(true), "produce help") ("verbose,v", po::value(&VERBOSE) ->default_value(VERBOSE)->implicit_value(true), "verbose output") ("test", po::value<int>()->default_value(0)->implicit_value(1)) ("mode", po::value(&MODE)->default_value(MODE)) ("symmetric", po::value(&SYMMETRIC)->default_value(SYMMETRIC)->implicit_value(true)) ("label", po::value(&LABEL)->default_value("default")) ("top_dir", po::value<std::string>()->default_value(OUT_DIR.string())) ("patch_size,k", po::value(&INITIAL_PATCH_SIZE)->default_value(INITIAL_PATCH_SIZE)) ("row", po::value(&NUM_ROWS)->default_value(NUM_ROWS)) ("col", po::value(&NUM_COLS)->default_value(NUM_COLS)) ("dimensions,D", po::value(&DIMENSIONS)->default_value(DIMENSIONS)) ("time,T", po::value(&ENTIRE_PERIOD)->default_value(ENTIRE_PERIOD)) ("interval,I", po::value(&OBSERVATION_CYCLE)->default_value(OBSERVATION_CYCLE)) ("seed", po::value(&SEED)->default_value(SEED)) ; return description; } //! Unit test for each class inline void test() {HERE; Individual::unit_test(); Patch::unit_test(); } Simulation::Simulation(int argc, char* argv[]) {HERE; std::ios::sync_with_stdio(false); std::cin.tie(0); std::cout.precision(15); std::cerr.precision(6); std::vector<std::string> arguments(argv, argv + argc); std::cout << wtl::str_join(arguments, " ") << std::endl; std::cout << wtl::iso8601datetime() << std::endl; namespace po = boost::program_options; po::options_description description; description.add(opt_description()); description.add(Individual::opt_description()); po::variables_map vm; po::store(po::parse_command_line(argc, argv, description), vm); po::notify(vm); if (vm["help"].as<bool>()) { description.print(std::cout); exit(0); } OUT_DIR = fs::path(vm["top_dir"].as<std::string>()); wtl::sfmt().seed(SEED); if (DIMENSIONS == 1) { std::ostringstream ost; ost << "diameter_pref = 1e6\n" << "limb_select = 1e6\n" << "mutation_mask = 10\n"; std::istringstream ist(ost.str()); po::store(po::parse_config_file(ist, description, false), vm); vm.notify(); } if (SYMMETRIC) { std::ostringstream ost; ost << "diameter_pref = " << vm["height_pref"].as<double>() << "\n" << "limb_select = " << vm["toepad_select"].as<double>() << "\n"; std::istringstream ist(ost.str()); po::store(po::parse_config_file(ist, description, false), vm); vm.notify(); } const std::string CONFIG_STRING = wtl::flags_into_string(vm); if (VERBOSE) { std::cout << CONFIG_STRING << std::endl; } if (ENTIRE_PERIOD % OBSERVATION_CYCLE > 0) { std::cerr << wtl::strprintf( "T=%d is not a multiple of I=%d", ENTIRE_PERIOD, OBSERVATION_CYCLE) << std::endl; exit(1); } switch (vm["test"].as<int>()) { case 0: break; case 1: test(); exit(0); default: exit(1); } const std::string now(wtl::strftime("%Y%m%d_%H%M%S")); std::ostringstream pid_at_host; pid_at_host << ::getpid() << "@" << boost::asio::ip::host_name(); WORK_DIR = TMP_DIR / (now + "_" + LABEL + "_" + pid_at_host.str()); DCERR("mkdir && cd to " << WORK_DIR << std::endl); fs::create_directory(WORK_DIR); fs::current_path(WORK_DIR.string()); fs::create_directory(OUT_DIR); OUT_DIR /= (LABEL + "_" + now + "_" + pid_at_host.str()); wtl::opfstream{"program_options.conf"} << CONFIG_STRING; } void Simulation::run() {HERE; switch (MODE) { case 0: evolve(); break; case 1: Individual::write_resource_abundance(); break; case 2: wtl::ozfstream{"possible_geographic.csv.gz"} << Individual::possible_geographic(); wtl::ozfstream{"possible_phenotypes.csv.gz"} << Individual::possible_phenotypes(); break; default: exit(1); } DCERR("mv results to " << OUT_DIR << std::endl); fs::rename(WORK_DIR, OUT_DIR); std::cout << wtl::iso8601datetime() << std::endl; } void Simulation::evolve() {HERE; assert(ENTIRE_PERIOD % OBSERVATION_CYCLE == 0); population.assign(NUM_ROWS, std::vector<Patch>(NUM_COLS)); if (DIMENSIONS == 1) { population[0][0] = Patch(INITIAL_PATCH_SIZE, Individual{{15, 0, 15, 0}}); } else { population[0][0] = Patch(INITIAL_PATCH_SIZE); } std::ostringstream ost; for (size_t t=0; t<=ENTIRE_PERIOD; ++t) { if (VERBOSE) { std::cout << "\nT = " << t << "\n" << wtl::str_matrix(population, " ", wtl::make_oss(), [](const Patch& p) {return p.size();}) << std::flush; } if (t % OBSERVATION_CYCLE == 0) { write_snapshot(t, ost); } if (t < ENTIRE_PERIOD) { life_cycle(); } } wtl::ozfstream{"evolution.csv.gz"} << ost.str(); } /*! @brief Change row/col with probability \f$m\f$ = Individual::MIGRATION_RATE_ > With probability \f$ m > 0 \f$, each offspring becomes a "migrant." > Each migrant goes to one of the 8 neighboring patches. > For patches at the boundary, > the probability \f$ m \f$ is reduced according to the number of neighbors they have. */ inline std::pair<size_t, size_t> choose_patch(size_t row, size_t col) { if (!std::bernoulli_distribution(Individual::MIGRATION_RATE())(wtl::sfmt())) {return {row, col};} switch (std::uniform_int_distribution<size_t>(0, 7)(wtl::sfmt())) { case 0: ++col; break; case 1: ++row; ++col; break; case 2: ++row; break; case 3: ++row; --col; break; case 4: --col; break; case 5: --row; --col; break; case 6: --row; break; case 7: --row; ++col; break; } return {row, col}; } void Simulation::life_cycle() { std::vector<std::vector<Patch> > parents(population); auto reproduction = [&](const size_t row, const size_t col) { auto offsprings = parents[row][col].mate_and_reproduce(wtl::sfmt()); std::vector<std::pair<size_t, size_t> > destinations; destinations.reserve(offsprings.size()); for (size_t i=0; i<offsprings.size(); ++i) { const auto dst = choose_patch(row, col); if ((dst.first >= NUM_ROWS) | (dst.second >= NUM_COLS)) { destinations.emplace_back(row, col); } else { destinations.push_back(std::move(dst)); } } for (size_t i=0; i<offsprings.size(); ++i) { const auto& dst = destinations[i]; population[dst.first][dst.second].append(std::move(offsprings[i])); } }; for (size_t row=0; row<NUM_ROWS; ++row) { for (size_t col=0; col<NUM_COLS; ++col) { reproduction(row, col); } } for (size_t row=0; row<NUM_ROWS; ++row) { for (size_t col=0; col<NUM_COLS; ++col) { population[row][col].viability_selection(wtl::sfmt()); } } } void Simulation::write_snapshot(const size_t time, std::ostream& ost) const { const char* sep = ","; if (time == 0) { ost << "time" << sep << "row" << sep << "col" << sep << "n" << sep << Individual::header() << "\n"; } std::size_t popsize = 0; for (size_t row=0; row<population.size(); ++row) { for (size_t col=0; col<population[row].size(); ++col) { for (const auto& item: population[row][col].summarize()) { ost << time << sep << row << sep << col << sep << item.second << sep << item.first << "\n"; popsize += item.second; } } } DCERR("N = " << popsize << std::endl); } <commit_msg>Use po::bool_switch()<commit_after>// -*- mode: c++; coding: utf-8 -*- /*! @file simulation.cpp @brief Implementation of Simulation class */ #include "simulation.hpp" #include <wtl/debug.hpp> #include <wtl/iostr.hpp> #include <wtl/getopt.hpp> #include <wtl/zfstream.hpp> #include <sfmt.hpp> #include <boost/asio.hpp> #include "individual.hpp" /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// // functions //! Symbols for the program options can be different from those in equations /*! @ingroup biol_param @return Program options description Command line option | Symbol | Variable ------------------- | --------- | ------------------------------------------ `-k,--patch_size` | \f$K_0\f$ | Simulation::INITIAL_PATCH_SIZE `--row,--col` | - | Simulation::NUM_COLS, Simulation::NUM_ROWS `-T,--time` | - | Simulation::ENTIRE_PERIOD `-I,--interval` | - | Simulation::OBSERVATION_CYCLE */ boost::program_options::options_description Simulation::opt_description() {HERE; namespace po = boost::program_options; po::options_description description("Simulation"); description.add_options() ("help,h", po::bool_switch(), "produce help") ("verbose,v", po::bool_switch(&VERBOSE), "verbose output") ("test", po::value<int>()->default_value(0)->implicit_value(1)) ("mode", po::value(&MODE)->default_value(MODE)) ("symmetric", po::bool_switch(&SYMMETRIC)) ("label", po::value(&LABEL)->default_value("default")) ("top_dir", po::value<std::string>()->default_value(OUT_DIR.string())) ("patch_size,k", po::value(&INITIAL_PATCH_SIZE)->default_value(INITIAL_PATCH_SIZE)) ("row", po::value(&NUM_ROWS)->default_value(NUM_ROWS)) ("col", po::value(&NUM_COLS)->default_value(NUM_COLS)) ("dimensions,D", po::value(&DIMENSIONS)->default_value(DIMENSIONS)) ("time,T", po::value(&ENTIRE_PERIOD)->default_value(ENTIRE_PERIOD)) ("interval,I", po::value(&OBSERVATION_CYCLE)->default_value(OBSERVATION_CYCLE)) ("seed", po::value(&SEED)->default_value(SEED)) ; return description; } //! Unit test for each class inline void test() {HERE; Individual::unit_test(); Patch::unit_test(); } Simulation::Simulation(int argc, char* argv[]) {HERE; std::ios::sync_with_stdio(false); std::cin.tie(0); std::cout.precision(15); std::cerr.precision(6); std::vector<std::string> arguments(argv, argv + argc); std::cout << wtl::str_join(arguments, " ") << std::endl; std::cout << wtl::iso8601datetime() << std::endl; namespace po = boost::program_options; po::options_description description; description.add(opt_description()); description.add(Individual::opt_description()); po::variables_map vm; po::store(po::parse_command_line(argc, argv, description), vm); po::notify(vm); if (vm["help"].as<bool>()) { description.print(std::cout); exit(0); } OUT_DIR = fs::path(vm["top_dir"].as<std::string>()); wtl::sfmt().seed(SEED); if (DIMENSIONS == 1) { std::ostringstream ost; ost << "diameter_pref = 1e6\n" << "limb_select = 1e6\n" << "mutation_mask = 10\n"; std::istringstream ist(ost.str()); po::store(po::parse_config_file(ist, description, false), vm); vm.notify(); } if (SYMMETRIC) { std::ostringstream ost; ost << "diameter_pref = " << vm["height_pref"].as<double>() << "\n" << "limb_select = " << vm["toepad_select"].as<double>() << "\n"; std::istringstream ist(ost.str()); po::store(po::parse_config_file(ist, description, false), vm); vm.notify(); } const std::string CONFIG_STRING = wtl::flags_into_string(vm); if (VERBOSE) { std::cout << CONFIG_STRING << std::endl; } if (ENTIRE_PERIOD % OBSERVATION_CYCLE > 0) { std::cerr << wtl::strprintf( "T=%d is not a multiple of I=%d", ENTIRE_PERIOD, OBSERVATION_CYCLE) << std::endl; exit(1); } switch (vm["test"].as<int>()) { case 0: break; case 1: test(); exit(0); default: exit(1); } const std::string now(wtl::strftime("%Y%m%d_%H%M%S")); std::ostringstream pid_at_host; pid_at_host << ::getpid() << "@" << boost::asio::ip::host_name(); WORK_DIR = TMP_DIR / (now + "_" + LABEL + "_" + pid_at_host.str()); DCERR("mkdir && cd to " << WORK_DIR << std::endl); fs::create_directory(WORK_DIR); fs::current_path(WORK_DIR.string()); fs::create_directory(OUT_DIR); OUT_DIR /= (LABEL + "_" + now + "_" + pid_at_host.str()); wtl::opfstream{"program_options.conf"} << CONFIG_STRING; } void Simulation::run() {HERE; switch (MODE) { case 0: evolve(); break; case 1: Individual::write_resource_abundance(); break; case 2: wtl::ozfstream{"possible_geographic.csv.gz"} << Individual::possible_geographic(); wtl::ozfstream{"possible_phenotypes.csv.gz"} << Individual::possible_phenotypes(); break; default: exit(1); } DCERR("mv results to " << OUT_DIR << std::endl); fs::rename(WORK_DIR, OUT_DIR); std::cout << wtl::iso8601datetime() << std::endl; } void Simulation::evolve() {HERE; assert(ENTIRE_PERIOD % OBSERVATION_CYCLE == 0); population.assign(NUM_ROWS, std::vector<Patch>(NUM_COLS)); if (DIMENSIONS == 1) { population[0][0] = Patch(INITIAL_PATCH_SIZE, Individual{{15, 0, 15, 0}}); } else { population[0][0] = Patch(INITIAL_PATCH_SIZE); } std::ostringstream ost; for (size_t t=0; t<=ENTIRE_PERIOD; ++t) { if (VERBOSE) { std::cout << "\nT = " << t << "\n" << wtl::str_matrix(population, " ", wtl::make_oss(), [](const Patch& p) {return p.size();}) << std::flush; } if (t % OBSERVATION_CYCLE == 0) { write_snapshot(t, ost); } if (t < ENTIRE_PERIOD) { life_cycle(); } } wtl::ozfstream{"evolution.csv.gz"} << ost.str(); } /*! @brief Change row/col with probability \f$m\f$ = Individual::MIGRATION_RATE_ > With probability \f$ m > 0 \f$, each offspring becomes a "migrant." > Each migrant goes to one of the 8 neighboring patches. > For patches at the boundary, > the probability \f$ m \f$ is reduced according to the number of neighbors they have. */ inline std::pair<size_t, size_t> choose_patch(size_t row, size_t col) { if (!std::bernoulli_distribution(Individual::MIGRATION_RATE())(wtl::sfmt())) {return {row, col};} switch (std::uniform_int_distribution<size_t>(0, 7)(wtl::sfmt())) { case 0: ++col; break; case 1: ++row; ++col; break; case 2: ++row; break; case 3: ++row; --col; break; case 4: --col; break; case 5: --row; --col; break; case 6: --row; break; case 7: --row; ++col; break; } return {row, col}; } void Simulation::life_cycle() { std::vector<std::vector<Patch> > parents(population); auto reproduction = [&](const size_t row, const size_t col) { auto offsprings = parents[row][col].mate_and_reproduce(wtl::sfmt()); std::vector<std::pair<size_t, size_t> > destinations; destinations.reserve(offsprings.size()); for (size_t i=0; i<offsprings.size(); ++i) { const auto dst = choose_patch(row, col); if ((dst.first >= NUM_ROWS) | (dst.second >= NUM_COLS)) { destinations.emplace_back(row, col); } else { destinations.push_back(std::move(dst)); } } for (size_t i=0; i<offsprings.size(); ++i) { const auto& dst = destinations[i]; population[dst.first][dst.second].append(std::move(offsprings[i])); } }; for (size_t row=0; row<NUM_ROWS; ++row) { for (size_t col=0; col<NUM_COLS; ++col) { reproduction(row, col); } } for (size_t row=0; row<NUM_ROWS; ++row) { for (size_t col=0; col<NUM_COLS; ++col) { population[row][col].viability_selection(wtl::sfmt()); } } } void Simulation::write_snapshot(const size_t time, std::ostream& ost) const { const char* sep = ","; if (time == 0) { ost << "time" << sep << "row" << sep << "col" << sep << "n" << sep << Individual::header() << "\n"; } std::size_t popsize = 0; for (size_t row=0; row<population.size(); ++row) { for (size_t col=0; col<population[row].size(); ++col) { for (const auto& item: population[row][col].summarize()) { ost << time << sep << row << sep << col << sep << item.second << sep << item.first << "\n"; popsize += item.second; } } } DCERR("N = " << popsize << std::endl); } <|endoftext|>
<commit_before>//===- mlir-op-gen.cpp - MLIR op generator --------------------------------===// // // Copyright 2019 The MLIR 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. // ============================================================================= // // This is a command line utility that generates C++ definitions for ops // declared in a op database. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Main.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/TableGenBackend.h" using namespace llvm; enum ActionType { PrintRecords, GenDefFile, GenOpDefinitions }; static cl::opt<ActionType> action( cl::desc("Action to perform:"), cl::values(clEnumValN(PrintRecords, "print-records", "Print all records to stdout (default)"), clEnumValN(GenDefFile, "gen-def-file", "Generate def file"), clEnumValN(GenOpDefinitions, "gen-op-definitions", "Generate op definitions"))); static cl::opt<std::string> opcodeClass("opcode-enum", cl::desc("The opcode enum to use")); // TODO(jpienaar): The builder body should probably be separate from the header. using AttrPair = std::pair<const RecordVal *, const Record *>; using AttrVector = SmallVectorImpl<AttrPair>; // Variation of method in FormatVariadic.h which takes a StringRef as input // instead. template <typename... Ts> inline auto formatv(StringRef fmt, Ts &&... vals) -> formatv_object<decltype( std::make_tuple(detail::build_format_adapter(std::forward<Ts>(vals))...))> { using ParamTuple = decltype( std::make_tuple(detail::build_format_adapter(std::forward<Ts>(vals))...)); return llvm::formatv_object<ParamTuple>( fmt, std::make_tuple(detail::build_format_adapter(std::forward<Ts>(vals))...)); } namespace { // Simple RAII helper for defining ifdef-undef-endif scopes. class IfDefScope { public: IfDefScope(StringRef name, raw_ostream &os) : name(name), os(os) { os << "#ifdef " << name << "\n" << "#undef " << name << "\n"; } ~IfDefScope() { os << "\n#endif // " << name << "\n\n"; } private: StringRef name; raw_ostream &os; }; } // end anonymous namespace namespace { // Helper class to emit a record into the given output stream. class OpEmitter { public: static void emit(const Record &def, raw_ostream &os); // Emit getters for the attributes of the operation. void emitAttrGetters(); // Emit builder method for the operation. void emitBuilder(); // Emit method declaration for the getCanonicalizationPatterns() interface. void emitCanonicalizationPatterns(); // Emit the parser for the operation. void emitParser(); // Emit the printer for the operation. void emitPrinter(); // Emit verify method for the operation. void emitVerifier(); // Emit the traits used by the object. void emitTraits(); // Populate the attributes of the op from its definition. void getAttributes(); private: OpEmitter(const Record &def, raw_ostream &os) : def(def), os(os){}; SmallVector<AttrPair, 4> attrs; const Record &def; raw_ostream &os; }; } // end anonymous namespace void OpEmitter::emit(const Record &def, raw_ostream &os) { OpEmitter emitter(def, os); // Query the returned type and operands types of the op. emitter.getAttributes(); os << "\nclass " << def.getName() << " : public Op<" << def.getName(); emitter.emitTraits(); os << "> {\npublic:\n"; // Build operation name. os << " static StringRef getOperationName() { return \"" << def.getValueAsString("name") << "\"; };\n"; emitter.emitBuilder(); emitter.emitParser(); emitter.emitPrinter(); emitter.emitVerifier(); emitter.emitAttrGetters(); emitter.emitCanonicalizationPatterns(); os << "private:\n friend class ::mlir::Operation;\n"; os << " explicit " << def.getName() << "(const Operation* state) : Op(state) {}\n"; os << "};\n"; } void OpEmitter::getAttributes() { const auto &recordKeeper = def.getRecords(); const auto attrType = recordKeeper.getClass("Attr"); for (const auto &val : def.getValues()) { if (auto *record = dyn_cast<RecordRecTy>(val.getType())) { if (record->isSubClassOf(attrType)) { if (record->getClasses().size() != 1) { PrintFatalError( def.getLoc(), "unsupported attribute modelling, only single class expected"); } attrs.emplace_back(&val, *record->getClasses().begin()); } } } } void OpEmitter::emitAttrGetters() { const auto &recordKeeper = def.getRecords(); const auto *derivedAttrType = recordKeeper.getClass("DerivedAttr")->getType(); for (const auto &pair : attrs) { auto &val = *pair.first; auto &attr = *pair.second; // Emit the derived attribute body. if (auto defInit = dyn_cast<DefInit>(val.getValue())) { if (defInit->getType()->typeIsA(derivedAttrType)) { auto *def = defInit->getDef(); os << " " << def->getValueAsString("returnType").trim() << ' ' << val.getName() << "() const {" << def->getValueAsString("body") << " }\n"; continue; } } // Emit normal emitter. os << " " << attr.getValueAsString("returnType").trim() << ' ' << val.getName() << "() const {\n"; // Return the queried attribute with the correct return type. const auto &attrVal = Twine("this->getAttrOfType<") + attr.getValueAsString("storageType").trim() + ">(\"" + val.getName() + "\").getValue()"; os << formatv(attr.getValueAsString("convertFromStorage"), attrVal.str()) << "\n }\n"; } } void OpEmitter::emitBuilder() { // If a custom builder is given then print that out instead. auto valueInit = def.getValueInit("builder"); CodeInit *codeInit = dyn_cast<CodeInit>(valueInit); if (!codeInit) return; auto builder = codeInit->getValue(); if (!builder.empty()) { os << builder << '\n'; return; } // TODO(jpienaar): Redo generating builder. } void OpEmitter::emitCanonicalizationPatterns() { if (!def.getValueAsBit("hasCanonicalizationPatterns")) return; os << " static void getCanonicalizationPatterns(" << "OwningRewritePatternList &results, MLIRContext* context);\n"; } void OpEmitter::emitParser() { auto valueInit = def.getValueInit("parser"); CodeInit *codeInit = dyn_cast<CodeInit>(valueInit); if (!codeInit) return; auto parser = codeInit->getValue(); os << " static bool parse(OpAsmParser *parser, OperationState *result) {" << "\n " << parser << "\n }\n"; } void OpEmitter::emitPrinter() { auto valueInit = def.getValueInit("printer"); CodeInit *codeInit = dyn_cast<CodeInit>(valueInit); if (!codeInit) return; auto printer = codeInit->getValue(); os << " void print(OpAsmPrinter *p) const {\n" << " " << printer << "\n }\n"; } void OpEmitter::emitVerifier() { auto valueInit = def.getValueInit("verifier"); CodeInit *codeInit = dyn_cast<CodeInit>(valueInit); bool hasCustomVerify = codeInit && !codeInit->getValue().empty(); if (!hasCustomVerify && attrs.empty()) return; const auto &recordKeeper = def.getRecords(); const auto *derivedAttrType = recordKeeper.getClass("DerivedAttr")->getType(); os << " bool verify() const {\n"; // Verify the attributes have the correct type. for (const auto attr : attrs) { // Skip verification for derived attributes. if (auto defInit = dyn_cast<DefInit>(attr.first->getValue())) if (defInit->getType()->typeIsA(derivedAttrType)) continue; auto name = attr.first->getName(); os << " if (!this->getAttr(\"" << name << "\").dyn_cast_or_null<" << attr.second->getValueAsString("storageType").trim() << ">(" << ")) return emitOpError(\"requires " << attr.second->getValueAsString("returnType").trim() << " attribute '" << name << "'\");\n"; } if (hasCustomVerify) os << " " << codeInit->getValue() << "\n"; else os << " return false;\n"; os << " }\n"; } void OpEmitter::emitTraits() { std::vector<Record *> returnTypes = def.getValueAsListOfDefs("returnTypes"); std::vector<Record *> operandTypes = def.getValueAsListOfDefs("operandTypes"); // Add return size trait. switch (returnTypes.size()) { case 0: os << ", OpTrait::ZeroResult"; break; case 1: os << ", OpTrait::OneResult"; break; default: os << ", OpTrait::NResults<" << returnTypes.size() << ">::Impl"; break; } // Add operand size trait. switch (operandTypes.size()) { case 0: os << ", OpTrait::ZeroOperands"; break; case 1: os << ", OpTrait::OneOperand"; break; default: os << ", OpTrait::NOperands<" << operandTypes.size() << ">::Impl"; break; } // Add op property traits. These match the propoerties specified in the table // with the OperationProperty specified in OperationSupport.h. for (Record *property : def.getValueAsListOfDefs("properties")) { if (property->getName() == "Commutative") { os << ", OpTrait::IsCommutative"; } else if (property->getName() == "NoSideEffect") { os << ", OpTrait::HasNoSideEffect"; } } // Add explicitly added traits. // TODO(jpienaar): Improve Trait specification to make adding them in the // tblgen file better. auto *recordVal = def.getValue("traits"); if (!recordVal || !recordVal->getValue()) return; auto traitList = dyn_cast<ListInit>(recordVal->getValue())->getValues(); for (Init *trait : traitList) os << ", OpTrait::" << StringRef(trait->getAsUnquotedString()).trim(); } // Emits the opcode enum and op classes. static void emitOpClasses(const RecordKeeper &recordKeeper, const std::vector<Record *> &defs, raw_ostream &os) { IfDefScope scope("GET_OP_CLASSES", os); // Enumeration of all the ops defined. os << "enum " << opcodeClass << " {\n"; for (int i = 0, e = defs.size(); i != e; ++i) { auto &def = defs[i]; os << (i != 0 ? "," : "") << "k" << def->getName(); } os << "\n};\n"; for (auto *def : defs) OpEmitter::emit(*def, os); } // Emits a comma-separated list of the ops. static void emitOpList(const std::vector<Record *> &defs, raw_ostream &os) { IfDefScope scope("GET_OP_LIST", os); bool first = true; for (auto &def : defs) { if (!first) os << ","; os << def->getName(); first = false; } } static void emitOpDefinitions(const RecordKeeper &recordKeeper, raw_ostream &os) { emitSourceFileHeader("List of ops", os); const auto &defs = recordKeeper.getAllDerivedDefinitions("Op"); emitOpList(defs, os); emitOpClasses(recordKeeper, defs, os); } static void emitOpDefFile(const RecordKeeper &recordKeeper, raw_ostream &os) { emitSourceFileHeader("Op def file", os); const auto &defs = recordKeeper.getAllDerivedDefinitions("Op"); os << "#ifndef ALL_OPS\n#define ALL_OPS(OP, NAME)\n#endif\n"; for (const auto *def : defs) { os << "ALL_OPS(" << def->getName() << ", \"" << def->getValueAsString("name") << "\")\n"; } os << "#undef ALL_OPS"; } static bool MlirOpTableGenMain(raw_ostream &os, RecordKeeper &records) { switch (action) { case PrintRecords: os << records; return false; case GenOpDefinitions: emitOpDefinitions(records, os); return false; case GenDefFile: emitOpDefFile(records, os); return false; } } int main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(argv[0]); PrettyStackTraceProgram X(argc, argv); cl::ParseCommandLineOptions(argc, argv); llvm_shutdown_obj Y; return TableGenMain(argv[0], &MlirOpTableGenMain); } <commit_msg>Enable using bare attributes.<commit_after>//===- mlir-op-gen.cpp - MLIR op generator --------------------------------===// // // Copyright 2019 The MLIR 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. // ============================================================================= // // This is a command line utility that generates C++ definitions for ops // declared in a op database. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Main.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/TableGenBackend.h" using namespace llvm; enum ActionType { PrintRecords, GenDefFile, GenOpDefinitions }; static cl::opt<ActionType> action( cl::desc("Action to perform:"), cl::values(clEnumValN(PrintRecords, "print-records", "Print all records to stdout (default)"), clEnumValN(GenDefFile, "gen-def-file", "Generate def file"), clEnumValN(GenOpDefinitions, "gen-op-definitions", "Generate op definitions"))); static cl::opt<std::string> opcodeClass("opcode-enum", cl::desc("The opcode enum to use")); // TODO(jpienaar): The builder body should probably be separate from the header. using AttrPair = std::pair<const RecordVal *, const Record *>; using AttrVector = SmallVectorImpl<AttrPair>; // Variation of method in FormatVariadic.h which takes a StringRef as input // instead. template <typename... Ts> inline auto formatv(StringRef fmt, Ts &&... vals) -> formatv_object<decltype( std::make_tuple(detail::build_format_adapter(std::forward<Ts>(vals))...))> { using ParamTuple = decltype( std::make_tuple(detail::build_format_adapter(std::forward<Ts>(vals))...)); return llvm::formatv_object<ParamTuple>( fmt, std::make_tuple(detail::build_format_adapter(std::forward<Ts>(vals))...)); } // Returns whether the record has a value of the given name that can be returned // via getValueAsString. static inline bool hasStringAttribute(const Record &record, StringRef fieldName) { auto valueInit = record.getValueInit(fieldName); return isa<CodeInit>(valueInit) || isa<StringInit>(valueInit); } namespace { // Simple RAII helper for defining ifdef-undef-endif scopes. class IfDefScope { public: IfDefScope(StringRef name, raw_ostream &os) : name(name), os(os) { os << "#ifdef " << name << "\n" << "#undef " << name << "\n"; } ~IfDefScope() { os << "\n#endif // " << name << "\n\n"; } private: StringRef name; raw_ostream &os; }; } // end anonymous namespace namespace { // Helper class to emit a record into the given output stream. class OpEmitter { public: static void emit(const Record &def, raw_ostream &os); // Emit getters for the attributes of the operation. void emitAttrGetters(); // Emit builder method for the operation. void emitBuilder(); // Emit method declaration for the getCanonicalizationPatterns() interface. void emitCanonicalizationPatterns(); // Emit the parser for the operation. void emitParser(); // Emit the printer for the operation. void emitPrinter(); // Emit verify method for the operation. void emitVerifier(); // Emit the traits used by the object. void emitTraits(); // Populate the attributes of the op from its definition. void getAttributes(); private: OpEmitter(const Record &def, raw_ostream &os) : def(def), os(os){}; SmallVector<AttrPair, 4> attrs; const Record &def; raw_ostream &os; }; } // end anonymous namespace void OpEmitter::emit(const Record &def, raw_ostream &os) { OpEmitter emitter(def, os); // Query the returned type and operands types of the op. emitter.getAttributes(); os << "\nclass " << def.getName() << " : public Op<" << def.getName(); emitter.emitTraits(); os << "> {\npublic:\n"; // Build operation name. os << " static StringRef getOperationName() { return \"" << def.getValueAsString("name") << "\"; };\n"; emitter.emitBuilder(); emitter.emitParser(); emitter.emitPrinter(); emitter.emitVerifier(); emitter.emitAttrGetters(); emitter.emitCanonicalizationPatterns(); os << "private:\n friend class ::mlir::Operation;\n"; os << " explicit " << def.getName() << "(const Operation* state) : Op(state) {}\n"; os << "};\n"; } void OpEmitter::getAttributes() { const auto &recordKeeper = def.getRecords(); const auto attrType = recordKeeper.getClass("Attr"); for (const auto &val : def.getValues()) { if (auto *record = dyn_cast<RecordRecTy>(val.getType())) { if (record->isSubClassOf(attrType)) { if (record->getClasses().size() != 1) { PrintFatalError( def.getLoc(), "unsupported attribute modelling, only single class expected"); } attrs.emplace_back(&val, *record->getClasses().begin()); } } } } void OpEmitter::emitAttrGetters() { const auto &recordKeeper = def.getRecords(); const auto *derivedAttrType = recordKeeper.getClass("DerivedAttr")->getType(); for (const auto &pair : attrs) { auto &val = *pair.first; auto &attr = *pair.second; // Emit the derived attribute body. if (auto defInit = dyn_cast<DefInit>(val.getValue())) { if (defInit->getType()->typeIsA(derivedAttrType)) { auto *def = defInit->getDef(); os << " " << def->getValueAsString("returnType").trim() << ' ' << val.getName() << "() const {" << def->getValueAsString("body") << " }\n"; continue; } } // Emit normal emitter. if (!hasStringAttribute(attr, "storageType")) { // Handle the base case where there is no storage type specified. os << " Attribute " << val.getName() << "() const {\n return getAttr(\"" << val.getName() << "\");\n }\n"; continue; } os << " " << attr.getValueAsString("returnType").trim() << ' ' << val.getName() << "() const {\n"; // Return the queried attribute with the correct return type. const auto &attrVal = Twine("this->getAttrOfType<") + attr.getValueAsString("storageType").trim() + ">(\"" + val.getName() + "\").getValue()"; os << formatv(attr.getValueAsString("convertFromStorage"), attrVal.str()) << "\n }\n"; } } void OpEmitter::emitBuilder() { if (!hasStringAttribute(def, "builder")) return; // If a custom builder is given then print that out instead. auto builder = def.getValueAsString("builder"); if (!builder.empty()) { os << builder << '\n'; return; } // TODO(jpienaar): Redo generating builder. } void OpEmitter::emitCanonicalizationPatterns() { if (!def.getValueAsBit("hasCanonicalizationPatterns")) return; os << " static void getCanonicalizationPatterns(" << "OwningRewritePatternList &results, MLIRContext* context);\n"; } void OpEmitter::emitParser() { if (!hasStringAttribute(def, "parser")) return; os << " static bool parse(OpAsmParser *parser, OperationState *result) {" << "\n " << def.getValueAsString("parser") << "\n }\n"; } void OpEmitter::emitPrinter() { auto valueInit = def.getValueInit("printer"); CodeInit *codeInit = dyn_cast<CodeInit>(valueInit); if (!codeInit) return; auto printer = codeInit->getValue(); os << " void print(OpAsmPrinter *p) const {\n" << " " << printer << "\n }\n"; } void OpEmitter::emitVerifier() { auto valueInit = def.getValueInit("verifier"); CodeInit *codeInit = dyn_cast<CodeInit>(valueInit); bool hasCustomVerify = codeInit && !codeInit->getValue().empty(); if (!hasCustomVerify && attrs.empty()) return; const auto &recordKeeper = def.getRecords(); const auto *derivedAttrType = recordKeeper.getClass("DerivedAttr")->getType(); os << " bool verify() const {\n"; // Verify the attributes have the correct type. for (const auto attr : attrs) { // Skip verification for derived attributes. if (auto defInit = dyn_cast<DefInit>(attr.first->getValue())) if (defInit->getType()->typeIsA(derivedAttrType)) continue; auto name = attr.first->getName(); if (!hasStringAttribute(*attr.second, "storageType")) { os << " if (!this->getAttr(\"" << name << "\")) return emitOpError(\"requires attribute '" << name << "'\");\n"; continue; } os << " if (!this->getAttr(\"" << name << "\").dyn_cast_or_null<" << attr.second->getValueAsString("storageType").trim() << ">(" << ")) return emitOpError(\"requires " << attr.second->getValueAsString("returnType").trim() << " attribute '" << name << "'\");\n"; } if (hasCustomVerify) os << " " << codeInit->getValue() << "\n"; else os << " return false;\n"; os << " }\n"; } void OpEmitter::emitTraits() { std::vector<Record *> returnTypes = def.getValueAsListOfDefs("returnTypes"); std::vector<Record *> operandTypes = def.getValueAsListOfDefs("operandTypes"); // Add return size trait. switch (returnTypes.size()) { case 0: os << ", OpTrait::ZeroResult"; break; case 1: os << ", OpTrait::OneResult"; break; default: os << ", OpTrait::NResults<" << returnTypes.size() << ">::Impl"; break; } // Add operand size trait. switch (operandTypes.size()) { case 0: os << ", OpTrait::ZeroOperands"; break; case 1: os << ", OpTrait::OneOperand"; break; default: os << ", OpTrait::NOperands<" << operandTypes.size() << ">::Impl"; break; } // Add op property traits. These match the propoerties specified in the table // with the OperationProperty specified in OperationSupport.h. for (Record *property : def.getValueAsListOfDefs("properties")) { if (property->getName() == "Commutative") { os << ", OpTrait::IsCommutative"; } else if (property->getName() == "NoSideEffect") { os << ", OpTrait::HasNoSideEffect"; } } // Add explicitly added traits. // TODO(jpienaar): Improve Trait specification to make adding them in the // tblgen file better. auto *recordVal = def.getValue("traits"); if (!recordVal || !recordVal->getValue()) return; auto traitList = dyn_cast<ListInit>(recordVal->getValue())->getValues(); for (Init *trait : traitList) os << ", OpTrait::" << StringRef(trait->getAsUnquotedString()).trim(); } // Emits the opcode enum and op classes. static void emitOpClasses(const RecordKeeper &recordKeeper, const std::vector<Record *> &defs, raw_ostream &os) { IfDefScope scope("GET_OP_CLASSES", os); // Enumeration of all the ops defined. os << "enum " << opcodeClass << " {\n"; for (int i = 0, e = defs.size(); i != e; ++i) { auto &def = defs[i]; os << (i != 0 ? "," : "") << "k" << def->getName(); } os << "\n};\n"; for (auto *def : defs) OpEmitter::emit(*def, os); } // Emits a comma-separated list of the ops. static void emitOpList(const std::vector<Record *> &defs, raw_ostream &os) { IfDefScope scope("GET_OP_LIST", os); bool first = true; for (auto &def : defs) { if (!first) os << ","; os << def->getName(); first = false; } } static void emitOpDefinitions(const RecordKeeper &recordKeeper, raw_ostream &os) { emitSourceFileHeader("List of ops", os); const auto &defs = recordKeeper.getAllDerivedDefinitions("Op"); emitOpList(defs, os); emitOpClasses(recordKeeper, defs, os); } static void emitOpDefFile(const RecordKeeper &recordKeeper, raw_ostream &os) { emitSourceFileHeader("Op def file", os); const auto &defs = recordKeeper.getAllDerivedDefinitions("Op"); os << "#ifndef ALL_OPS\n#define ALL_OPS(OP, NAME)\n#endif\n"; for (const auto *def : defs) { os << "ALL_OPS(" << def->getName() << ", \"" << def->getValueAsString("name") << "\")\n"; } os << "#undef ALL_OPS"; } static bool MlirOpTableGenMain(raw_ostream &os, RecordKeeper &records) { switch (action) { case PrintRecords: os << records; return false; case GenOpDefinitions: emitOpDefinitions(records, os); return false; case GenDefFile: emitOpDefFile(records, os); return false; } } int main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(argv[0]); PrettyStackTraceProgram X(argc, argv); cl::ParseCommandLineOptions(argc, argv); llvm_shutdown_obj Y; return TableGenMain(argv[0], &MlirOpTableGenMain); } <|endoftext|>
<commit_before>/* * This file is part of QZeitgeist. * * Copyright (C) 2013 David Rosca <nowrep@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ extern "C" { #include <zeitgeist.h> } #include "monitor.h" #include "resultset.h" #include "tools.h" namespace QZeitgeist { static void on_events_deleted(ZeitgeistMonitor *, ZeitgeistTimeRange *time_range, guint32 *event_ids, int events_length, gpointer user_data) { Monitor *monitor = (Monitor *)user_data; TimeRange tr = TimeRange::fromHandle(time_range); QList<quint32> ids; for (int i = 0; i < events_length; ++i) { ids.append(event_ids[i]); } Q_EMIT monitor->eventsDeleted(tr, ids); } static void on_events_inserted(ZeitgeistMonitor *, ZeitgeistTimeRange *time_range, ZeitgeistResultSet *events, gpointer user_data) { Monitor *monitor = (Monitor *)user_data; TimeRange tr = TimeRange::fromHandle(time_range); ResultSet resultSet(events); Q_EMIT monitor->eventsInserted(tr, resultSet); } Monitor::Monitor(const TimeRange &timeRange, const QList<Event> &eventTemplates, QObject *parent) : QObject(parent) { ZeitgeistTimeRange *tr = (ZeitgeistTimeRange *)timeRange.createHandle(); GPtrArray *templates = Tools::eventsToPtrArray(eventTemplates); ZeitgeistMonitor *monitor = zeitgeist_monitor_new(tr, templates); g_signal_connect(monitor, "events-deleted", G_CALLBACK(on_events_deleted), this); g_signal_connect(monitor, "events-inserted", G_CALLBACK(on_events_inserted), this); g_object_unref(tr); g_ptr_array_unref(templates); m_handle = monitor; Q_ASSERT(m_handle); } Monitor::~Monitor() { g_object_unref(m_handle); } QList<Event> Monitor::eventTemplates() const { GPtrArray *templates = zeitgeist_monitor_get_event_templates((ZeitgeistMonitor *)m_handle); return Tools::eventsFromPtrArray(templates); } void Monitor::setEventTemplates(const QList<Event> &eventTemplates) { GPtrArray *templates = Tools::eventsToPtrArray(eventTemplates); zeitgeist_monitor_set_event_templates((ZeitgeistMonitor *)m_handle, templates); g_ptr_array_unref(templates); } TimeRange Monitor::timeRange() const { ZeitgeistTimeRange *tr = zeitgeist_monitor_get_time_range((ZeitgeistMonitor *)m_handle); return TimeRange::fromHandle(tr); } void Monitor::setTimeRange(const TimeRange &timeRange) { ZeitgeistTimeRange *tr = (ZeitgeistTimeRange *)timeRange.createHandle(); zeitgeist_monitor_set_time_range((ZeitgeistMonitor *)m_handle, tr); g_object_unref(tr); } HANDLE Monitor::getHandle() const { return m_handle; } }; // namespace QZeitgeist <commit_msg>Use C++ static_cast when casting to class pointers.<commit_after>/* * This file is part of QZeitgeist. * * Copyright (C) 2013 David Rosca <nowrep@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ extern "C" { #include <zeitgeist.h> } #include "monitor.h" #include "resultset.h" #include "tools.h" namespace QZeitgeist { static void on_events_deleted(ZeitgeistMonitor *, ZeitgeistTimeRange *time_range, guint32 *event_ids, int events_length, gpointer user_data) { Monitor *monitor = static_cast<Monitor *>(user_data); TimeRange tr = TimeRange::fromHandle(time_range); QList<quint32> ids; for (int i = 0; i < events_length; ++i) { ids.append(event_ids[i]); } Q_EMIT monitor->eventsDeleted(tr, ids); } static void on_events_inserted(ZeitgeistMonitor *, ZeitgeistTimeRange *time_range, ZeitgeistResultSet *events, gpointer user_data) { Monitor *monitor = static_cast<Monitor *>(user_data); TimeRange tr = TimeRange::fromHandle(time_range); ResultSet resultSet(events); Q_EMIT monitor->eventsInserted(tr, resultSet); } Monitor::Monitor(const TimeRange &timeRange, const QList<Event> &eventTemplates, QObject *parent) : QObject(parent) { ZeitgeistTimeRange *tr = (ZeitgeistTimeRange *)timeRange.createHandle(); GPtrArray *templates = Tools::eventsToPtrArray(eventTemplates); ZeitgeistMonitor *monitor = zeitgeist_monitor_new(tr, templates); g_signal_connect(monitor, "events-deleted", G_CALLBACK(on_events_deleted), this); g_signal_connect(monitor, "events-inserted", G_CALLBACK(on_events_inserted), this); g_object_unref(tr); g_ptr_array_unref(templates); m_handle = monitor; Q_ASSERT(m_handle); } Monitor::~Monitor() { g_object_unref(m_handle); } QList<Event> Monitor::eventTemplates() const { GPtrArray *templates = zeitgeist_monitor_get_event_templates((ZeitgeistMonitor *)m_handle); return Tools::eventsFromPtrArray(templates); } void Monitor::setEventTemplates(const QList<Event> &eventTemplates) { GPtrArray *templates = Tools::eventsToPtrArray(eventTemplates); zeitgeist_monitor_set_event_templates((ZeitgeistMonitor *)m_handle, templates); g_ptr_array_unref(templates); } TimeRange Monitor::timeRange() const { ZeitgeistTimeRange *tr = zeitgeist_monitor_get_time_range((ZeitgeistMonitor *)m_handle); return TimeRange::fromHandle(tr); } void Monitor::setTimeRange(const TimeRange &timeRange) { ZeitgeistTimeRange *tr = (ZeitgeistTimeRange *)timeRange.createHandle(); zeitgeist_monitor_set_time_range((ZeitgeistMonitor *)m_handle, tr); g_object_unref(tr); } HANDLE Monitor::getHandle() const { return m_handle; } }; // namespace QZeitgeist <|endoftext|>
<commit_before>/* Copyright (C) Gbor "Razzie" Grzsny Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE */ #pragma once #include <array> #include <cstdint> #include <map> #include <memory> #include <tuple> #include <type_traits> #include "raz/hash.hpp" #ifndef RAZ_INPUT_AXIS_DIMENSION #define RAZ_INPUT_AXIS_DIMENSION 2 #endif namespace raz { struct Input { enum InputType : unsigned { Unknown = (1 << 0), ButtonPressed = (1 << 1), ButtonHold = (1 << 2), ButtonReleased = (1 << 3), AxisChanged = (1 << 4) }; typedef std::array<float, RAZ_INPUT_AXIS_DIMENSION> AxisValue; Input() : type(InputType::Unknown), button(0), axis(0), device(0), action(0) { axis_value.fill(0.f); axis_delta.fill(0.f); } InputType type; uint32_t button; uint32_t axis; AxisValue axis_value; AxisValue axis_delta; uint32_t device; uint32_t action; mutable bool handled = false; }; class Action; typedef std::shared_ptr<Action> ActionPtr; class Action : public std::enable_shared_from_this<Action> { public: virtual ~Action() = default; virtual bool tryInput(const Input&) const = 0; operator ActionPtr() { return shared_from_this(); } static ActionPtr createButtonAction(uint32_t button, Input::InputType mask = static_cast<Input::InputType>(Input::ButtonPressed | Input::ButtonHold)) { class ButtonAction : public Action { public: ButtonAction(uint32_t button, Input::InputType mask) : m_button(button), m_mask(mask) { } virtual bool tryInput(const Input& input) const { return ((input.button == m_button) && (input.type & m_mask)); } private: uint32_t m_button; Input::InputType m_mask; }; return std::make_shared<ButtonAction>(button, mask); } static ActionPtr createAxisAction(uint32_t axis) { class AxisAction : public Action { public: AxisAction(uint32_t axis) : m_axis(axis) { } virtual bool tryInput(const Input& input) const { return (input.axis == m_axis); } private: uint32_t m_axis; }; return std::make_shared<AxisAction>(axis); } }; template<uint32_t ButtonCount, uint32_t AxisCount, uint32_t ID = 0> class InputDevice { public: enum ButtonState { Released, Pressed, Hold }; struct ButtonPressed { typedef InputDevice Device; ButtonPressed(uint32_t button) : button(button) { } uint32_t button; }; struct ButtonReleased { typedef InputDevice Device; ButtonReleased(uint32_t button) : button(button) { } uint32_t button; }; struct AxisChanged { typedef InputDevice Device; AxisChanged(uint32_t axis, Input::AxisValue axis_value) : axis(axis), axis_value(axis_value) { } uint32_t axis; Input::AxisValue axis_value; }; InputDevice() { for (auto& axis_value : m_axis_values) axis_value.fill(0.f); } static constexpr uint32_t getID() { return ID; } ButtonState getButtonState(uint32_t button) { return m_btn_states[button]; } float getAxisValue(uint32_t axis) { m_axis_values[axis]; } Input operator()(ButtonPressed event) { auto& state = m_btn_states[event.button]; if (state == ButtonState::Pressed) state = ButtonState::Hold; else state = ButtonState::Pressed; Input input; input.type = Input::ButtonPressed; input.button = event.button; input.device = ID; return input; } Input operator()(ButtonReleased event) { auto& state = m_btn_states[event.button]; state = ButtonState::Released; Input input; input.type = Input::ButtonReleased; input.button = event.button; input.device = ID; return input; } Input operator()(AxisChanged event) { auto& axis_value = m_axis_values[event.axis]; auto old_axis_value = axis_value; axis_value = event.axis_value; Input input; input.type = Input::AxisChanged; input.axis = event.axis; input.axis_value = event.axis; input.axis_delta = event.axis_value; for (int i = 0; i < input.axis_delta.size(); ++i) input.axis_delta[i] -= old_axis_value[i]; input.device = ID; return input; } private: std::conditional_t<(ButtonCount > 256), typename std::map<uint32_t, ButtonState>, typename std::array<ButtonState, ButtonCount>> m_btn_states; std::array<Input::AxisValue, AxisCount> m_axis_values; }; typedef InputDevice<256, 0> CharKeyboard; typedef InputDevice<~0u, 0> Keyboard; typedef InputDevice<3, 3> Mouse; template<uint32_t ID> using GamePad = typename InputDevice<12, 6, ID>; template<class... InputDevices> class ActionMap { public: void bind(uint32_t action_id, ActionPtr action_ptr) { m_actions[action_id] = action_ptr; } void unbind(uint32_t action_id) { m_actions.erase(action_id); } template<class InputEvent, class... Handlers> void operator()(InputEvent event, Handlers&... handlers) { auto& device = std::get<typename InputEvent::Device>(m_devices); auto input = device(event); tryActions(input, handlers...); } private: std::tuple<InputDevices...> m_devices; std::map<uint32_t, ActionPtr> m_actions; template<class... Handlers> void tryActions(Input input, Handlers&... handlers) { for (auto& action : m_actions) { if (action.second->tryInput(input)) { input.action = action.first; invokeHandlers(input, handlers...); } } } template<class Handler0, class... Handlers> void invokeHandlers(const Input& input, Handler0& handler, Handlers&... handlers) { handler(input); if (!input.handled) invokeHandlers(input, handlers...); } template<class... Handlers> void invokeHandlers(const Input& input, Handlers&... handlers) { } }; namespace literal { constexpr uint32_t operator"" _action(const char* action, size_t) { return (uint32_t)hash(action); } } } raz::ActionPtr operator&&(raz::ActionPtr action1, raz::ActionPtr action2) { class AndAction : public raz::Action { public: AndAction(raz::ActionPtr action1, raz::ActionPtr action2) : m_action1(action1), m_action2(action2) { } virtual bool tryInput(const raz::Input& input) const { return (m_action1->tryInput(input) && m_action2->tryInput(input)); } private: raz::ActionPtr m_action1; raz::ActionPtr m_action2; }; return std::make_shared<AndAction>(action1, action2); } raz::ActionPtr operator||(raz::ActionPtr action1, raz::ActionPtr action2) { class OrAction : public raz::Action { public: OrAction(raz::ActionPtr action1, raz::ActionPtr action2) : m_action1(action1), m_action2(action2) { } virtual bool tryInput(const raz::Input& input) const { return (m_action1->tryInput(input) || m_action2->tryInput(input)); } private: raz::ActionPtr m_action1; raz::ActionPtr m_action2; }; return std::make_shared<OrAction>(action1, action2); } raz::ActionPtr operator!(raz::ActionPtr action) { class NotAction : public raz::Action { public: NotAction(raz::ActionPtr action) : m_action(action) { } virtual bool tryInput(const raz::Input& input) const { return (!m_action->tryInput(input)); } private: raz::ActionPtr m_action; }; return std::make_shared<NotAction>(action); } <commit_msg>Minor changes in event handling<commit_after>/* Copyright (C) Gbor "Razzie" Grzsny Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE */ #pragma once #include <array> #include <cstdint> #include <map> #include <memory> #include <tuple> #include <type_traits> #include "raz/hash.hpp" #ifndef RAZ_INPUT_AXIS_DIMENSION #define RAZ_INPUT_AXIS_DIMENSION 2 #endif namespace raz { struct Input { enum InputType : unsigned { Unknown = (1 << 0), ButtonPressed = (1 << 1), ButtonHold = (1 << 2), ButtonReleased = (1 << 3), AxisChanged = (1 << 4) }; typedef std::array<float, RAZ_INPUT_AXIS_DIMENSION> AxisValue; Input() : type(InputType::Unknown), button(0), axis(0), device(0), action(0), handled(false) { axis_value.fill(0.f); axis_delta.fill(0.f); } InputType type; uint32_t button; uint32_t axis; AxisValue axis_value; AxisValue axis_delta; uint32_t device; uint32_t action; mutable bool handled; }; class Action; typedef std::shared_ptr<Action> ActionPtr; class Action : public std::enable_shared_from_this<Action> { public: static ActionPtr createButtonAction(uint32_t button, Input::InputType mask = static_cast<Input::InputType>(Input::ButtonPressed | Input::ButtonHold)) { class ButtonAction : public Action { public: ButtonAction(uint32_t button, Input::InputType mask) : m_button(button), m_mask(mask) { } virtual bool tryInput(const Input& input) const { return ((input.button == m_button) && (input.type & m_mask)); } private: uint32_t m_button; Input::InputType m_mask; }; return std::make_shared<ButtonAction>(button, mask); } static ActionPtr createAxisAction(uint32_t axis) { class AxisAction : public Action { public: AxisAction(uint32_t axis) : m_axis(axis) { } virtual bool tryInput(const Input& input) const { return (input.axis == m_axis); } private: uint32_t m_axis; }; return std::make_shared<AxisAction>(axis); } virtual ~Action() = default; virtual bool tryInput(const Input&) const = 0; operator ActionPtr() { return shared_from_this(); } }; template<uint32_t ButtonCount, uint32_t AxisCount, uint32_t ID = 0> class InputDevice { public: enum ButtonState { Released, Pressed, Hold }; struct ButtonPressed { typedef InputDevice Device; ButtonPressed(uint32_t button) : button(button) { } uint32_t button; }; struct ButtonReleased { typedef InputDevice Device; ButtonReleased(uint32_t button) : button(button) { } uint32_t button; }; struct AxisChanged { typedef InputDevice Device; AxisChanged(uint32_t axis, Input::AxisValue axis_value) : axis(axis), axis_value(axis_value) { } uint32_t axis; Input::AxisValue axis_value; }; InputDevice() { for (auto& axis_value : m_axis_values) axis_value.fill(0.f); } static constexpr uint32_t getID() { return ID; } ButtonState getButtonState(uint32_t button) const { return m_btn_states[button]; } const Input::AxisValue& getAxisValue(uint32_t axis) const { m_axis_values[axis]; } Input operator()(ButtonPressed event) { auto& state = m_btn_states[event.button]; if (state == ButtonState::Pressed) state = ButtonState::Hold; else state = ButtonState::Pressed; Input input; input.type = Input::ButtonPressed; input.button = event.button; input.device = ID; return input; } Input operator()(ButtonReleased event) { auto& state = m_btn_states[event.button]; state = ButtonState::Released; Input input; input.type = Input::ButtonReleased; input.button = event.button; input.device = ID; return input; } Input operator()(AxisChanged event) { auto& axis_value = m_axis_values[event.axis]; auto old_axis_value = axis_value; axis_value = event.axis_value; Input input; input.type = Input::AxisChanged; input.axis = event.axis; input.axis_value = event.axis; input.axis_delta = event.axis_value; for (int i = 0; i < input.axis_delta.size(); ++i) input.axis_delta[i] -= old_axis_value[i]; input.device = ID; return input; } private: std::conditional_t<(ButtonCount > 256), typename std::map<uint32_t, ButtonState>, typename std::array<ButtonState, ButtonCount>> m_btn_states; std::array<Input::AxisValue, AxisCount> m_axis_values; }; typedef InputDevice<256, 0> CharKeyboard; typedef InputDevice<~0u, 0> Keyboard; typedef InputDevice<3, 2> Mouse; // three buttons + one XY axis and a mouse wheel one template<uint32_t ID> using GamePad = typename InputDevice<12, 4, ID>; template<class... InputDevices> class ActionMap { public: void bind(uint32_t action_id, ActionPtr action_ptr) { m_actions[action_id] = action_ptr; } void unbind(uint32_t action_id) { m_actions.erase(action_id); } template<class InputEvent, class... Handlers> void operator()(InputEvent event, Handlers&... handlers) { auto& device = std::get<typename InputEvent::Device>(m_devices); auto input = device(event); tryActions(input, handlers...); } private: std::tuple<InputDevices...> m_devices; std::map<uint32_t, ActionPtr> m_actions; template<class... Handlers> void tryActions(Input input, Handlers&... handlers) { for (auto& action : m_actions) { if (action.second->tryInput(input)) { input.action = action.first; invokeHandlers(input, handlers...); } } } template<class Handler0, class... Handlers> void invokeHandlers(const Input& input, Handler0& handler, Handlers&... handlers) { handler(input); if (!input.handled) invokeHandlers(input, handlers...); } template<class... Handlers> void invokeHandlers(const Input& input, Handlers&... handlers) { } }; namespace literal { constexpr uint32_t operator"" _action(const char* action, size_t) { return (uint32_t)hash(action); } } } raz::ActionPtr operator&&(raz::ActionPtr action1, raz::ActionPtr action2) { class AndAction : public raz::Action { public: AndAction(raz::ActionPtr action1, raz::ActionPtr action2) : m_action1(action1), m_action2(action2) { } virtual bool tryInput(const raz::Input& input) const { return (m_action1->tryInput(input) && m_action2->tryInput(input)); } private: raz::ActionPtr m_action1; raz::ActionPtr m_action2; }; return std::make_shared<AndAction>(action1, action2); } raz::ActionPtr operator||(raz::ActionPtr action1, raz::ActionPtr action2) { class OrAction : public raz::Action { public: OrAction(raz::ActionPtr action1, raz::ActionPtr action2) : m_action1(action1), m_action2(action2) { } virtual bool tryInput(const raz::Input& input) const { return (m_action1->tryInput(input) || m_action2->tryInput(input)); } private: raz::ActionPtr m_action1; raz::ActionPtr m_action2; }; return std::make_shared<OrAction>(action1, action2); } raz::ActionPtr operator!(raz::ActionPtr action) { class NotAction : public raz::Action { public: NotAction(raz::ActionPtr action) : m_action(action) { } virtual bool tryInput(const raz::Input& input) const { return (!m_action->tryInput(input)); } private: raz::ActionPtr m_action; }; return std::make_shared<NotAction>(action); } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <linux/joystick.h> #define JOY_DEV "/dev/input/js0" int main() { int joy_fd, *axis=NULL, num_of_axis=0, num_of_buttons=0, x; char *button=NULL, name_of_joystick[80]; struct js_event js; if( ( joy_fd = open( JOY_DEV , O_RDONLY)) == -1 ) { printf( "Couldn't open joystick\n" ); return -1; } ioctl( joy_fd, JSIOCGAXES, &num_of_axis ); ioctl( joy_fd, JSIOCGBUTTONS, &num_of_buttons ); ioctl( joy_fd, JSIOCGNAME(80), &name_of_joystick ); axis = (int *) calloc( num_of_axis, sizeof( int ) ); button = (char *) calloc( num_of_buttons, sizeof( char ) ); printf("Joystick detected: %s\n\t%d axis\n\t%d buttons\n\n" , name_of_joystick , num_of_axis , num_of_buttons ); fcntl( joy_fd, F_SETFL, O_NONBLOCK ); /* use non-blocking mode */ while( 1 ) /* infinite loop */ { /* read the joystick state */ read(joy_fd, &js, sizeof(struct js_event)); /* see what to do with the event */ switch (js.type & ~JS_EVENT_INIT) { case JS_EVENT_AXIS: axis [ js.number ] = js.value; break; case JS_EVENT_BUTTON: button [ js.number ] = js.value; break; } /* print the results */ printf( "X: %6d Y: %6d ", axis[0], axis[1] ); if( num_of_axis > 2 ) printf("Z: %6d ", axis[2] ); if( num_of_axis > 3 ) printf("R: %6d ", axis[3] ); for( x=0 ; x<num_of_buttons ; ++x ) printf("B%d: %d ", x, button[x] ); printf(" \r"); fflush(stdout); } close( joy_fd ); /* too bad we never get here */ return 0; } <commit_msg>moving js stuff to joystick<commit_after><|endoftext|>
<commit_before>/* * DesktopWebView.cpp * * Copyright (C) 2009-18 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "DesktopWebView.hpp" #include <QApplication> #include <QClipboard> #include <QMenu> #include <QNetworkReply> #include <QStyleFactory> #include <QWebEngineContextMenuData> #include <QWebEngineSettings> #include <QWebEngineHistory> #include <core/system/Environment.hpp> #include "DesktopBrowserWindow.hpp" #ifdef _WIN32 #include <windows.h> #include <wingdi.h> #endif namespace rstudio { namespace desktop { namespace { #if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0) class DevToolsWindow : public QMainWindow { public: DevToolsWindow() : webPage_(new QWebEnginePage(this)), webView_(new QWebEngineView(this)) { webView_->setPage(webPage_); QScreen* screen = QApplication::primaryScreen(); QRect geometry = screen->geometry(); resize(geometry.width() * 0.7, geometry.height() * 0.7); setWindowTitle(QStringLiteral("RStudio DevTools")); setAttribute(Qt::WA_DeleteOnClose, false); setAttribute(Qt::WA_QuitOnClose, true); setUnifiedTitleAndToolBarOnMac(true); setCentralWidget(webView_); } QWebEnginePage* webPage() { return webPage_; } QWebEngineView* webView() { return webView_; } private: QWebEnginePage* webPage_; QWebEngineView* webView_; }; std::map<QWebEnginePage*, DevToolsWindow*> s_devToolsWindows; #endif } // end anonymous namespace WebView::WebView(QUrl baseUrl, QWidget *parent, bool allowExternalNavigate) : QWebEngineView(parent), baseUrl_(baseUrl) { #ifdef Q_OS_LINUX if (!core::system::getenv("KDE_FULL_SESSION").empty()) { QString fusion = QString::fromUtf8("fusion"); if (QStyleFactory::keys().contains(fusion)) setStyle(QStyleFactory::create(fusion)); } #endif pWebPage_ = new WebPage(baseUrl, this, allowExternalNavigate); setPage(pWebPage_); } void WebView::setBaseUrl(const QUrl& baseUrl) { baseUrl_ = baseUrl; pWebPage_->setBaseUrl(baseUrl_); } QUrl WebView::baseUrl() { return baseUrl_; } void WebView::activateSatelliteWindow(QString name) { pWebPage_->activateWindow(name); } void WebView::prepareForWindow(const PendingWindow& pendingWnd) { pWebPage_->prepareForWindow(pendingWnd); } QString WebView::promptForFilename(const QNetworkRequest& request, QNetworkReply* pReply = nullptr) { QString defaultFileName = QFileInfo(request.url().path()).fileName(); // Content-Disposition's filename parameter should be used as the // default, if present. if (pReply && pReply->hasRawHeader("content-disposition")) { QString headerValue = QString::fromUtf8(pReply->rawHeader("content-disposition")); QRegExp regexp(QString::fromUtf8("filename=\"?([^\"]+)\"?"), Qt::CaseInsensitive); if (regexp.indexIn(headerValue) >= 0) { defaultFileName = regexp.cap(1); } } QString fileName = QFileDialog::getSaveFileName(this, tr("Download File"), defaultFileName, QString(), nullptr, standardFileDialogOptions()); return fileName; } void WebView::keyPressEvent(QKeyEvent* pEvent) { #ifdef Q_OS_MAC if (pEvent->key() == Qt::Key_W && pEvent->modifiers() == Qt::CTRL) { // on macOS, intercept Cmd+W and emit the window close signal onCloseWindowShortcut(); } else { // pass other key events through to WebEngine QWebEngineView::keyPressEvent(pEvent); } #else QWebEngineView::keyPressEvent(pEvent); #endif } void WebView::openFile(QString fileName) { // force use of Preview for PDFs on the Mac (Adobe Reader 10.01 crashes) #ifdef Q_OS_MAC if (fileName.toLower().endsWith(QString::fromUtf8(".pdf"))) { QStringList args; args.append(QString::fromUtf8("-a")); args.append(QString::fromUtf8("Preview")); args.append(fileName); QProcess::startDetached(QString::fromUtf8("open"), args); return; } #endif QDesktopServices::openUrl(QUrl::fromLocalFile(fileName)); } bool WebView::event(QEvent* event) { if (event->type() == QEvent::ShortcutOverride) { // take a first crack at shortcuts keyPressEvent(static_cast<QKeyEvent*>(event)); return true; } return this->QWebEngineView::event(event); } void WebView::closeEvent(QCloseEvent*) { } void WebView::contextMenuEvent(QContextMenuEvent* event) { QMenu* menu = new QMenu(this); const auto& data = webPage()->contextMenuData(); bool canNavigateHistory = webPage()->history()->canGoBack() || webPage()->history()->canGoForward(); if (data.selectedText().isEmpty() && canNavigateHistory) { auto* back = menu->addAction(tr("&Back"), [&]() { webPage()->history()->back(); }); back->setEnabled(webPage()->history()->canGoBack()); auto* forward = menu->addAction(tr("&Forward"), [&]() { webPage()->history()->forward(); }); forward->setEnabled(webPage()->history()->canGoForward()); menu->addSeparator(); } if (data.mediaUrl().isValid()) { switch (data.mediaType()) { case QWebEngineContextMenuData::MediaTypeImage: menu->addAction(webPage()->action(QWebEnginePage::DownloadImageToDisk)); menu->addAction(webPage()->action(QWebEnginePage::CopyImageUrlToClipboard)); menu->addAction(webPage()->action(QWebEnginePage::CopyImageToClipboard)); break; case QWebEngineContextMenuData::MediaTypeAudio: case QWebEngineContextMenuData::MediaTypeVideo: menu->addAction(webPage()->action(QWebEnginePage::DownloadMediaToDisk)); menu->addAction(webPage()->action(QWebEnginePage::CopyMediaUrlToClipboard)); menu->addAction(webPage()->action(QWebEnginePage::ToggleMediaPlayPause)); menu->addAction(webPage()->action(QWebEnginePage::ToggleMediaLoop)); break; case QWebEngineContextMenuData::MediaTypeFile: menu->addAction(webPage()->action(QWebEnginePage::DownloadLinkToDisk)); menu->addAction(webPage()->action(QWebEnginePage::CopyMediaUrlToClipboard)); break; default: break; } } else if (data.linkUrl().isValid()) { menu->addAction(tr("Open Link in &Browser"), [=]() { desktop::openUrl(data.linkUrl()); }); menu->addAction(webPage()->action(QWebEnginePage::CopyLinkToClipboard)); menu->addAction(tr("&Save Link As..."), [=]() { triggerPageAction(QWebEnginePage::DownloadLinkToDisk); }); } else { // always show cut / copy / paste, but only enable cut / copy if there // is some selected text, and only enable paste if there is something // on the clipboard. note that this isn't perfect -- the highlighted // text may not correspond to the context menu click target -- but // in general users who want to copy text will right-click on the // selection, rather than elsewhere on the screen. auto* cut = webPage()->action(QWebEnginePage::Cut); auto* copy = webPage()->action(QWebEnginePage::Copy); auto* paste = webPage()->action(QWebEnginePage::Paste); cut->setEnabled(data.isContentEditable() && !data.selectedText().isEmpty()); copy->setEnabled(!data.selectedText().isEmpty()); paste->setEnabled(QApplication::clipboard()->mimeData()->hasText()); menu->addAction(cut); menu->addAction(copy); menu->addAction(paste); menu->addSeparator(); menu->addAction(webPage()->action(QWebEnginePage::SelectAll)); } #if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0) menu->addSeparator(); menu->addAction(tr("&Reload"), [&]() { triggerPageAction(QWebEnginePage::Reload); }); menu->addAction(tr("&Inspect Element"), [&]() { QWebEnginePage* devToolsPage = webPage()->devToolsPage(); if (devToolsPage == nullptr) { DevToolsWindow* devToolsWindow = new DevToolsWindow(); devToolsPage = devToolsWindow->webPage(); webPage()->setDevToolsPage(devToolsPage); s_devToolsWindows[webPage()] = devToolsWindow; } // make sure the devtools window is showing and focused DevToolsWindow* devToolsWindow = s_devToolsWindows[webPage()]; devToolsWindow->show(); devToolsWindow->raise(); devToolsWindow->setFocus(); // we have a window; invoke Inspect Element now webPage()->triggerAction(QWebEnginePage::InspectElement); }); #else # ifndef NDEBUG menu->addSeparator(); menu->addAction(tr("&Reload"), [&]() { triggerPageAction(QWebEnginePage::Reload); }); menu->addAction(webPage()->action(QWebEnginePage::InspectElement)); # endif #endif menu->setAttribute(Qt::WA_DeleteOnClose, true); menu->exec(event->globalPos()); } } // namespace desktop } // namespace rstudio <commit_msg>handle case in context menu; tweak context items<commit_after>/* * DesktopWebView.cpp * * Copyright (C) 2009-18 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "DesktopWebView.hpp" #include <QApplication> #include <QClipboard> #include <QMenu> #include <QNetworkReply> #include <QStyleFactory> #include <QWebEngineContextMenuData> #include <QWebEngineSettings> #include <QWebEngineHistory> #include <core/system/Environment.hpp> #include "DesktopBrowserWindow.hpp" #ifdef _WIN32 #include <windows.h> #include <wingdi.h> #endif namespace rstudio { namespace desktop { namespace { #if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0) class DevToolsWindow : public QMainWindow { public: DevToolsWindow() : webPage_(new QWebEnginePage(this)), webView_(new QWebEngineView(this)) { webView_->setPage(webPage_); QScreen* screen = QApplication::primaryScreen(); QRect geometry = screen->geometry(); resize(geometry.width() * 0.7, geometry.height() * 0.7); setWindowTitle(QStringLiteral("RStudio DevTools")); setAttribute(Qt::WA_DeleteOnClose, false); setAttribute(Qt::WA_QuitOnClose, true); setUnifiedTitleAndToolBarOnMac(true); setCentralWidget(webView_); } QWebEnginePage* webPage() { return webPage_; } QWebEngineView* webView() { return webView_; } private: QWebEnginePage* webPage_; QWebEngineView* webView_; }; std::map<QWebEnginePage*, DevToolsWindow*> s_devToolsWindows; #endif } // end anonymous namespace WebView::WebView(QUrl baseUrl, QWidget *parent, bool allowExternalNavigate) : QWebEngineView(parent), baseUrl_(baseUrl) { #ifdef Q_OS_LINUX if (!core::system::getenv("KDE_FULL_SESSION").empty()) { QString fusion = QString::fromUtf8("fusion"); if (QStyleFactory::keys().contains(fusion)) setStyle(QStyleFactory::create(fusion)); } #endif pWebPage_ = new WebPage(baseUrl, this, allowExternalNavigate); setPage(pWebPage_); } void WebView::setBaseUrl(const QUrl& baseUrl) { baseUrl_ = baseUrl; pWebPage_->setBaseUrl(baseUrl_); } QUrl WebView::baseUrl() { return baseUrl_; } void WebView::activateSatelliteWindow(QString name) { pWebPage_->activateWindow(name); } void WebView::prepareForWindow(const PendingWindow& pendingWnd) { pWebPage_->prepareForWindow(pendingWnd); } QString WebView::promptForFilename(const QNetworkRequest& request, QNetworkReply* pReply = nullptr) { QString defaultFileName = QFileInfo(request.url().path()).fileName(); // Content-Disposition's filename parameter should be used as the // default, if present. if (pReply && pReply->hasRawHeader("content-disposition")) { QString headerValue = QString::fromUtf8(pReply->rawHeader("content-disposition")); QRegExp regexp(QString::fromUtf8("filename=\"?([^\"]+)\"?"), Qt::CaseInsensitive); if (regexp.indexIn(headerValue) >= 0) { defaultFileName = regexp.cap(1); } } QString fileName = QFileDialog::getSaveFileName(this, tr("Download File"), defaultFileName, QString(), nullptr, standardFileDialogOptions()); return fileName; } void WebView::keyPressEvent(QKeyEvent* pEvent) { #ifdef Q_OS_MAC if (pEvent->key() == Qt::Key_W && pEvent->modifiers() == Qt::CTRL) { // on macOS, intercept Cmd+W and emit the window close signal onCloseWindowShortcut(); } else { // pass other key events through to WebEngine QWebEngineView::keyPressEvent(pEvent); } #else QWebEngineView::keyPressEvent(pEvent); #endif } void WebView::openFile(QString fileName) { // force use of Preview for PDFs on the Mac (Adobe Reader 10.01 crashes) #ifdef Q_OS_MAC if (fileName.toLower().endsWith(QString::fromUtf8(".pdf"))) { QStringList args; args.append(QString::fromUtf8("-a")); args.append(QString::fromUtf8("Preview")); args.append(fileName); QProcess::startDetached(QString::fromUtf8("open"), args); return; } #endif QDesktopServices::openUrl(QUrl::fromLocalFile(fileName)); } bool WebView::event(QEvent* event) { if (event->type() == QEvent::ShortcutOverride) { // take a first crack at shortcuts keyPressEvent(static_cast<QKeyEvent*>(event)); return true; } return this->QWebEngineView::event(event); } void WebView::closeEvent(QCloseEvent*) { } namespace { QString label(QString label) { #ifdef Q_OS_MAC static const QChar ampersand = QChar::fromLatin1('&'); static const QString space = QStringLiteral(" "); QStringList words = label.split(space); for (QString& word : words) { int index = 0; if (word[index] == ampersand) index = 1; word[index] = word[index].toUpper(); } return words.join(space); #else return label; #endif } } // end anonymous namespace void WebView::contextMenuEvent(QContextMenuEvent* event) { QMenu* menu = new QMenu(this); const auto& data = webPage()->contextMenuData(); const auto& mediaFlags = data.mediaFlags(); bool canNavigateHistory = webPage()->history()->canGoBack() || webPage()->history()->canGoForward(); if (data.selectedText().isEmpty() && canNavigateHistory) { auto* back = menu->addAction(label(tr("&Back")), [&]() { webPage()->history()->back(); }); auto* forward = menu->addAction(label(tr("&Forward")), [&]() { webPage()->history()->forward(); }); back->setEnabled(webPage()->history()->canGoBack()); forward->setEnabled(webPage()->history()->canGoForward()); menu->addAction(label(tr("&Reload")), [&]() { triggerPageAction(QWebEnginePage::Reload); }); menu->addSeparator(); } if (data.mediaUrl().isValid()) { switch (data.mediaType()) { case QWebEngineContextMenuData::MediaTypeImage: menu->addAction(label(tr("Sa&ve image as...")), [&]() { triggerPageAction(QWebEnginePage::DownloadImageToDisk); }); menu->addAction(label(tr("Cop&y image")), [&]() { triggerPageAction(QWebEnginePage::CopyImageToClipboard); }); menu->addAction(label(tr("C&opy image address")), [&]() { triggerPageAction(QWebEnginePage::CopyImageUrlToClipboard); }); break; case QWebEngineContextMenuData::MediaTypeAudio: if (mediaFlags.testFlag(QWebEngineContextMenuData::MediaPaused)) menu->addAction(label(tr("&Play")), [&]() { triggerPageAction(QWebEnginePage::ToggleMediaPlayPause); }); else menu->addAction(label(tr("&Pause")), [&]() { triggerPageAction(QWebEnginePage::ToggleMediaPlayPause); }); menu->addAction(label(tr("&Loop")), [&]() { triggerPageAction(QWebEnginePage::ToggleMediaLoop); }); menu->addAction(label(tr("Toggle &controls")), [&]() { triggerPageAction(QWebEnginePage::ToggleMediaControls); }); menu->addSeparator(); menu->addAction(label(tr("Sa&ve audio as...")), [&]() { triggerPageAction(QWebEnginePage::DownloadMediaToDisk); }); menu->addAction(label(tr("C&opy audio address")), [&]() { triggerPageAction(QWebEnginePage::CopyMediaUrlToClipboard); }); break; case QWebEngineContextMenuData::MediaTypeVideo: if (mediaFlags.testFlag(QWebEngineContextMenuData::MediaPaused)) menu->addAction(label(tr("&Play")), [&]() { triggerPageAction(QWebEnginePage::ToggleMediaPlayPause); }); else menu->addAction(label(tr("&Pause")), [&]() { triggerPageAction(QWebEnginePage::ToggleMediaPlayPause); }); menu->addAction(label(tr("&Loop")), [&]() { triggerPageAction(QWebEnginePage::ToggleMediaLoop); }); menu->addAction(label(tr("Toggle &controls")), [&]() { triggerPageAction(QWebEnginePage::ToggleMediaControls); }); menu->addSeparator(); menu->addAction(label(tr("Sa&ve video as...")), [&]() { triggerPageAction(QWebEnginePage::DownloadMediaToDisk); }); menu->addAction(label(tr("C&opy video address")), [&]() { triggerPageAction(QWebEnginePage::CopyMediaUrlToClipboard); }); break; case QWebEngineContextMenuData::MediaTypeFile: menu->addAction(label(tr("Sa&ve file as...")), [&]() { triggerPageAction(QWebEnginePage::DownloadLinkToDisk); }); menu->addAction(label(tr("C&opy link address")), [&]() { triggerPageAction(QWebEnginePage::CopyMediaUrlToClipboard); }); break; default: break; } } else if (data.linkUrl().isValid()) { menu->addAction(label(tr("Open link in &browser")), [&]() { desktop::openUrl(data.linkUrl()); }); menu->addAction(label(tr("Save lin&k as...")), [&]() { triggerPageAction(QWebEnginePage::DownloadLinkToDisk); }); menu->addAction(label(tr("Copy link addr&ess")), [&]() { triggerPageAction(QWebEnginePage::CopyLinkToClipboard); }); } else { // always show cut / copy / paste, but only enable cut / copy if there // is some selected text, and only enable paste if there is something // on the clipboard. note that this isn't perfect -- the highlighted // text may not correspond to the context menu click target -- but // in general users who want to copy text will right-click on the // selection, rather than elsewhere on the screen. auto* cut = webPage()->action(QWebEnginePage::Cut); auto* copy = webPage()->action(QWebEnginePage::Copy); auto* paste = webPage()->action(QWebEnginePage::Paste); auto* selectAll = webPage()->action(QWebEnginePage::SelectAll); cut->setText(label(tr("Cu&t"))); copy->setText(label(tr("&Copy"))); paste->setText(label(tr("&Paste"))); selectAll->setText(label(tr("Select &all"))); cut->setEnabled(data.isContentEditable() && !data.selectedText().isEmpty()); copy->setEnabled(!data.selectedText().isEmpty()); paste->setEnabled(QApplication::clipboard()->mimeData()->hasText()); menu->addAction(cut); menu->addAction(copy); menu->addAction(paste); menu->addAction(selectAll); } #if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0) menu->addSeparator(); menu->addAction(label(tr("I&nspect element")), [&]() { QWebEnginePage* devToolsPage = webPage()->devToolsPage(); if (devToolsPage == nullptr) { DevToolsWindow* devToolsWindow = new DevToolsWindow(); devToolsPage = devToolsWindow->webPage(); webPage()->setDevToolsPage(devToolsPage); s_devToolsWindows[webPage()] = devToolsWindow; } // make sure the devtools window is showing and focused DevToolsWindow* devToolsWindow = s_devToolsWindows[webPage()]; devToolsWindow->show(); devToolsWindow->raise(); devToolsWindow->setFocus(); // we have a window; invoke Inspect Element now webPage()->triggerAction(QWebEnginePage::InspectElement); }); #else # ifndef NDEBUG menu->addSeparator(); menu->addAction(label(tr("I&nspect element")), [&]() { triggerPageAction(QWebEnginePage::InspectElement); }); # endif #endif menu->setAttribute(Qt::WA_DeleteOnClose, true); menu->exec(event->globalPos()); } } // namespace desktop } // namespace rstudio <|endoftext|>
<commit_before>/* * uuid.hpp * * Created on: 2015. 10. 13. * Author: hwang */ #ifndef INCLUDE_UTIL_UUID_HPP_ #define INCLUDE_UTIL_UUID_HPP_ #include <uuid/uuid.h> #include <string> using namespace std; namespace cossb { namespace util { typedef struct _uuid { public: _uuid() { uuid_generate(code); memset(encoded, 0x00, sizeof(encoded)); uuid_unparse(code, encoded); } const char* str() { return (const char*)encoded; } bool operator<(const _uuid& other) const { return (uuid_compare(this->code, other.code)<0)?true:false; } bool operator>(const _uuid& other) const { return (uuid_compare(this->code, other.code)>0)?true:false; } bool operator==(const _uuid& other) const { return (uuid_compare(this->code, other.code)==0)?true:false; } private: unsigned char code[16]; char encoded[64]; } uuid; } /* namespace util */ } /* namespace cossb */ #endif /* INCLUDE_UTIL_UUID_HPP_ */ <commit_msg>remove print which used for test<commit_after>/* * uuid.hpp * * Created on: 2015. 10. 13. * Author: hwang */ #ifndef INCLUDE_UTIL_UUID_HPP_ #define INCLUDE_UTIL_UUID_HPP_ #include <uuid/uuid.h> #include <string> using namespace std; namespace cossb { namespace util { typedef struct _uuid { public: _uuid() { uuid_generate(code); memset(encoded, 0x00, sizeof(encoded)); uuid_unparse_lower(code, encoded); } _uuid(string suuid) { std::transform(suuid.begin(), suuid.end(), suuid.begin(), ::tolower); if(suuid.size()==32) { for(int i=0;i<(int)sizeof(code);i++) { char t = suuid.at(i); if(t>96 && t<103) code[i] = t-86; else if(t>47 && t<58) code[i] = t-48; else { memset(code, 0x30, sizeof(code)); break; } } } else memset(code, 0x30, sizeof(code)); memset(encoded, 0x00, sizeof(encoded)); uuid_unparse_lower(code, encoded); } const char* str() { return (const char*)encoded; } bool operator<(const _uuid& other) const { return (uuid_compare(this->code, other.code)<0)?true:false; } bool operator>(const _uuid& other) const { return (uuid_compare(this->code, other.code)>0)?true:false; } bool operator==(const _uuid& other) const { return (uuid_compare(this->code, other.code)==0)?true:false; } _uuid& operator=(const _uuid& other) { memcpy(this, &other, sizeof(_uuid)); return *this; } private: bool valid() { return true; } private: unsigned char code[16]; char encoded[64]; } uuid; } /* namespace util */ } /* namespace cossb */ #endif /* INCLUDE_UTIL_UUID_HPP_ */ <|endoftext|>
<commit_before>#include "network.h" #include <memory> #include <sstream> using namespace std::string_literals; // NOLINT (google-build-using-namespace) namespace franka { Network::Network(const std::string& franka_address, uint16_t franka_port, std::chrono::milliseconds timeout) : tcp_socket_(), udp_socket_() { try { Poco::Timespan poco_timeout(1000l * timeout.count()); tcp_socket_.connect({franka_address, franka_port}, poco_timeout); tcp_socket_.setBlocking(true); tcp_socket_.setSendTimeout(poco_timeout); tcp_socket_.setReceiveTimeout(poco_timeout); udp_socket_.setReceiveTimeout(Poco::Timespan{1000l * timeout.count()}); udp_socket_.bind({"0.0.0.0", 0}); } catch (const Poco::Net::NetException& e) { throw NetworkException("libfranka: FRANKA connection error: "s + e.what()); } catch (const Poco::TimeoutException& e) { throw NetworkException("libfranka: FRANKA connection timeout"s); } catch (const Poco::Exception& e) { throw NetworkException("libfranka: "s + e.what()); } } Network::~Network() try { tcp_socket_.shutdown(); } catch (...) { } uint16_t Network::udpPort() const noexcept { return udp_socket_.address().port(); } void Network::udpSendRobotCommand( const research_interface::RobotCommand& command) try { int bytes_sent = udp_socket_.sendTo(&command, sizeof(command), udp_server_address_); if (bytes_sent != sizeof(command)) { throw NetworkException("libfranka: robot command send error"); } } catch (const Poco::Exception& e) { throw NetworkException("libfranka: udp send: "s + e.what()); } research_interface::RobotState Network::udpReadRobotState() try { std::array<uint8_t, sizeof(research_interface::RobotState)> buffer; int bytes_received = udp_socket_.receiveFrom(buffer.data(), buffer.size(), udp_server_address_); if (bytes_received != buffer.size()) { throw ProtocolException("libfranka: incorrect object size"); } return *reinterpret_cast<research_interface::RobotState*>(buffer.data()); } catch (const Poco::Exception& e) { throw NetworkException("libfranka: udp read: "s + e.what()); } int Network::tcpReceiveIntoBuffer() try { size_t offset = read_buffer_.size(); read_buffer_.resize(offset + tcp_socket_.available()); return tcp_socket_.receiveBytes(&read_buffer_[offset], tcp_socket_.available()); } catch (const Poco::Exception& e) { throw NetworkException("libfranka: "s + e.what()); } bool Network::tcpReadResponse(research_interface::Function* function) try { if (tcp_socket_.poll(0, Poco::Net::Socket::SELECT_READ)) { int rv = tcpReceiveIntoBuffer(); if (rv == 0) { throw NetworkException("libfranka: server closed connection"); } if (read_buffer_.size() < sizeof(research_interface::Function)) { return false; } *function = *reinterpret_cast<research_interface::Function*>(read_buffer_.data()); return true; } return false; } catch (const Poco::Exception& e) { throw NetworkException("libfranka: "s + e.what()); } } // namespace franka <commit_msg>clang-format<commit_after>#include "network.h" #include <memory> #include <sstream> using namespace std::string_literals; // NOLINT (google-build-using-namespace) namespace franka { Network::Network(const std::string& franka_address, uint16_t franka_port, std::chrono::milliseconds timeout) : tcp_socket_(), udp_socket_() { try { Poco::Timespan poco_timeout(1000l * timeout.count()); tcp_socket_.connect({franka_address, franka_port}, poco_timeout); tcp_socket_.setBlocking(true); tcp_socket_.setSendTimeout(poco_timeout); tcp_socket_.setReceiveTimeout(poco_timeout); udp_socket_.setReceiveTimeout(Poco::Timespan{1000l * timeout.count()}); udp_socket_.bind({"0.0.0.0", 0}); } catch (const Poco::Net::NetException& e) { throw NetworkException("libfranka: FRANKA connection error: "s + e.what()); } catch (const Poco::TimeoutException& e) { throw NetworkException("libfranka: FRANKA connection timeout"s); } catch (const Poco::Exception& e) { throw NetworkException("libfranka: "s + e.what()); } } Network::~Network() try { tcp_socket_.shutdown(); } catch (...) { } uint16_t Network::udpPort() const noexcept { return udp_socket_.address().port(); } void Network::udpSendRobotCommand( const research_interface::RobotCommand& command) try { int bytes_sent = udp_socket_.sendTo(&command, sizeof(command), udp_server_address_); if (bytes_sent != sizeof(command)) { throw NetworkException("libfranka: robot command send error"); } } catch (const Poco::Exception& e) { throw NetworkException("libfranka: udp send: "s + e.what()); } research_interface::RobotState Network::udpReadRobotState() try { std::array<uint8_t, sizeof(research_interface::RobotState)> buffer; int bytes_received = udp_socket_.receiveFrom(buffer.data(), buffer.size(), udp_server_address_); if (bytes_received != buffer.size()) { throw ProtocolException("libfranka: incorrect object size"); } return *reinterpret_cast<research_interface::RobotState*>(buffer.data()); } catch (const Poco::Exception& e) { throw NetworkException("libfranka: udp read: "s + e.what()); } int Network::tcpReceiveIntoBuffer() try { size_t offset = read_buffer_.size(); read_buffer_.resize(offset + tcp_socket_.available()); return tcp_socket_.receiveBytes(&read_buffer_[offset], tcp_socket_.available()); } catch (const Poco::Exception& e) { throw NetworkException("libfranka: "s + e.what()); } bool Network::tcpReadResponse(research_interface::Function* function) try { if (tcp_socket_.poll(0, Poco::Net::Socket::SELECT_READ)) { int rv = tcpReceiveIntoBuffer(); if (rv == 0) { throw NetworkException("libfranka: server closed connection"); } if (read_buffer_.size() < sizeof(research_interface::Function)) { return false; } *function = *reinterpret_cast<research_interface::Function*>(read_buffer_.data()); return true; } return false; } catch (const Poco::Exception& e) { throw NetworkException("libfranka: "s + e.what()); } } // namespace franka <|endoftext|>
<commit_before>#include "defaults.h" #include "wsauthenticator.h" #include "wsremoteconnector_p.h" #include <QtCore/QDebug> #include <QtCore/QJsonDocument> #include <QtCore/QJsonObject> #include <QtCore/QTimer> #include <QtCore/QTimerEvent> using namespace QtDataSync; #define LOG defaults()->loggingCategory() const QString WsRemoteConnector::keyRemoteEnabled(QStringLiteral("RemoteConnector/remoteEnabled")); const QString WsRemoteConnector::keyRemoteUrl(QStringLiteral("RemoteConnector/remoteUrl")); const QString WsRemoteConnector::keyHeadersGroup(QStringLiteral("RemoteConnector/headers")); const QString WsRemoteConnector::keyVerifyPeer(QStringLiteral("RemoteConnector/verifyPeer")); const QString WsRemoteConnector::keyUserIdentity(QStringLiteral("RemoteConnector/userIdentity")); const QString WsRemoteConnector::keySharedSecret(QStringLiteral("RemoteConnector/sharedSecret")); const QVector<int> WsRemoteConnector::timeouts = {5 * 1000, 10 * 1000, 30 * 1000, 60 * 1000, 5 * 60 * 1000, 10 * 60 * 1000}; WsRemoteConnector::WsRemoteConnector(QObject *parent) : RemoteConnector(parent), socket(nullptr), settings(nullptr), cryptor(nullptr), state(Disconnected), retryIndex(0), needResync(false), operationTimer(new QTimer(this)), pingTimerId(-1), decryptReply(false), currentKey(), currentKeyProperty() {} void WsRemoteConnector::initialize(Defaults *defaults, Encryptor *cryptor) { RemoteConnector::initialize(defaults, cryptor); settings = defaults->createSettings(this); this->cryptor = cryptor; operationTimer->setInterval(30000);//30 secs timout operationTimer->setSingleShot(true); connect(operationTimer, &QTimer::timeout, this, &WsRemoteConnector::operationTimeout); pingTimerId = startTimer(3 * 60 * 1000, Qt::VeryCoarseTimer);//ping every 3 minutes to keep alive reconnect(); } void WsRemoteConnector::finalize() { RemoteConnector::finalize(); } Authenticator *WsRemoteConnector::createAuthenticator(Defaults *defaults, QObject *parent) { return new WsAuthenticator(this, defaults, parent); } void WsRemoteConnector::reconnect() { if(state == Connecting || state == Closing) return; if(socket) { state = Closing; connect(socket, &QWebSocket::destroyed, this, &WsRemoteConnector::reconnect, Qt::QueuedConnection); socket->close(); } else { emit clearAuthenticationError(); state = Connecting; settings->sync(); auto remoteUrl = settings->value(keyRemoteUrl).toUrl(); if(!remoteUrl.isValid() || !settings->value(keyRemoteEnabled, true).toBool()) { state = Disconnected; remoteStateChanged(RemoteDisconnected); return; } socket = new QWebSocket(settings->value(keySharedSecret, QStringLiteral("QtDataSync")).toString(), QWebSocketProtocol::VersionLatest, this); if(!settings->value(keyVerifyPeer, true).toBool()) { auto conf = socket->sslConfiguration(); conf.setPeerVerifyMode(QSslSocket::VerifyNone); socket->setSslConfiguration(conf); } connect(socket, &QWebSocket::connected, this, &WsRemoteConnector::connected); connect(socket, &QWebSocket::binaryMessageReceived, this, &WsRemoteConnector::binaryMessageReceived); connect(socket, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error), this, &WsRemoteConnector::error); connect(socket, &QWebSocket::sslErrors, this, &WsRemoteConnector::sslErrors); connect(socket, &QWebSocket::disconnected, this, &WsRemoteConnector::disconnected, Qt::QueuedConnection); QNetworkRequest request(remoteUrl); request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); request.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true); request.setAttribute(QNetworkRequest::SpdyAllowedAttribute, true); request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, true); settings->beginGroup(keyHeadersGroup); auto keys = settings->childKeys(); foreach(auto key, keys) request.setRawHeader(key.toUtf8(), settings->value(key).toByteArray()); settings->endGroup(); socket->open(request); } } void WsRemoteConnector::reloadRemoteState() { switch (state) { case Disconnected: reconnect(); break; case Idle: remoteStateChanged(RemoteLoadingState); if(needResync) emit performLocalReset(false);//direct connected, thus "inline" state = Reloading; sendCommand("loadChanges", needResync); needResync = false; break; case Operating: retry(); break; default: break; } } void WsRemoteConnector::requestResync() { needResync = true; reloadRemoteState(); } void WsRemoteConnector::download(const ObjectKey &key, const QByteArray &keyProperty) { if(state != Idle) emit operationFailed(QStringLiteral("Remote connector state does not allow downloads")); else { state = Operating; QJsonObject data; data[QStringLiteral("type")] = QString::fromUtf8(key.first); data[QStringLiteral("key")] = key.second; data[QStringLiteral("keyProperty")] = QString::fromUtf8(keyProperty); sendCommand("load", data); //if cryptor is valid, expect the reply to be encrypted if(cryptor) { currentKey = key; currentKeyProperty = keyProperty; decryptReply = true; } } } void WsRemoteConnector::upload(const ObjectKey &key, const QJsonObject &object, const QByteArray &keyProperty) { if(state != Idle) emit operationFailed(QStringLiteral("Remote connector state does not allow uploads")); else { state = Operating; QJsonObject data; data[QStringLiteral("type")] = QString::fromUtf8(key.first); data[QStringLiteral("key")] = key.second; data[QStringLiteral("keyProperty")] = QString::fromUtf8(keyProperty); if(cryptor) { try { data[QStringLiteral("value")] = cryptor->encrypt(key, object, keyProperty); sendCommand("save", data); } catch(QException &e) { emit operationFailed(QString::fromUtf8(e.what())); state = Idle; } } else { data[QStringLiteral("value")] = object; sendCommand("save", data); } } } void WsRemoteConnector::remove(const ObjectKey &key, const QByteArray &keyProperty) { if(state != Idle) emit operationFailed(QStringLiteral("Remote connector state does not allow removals")); else { state = Operating; QJsonObject data; data[QStringLiteral("type")] = QString::fromUtf8(key.first); data[QStringLiteral("key")] = key.second; data[QStringLiteral("keyProperty")] = QString::fromUtf8(keyProperty); sendCommand("remove", data); } } void WsRemoteConnector::markUnchanged(const ObjectKey &key, const QByteArray &keyProperty) { if(state != Idle) emit operationFailed(QStringLiteral("Remote connector state does not allow marking as unchanged")); else { state = Operating; QJsonObject data; data[QStringLiteral("type")] = QString::fromUtf8(key.first); data[QStringLiteral("key")] = key.second; data[QStringLiteral("keyProperty")] = QString::fromUtf8(keyProperty); sendCommand("markUnchanged", data); } } void WsRemoteConnector::resetUserData(const QVariant &extraData, const QByteArray &) { if(socket) { sendCommand("deleteOldDevice"); operationTimer->stop();//unimportant message, no timeout } if(extraData.isValid()) settings->setValue(keyUserIdentity, extraData); else settings->remove(keyUserIdentity); reconnect(); } void WsRemoteConnector::timerEvent(QTimerEvent *event) { if(event->timerId() == pingTimerId) { event->accept(); if(socket) socket->ping(); } else RemoteConnector::timerEvent(event); } void WsRemoteConnector::connected() { //reset retry retryIndex = 0; state = Identifying; //check if a client ID exists auto id = settings->value(keyUserIdentity).toByteArray(); if(id.isNull()) { QJsonObject data; data[QStringLiteral("deviceId")] = QString::fromUtf8(getDeviceId()); sendCommand("createIdentity", data); } else { QJsonObject data; data[QStringLiteral("userId")] = QString::fromUtf8(id); data[QStringLiteral("deviceId")] = QString::fromUtf8(getDeviceId()); sendCommand("identify", data); } } void WsRemoteConnector::disconnected() { operationTimer->stop();//just to make shure if(state == Operating) emit operationFailed(QStringLiteral("Connection closed")); if(state != Closing) { auto delta = retry(); if(state == Connecting) { qCWarning(LOG) << "Unable to connect to server. Retrying in" << delta / 1000 << "seconds"; } else { qCWarning(LOG) << "Unexpected disconnect from server with exit code" << socket->closeCode() << ":" << socket->closeReason() << ". Retrying in" << delta / 1000 << "seconds"; } } state = Disconnected; socket->deleteLater(); socket = nullptr; //always "disable" remote for the state changer emit remoteStateChanged(RemoteDisconnected); } void WsRemoteConnector::binaryMessageReceived(const QByteArray &message) { operationTimer->stop(); QJsonParseError error; auto doc = QJsonDocument::fromJson(message, &error); if(error.error != QJsonParseError::NoError) { qCWarning(LOG) << "Invalid data received. Parser error:" << error.errorString(); return; } auto obj = doc.object(); auto data = obj[QStringLiteral("data")]; if(obj[QStringLiteral("command")] == QStringLiteral("identified")) identified(data.toObject()); else if(obj[QStringLiteral("command")] == QStringLiteral("identifyFailed")) identifyFailed(); else if(obj[QStringLiteral("command")] == QStringLiteral("changeState")) changeState(data.toObject()); else if(obj[QStringLiteral("command")] == QStringLiteral("notifyChanged")) notifyChanged(data.toObject()); else if(obj[QStringLiteral("command")] == QStringLiteral("completed")) completed(data.toObject()); else { qCWarning(LOG) << "Unkown command received:" << obj[QStringLiteral("command")].toString(); } } void WsRemoteConnector::error() { qCWarning(LOG) << "Socket error" << socket->errorString(); socket->close(); } void WsRemoteConnector::sslErrors(const QList<QSslError> &errors) { foreach(auto error, errors) { qCWarning(LOG) << "SSL errors" << error.errorString(); } if(settings->value(keyVerifyPeer, true).toBool()) socket->close(); } void WsRemoteConnector::sendCommand(const QByteArray &command, const QJsonValue &data) { QJsonObject message; message[QStringLiteral("command")] = QString::fromUtf8(command); message[QStringLiteral("data")] = data; QJsonDocument doc(message); socket->sendBinaryMessage(doc.toJson(QJsonDocument::Compact)); operationTimer->start(); } void WsRemoteConnector::operationTimeout() { qCWarning(LOG) << "Network operation timed out! Try to reconnect to server."; reconnect(); } void WsRemoteConnector::identified(const QJsonObject &data) { auto userId = data[QStringLiteral("userId")].toString(); needResync = needResync || data[QStringLiteral("resync")].toBool(); settings->setValue(keyUserIdentity, userId.toUtf8()); qCDebug(LOG) << "Identification successful"; state = Idle; reloadRemoteState(); } void WsRemoteConnector::identifyFailed() { state = Closing; emit authenticationFailed(QStringLiteral("User does not exist!")); socket->close(); } void WsRemoteConnector::changeState(const QJsonObject &data) { if(data[QStringLiteral("success")].toBool()) { //reset retry & need resync retryIndex = 0; StateHolder::ChangeHash changeState; foreach(auto value, data[QLatin1String("data")].toArray()) { auto obj = value.toObject(); ObjectKey key; key.first = obj[QStringLiteral("type")].toString().toUtf8(); key.second = obj[QStringLiteral("key")].toString(); changeState.insert(key, obj[QStringLiteral("changed")].toBool() ? StateHolder::Changed : StateHolder::Deleted); } emit remoteStateChanged(RemoteReady, changeState); } else { auto delta = retry(); qCWarning(LOG) << "Failed to load state with error:" << data[QStringLiteral("error")].toString() << ". Retrying in" << delta / 1000 << "seconds"; } state = Idle; } void WsRemoteConnector::notifyChanged(const QJsonObject &data) { ObjectKey key; key.first = data[QStringLiteral("type")].toString().toUtf8(); key.second = data[QStringLiteral("key")].toString(); emit remoteDataChanged(key, data[QStringLiteral("changed")].toBool() ? StateHolder::Changed : StateHolder::Deleted); } void WsRemoteConnector::completed(const QJsonObject &result) { if(result[QStringLiteral("success")].toBool()) { if(decryptReply) { try { auto data = cryptor->decrypt(currentKey, result[QStringLiteral("data")], currentKeyProperty); emit operationDone(data); } catch(QException &e) { emit operationFailed(QString::fromUtf8(e.what())); } currentKey = {}; currentKeyProperty.clear(); decryptReply = false; } else emit operationDone(result[QStringLiteral("data")]); } else emit operationFailed(result[QStringLiteral("error")].toString()); state = Idle; } int WsRemoteConnector::retry() { auto retryTimeout = 0; if(retryIndex >= timeouts.size()) retryTimeout = timeouts.last(); else retryTimeout = timeouts[retryIndex++]; QTimer::singleShot(retryTimeout, this, &WsRemoteConnector::reloadRemoteState); return retryTimeout; } <commit_msg>removed key property from server message (unused)<commit_after>#include "defaults.h" #include "wsauthenticator.h" #include "wsremoteconnector_p.h" #include <QtCore/QDebug> #include <QtCore/QJsonDocument> #include <QtCore/QJsonObject> #include <QtCore/QTimer> #include <QtCore/QTimerEvent> using namespace QtDataSync; #define LOG defaults()->loggingCategory() const QString WsRemoteConnector::keyRemoteEnabled(QStringLiteral("RemoteConnector/remoteEnabled")); const QString WsRemoteConnector::keyRemoteUrl(QStringLiteral("RemoteConnector/remoteUrl")); const QString WsRemoteConnector::keyHeadersGroup(QStringLiteral("RemoteConnector/headers")); const QString WsRemoteConnector::keyVerifyPeer(QStringLiteral("RemoteConnector/verifyPeer")); const QString WsRemoteConnector::keyUserIdentity(QStringLiteral("RemoteConnector/userIdentity")); const QString WsRemoteConnector::keySharedSecret(QStringLiteral("RemoteConnector/sharedSecret")); const QVector<int> WsRemoteConnector::timeouts = {5 * 1000, 10 * 1000, 30 * 1000, 60 * 1000, 5 * 60 * 1000, 10 * 60 * 1000}; WsRemoteConnector::WsRemoteConnector(QObject *parent) : RemoteConnector(parent), socket(nullptr), settings(nullptr), cryptor(nullptr), state(Disconnected), retryIndex(0), needResync(false), operationTimer(new QTimer(this)), pingTimerId(-1), decryptReply(false), currentKey(), currentKeyProperty() {} void WsRemoteConnector::initialize(Defaults *defaults, Encryptor *cryptor) { RemoteConnector::initialize(defaults, cryptor); settings = defaults->createSettings(this); this->cryptor = cryptor; operationTimer->setInterval(30000);//30 secs timout operationTimer->setSingleShot(true); connect(operationTimer, &QTimer::timeout, this, &WsRemoteConnector::operationTimeout); pingTimerId = startTimer(3 * 60 * 1000, Qt::VeryCoarseTimer);//ping every 3 minutes to keep alive reconnect(); } void WsRemoteConnector::finalize() { RemoteConnector::finalize(); } Authenticator *WsRemoteConnector::createAuthenticator(Defaults *defaults, QObject *parent) { return new WsAuthenticator(this, defaults, parent); } void WsRemoteConnector::reconnect() { if(state == Connecting || state == Closing) return; if(socket) { state = Closing; connect(socket, &QWebSocket::destroyed, this, &WsRemoteConnector::reconnect, Qt::QueuedConnection); socket->close(); } else { emit clearAuthenticationError(); state = Connecting; settings->sync(); auto remoteUrl = settings->value(keyRemoteUrl).toUrl(); if(!remoteUrl.isValid() || !settings->value(keyRemoteEnabled, true).toBool()) { state = Disconnected; remoteStateChanged(RemoteDisconnected); return; } socket = new QWebSocket(settings->value(keySharedSecret, QStringLiteral("QtDataSync")).toString(), QWebSocketProtocol::VersionLatest, this); if(!settings->value(keyVerifyPeer, true).toBool()) { auto conf = socket->sslConfiguration(); conf.setPeerVerifyMode(QSslSocket::VerifyNone); socket->setSslConfiguration(conf); } connect(socket, &QWebSocket::connected, this, &WsRemoteConnector::connected); connect(socket, &QWebSocket::binaryMessageReceived, this, &WsRemoteConnector::binaryMessageReceived); connect(socket, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error), this, &WsRemoteConnector::error); connect(socket, &QWebSocket::sslErrors, this, &WsRemoteConnector::sslErrors); connect(socket, &QWebSocket::disconnected, this, &WsRemoteConnector::disconnected, Qt::QueuedConnection); QNetworkRequest request(remoteUrl); request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); request.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true); request.setAttribute(QNetworkRequest::SpdyAllowedAttribute, true); request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, true); settings->beginGroup(keyHeadersGroup); auto keys = settings->childKeys(); foreach(auto key, keys) request.setRawHeader(key.toUtf8(), settings->value(key).toByteArray()); settings->endGroup(); socket->open(request); } } void WsRemoteConnector::reloadRemoteState() { switch (state) { case Disconnected: reconnect(); break; case Idle: remoteStateChanged(RemoteLoadingState); if(needResync) emit performLocalReset(false);//direct connected, thus "inline" state = Reloading; sendCommand("loadChanges", needResync); needResync = false; break; case Operating: retry(); break; default: break; } } void WsRemoteConnector::requestResync() { needResync = true; reloadRemoteState(); } void WsRemoteConnector::download(const ObjectKey &key, const QByteArray &keyProperty) { if(state != Idle) emit operationFailed(QStringLiteral("Remote connector state does not allow downloads")); else { state = Operating; QJsonObject data; data[QStringLiteral("type")] = QString::fromUtf8(key.first); data[QStringLiteral("key")] = key.second; sendCommand("load", data); //if cryptor is valid, expect the reply to be encrypted if(cryptor) { currentKey = key; currentKeyProperty = keyProperty; decryptReply = true; } } } void WsRemoteConnector::upload(const ObjectKey &key, const QJsonObject &object, const QByteArray &keyProperty) { if(state != Idle) emit operationFailed(QStringLiteral("Remote connector state does not allow uploads")); else { state = Operating; QJsonObject data; data[QStringLiteral("type")] = QString::fromUtf8(key.first); data[QStringLiteral("key")] = key.second; if(cryptor) { try { data[QStringLiteral("value")] = cryptor->encrypt(key, object, keyProperty); sendCommand("save", data); } catch(QException &e) { emit operationFailed(QString::fromUtf8(e.what())); state = Idle; } } else { data[QStringLiteral("value")] = object; sendCommand("save", data); } } } void WsRemoteConnector::remove(const ObjectKey &key, const QByteArray &) { if(state != Idle) emit operationFailed(QStringLiteral("Remote connector state does not allow removals")); else { state = Operating; QJsonObject data; data[QStringLiteral("type")] = QString::fromUtf8(key.first); data[QStringLiteral("key")] = key.second; sendCommand("remove", data); } } void WsRemoteConnector::markUnchanged(const ObjectKey &key, const QByteArray &) { if(state != Idle) emit operationFailed(QStringLiteral("Remote connector state does not allow marking as unchanged")); else { state = Operating; QJsonObject data; data[QStringLiteral("type")] = QString::fromUtf8(key.first); data[QStringLiteral("key")] = key.second; sendCommand("markUnchanged", data); } } void WsRemoteConnector::resetUserData(const QVariant &extraData, const QByteArray &) { if(socket) { sendCommand("deleteOldDevice"); operationTimer->stop();//unimportant message, no timeout } if(extraData.isValid()) settings->setValue(keyUserIdentity, extraData); else settings->remove(keyUserIdentity); reconnect(); } void WsRemoteConnector::timerEvent(QTimerEvent *event) { if(event->timerId() == pingTimerId) { event->accept(); if(socket) socket->ping(); } else RemoteConnector::timerEvent(event); } void WsRemoteConnector::connected() { //reset retry retryIndex = 0; state = Identifying; //check if a client ID exists auto id = settings->value(keyUserIdentity).toByteArray(); if(id.isNull()) { QJsonObject data; data[QStringLiteral("deviceId")] = QString::fromUtf8(getDeviceId()); sendCommand("createIdentity", data); } else { QJsonObject data; data[QStringLiteral("userId")] = QString::fromUtf8(id); data[QStringLiteral("deviceId")] = QString::fromUtf8(getDeviceId()); sendCommand("identify", data); } } void WsRemoteConnector::disconnected() { operationTimer->stop();//just to make shure if(state == Operating) emit operationFailed(QStringLiteral("Connection closed")); if(state != Closing) { auto delta = retry(); if(state == Connecting) { qCWarning(LOG) << "Unable to connect to server. Retrying in" << delta / 1000 << "seconds"; } else { qCWarning(LOG) << "Unexpected disconnect from server with exit code" << socket->closeCode() << ":" << socket->closeReason() << ". Retrying in" << delta / 1000 << "seconds"; } } state = Disconnected; socket->deleteLater(); socket = nullptr; //always "disable" remote for the state changer emit remoteStateChanged(RemoteDisconnected); } void WsRemoteConnector::binaryMessageReceived(const QByteArray &message) { operationTimer->stop(); QJsonParseError error; auto doc = QJsonDocument::fromJson(message, &error); if(error.error != QJsonParseError::NoError) { qCWarning(LOG) << "Invalid data received. Parser error:" << error.errorString(); return; } auto obj = doc.object(); auto data = obj[QStringLiteral("data")]; if(obj[QStringLiteral("command")] == QStringLiteral("identified")) identified(data.toObject()); else if(obj[QStringLiteral("command")] == QStringLiteral("identifyFailed")) identifyFailed(); else if(obj[QStringLiteral("command")] == QStringLiteral("changeState")) changeState(data.toObject()); else if(obj[QStringLiteral("command")] == QStringLiteral("notifyChanged")) notifyChanged(data.toObject()); else if(obj[QStringLiteral("command")] == QStringLiteral("completed")) completed(data.toObject()); else { qCWarning(LOG) << "Unkown command received:" << obj[QStringLiteral("command")].toString(); } } void WsRemoteConnector::error() { qCWarning(LOG) << "Socket error" << socket->errorString(); socket->close(); } void WsRemoteConnector::sslErrors(const QList<QSslError> &errors) { foreach(auto error, errors) { qCWarning(LOG) << "SSL errors" << error.errorString(); } if(settings->value(keyVerifyPeer, true).toBool()) socket->close(); } void WsRemoteConnector::sendCommand(const QByteArray &command, const QJsonValue &data) { QJsonObject message; message[QStringLiteral("command")] = QString::fromUtf8(command); message[QStringLiteral("data")] = data; QJsonDocument doc(message); socket->sendBinaryMessage(doc.toJson(QJsonDocument::Compact)); operationTimer->start(); } void WsRemoteConnector::operationTimeout() { qCWarning(LOG) << "Network operation timed out! Try to reconnect to server."; reconnect(); } void WsRemoteConnector::identified(const QJsonObject &data) { auto userId = data[QStringLiteral("userId")].toString(); needResync = needResync || data[QStringLiteral("resync")].toBool(); settings->setValue(keyUserIdentity, userId.toUtf8()); qCDebug(LOG) << "Identification successful"; state = Idle; reloadRemoteState(); } void WsRemoteConnector::identifyFailed() { state = Closing; emit authenticationFailed(QStringLiteral("User does not exist!")); socket->close(); } void WsRemoteConnector::changeState(const QJsonObject &data) { if(data[QStringLiteral("success")].toBool()) { //reset retry & need resync retryIndex = 0; StateHolder::ChangeHash changeState; foreach(auto value, data[QLatin1String("data")].toArray()) { auto obj = value.toObject(); ObjectKey key; key.first = obj[QStringLiteral("type")].toString().toUtf8(); key.second = obj[QStringLiteral("key")].toString(); changeState.insert(key, obj[QStringLiteral("changed")].toBool() ? StateHolder::Changed : StateHolder::Deleted); } emit remoteStateChanged(RemoteReady, changeState); } else { auto delta = retry(); qCWarning(LOG) << "Failed to load state with error:" << data[QStringLiteral("error")].toString() << ". Retrying in" << delta / 1000 << "seconds"; } state = Idle; } void WsRemoteConnector::notifyChanged(const QJsonObject &data) { ObjectKey key; key.first = data[QStringLiteral("type")].toString().toUtf8(); key.second = data[QStringLiteral("key")].toString(); emit remoteDataChanged(key, data[QStringLiteral("changed")].toBool() ? StateHolder::Changed : StateHolder::Deleted); } void WsRemoteConnector::completed(const QJsonObject &result) { if(result[QStringLiteral("success")].toBool()) { if(decryptReply) { try { auto data = cryptor->decrypt(currentKey, result[QStringLiteral("data")], currentKeyProperty); emit operationDone(data); } catch(QException &e) { emit operationFailed(QString::fromUtf8(e.what())); } currentKey = {}; currentKeyProperty.clear(); decryptReply = false; } else emit operationDone(result[QStringLiteral("data")]); } else emit operationFailed(result[QStringLiteral("error")].toString()); state = Idle; } int WsRemoteConnector::retry() { auto retryTimeout = 0; if(retryIndex >= timeouts.size()) retryTimeout = timeouts.last(); else retryTimeout = timeouts[retryIndex++]; QTimer::singleShot(retryTimeout, this, &WsRemoteConnector::reloadRemoteState); return retryTimeout; } <|endoftext|>
<commit_before>/* * MDE4CPP - Model Driven Engineering for C++ * * Copyright (c) TU Ilmenau, Systems and Software Engineering Group * All rights reserved. * * MIT License * * 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 "EnvironmentFactory.h" #include "OclReflection.h" #include <ocl/Expressions/ExpressionsFactory.hpp> #include <ocl/Expressions/Variable.hpp> #include <ocl/Values/NameValueBinding.hpp> #include <ocl/Values/ObjectValue.hpp> #include <ocl/Values/LocalSnapshot.hpp> #include <ecore/EOperation.hpp> #include <ecore/EParameter.hpp> #include <ecore/EClassifier.hpp> #include <ecore/EClass.hpp> #include <ecore/EPackage.hpp> #include <ecore/ecoreFactory.hpp> using namespace ocl; using namespace ocl::Expressions; using namespace ocl::Values; using namespace Utilities; EnvironmentFactory EnvironmentFactory::m_instance; std::shared_ptr<Environment> EnvironmentFactory::createEnvironment(std::shared_ptr<Environment> parent) { return std::make_shared<Environment>(parent); } std::shared_ptr<Environment> EnvironmentFactory::createRootEnvironment(std::shared_ptr<ecore::EObject> context) { std::shared_ptr<Environment> env = createEnvironment(nullptr); std::shared_ptr<uml::Element> element = std::dynamic_pointer_cast<uml::Element>(context); std::shared_ptr<ecore::EPackage> epackage = nullptr; std::shared_ptr<ecore::EClassifier> classifier = nullptr; if(element != nullptr) { std::shared_ptr<ecore::EClass> eClass=element->eClass(); // TODO alternative UML-Modellunterscheidung: if(nullptr!=uobj->getMetaClass()) std::shared_ptr<uml::NamedElement> namedElement = std::dynamic_pointer_cast<uml::NamedElement>(context); if(nullptr!=namedElement) { std::shared_ptr<ecore::EPackage> package=eClass->getEPackage().lock(); if(nullptr!=package) { epackage = uml::umlPackage::eInstance(); //OclReflection::umlPackage2Ecore(element->getMetaClass()->getPackage().lock()); classifier = element->eClass(); //epackage->getEClassifier(element->getMetaClass()->getName()); } } if(nullptr==epackage) // UML-Modell UMLReflection (ecore-)Model necessary! --> TODO!!! use Plugin-Manager !!! { std::shared_ptr<uml::Class> metaClass=element->getMetaClass(); if(nullptr!=metaClass && nullptr != metaClass->getPackage().lock()) { //Bad Workaround ToDo: Support UML-Based OCL-Reflection use uml::get instead of eGet... //Use Pluginframework for unknown / uml Packages to find classifier epackage = OclReflection::umlPackage2Ecore(metaClass->getPackage().lock()); classifier = epackage->getEClassifier(metaClass->getName()); } else // last chance... // use Ecore MetaMeta { // epackage = uml::umlPackage::eInstance(); //OclReflection::umlPackage2Ecore(element->getMetaClass()->getPackage().lock()); classifier = context->eClass(); //epackage->getEClassifier(element->getMetaClass()->getName()); epackage = classifier->getEPackage().lock(); } } } else { classifier = context->eClass(); epackage = classifier->getEPackage().lock(); } std::shared_ptr<Variable> self = ocl::Expressions::ExpressionsFactory::eInstance()->createVariable(); self->setEType(classifier); self->setName(classifier->getName()); self->setValue(OclReflection::createValue(context)); env->setSelfVariable(self); env->addElement(Environment::SELF_VARIABLE_NAME, self, true); if(epackage) { std::shared_ptr<Variable> packageVar = ocl::Expressions::ExpressionsFactory::eInstance()->createVariable(); packageVar->setName(epackage->getName()); packageVar->setEType(epackage->eClass()); packageVar->setValue(OclReflection::createValue(epackage)); env->addElement(packageVar->getName(), packageVar, false); } /* } else { std::shared_ptr<Variable> self = ocl::Expressions::ExpressionsFactory::eInstance()->createVariable(); self->setName(Environment::SELF_VARIABLE_NAME); self->setEType(context->eClass()); self->setValue(OclReflection::createValue(context)); env->addElement(self->getName(), self, true); env->setSelfVariable(self); } */ return env; } <commit_msg>[ocl4cpp] extend createRootEnvironment to possible EClassifiers and EPackages<commit_after>/* * MDE4CPP - Model Driven Engineering for C++ * * Copyright (c) TU Ilmenau, Systems and Software Engineering Group * All rights reserved. * * MIT License * * 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 "EnvironmentFactory.h" #include "OclReflection.h" #include <ocl/Expressions/ExpressionsFactory.hpp> #include <ocl/Expressions/Variable.hpp> #include <ocl/Values/NameValueBinding.hpp> #include <ocl/Values/ObjectValue.hpp> #include <ocl/Values/LocalSnapshot.hpp> #include <ecore/EOperation.hpp> #include <ecore/EParameter.hpp> #include <ecore/EClassifier.hpp> #include <ecore/EClass.hpp> #include <ecore/EPackage.hpp> #include <ecore/ecoreFactory.hpp> using namespace ocl; using namespace ocl::Expressions; using namespace ocl::Values; using namespace Utilities; EnvironmentFactory EnvironmentFactory::m_instance; std::shared_ptr<Environment> EnvironmentFactory::createEnvironment(std::shared_ptr<Environment> parent) { return std::make_shared<Environment>(parent); } std::shared_ptr<Environment> EnvironmentFactory::createRootEnvironment(std::shared_ptr<ecore::EObject> context) { std::shared_ptr<Environment> env = createEnvironment(nullptr); std::shared_ptr<uml::Element> element = std::dynamic_pointer_cast<uml::Element>(context); std::shared_ptr<ecore::EPackage> epackage = nullptr; std::shared_ptr<ecore::EClassifier> classifier = nullptr; if(element != nullptr) { std::shared_ptr<ecore::EClass> eClass=element->eClass(); // TODO alternative UML-Modellunterscheidung: if(nullptr!=uobj->getMetaClass()) std::shared_ptr<uml::NamedElement> namedElement = std::dynamic_pointer_cast<uml::NamedElement>(context); if(nullptr!=namedElement) { std::shared_ptr<ecore::EPackage> package=eClass->getEPackage().lock(); if(nullptr!=package) { epackage = uml::umlPackage::eInstance(); //OclReflection::umlPackage2Ecore(element->getMetaClass()->getPackage().lock()); classifier = element->eClass(); //epackage->getEClassifier(element->getMetaClass()->getName()); } } if(nullptr==epackage) // UML-Modell UMLReflection (ecore-)Model necessary! --> TODO!!! use Plugin-Manager !!! { std::shared_ptr<uml::Class> metaClass=element->getMetaClass(); if(nullptr!=metaClass && nullptr != metaClass->getPackage().lock()) { //Bad Workaround ToDo: Support UML-Based OCL-Reflection use uml::get instead of eGet... //Use Pluginframework for unknown / uml Packages to find classifier epackage = OclReflection::umlPackage2Ecore(metaClass->getPackage().lock()); classifier = epackage->getEClassifier(metaClass->getName()); } else // last chance... // use Ecore MetaMeta { // epackage = uml::umlPackage::eInstance(); //OclReflection::umlPackage2Ecore(element->getMetaClass()->getPackage().lock()); classifier = context->eClass(); //epackage->getEClassifier(element->getMetaClass()->getName()); epackage = classifier->getEPackage().lock(); } } } else { classifier = context->eClass(); std::shared_ptr<ecore::EClassifier> contextAsClass = std::dynamic_pointer_cast<ecore::EClassifier>(context); // if the context is an Ecore Model element, the package can be uses if(nullptr!=contextAsClass)// if the context is an Ecore Classifier, the package can be uses { epackage = contextAsClass->getEPackage().lock(); } else { std::shared_ptr<ecore::EPackage> contextAsPackage = std::dynamic_pointer_cast<ecore::EPackage>(context); // if the context is an Ecore Model element, the package can be uses if(nullptr!=contextAsPackage)// 2. try if the context is an Ecore Package { epackage = contextAsPackage; } else { // last try use Metainformation as Package epackage = classifier->getEPackage().lock(); } } } std::shared_ptr<Variable> self = ocl::Expressions::ExpressionsFactory::eInstance()->createVariable(); self->setEType(classifier); self->setName(classifier->getName()); self->setValue(OclReflection::createValue(context)); env->setSelfVariable(self); env->addElement(Environment::SELF_VARIABLE_NAME, self, true); if(epackage) { std::shared_ptr<Variable> packageVar = ocl::Expressions::ExpressionsFactory::eInstance()->createVariable(); packageVar->setName(epackage->getName()); packageVar->setEType(epackage->eClass()); packageVar->setValue(OclReflection::createValue(epackage)); env->addElement(packageVar->getName(), packageVar, false); } /* } else { std::shared_ptr<Variable> self = ocl::Expressions::ExpressionsFactory::eInstance()->createVariable(); self->setName(Environment::SELF_VARIABLE_NAME); self->setEType(context->eClass()); self->setValue(OclReflection::createValue(context)); env->addElement(self->getName(), self, true); env->setSelfVariable(self); } */ return env; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qfxflipable.h" #include "private/qfxitem_p.h" #include "qfxtransform.h" #include <QtDeclarative/qmlinfo.h> QML_DEFINE_TYPE(QFxFlipable,Flipable); class QFxFlipablePrivate : public QFxItemPrivate { public: QFxFlipablePrivate() : current(QFxFlipable::Front), front(0), back(0), axis(0), rotation(0) {} void setBackTransform(); void _q_updateAxis(); QFxFlipable::Side current; QFxItem *front; QFxItem *back; QFxAxis *axis; QFxRotation3D axisRotation; qreal rotation; }; /*! \qmlclass Flipable QFxFlipable \brief The Flipable item provides a surface that can be flipped. \inherits Item Flipable allows you to specify a front and a back and then flip between those sides. \qml Flipable { id: flipable width: 40 height: 40 axis: Axis { startX: 20 startY: 0 endX: 20 endY: 40 } front: Image { source: "front.png" } back: Image { source: "back.png" } states: [ State { name: "back" SetProperty { target: flipable property: "rotation" value: 180 } } ] transitions: [ Transition { NumericAnimation { easing: "easeInOutQuad" properties: "rotation" } } ] } \endqml \image flipable.gif */ /*! \internal \class QFxFlipable \brief The QFxFlipable class provides a flipable surface. \ingroup group_widgets QFxFlipable allows you to specify a front and a back, as well as an axis for the flip. */ QFxFlipable::QFxFlipable(QFxItem *parent) : QFxItem(*(new QFxFlipablePrivate), parent) { } QFxFlipable::~QFxFlipable() { } /*! \qmlproperty Item Flipable::front \qmlproperty Item Flipable::back The front and back sides of the flipable. */ QFxItem *QFxFlipable::front() { Q_D(const QFxFlipable); return d->front; } void QFxFlipable::setFront(QFxItem *front) { Q_D(QFxFlipable); if (d->front) { qmlInfo(this) << "front is a write-once property"; return; } d->front = front; children()->append(d->front); if (Back == d->current) d->front->setOpacity(0.); } QFxItem *QFxFlipable::back() { Q_D(const QFxFlipable); return d->back; } void QFxFlipable::setBack(QFxItem *back) { Q_D(QFxFlipable); if (d->back) { qmlInfo(this) << "back is a write-once property"; return; } d->back = back; children()->append(d->back); if (Front == d->current) d->back->setOpacity(0.); d->setBackTransform(); } /*! \qmlproperty Axis Flipable::axis The axis to flip around. See the \l Axis documentation for more information on specifying an axis. */ QFxAxis *QFxFlipable::axis() { Q_D(QFxFlipable); return d->axis; } void QFxFlipable::setAxis(QFxAxis *axis) { Q_D(QFxFlipable); //### disconnect if we are already connected? if (d->axis) disconnect(d->axis, SIGNAL(updated()), this, SLOT(_q_updateAxis())); d->axis = axis; connect(d->axis, SIGNAL(updated()), this, SLOT(_q_updateAxis())); d->_q_updateAxis(); } void QFxFlipablePrivate::_q_updateAxis() { axisRotation.axis()->setStartX(axis->startX()); axisRotation.axis()->setStartY(axis->startY()); axisRotation.axis()->setEndX(axis->endX()); axisRotation.axis()->setEndY(axis->endY()); axisRotation.axis()->setEndZ(axis->endZ()); setBackTransform(); } void QFxFlipablePrivate::setBackTransform() { if (!back) return; QPointF p1(0, 0); QPointF p2(1, 0); QPointF p3(1, 1); axisRotation.setAngle(180); p1 = axisRotation.transform().map(p1); p2 = axisRotation.transform().map(p2); p3 = axisRotation.transform().map(p3); axisRotation.setAngle(rotation); QSimpleCanvas::Matrix mat; #ifdef QFX_RENDER_OPENGL mat.translate(back->width()/2,back->height()/2, 0); if (back->width() && p1.x() >= p2.x()) mat.rotate(180, 0, 1, 0); if (back->height() && p2.y() >= p3.y()) mat.rotate(180, 1, 0, 0); mat.translate(-back->width()/2,-back->height()/2, 0); #else mat.translate(back->width()/2,back->height()/2); if (back->width() && p1.x() >= p2.x()) mat.rotate(180, Qt::YAxis); if (back->height() && p2.y() >= p3.y()) mat.rotate(180, Qt::XAxis); mat.translate(-back->width()/2,-back->height()/2); #endif back->setTransform(mat); } /*! \qmlproperty real Flipable::rotation The angle to rotate the flipable. For example, to show the back side of the flipable you can set the rotation to 180. */ qreal QFxFlipable::rotation() const { Q_D(const QFxFlipable); return d->rotation; } void QFxFlipable::setRotation(qreal angle) { Q_D(QFxFlipable); d->rotation = angle; d->axisRotation.setAngle(angle); setTransform(d->axisRotation.transform()); int simpleAngle = int(angle) % 360; Side newSide; if (simpleAngle < 91 || simpleAngle > 270) { newSide = Front; } else { newSide = Back; } if (newSide != d->current) { d->current = newSide; if (d->front) d->front->setOpacity((d->current==Front)?1.:0.); if (d->back) d->back->setOpacity((d->current==Back)?1.:0.); emit sideChanged(); } } /*! \qmlproperty enumeration Flipable::side The side of the Flippable currently visible. Possible values are \c Front and \c Back. */ QFxFlipable::Side QFxFlipable::side() const { Q_D(const QFxFlipable); return d->current; } //in some cases the user may want to specify a more complex transformation. //in that case, we still allow the generic use of transform. //(the logic here should be kept in sync with setBackTransform and setRotation) void QFxFlipable::transformChanged(const QSimpleCanvas::Matrix &trans) { qWarning("Transform changed"); Q_D(QFxFlipable); QPointF p1(0, 0); QPointF p2(1, 0); QPointF p3(1, 1); p1 = trans.map(p1); p2 = trans.map(p2); p3 = trans.map(p3); qreal cross = (p1.x() - p2.x()) * (p3.y() - p2.y()) - (p1.y() - p2.y()) * (p3.x() - p2.x()); Side newSide; if (cross > 0) { newSide = Back; } else { newSide = Front; } if (newSide != d->current) { d->current = newSide; if (d->current==Back) { QSimpleCanvas::Matrix mat; #ifdef QFX_RENDER_OPENGL mat.translate(d->back->width()/2,d->back->height()/2, 0); if (d->back->width() && p1.x() >= p2.x()) mat.rotate(180, 0, 1, 0); if (d->back->height() && p2.y() >= p3.y()) mat.rotate(180, 1, 0, 0); mat.translate(-d->back->width()/2,-d->back->height()/2, 0); #else mat.translate(d->back->width()/2,d->back->height()/2); if (d->back->width() && p1.x() >= p2.x()) mat.rotate(180, Qt::YAxis); if (d->back->height() && p2.y() >= p3.y()) mat.rotate(180, Qt::XAxis); mat.translate(-d->back->width()/2,-d->back->height()/2); #endif d->back->setTransform(mat); } if (d->front) d->front->setOpacity((d->current==Front)?1.:0.); if (d->back) d->back->setOpacity((d->current==Back)?1.:0.); emit sideChanged(); } } QT_END_NAMESPACE #include "moc_qfxflipable.cpp" <commit_msg>Remove debug.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qfxflipable.h" #include "private/qfxitem_p.h" #include "qfxtransform.h" #include <QtDeclarative/qmlinfo.h> QML_DEFINE_TYPE(QFxFlipable,Flipable); class QFxFlipablePrivate : public QFxItemPrivate { public: QFxFlipablePrivate() : current(QFxFlipable::Front), front(0), back(0), axis(0), rotation(0) {} void setBackTransform(); void _q_updateAxis(); QFxFlipable::Side current; QFxItem *front; QFxItem *back; QFxAxis *axis; QFxRotation3D axisRotation; qreal rotation; }; /*! \qmlclass Flipable QFxFlipable \brief The Flipable item provides a surface that can be flipped. \inherits Item Flipable allows you to specify a front and a back and then flip between those sides. \qml Flipable { id: flipable width: 40 height: 40 axis: Axis { startX: 20 startY: 0 endX: 20 endY: 40 } front: Image { source: "front.png" } back: Image { source: "back.png" } states: [ State { name: "back" SetProperty { target: flipable property: "rotation" value: 180 } } ] transitions: [ Transition { NumericAnimation { easing: "easeInOutQuad" properties: "rotation" } } ] } \endqml \image flipable.gif */ /*! \internal \class QFxFlipable \brief The QFxFlipable class provides a flipable surface. \ingroup group_widgets QFxFlipable allows you to specify a front and a back, as well as an axis for the flip. */ QFxFlipable::QFxFlipable(QFxItem *parent) : QFxItem(*(new QFxFlipablePrivate), parent) { } QFxFlipable::~QFxFlipable() { } /*! \qmlproperty Item Flipable::front \qmlproperty Item Flipable::back The front and back sides of the flipable. */ QFxItem *QFxFlipable::front() { Q_D(const QFxFlipable); return d->front; } void QFxFlipable::setFront(QFxItem *front) { Q_D(QFxFlipable); if (d->front) { qmlInfo(this) << "front is a write-once property"; return; } d->front = front; children()->append(d->front); if (Back == d->current) d->front->setOpacity(0.); } QFxItem *QFxFlipable::back() { Q_D(const QFxFlipable); return d->back; } void QFxFlipable::setBack(QFxItem *back) { Q_D(QFxFlipable); if (d->back) { qmlInfo(this) << "back is a write-once property"; return; } d->back = back; children()->append(d->back); if (Front == d->current) d->back->setOpacity(0.); d->setBackTransform(); } /*! \qmlproperty Axis Flipable::axis The axis to flip around. See the \l Axis documentation for more information on specifying an axis. */ QFxAxis *QFxFlipable::axis() { Q_D(QFxFlipable); return d->axis; } void QFxFlipable::setAxis(QFxAxis *axis) { Q_D(QFxFlipable); //### disconnect if we are already connected? if (d->axis) disconnect(d->axis, SIGNAL(updated()), this, SLOT(_q_updateAxis())); d->axis = axis; connect(d->axis, SIGNAL(updated()), this, SLOT(_q_updateAxis())); d->_q_updateAxis(); } void QFxFlipablePrivate::_q_updateAxis() { axisRotation.axis()->setStartX(axis->startX()); axisRotation.axis()->setStartY(axis->startY()); axisRotation.axis()->setEndX(axis->endX()); axisRotation.axis()->setEndY(axis->endY()); axisRotation.axis()->setEndZ(axis->endZ()); setBackTransform(); } void QFxFlipablePrivate::setBackTransform() { if (!back) return; QPointF p1(0, 0); QPointF p2(1, 0); QPointF p3(1, 1); axisRotation.setAngle(180); p1 = axisRotation.transform().map(p1); p2 = axisRotation.transform().map(p2); p3 = axisRotation.transform().map(p3); axisRotation.setAngle(rotation); QSimpleCanvas::Matrix mat; #ifdef QFX_RENDER_OPENGL mat.translate(back->width()/2,back->height()/2, 0); if (back->width() && p1.x() >= p2.x()) mat.rotate(180, 0, 1, 0); if (back->height() && p2.y() >= p3.y()) mat.rotate(180, 1, 0, 0); mat.translate(-back->width()/2,-back->height()/2, 0); #else mat.translate(back->width()/2,back->height()/2); if (back->width() && p1.x() >= p2.x()) mat.rotate(180, Qt::YAxis); if (back->height() && p2.y() >= p3.y()) mat.rotate(180, Qt::XAxis); mat.translate(-back->width()/2,-back->height()/2); #endif back->setTransform(mat); } /*! \qmlproperty real Flipable::rotation The angle to rotate the flipable. For example, to show the back side of the flipable you can set the rotation to 180. */ qreal QFxFlipable::rotation() const { Q_D(const QFxFlipable); return d->rotation; } void QFxFlipable::setRotation(qreal angle) { Q_D(QFxFlipable); d->rotation = angle; d->axisRotation.setAngle(angle); setTransform(d->axisRotation.transform()); int simpleAngle = int(angle) % 360; Side newSide; if (simpleAngle < 91 || simpleAngle > 270) { newSide = Front; } else { newSide = Back; } if (newSide != d->current) { d->current = newSide; if (d->front) d->front->setOpacity((d->current==Front)?1.:0.); if (d->back) d->back->setOpacity((d->current==Back)?1.:0.); emit sideChanged(); } } /*! \qmlproperty enumeration Flipable::side The side of the Flippable currently visible. Possible values are \c Front and \c Back. */ QFxFlipable::Side QFxFlipable::side() const { Q_D(const QFxFlipable); return d->current; } //in some cases the user may want to specify a more complex transformation. //in that case, we still allow the generic use of transform. //(the logic here should be kept in sync with setBackTransform and setRotation) void QFxFlipable::transformChanged(const QSimpleCanvas::Matrix &trans) { Q_D(QFxFlipable); QPointF p1(0, 0); QPointF p2(1, 0); QPointF p3(1, 1); p1 = trans.map(p1); p2 = trans.map(p2); p3 = trans.map(p3); qreal cross = (p1.x() - p2.x()) * (p3.y() - p2.y()) - (p1.y() - p2.y()) * (p3.x() - p2.x()); Side newSide; if (cross > 0) { newSide = Back; } else { newSide = Front; } if (newSide != d->current) { d->current = newSide; if (d->current==Back) { QSimpleCanvas::Matrix mat; #ifdef QFX_RENDER_OPENGL mat.translate(d->back->width()/2,d->back->height()/2, 0); if (d->back->width() && p1.x() >= p2.x()) mat.rotate(180, 0, 1, 0); if (d->back->height() && p2.y() >= p3.y()) mat.rotate(180, 1, 0, 0); mat.translate(-d->back->width()/2,-d->back->height()/2, 0); #else mat.translate(d->back->width()/2,d->back->height()/2); if (d->back->width() && p1.x() >= p2.x()) mat.rotate(180, Qt::YAxis); if (d->back->height() && p2.y() >= p3.y()) mat.rotate(180, Qt::XAxis); mat.translate(-d->back->width()/2,-d->back->height()/2); #endif d->back->setTransform(mat); } if (d->front) d->front->setOpacity((d->current==Front)?1.:0.); if (d->back) d->back->setOpacity((d->current==Back)?1.:0.); emit sideChanged(); } } QT_END_NAMESPACE #include "moc_qfxflipable.cpp" <|endoftext|>
<commit_before>//===-- RuntimeDyld.h - Run-time dynamic linker for MC-JIT ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implementation of the MC-JIT runtime dynamic linker. // //===----------------------------------------------------------------------===// #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/ExecutionEngine/RuntimeDyld.h" #include "llvm/Object/MachOObject.h" #include "llvm/Support/Memory.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/system_error.h" using namespace llvm; using namespace llvm::object; namespace llvm { class RuntimeDyldImpl { // Master symbol table. As modules are loaded and external symbols are // resolved, their addresses are stored here. StringMap<void*> SymbolTable; // FIXME: Should have multiple data blocks, one for each loaded chunk of // compiled code. sys::MemoryBlock Data; bool HasError; std::string ErrorStr; // Set the error state and record an error string. bool Error(const Twine &Msg) { ErrorStr = Msg.str(); HasError = true; return true; } bool loadSegment32(const MachOObject *Obj, const MachOObject::LoadCommandInfo *SegmentLCI, const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC); bool loadSegment64(const MachOObject *Obj, const MachOObject::LoadCommandInfo *SegmentLCI, const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC); public: RuntimeDyldImpl() : HasError(false) {} bool loadObject(MemoryBuffer *InputBuffer); void *getSymbolAddress(StringRef Name) { // Use lookup() rather than [] because we don't want to add an entry // if there isn't one already, which the [] operator does. return SymbolTable.lookup(Name); } sys::MemoryBlock getMemoryBlock() { return Data; } // Is the linker in an error state? bool hasError() { return HasError; } // Mark the error condition as handled and continue. void clearError() { HasError = false; } // Get the error message. StringRef getErrorString() { return ErrorStr; } }; bool RuntimeDyldImpl:: loadSegment32(const MachOObject *Obj, const MachOObject::LoadCommandInfo *SegmentLCI, const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) { InMemoryStruct<macho::SegmentLoadCommand> Segment32LC; Obj->ReadSegmentLoadCommand(*SegmentLCI, Segment32LC); if (!Segment32LC) return Error("unable to load segment load command"); // Map the segment into memory. std::string ErrorStr; Data = sys::Memory::AllocateRWX(Segment32LC->VMSize, 0, &ErrorStr); if (!Data.base()) return Error("unable to allocate memory block: '" + ErrorStr + "'"); memcpy(Data.base(), Obj->getData(Segment32LC->FileOffset, Segment32LC->FileSize).data(), Segment32LC->FileSize); memset((char*)Data.base() + Segment32LC->FileSize, 0, Segment32LC->VMSize - Segment32LC->FileSize); // Bind the section indices to address. void **SectionBases = new void*[Segment32LC->NumSections]; for (unsigned i = 0; i != Segment32LC->NumSections; ++i) { InMemoryStruct<macho::Section> Sect; Obj->ReadSection(*SegmentLCI, i, Sect); if (!Sect) return Error("unable to load section: '" + Twine(i) + "'"); // FIXME: We don't support relocations yet. if (Sect->NumRelocationTableEntries != 0) return Error("not yet implemented: relocations!"); // FIXME: Improve check. if (Sect->Flags != 0x80000400) return Error("unsupported section type!"); SectionBases[i] = (char*) Data.base() + Sect->Address; } // Bind all the symbols to address. for (unsigned i = 0; i != SymtabLC->NumSymbolTableEntries; ++i) { InMemoryStruct<macho::SymbolTableEntry> STE; Obj->ReadSymbolTableEntry(SymtabLC->SymbolTableOffset, i, STE); if (!STE) return Error("unable to read symbol: '" + Twine(i) + "'"); if (STE->SectionIndex == 0) return Error("unexpected undefined symbol!"); unsigned Index = STE->SectionIndex - 1; if (Index >= Segment32LC->NumSections) return Error("invalid section index for symbol: '" + Twine() + "'"); // Get the symbol name. StringRef Name = Obj->getStringAtIndex(STE->StringIndex); // Get the section base address. void *SectionBase = SectionBases[Index]; // Get the symbol address. void *Address = (char*) SectionBase + STE->Value; // FIXME: Check the symbol type and flags. if (STE->Type != 0xF) return Error("unexpected symbol type!"); if (STE->Flags != 0x0) return Error("unexpected symbol type!"); SymbolTable[Name] = Address; } // We've loaded the section; now mark the functions in it as executable. // FIXME: We really should use the JITMemoryManager for this. sys::Memory::setRangeExecutable(Data.base(), Data.size()); delete SectionBases; return false; } bool RuntimeDyldImpl:: loadSegment64(const MachOObject *Obj, const MachOObject::LoadCommandInfo *SegmentLCI, const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) { InMemoryStruct<macho::Segment64LoadCommand> Segment64LC; Obj->ReadSegment64LoadCommand(*SegmentLCI, Segment64LC); if (!Segment64LC) return Error("unable to load segment load command"); // Map the segment into memory. std::string ErrorStr; Data = sys::Memory::AllocateRWX(Segment64LC->VMSize, 0, &ErrorStr); if (!Data.base()) return Error("unable to allocate memory block: '" + ErrorStr + "'"); memcpy(Data.base(), Obj->getData(Segment64LC->FileOffset, Segment64LC->FileSize).data(), Segment64LC->FileSize); memset((char*)Data.base() + Segment64LC->FileSize, 0, Segment64LC->VMSize - Segment64LC->FileSize); // Bind the section indices to address. void **SectionBases = new void*[Segment64LC->NumSections]; for (unsigned i = 0; i != Segment64LC->NumSections; ++i) { InMemoryStruct<macho::Section64> Sect; Obj->ReadSection64(*SegmentLCI, i, Sect); if (!Sect) return Error("unable to load section: '" + Twine(i) + "'"); // FIXME: We don't support relocations yet. if (Sect->NumRelocationTableEntries != 0) return Error("not yet implemented: relocations!"); // FIXME: Improve check. if (Sect->Flags != 0x80000400) return Error("unsupported section type!"); SectionBases[i] = (char*) Data.base() + Sect->Address; } // Bind all the symbols to address. for (unsigned i = 0; i != SymtabLC->NumSymbolTableEntries; ++i) { InMemoryStruct<macho::Symbol64TableEntry> STE; Obj->ReadSymbol64TableEntry(SymtabLC->SymbolTableOffset, i, STE); if (!STE) return Error("unable to read symbol: '" + Twine(i) + "'"); if (STE->SectionIndex == 0) return Error("unexpected undefined symbol!"); unsigned Index = STE->SectionIndex - 1; if (Index >= Segment64LC->NumSections) return Error("invalid section index for symbol: '" + Twine() + "'"); // Get the symbol name. StringRef Name = Obj->getStringAtIndex(STE->StringIndex); // Get the section base address. void *SectionBase = SectionBases[Index]; // Get the symbol address. void *Address = (char*) SectionBase + STE->Value; // FIXME: Check the symbol type and flags. if (STE->Type != 0xF) return Error("unexpected symbol type!"); if (STE->Flags != 0x0) return Error("unexpected symbol type!"); SymbolTable[Name] = Address; } // We've loaded the section; now mark the functions in it as executable. // FIXME: We really should use the JITMemoryManager for this. sys::Memory::setRangeExecutable(Data.base(), Data.size()); delete SectionBases; return false; } bool RuntimeDyldImpl::loadObject(MemoryBuffer *InputBuffer) { // If the linker is in an error state, don't do anything. if (hasError()) return true; // Load the Mach-O wrapper object. std::string ErrorStr; OwningPtr<MachOObject> Obj( MachOObject::LoadFromBuffer(InputBuffer, &ErrorStr)); if (!Obj) return Error("unable to load object: '" + ErrorStr + "'"); // Validate that the load commands match what we expect. const MachOObject::LoadCommandInfo *SegmentLCI = 0, *SymtabLCI = 0, *DysymtabLCI = 0; for (unsigned i = 0; i != Obj->getHeader().NumLoadCommands; ++i) { const MachOObject::LoadCommandInfo &LCI = Obj->getLoadCommandInfo(i); switch (LCI.Command.Type) { case macho::LCT_Segment: case macho::LCT_Segment64: if (SegmentLCI) return Error("unexpected input object (multiple segments)"); SegmentLCI = &LCI; break; case macho::LCT_Symtab: if (SymtabLCI) return Error("unexpected input object (multiple symbol tables)"); SymtabLCI = &LCI; break; case macho::LCT_Dysymtab: if (DysymtabLCI) return Error("unexpected input object (multiple symbol tables)"); DysymtabLCI = &LCI; break; default: return Error("unexpected input object (unexpected load command"); } } if (!SymtabLCI) return Error("no symbol table found in object"); if (!SegmentLCI) return Error("no symbol table found in object"); // Read and register the symbol table data. InMemoryStruct<macho::SymtabLoadCommand> SymtabLC; Obj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC); if (!SymtabLC) return Error("unable to load symbol table load command"); Obj->RegisterStringTable(*SymtabLC); // Read the dynamic link-edit information, if present (not present in static // objects). if (DysymtabLCI) { InMemoryStruct<macho::DysymtabLoadCommand> DysymtabLC; Obj->ReadDysymtabLoadCommand(*DysymtabLCI, DysymtabLC); if (!DysymtabLC) return Error("unable to load dynamic link-exit load command"); // FIXME: We don't support anything interesting yet. if (DysymtabLC->LocalSymbolsIndex != 0) return Error("NOT YET IMPLEMENTED: local symbol entries"); if (DysymtabLC->ExternalSymbolsIndex != 0) return Error("NOT YET IMPLEMENTED: non-external symbol entries"); if (DysymtabLC->UndefinedSymbolsIndex != SymtabLC->NumSymbolTableEntries) return Error("NOT YET IMPLEMENTED: undefined symbol entries"); } // Load the segment load command. if (SegmentLCI->Command.Type == macho::LCT_Segment) { if (loadSegment32(Obj.get(), SegmentLCI, SymtabLC)) return true; } else { if (loadSegment64(Obj.get(), SegmentLCI, SymtabLC)) return true; } return false; } //===----------------------------------------------------------------------===// // RuntimeDyld class implementation RuntimeDyld::RuntimeDyld() { Dyld = new RuntimeDyldImpl; } RuntimeDyld::~RuntimeDyld() { delete Dyld; } bool RuntimeDyld::loadObject(MemoryBuffer *InputBuffer) { return Dyld->loadObject(InputBuffer); } void *RuntimeDyld::getSymbolAddress(StringRef Name) { return Dyld->getSymbolAddress(Name); } sys::MemoryBlock RuntimeDyld::getMemoryBlock() { return Dyld->getMemoryBlock(); } StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); } } // end namespace llvm <commit_msg>Tidy up.<commit_after>//===-- RuntimeDyld.h - Run-time dynamic linker for MC-JIT ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implementation of the MC-JIT runtime dynamic linker. // //===----------------------------------------------------------------------===// #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/ExecutionEngine/RuntimeDyld.h" #include "llvm/Object/MachOObject.h" #include "llvm/Support/Memory.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/system_error.h" using namespace llvm; using namespace llvm::object; namespace llvm { class RuntimeDyldImpl { // Master symbol table. As modules are loaded and external symbols are // resolved, their addresses are stored here. StringMap<void*> SymbolTable; // FIXME: Should have multiple data blocks, one for each loaded chunk of // compiled code. sys::MemoryBlock Data; bool HasError; std::string ErrorStr; // Set the error state and record an error string. bool Error(const Twine &Msg) { ErrorStr = Msg.str(); HasError = true; return true; } bool loadSegment32(const MachOObject *Obj, const MachOObject::LoadCommandInfo *SegmentLCI, const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC); bool loadSegment64(const MachOObject *Obj, const MachOObject::LoadCommandInfo *SegmentLCI, const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC); public: RuntimeDyldImpl() : HasError(false) {} bool loadObject(MemoryBuffer *InputBuffer); void *getSymbolAddress(StringRef Name) { // Use lookup() rather than [] because we don't want to add an entry // if there isn't one already, which the [] operator does. return SymbolTable.lookup(Name); } sys::MemoryBlock getMemoryBlock() { return Data; } // Is the linker in an error state? bool hasError() { return HasError; } // Mark the error condition as handled and continue. void clearError() { HasError = false; } // Get the error message. StringRef getErrorString() { return ErrorStr; } }; bool RuntimeDyldImpl:: loadSegment32(const MachOObject *Obj, const MachOObject::LoadCommandInfo *SegmentLCI, const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) { InMemoryStruct<macho::SegmentLoadCommand> Segment32LC; Obj->ReadSegmentLoadCommand(*SegmentLCI, Segment32LC); if (!Segment32LC) return Error("unable to load segment load command"); // Map the segment into memory. std::string ErrorStr; Data = sys::Memory::AllocateRWX(Segment32LC->VMSize, 0, &ErrorStr); if (!Data.base()) return Error("unable to allocate memory block: '" + ErrorStr + "'"); memcpy(Data.base(), Obj->getData(Segment32LC->FileOffset, Segment32LC->FileSize).data(), Segment32LC->FileSize); memset((char*)Data.base() + Segment32LC->FileSize, 0, Segment32LC->VMSize - Segment32LC->FileSize); // Bind the section indices to address. void **SectionBases = new void*[Segment32LC->NumSections]; for (unsigned i = 0; i != Segment32LC->NumSections; ++i) { InMemoryStruct<macho::Section> Sect; Obj->ReadSection(*SegmentLCI, i, Sect); if (!Sect) return Error("unable to load section: '" + Twine(i) + "'"); // FIXME: We don't support relocations yet. if (Sect->NumRelocationTableEntries != 0) return Error("not yet implemented: relocations!"); // FIXME: Improve check. if (Sect->Flags != 0x80000400) return Error("unsupported section type!"); SectionBases[i] = (char*) Data.base() + Sect->Address; } // Bind all the symbols to address. for (unsigned i = 0; i != SymtabLC->NumSymbolTableEntries; ++i) { InMemoryStruct<macho::SymbolTableEntry> STE; Obj->ReadSymbolTableEntry(SymtabLC->SymbolTableOffset, i, STE); if (!STE) return Error("unable to read symbol: '" + Twine(i) + "'"); if (STE->SectionIndex == 0) return Error("unexpected undefined symbol!"); unsigned Index = STE->SectionIndex - 1; if (Index >= Segment32LC->NumSections) return Error("invalid section index for symbol: '" + Twine() + "'"); // Get the symbol name. StringRef Name = Obj->getStringAtIndex(STE->StringIndex); // Get the section base address. void *SectionBase = SectionBases[Index]; // Get the symbol address. void *Address = (char*) SectionBase + STE->Value; // FIXME: Check the symbol type and flags. if (STE->Type != 0xF) return Error("unexpected symbol type!"); if (STE->Flags != 0x0) return Error("unexpected symbol type!"); SymbolTable[Name] = Address; } // We've loaded the section; now mark the functions in it as executable. // FIXME: We really should use the JITMemoryManager for this. sys::Memory::setRangeExecutable(Data.base(), Data.size()); delete SectionBases; return false; } bool RuntimeDyldImpl:: loadSegment64(const MachOObject *Obj, const MachOObject::LoadCommandInfo *SegmentLCI, const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) { InMemoryStruct<macho::Segment64LoadCommand> Segment64LC; Obj->ReadSegment64LoadCommand(*SegmentLCI, Segment64LC); if (!Segment64LC) return Error("unable to load segment load command"); // Map the segment into memory. std::string ErrorStr; Data = sys::Memory::AllocateRWX(Segment64LC->VMSize, 0, &ErrorStr); if (!Data.base()) return Error("unable to allocate memory block: '" + ErrorStr + "'"); memcpy(Data.base(), Obj->getData(Segment64LC->FileOffset, Segment64LC->FileSize).data(), Segment64LC->FileSize); memset((char*)Data.base() + Segment64LC->FileSize, 0, Segment64LC->VMSize - Segment64LC->FileSize); // Bind the section indices to address. void **SectionBases = new void*[Segment64LC->NumSections]; for (unsigned i = 0; i != Segment64LC->NumSections; ++i) { InMemoryStruct<macho::Section64> Sect; Obj->ReadSection64(*SegmentLCI, i, Sect); if (!Sect) return Error("unable to load section: '" + Twine(i) + "'"); // FIXME: We don't support relocations yet. if (Sect->NumRelocationTableEntries != 0) return Error("not yet implemented: relocations!"); // FIXME: Improve check. if (Sect->Flags != 0x80000400) return Error("unsupported section type!"); SectionBases[i] = (char*) Data.base() + Sect->Address; } // Bind all the symbols to address. for (unsigned i = 0; i != SymtabLC->NumSymbolTableEntries; ++i) { InMemoryStruct<macho::Symbol64TableEntry> STE; Obj->ReadSymbol64TableEntry(SymtabLC->SymbolTableOffset, i, STE); if (!STE) return Error("unable to read symbol: '" + Twine(i) + "'"); if (STE->SectionIndex == 0) return Error("unexpected undefined symbol!"); unsigned Index = STE->SectionIndex - 1; if (Index >= Segment64LC->NumSections) return Error("invalid section index for symbol: '" + Twine() + "'"); // Get the symbol name. StringRef Name = Obj->getStringAtIndex(STE->StringIndex); // Get the section base address. void *SectionBase = SectionBases[Index]; // Get the symbol address. void *Address = (char*) SectionBase + STE->Value; // FIXME: Check the symbol type and flags. if (STE->Type != 0xF) return Error("unexpected symbol type!"); if (STE->Flags != 0x0) return Error("unexpected symbol type!"); SymbolTable[Name] = Address; } // We've loaded the section; now mark the functions in it as executable. // FIXME: We really should use the JITMemoryManager for this. sys::Memory::setRangeExecutable(Data.base(), Data.size()); delete SectionBases; return false; } bool RuntimeDyldImpl::loadObject(MemoryBuffer *InputBuffer) { // If the linker is in an error state, don't do anything. if (hasError()) return true; // Load the Mach-O wrapper object. std::string ErrorStr; OwningPtr<MachOObject> Obj( MachOObject::LoadFromBuffer(InputBuffer, &ErrorStr)); if (!Obj) return Error("unable to load object: '" + ErrorStr + "'"); // Validate that the load commands match what we expect. const MachOObject::LoadCommandInfo *SegmentLCI = 0, *SymtabLCI = 0, *DysymtabLCI = 0; for (unsigned i = 0; i != Obj->getHeader().NumLoadCommands; ++i) { const MachOObject::LoadCommandInfo &LCI = Obj->getLoadCommandInfo(i); switch (LCI.Command.Type) { case macho::LCT_Segment: case macho::LCT_Segment64: if (SegmentLCI) return Error("unexpected input object (multiple segments)"); SegmentLCI = &LCI; break; case macho::LCT_Symtab: if (SymtabLCI) return Error("unexpected input object (multiple symbol tables)"); SymtabLCI = &LCI; break; case macho::LCT_Dysymtab: if (DysymtabLCI) return Error("unexpected input object (multiple symbol tables)"); DysymtabLCI = &LCI; break; default: return Error("unexpected input object (unexpected load command"); } } if (!SymtabLCI) return Error("no symbol table found in object"); if (!SegmentLCI) return Error("no symbol table found in object"); // Read and register the symbol table data. InMemoryStruct<macho::SymtabLoadCommand> SymtabLC; Obj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC); if (!SymtabLC) return Error("unable to load symbol table load command"); Obj->RegisterStringTable(*SymtabLC); // Read the dynamic link-edit information, if present (not present in static // objects). if (DysymtabLCI) { InMemoryStruct<macho::DysymtabLoadCommand> DysymtabLC; Obj->ReadDysymtabLoadCommand(*DysymtabLCI, DysymtabLC); if (!DysymtabLC) return Error("unable to load dynamic link-exit load command"); // FIXME: We don't support anything interesting yet. if (DysymtabLC->LocalSymbolsIndex != 0) return Error("NOT YET IMPLEMENTED: local symbol entries"); if (DysymtabLC->ExternalSymbolsIndex != 0) return Error("NOT YET IMPLEMENTED: non-external symbol entries"); if (DysymtabLC->UndefinedSymbolsIndex != SymtabLC->NumSymbolTableEntries) return Error("NOT YET IMPLEMENTED: undefined symbol entries"); } // Load the segment load command. if (SegmentLCI->Command.Type == macho::LCT_Segment) { if (loadSegment32(Obj.get(), SegmentLCI, SymtabLC)) return true; } else { if (loadSegment64(Obj.get(), SegmentLCI, SymtabLC)) return true; } return false; } //===----------------------------------------------------------------------===// // RuntimeDyld class implementation RuntimeDyld::RuntimeDyld() { Dyld = new RuntimeDyldImpl; } RuntimeDyld::~RuntimeDyld() { delete Dyld; } bool RuntimeDyld::loadObject(MemoryBuffer *InputBuffer) { return Dyld->loadObject(InputBuffer); } void *RuntimeDyld::getSymbolAddress(StringRef Name) { return Dyld->getSymbolAddress(Name); } sys::MemoryBlock RuntimeDyld::getMemoryBlock() { return Dyld->getMemoryBlock(); } StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); } } // end namespace llvm <|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/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" // Tabs appears to timeout, or maybe crash on mac. // http://crbug.com/53779 #if defined(OS_MACOSX) #define MAYBE_Tabs FAILS_Tabs #else #define MAYBE_Tabs Tabs #endif // TabOnRemoved is flaky on chromeos and linux views debug build. // http://crbug.com/49258 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG) #define MAYBE_TabOnRemoved FLAKY_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { ASSERT_TRUE(test_server()->Start()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } <commit_msg>Mark ExtensionApiTest.Tabs as FAILS on ChromeOS BUG=58229 TBR=evan<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/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" #if defined(OS_CHROMEOS) // Tabs fails on ChromeOS. // http://crbug.com/58229 #define MAYBE_Tabs FAILS_Tabs #elif defined(OS_MACOSX) // Tabs appears to timeout, or maybe crash on mac. // http://crbug.com/53779 #define MAYBE_Tabs FAILS_Tabs #else #define MAYBE_Tabs Tabs #endif // TabOnRemoved is flaky on chromeos and linux views debug build. // http://crbug.com/49258 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG) #define MAYBE_TabOnRemoved FLAKY_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { ASSERT_TRUE(test_server()->Start()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } <|endoftext|>
<commit_before>// TRENTO: Reduced Thickness Event-by-event Nuclear Topology // Copyright 2015 Jonah E. Bernhard, J. Scott Moreland // MIT License #include "nucleon.h" #include <cmath> #include <limits> #include <random> #include <stdexcept> #include <cstdlib> #include <iostream> #include <fstream> #include <iomanip> #include <boost/math/constants/constants.hpp> #include <boost/math/special_functions/expint.hpp> #include <boost/math/tools/roots.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/math/special_functions/erf.hpp> #include <boost/filesystem.hpp> #include "fwd_decl.h" namespace trento { namespace { // These constants define distances in terms of the width of the nucleon profile // Gaussian thickness function. // Truncation radius of the thickness function. constexpr double radius_widths = 5.; // Maximum impact parameter for participation. constexpr double max_impact_widths = 6.; // Create ctor parameters for unit mean std::gamma_distribution. // mean = alpha*beta == 1 -> beta = 1/alpha // Used below in NucleonProfile ctor initializer list. template <typename RealType> using param_type = typename std::gamma_distribution<RealType>::param_type; template <typename RealType> param_type<RealType> gamma_param_unit_mean(RealType alpha = 1.) { return param_type<RealType>{alpha, 1./alpha}; } // Return appropriate path to temporary file directory. // Used to store cross section parameter \sigma_partonic. fs::path get_data_home() { const auto data_path = std::getenv("XDG_DATA_HOME"); if(data_path == nullptr) return fs::path{std::getenv("HOME")} / ".local/share"; return data_path; } // Test approximate cross section parameter equality bool almost_equal(double a, double b) { return fabs(a - b) < 1e-6; } // Default parton width to nucleon width. double infer_parton_width(const VarMap& var_map) { auto nucleon_width = var_map["nucleon-width"].as<double>(); auto parton_width = var_map["parton-width"].as<double>(); if (parton_width < 0) return nucleon_width; else return parton_width; } // Determine the effective parton-parton cross section for sampling participants. // TODO: derive this double analytic_partonic_cross_section(const VarMap& var_map) { // Read parameters from the configuration. auto sigma_nn = var_map["cross-section"].as<double>(); auto width = var_map["nucleon-width"].as<double>(); // TODO: automatically set from beam energy // if (sigma_nn < 0.) { // auto sqrt_s = var_map["beam-energy"].as<double>(); // } // Initialize arguments for boost root finding function. // Bracket min and max. auto a = -10.; auto b = 20.; // Tolerance function. // Require 3/4 of double precision. math::tools::eps_tolerance<double> tol{ (std::numeric_limits<double>::digits * 3) / 4}; // Maximum iterations. // This is overkill -- in testing only 10-20 iterations were required // (but no harm in overestimating). boost::uintmax_t max_iter = 1000; // The right-hand side of the equation. auto rhs = sigma_nn / (4 * math::double_constants::pi * sqr(width)); // This quantity appears a couple times in the equation. auto c = sqr(max_impact_widths) / 4; try { auto result = math::tools::toms748_solve( [&rhs, &c](double x) { using std::exp; using math::expint; return c - expint(-exp(x)) + expint(-exp(x-c)) - rhs; }, a, b, tol, max_iter); auto cross_section_param = .5*(result.first + result.second); return std::exp(cross_section_param) * 4 * math::double_constants::pi * sqr(width); } catch (const std::domain_error&) { // Root finding fails for very small nucleon widths, w^2/sigma_nn < ~0.01. throw std::domain_error{ "unable to fit cross section -- nucleon and/or parton width too small?"}; } } // Use Monte Carlo methods to determine the partonic cross section // \sigma_partonic. Solves MonteCarloCrossSection(sigma_partonic) = sigma_nn. double numeric_partonic_cross_section(const VarMap& var_map) { MonteCarloCrossSection mc_cross_section(var_map); auto sigma_nn = var_map["cross-section"].as<double>(); auto parton_width = infer_parton_width(var_map); // Bracket min and max. auto a = -10.; auto b = 20.; // Tolerance function. math::tools::eps_tolerance<double> tol{8}; // Maximum iterations. boost::uintmax_t max_iter = 20; // Dimensional constant [fm^-1] used to rescale sigma_partonic auto c = 4 * math::double_constants::pi * sqr(parton_width); try { auto result = math::tools::toms748_solve( [&sigma_nn, &mc_cross_section, &c](double cross_section_param) { auto x = std::exp(cross_section_param) * c; return mc_cross_section(x) - sigma_nn; }, a, b, tol, max_iter); auto cross_section_param = .5*(result.first + result.second); return std::exp(cross_section_param) * c; } catch (const std::domain_error&) { // Root finding fails for very small nucleon widths, w^2/sigma_nn < ~0.01. throw std::domain_error{ "unable to fit cross section -- nucleon and/or parton width too small?"}; } } // Determine the cross section parameter sigma_partonic, given the // nucleon width, parton width, nucleon-nucleon cross section, and parton number. double partonic_cross_section(const VarMap& var_map) { // Read parameters from the configuration. auto parton_width = infer_parton_width(var_map); auto nucleon_width = var_map["nucleon-width"].as<double>(); auto sigma_nn = var_map["cross-section"].as<double>(); auto nparton = var_map["parton-number"].as<int>(); // Cross section parameters int nparton_; double nucleon_width_; double parton_width_; double sigma_nn_; double sigma_partonic; // Establish trento cache path auto cache_dir = get_data_home() / "trento"; auto cache_path = cache_dir / "cross_section.dat"; fs::create_directory(cache_dir); // Check if cache exists if (fs::exists(cache_path.string())){ // Open cache read only std::fstream cache_read(cache_path.string(), std::ios_base::in); // Check cache for previously tabulated cross section parameters while(!cache_read.eof()) { cache_read >> nparton_ >> nucleon_width_ >> parton_width_ >> sigma_nn_ >> sigma_partonic; if (almost_equal(nucleon_width, nucleon_width_) && almost_equal(parton_width, parton_width_) && almost_equal(sigma_nn, sigma_nn_) && (nparton == nparton_)) { return sigma_partonic; } } // Close read-only file stream cache_read.close(); } // Open cache with write access std::fstream cache_write(cache_path.string(), std::ios_base::app); // Use a semi-analytic method to determine sigma_partonic // if there is no subnucleonic structure---otherwise use MC method. if (nucleon_width == parton_width) sigma_partonic = analytic_partonic_cross_section(var_map); else sigma_partonic = numeric_partonic_cross_section(var_map); // Save new cross section parameters to cache using std::fixed; using std::setprecision; using std::setw; using std::scientific; using std::endl; cache_write << setprecision(6) << std::left << setw(8) << fixed << nparton << setw(10) << fixed << nucleon_width << setw(10) << fixed << parton_width << setw(10) << fixed << sigma_nn << setw(14) << scientific << sigma_partonic << endl; return sigma_partonic; } // Determine the width of the normal distribution for sampling parton positions. double compute_parton_sampling_width(const VarMap& var_map) { // Read parameters from the configuration. auto nucleon_width = var_map["nucleon-width"].as<double>(); auto parton_width = var_map["parton-width"].as<double>(); // Default parton width to nucleon width. if (parton_width < 0) return 0.; // Compute Gaussian sampling width by deconvolving the parton profile from the // nucleon profile. The convolution of two Gaussians is a third Gaussian // with the variances simply added together. auto sampling_width_sq = sqr(nucleon_width) - sqr(parton_width); auto TINY = 1e-8; if (sampling_width_sq < -TINY) { throw std::out_of_range{ "the parton width cannot be larger than the nucleon width"}; } return std::sqrt(std::max(sampling_width_sq, 0.)); } } // unnamed namespace NucleonCommon::NucleonCommon(const VarMap& var_map) : fast_exp_(-.5*sqr(radius_widths), 0., 1000), max_impact_sq_(sqr(max_impact_widths*var_map["nucleon-width"].as<double>())), parton_width_sq_(sqr(infer_parton_width(var_map))), parton_radius_sq_(sqr(radius_widths)*parton_width_sq_), npartons_(std::size_t(var_map["parton-number"].as<int>())), sigma_partonic_(partonic_cross_section(var_map)), prefactor_(math::double_constants::one_div_two_pi/parton_width_sq_/npartons_), participant_fluctuation_dist_(gamma_param_unit_mean(var_map["fluctuation"].as<double>())), parton_position_dist_(0, compute_parton_sampling_width(var_map)) {} MonteCarloCrossSection::MonteCarloCrossSection(const VarMap& var_map) : npartons(std::size_t(var_map["parton-number"].as<int>())), nucleon_width(var_map["nucleon-width"].as<double>()), parton_width(infer_parton_width(var_map)), parton_sampling_width(compute_parton_sampling_width(var_map)), parton_width_sq(sqr(parton_width)), prefactor(math::double_constants::one_div_two_pi/parton_width_sq/npartons) {} double MonteCarloCrossSection::operator() (const double sigma_partonic) const { random::CyclicNormal<> cyclic_normal{ 0., parton_sampling_width, cache_size, n_loops }; struct Parton { double x, y; }; std::vector<Parton> nucleonA(npartons); std::vector<Parton> nucleonB(npartons); auto bmax = max_impact_widths * nucleon_width; auto arg_max = 0.25*sqr(bmax)/parton_width_sq; const FastExp<double> fast_exp(-arg_max, 0., 1000); double ref_cross_section = 0.; double prob_miss = 0.; int pass_tolerance = 0; for (std::size_t n = 0; n < n_max; ++n) { // Sample b from P(b)db = 2*pi*b. auto b = bmax * std::sqrt(random::canonical<double>()); for (auto&& p : nucleonA) { p.x = cyclic_normal(random::engine); p.y = cyclic_normal(random::engine); } for (auto&& p : nucleonB) { p.x = cyclic_normal(random::engine); p.y = cyclic_normal(random::engine); } auto overlap = 0.; for (auto&& pa : nucleonA) { for (auto&& pb : nucleonB) { auto distance_sq = sqr(pa.x - pb.x + b) + sqr(pa.y - pb.y); auto arg = .25*distance_sq/parton_width_sq; if (arg < arg_max) overlap += fast_exp(-arg); } } prob_miss += std::exp(-sigma_partonic * prefactor/(2.*npartons) * overlap); auto fraction_hit = 1. - (prob_miss/n); auto sample_area = math::double_constants::pi * sqr(bmax); auto cross_section = fraction_hit * sample_area; auto update_difference = std::abs((cross_section - ref_cross_section)/cross_section); if (update_difference < tolerance) { ++pass_tolerance; } else { pass_tolerance = 0; ref_cross_section = cross_section; } if (pass_tolerance > n_pass){ return cross_section; } } throw std::out_of_range{ "Partonic cross section failed to converge \ -- check nucleon-width, parton-width and npartons"}; // Code throws an error before it ever gets here. return -1; } } // namespace trento <commit_msg>have to add ios_base::out for ios_base::app<commit_after>// TRENTO: Reduced Thickness Event-by-event Nuclear Topology // Copyright 2015 Jonah E. Bernhard, J. Scott Moreland // MIT License #include "nucleon.h" #include <cmath> #include <limits> #include <random> #include <stdexcept> #include <cstdlib> #include <iostream> #include <fstream> #include <iomanip> #include <boost/math/constants/constants.hpp> #include <boost/math/special_functions/expint.hpp> #include <boost/math/tools/roots.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/math/special_functions/erf.hpp> #include <boost/filesystem.hpp> #include "fwd_decl.h" namespace trento { namespace { // These constants define distances in terms of the width of the nucleon profile // Gaussian thickness function. // Truncation radius of the thickness function. constexpr double radius_widths = 5.; // Maximum impact parameter for participation. constexpr double max_impact_widths = 6.; // Create ctor parameters for unit mean std::gamma_distribution. // mean = alpha*beta == 1 -> beta = 1/alpha // Used below in NucleonProfile ctor initializer list. template <typename RealType> using param_type = typename std::gamma_distribution<RealType>::param_type; template <typename RealType> param_type<RealType> gamma_param_unit_mean(RealType alpha = 1.) { return param_type<RealType>{alpha, 1./alpha}; } // Return appropriate path to temporary file directory. // Used to store cross section parameter \sigma_partonic. fs::path get_data_home() { const auto data_path = std::getenv("XDG_DATA_HOME"); if(data_path == nullptr) return fs::path{std::getenv("HOME")} / ".local/share"; return data_path; } // Test approximate cross section parameter equality bool almost_equal(double a, double b) { return fabs(a - b) < 1e-6; } // Default parton width to nucleon width. double infer_parton_width(const VarMap& var_map) { auto nucleon_width = var_map["nucleon-width"].as<double>(); auto parton_width = var_map["parton-width"].as<double>(); if (parton_width < 0) return nucleon_width; else return parton_width; } // Determine the effective parton-parton cross section for sampling participants. // TODO: derive this double analytic_partonic_cross_section(const VarMap& var_map) { // Read parameters from the configuration. auto sigma_nn = var_map["cross-section"].as<double>(); auto width = var_map["nucleon-width"].as<double>(); // TODO: automatically set from beam energy // if (sigma_nn < 0.) { // auto sqrt_s = var_map["beam-energy"].as<double>(); // } // Initialize arguments for boost root finding function. // Bracket min and max. auto a = -10.; auto b = 20.; // Tolerance function. // Require 3/4 of double precision. math::tools::eps_tolerance<double> tol{ (std::numeric_limits<double>::digits * 3) / 4}; // Maximum iterations. // This is overkill -- in testing only 10-20 iterations were required // (but no harm in overestimating). boost::uintmax_t max_iter = 1000; // The right-hand side of the equation. auto rhs = sigma_nn / (4 * math::double_constants::pi * sqr(width)); // This quantity appears a couple times in the equation. auto c = sqr(max_impact_widths) / 4; try { auto result = math::tools::toms748_solve( [&rhs, &c](double x) { using std::exp; using math::expint; return c - expint(-exp(x)) + expint(-exp(x-c)) - rhs; }, a, b, tol, max_iter); auto cross_section_param = .5*(result.first + result.second); return std::exp(cross_section_param) * 4 * math::double_constants::pi * sqr(width); } catch (const std::domain_error&) { // Root finding fails for very small nucleon widths, w^2/sigma_nn < ~0.01. throw std::domain_error{ "unable to fit cross section -- nucleon and/or parton width too small?"}; } } // Use Monte Carlo methods to determine the partonic cross section // \sigma_partonic. Solves MonteCarloCrossSection(sigma_partonic) = sigma_nn. double numeric_partonic_cross_section(const VarMap& var_map) { MonteCarloCrossSection mc_cross_section(var_map); auto sigma_nn = var_map["cross-section"].as<double>(); auto parton_width = infer_parton_width(var_map); // Bracket min and max. auto a = -10.; auto b = 20.; // Tolerance function. math::tools::eps_tolerance<double> tol{8}; // Maximum iterations. boost::uintmax_t max_iter = 20; // Dimensional constant [fm^-1] used to rescale sigma_partonic auto c = 4 * math::double_constants::pi * sqr(parton_width); try { auto result = math::tools::toms748_solve( [&sigma_nn, &mc_cross_section, &c](double cross_section_param) { auto x = std::exp(cross_section_param) * c; return mc_cross_section(x) - sigma_nn; }, a, b, tol, max_iter); auto cross_section_param = .5*(result.first + result.second); return std::exp(cross_section_param) * c; } catch (const std::domain_error&) { // Root finding fails for very small nucleon widths, w^2/sigma_nn < ~0.01. throw std::domain_error{ "unable to fit cross section -- nucleon and/or parton width too small?"}; } } // Determine the cross section parameter sigma_partonic, given the // nucleon width, parton width, nucleon-nucleon cross section, and parton number. double partonic_cross_section(const VarMap& var_map) { // Read parameters from the configuration. auto parton_width = infer_parton_width(var_map); auto nucleon_width = var_map["nucleon-width"].as<double>(); auto sigma_nn = var_map["cross-section"].as<double>(); auto nparton = var_map["parton-number"].as<int>(); // Cross section parameters int nparton_; double nucleon_width_; double parton_width_; double sigma_nn_; double sigma_partonic; // Establish trento cache path auto cache_dir = get_data_home() / "trento"; auto cache_path = cache_dir / "cross_section.dat"; fs::create_directory(cache_dir); // Check if cache exists if (fs::exists(cache_path.string())){ // Open cache read only std::fstream cache_read(cache_path.string(), std::ios_base::in); // Check cache for previously tabulated cross section parameters while(!cache_read.eof()) { cache_read >> nparton_ >> nucleon_width_ >> parton_width_ >> sigma_nn_ >> sigma_partonic; if (almost_equal(nucleon_width, nucleon_width_) && almost_equal(parton_width, parton_width_) && almost_equal(sigma_nn, sigma_nn_) && (nparton == nparton_)) { return sigma_partonic; } } // Close read-only file stream cache_read.close(); } // Open cache with write access std::fstream cache_write(cache_path.string(), std::ios_base::out | std::ios_base::app); // Use a semi-analytic method to determine sigma_partonic // if there is no subnucleonic structure---otherwise use MC method. if (nucleon_width == parton_width) sigma_partonic = analytic_partonic_cross_section(var_map); else sigma_partonic = numeric_partonic_cross_section(var_map); // Save new cross section parameters to cache using std::fixed; using std::setprecision; using std::setw; using std::scientific; using std::endl; cache_write << setprecision(6) << std::left << setw(8) << fixed << nparton << setw(10) << fixed << nucleon_width << setw(10) << fixed << parton_width << setw(10) << fixed << sigma_nn << setw(14) << scientific << sigma_partonic << endl; return sigma_partonic; } // Determine the width of the normal distribution for sampling parton positions. double compute_parton_sampling_width(const VarMap& var_map) { // Read parameters from the configuration. auto nucleon_width = var_map["nucleon-width"].as<double>(); auto parton_width = var_map["parton-width"].as<double>(); // Default parton width to nucleon width. if (parton_width < 0) return 0.; // Compute Gaussian sampling width by deconvolving the parton profile from the // nucleon profile. The convolution of two Gaussians is a third Gaussian // with the variances simply added together. auto sampling_width_sq = sqr(nucleon_width) - sqr(parton_width); auto TINY = 1e-8; if (sampling_width_sq < -TINY) { throw std::out_of_range{ "the parton width cannot be larger than the nucleon width"}; } return std::sqrt(std::max(sampling_width_sq, 0.)); } } // unnamed namespace NucleonCommon::NucleonCommon(const VarMap& var_map) : fast_exp_(-.5*sqr(radius_widths), 0., 1000), max_impact_sq_(sqr(max_impact_widths*var_map["nucleon-width"].as<double>())), parton_width_sq_(sqr(infer_parton_width(var_map))), parton_radius_sq_(sqr(radius_widths)*parton_width_sq_), npartons_(std::size_t(var_map["parton-number"].as<int>())), sigma_partonic_(partonic_cross_section(var_map)), prefactor_(math::double_constants::one_div_two_pi/parton_width_sq_/npartons_), participant_fluctuation_dist_(gamma_param_unit_mean(var_map["fluctuation"].as<double>())), parton_position_dist_(0, compute_parton_sampling_width(var_map)) {} MonteCarloCrossSection::MonteCarloCrossSection(const VarMap& var_map) : npartons(std::size_t(var_map["parton-number"].as<int>())), nucleon_width(var_map["nucleon-width"].as<double>()), parton_width(infer_parton_width(var_map)), parton_sampling_width(compute_parton_sampling_width(var_map)), parton_width_sq(sqr(parton_width)), prefactor(math::double_constants::one_div_two_pi/parton_width_sq/npartons) {} double MonteCarloCrossSection::operator() (const double sigma_partonic) const { random::CyclicNormal<> cyclic_normal{ 0., parton_sampling_width, cache_size, n_loops }; struct Parton { double x, y; }; std::vector<Parton> nucleonA(npartons); std::vector<Parton> nucleonB(npartons); auto bmax = max_impact_widths * nucleon_width; auto arg_max = 0.25*sqr(bmax)/parton_width_sq; const FastExp<double> fast_exp(-arg_max, 0., 1000); double ref_cross_section = 0.; double prob_miss = 0.; int pass_tolerance = 0; for (std::size_t n = 0; n < n_max; ++n) { // Sample b from P(b)db = 2*pi*b. auto b = bmax * std::sqrt(random::canonical<double>()); for (auto&& p : nucleonA) { p.x = cyclic_normal(random::engine); p.y = cyclic_normal(random::engine); } for (auto&& p : nucleonB) { p.x = cyclic_normal(random::engine); p.y = cyclic_normal(random::engine); } auto overlap = 0.; for (auto&& pa : nucleonA) { for (auto&& pb : nucleonB) { auto distance_sq = sqr(pa.x - pb.x + b) + sqr(pa.y - pb.y); auto arg = .25*distance_sq/parton_width_sq; if (arg < arg_max) overlap += fast_exp(-arg); } } prob_miss += std::exp(-sigma_partonic * prefactor/(2.*npartons) * overlap); auto fraction_hit = 1. - (prob_miss/n); auto sample_area = math::double_constants::pi * sqr(bmax); auto cross_section = fraction_hit * sample_area; auto update_difference = std::abs((cross_section - ref_cross_section)/cross_section); if (update_difference < tolerance) { ++pass_tolerance; } else { pass_tolerance = 0; ref_cross_section = cross_section; } if (pass_tolerance > n_pass){ return cross_section; } } throw std::out_of_range{ "Partonic cross section failed to converge \ -- check nucleon-width, parton-width and npartons"}; // Code throws an error before it ever gets here. return -1; } } // namespace trento <|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/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" // Tabs is flaky on chromeos and linux views debug build. // http://crbug.com/48920 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG) #define MAYBE_Tabs FLAKY_Tabs #else #define MAYBE_Tabs Tabs #endif // TabOnRemoved is flaky on chromeos and linux views debug build. // http://crbug.com/49258 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG) #define MAYBE_TabOnRemoved FLAKY_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { ASSERT_TRUE(StartHTTPServer()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } <commit_msg>Suppress ExtensionApiTest.CaptureVisibleTabPng<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/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" // Tabs is flaky on chromeos and linux views debug build. // http://crbug.com/48920 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG) #define MAYBE_Tabs FLAKY_Tabs #else #define MAYBE_Tabs Tabs #endif // TabOnRemoved is flaky on chromeos and linux views debug build. // http://crbug.com/49258 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG) #define MAYBE_TabOnRemoved FLAKY_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { ASSERT_TRUE(StartHTTPServer()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FAILS_CaptureVisibleTabPng) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(StartHTTPServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } <|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/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" #if defined(OS_MACOSX) // Tabs appears to timeout, or maybe crash on mac. // http://crbug.com/53779 #define MAYBE_Tabs FAILS_Tabs #else // It's flaky on win and linux. // http://crbug.com/58269 #define MAYBE_Tabs FLAKY_Tabs #endif // TabOnRemoved is flaky on chromeos and linux views debug build. // http://crbug.com/49258 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG) #define MAYBE_TabOnRemoved FLAKY_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { ASSERT_TRUE(test_server()->Start()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } <commit_msg>Remove FLAKY prefix from TabOnRemoved test.<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/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" #if defined(OS_MACOSX) // Tabs appears to timeout, or maybe crash on mac. // http://crbug.com/53779 #define MAYBE_Tabs FAILS_Tabs #else // It's flaky on win and linux. // http://crbug.com/58269 #define MAYBE_Tabs FLAKY_Tabs #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { ASSERT_TRUE(test_server()->Start()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabOnRemoved) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } <|endoftext|>
<commit_before>#include "opt_eval.h" #include <gflags/gflags.h> #include <iostream> #include <type_traits> #include "ncode_common/src/file.h" #include "ncode_common/src/logging.h" #include "ncode_common/src/lp/demand_matrix.h" #include "ncode_common/src/net/net_gen.h" #include "ncode_common/src/perfect_hash.h" #include "ncode_common/src/strutil.h" DEFINE_string(topology_files, "", "Topology files"); DEFINE_string( tm_files, "", "Traffic matrix file(s). If empty will look for TMs named like the " "topology, but with the .demands extension"); DEFINE_double(link_capacity_scale, 1.0, "By how much to scale all links"); DEFINE_double(tm_scale, 1.0, "By how much to scale the traffic matrix"); DEFINE_double(delay_scale, 1.0, "By how much to scale the delays of all links"); DEFINE_uint64(topology_size_limit, 100000, "Topologies with size more than this will be skipped"); DEFINE_uint64(topology_delay_limit_ms, 10, "Topologies with diameter less than this limit will be skipped"); DEFINE_uint64(tm_per_topology, std::numeric_limits<uint64_t>::max(), "How many TMs to run for each topology"); DEFINE_uint64(seed, 1, "Seed used when choosing TMs for each topology"); using namespace std::chrono; namespace ctr { static std::vector<std::string> GetTopologyFiles() { std::vector<std::string> out; std::vector<std::string> split = nc::Split(FLAGS_topology_files, ","); for (const std::string& piece : split) { std::vector<std::string> files = nc::Glob(piece); out.insert(out.end(), files.begin(), files.end()); } return out; } static std::vector<std::string> GetMatrixFiles( const std::string& topology_file) { if (!FLAGS_tm_files.empty()) { std::vector<std::string> out; for (const std::string& tm_file : nc::Split(FLAGS_tm_files, ",")) { std::vector<std::string> tm_globbed = nc::Glob(tm_file); out.insert(out.end(), tm_globbed.begin(), tm_globbed.end()); } return out; } std::string matrix_location = nc::StringReplace(topology_file, ".graph", ".*.demands", true); return nc::Glob(matrix_location); } std::pair<std::vector<std::unique_ptr<nc::net::GraphStorage>>, std::vector<OptEvalInput>> GetOptEvalInputs() { std::vector<std::string> topology_files = GetTopologyFiles(); CHECK(!topology_files.empty()); // All graphs. std::vector<std::unique_ptr<nc::net::GraphStorage>> graphs; // Inputs. std::vector<OptEvalInput> inputs; // Randomness to pick tms for each topology. std::mt19937 rnd(FLAGS_seed); for (const std::string& topology_file : topology_files) { std::vector<std::string> node_order; nc::net::GraphBuilder builder = nc::net::LoadRepetitaOrDie( nc::File::ReadFileToStringOrDie(topology_file), &node_order); builder.RemoveMultipleLinks(); builder.ScaleCapacity(FLAGS_link_capacity_scale); builder.ScaleDelay(FLAGS_delay_scale); auto graph = nc::make_unique<nc::net::GraphStorage>(builder); nc::net::GraphStats stats = graph->Stats(); CHECK(!stats.sp_delay_percentiles.empty()); if (stats.sp_delay_percentiles.back() == nc::net::Delay::max()) { LOG(INFO) << "Skipping " << topology_file << " graph partitioned "; continue; } size_t node_count = graph->AllNodes().Count(); if (node_count > FLAGS_topology_size_limit) { LOG(INFO) << "Skipping " << topology_file << " / " << topology_file << " size limit " << FLAGS_topology_size_limit << " vs " << node_count; continue; } nc::net::Delay diameter = graph->Stats().sp_delay_percentiles.back(); if (diameter < milliseconds(FLAGS_topology_delay_limit_ms)) { LOG(INFO) << "Skipping " << topology_file << " / " << topology_file << " delay limit " << FLAGS_topology_delay_limit_ms << "ms vs diameter delay " << duration_cast<milliseconds>(diameter).count() << "ms"; continue; } std::vector<std::string> matrix_files = GetMatrixFiles(topology_file); if (matrix_files.empty()) { LOG(ERROR) << "No matrices for " << topology_file; continue; } std::vector<OptEvalInput> inputs_for_topology; std::string top_file_trimmed = nc::Split(topology_file, "/").back(); for (const std::string& tm_file : matrix_files) { std::unique_ptr<nc::lp::DemandMatrix> demand_matrix = nc::lp::DemandMatrix::LoadRepetitaOrDie( nc::File::ReadFileToStringOrDie(tm_file), node_order, graph.get()); if (!demand_matrix) { LOG(INFO) << "Skipping " << tm_file << " inconsistent TM"; continue; } demand_matrix = demand_matrix->Scale(FLAGS_tm_scale); std::string tm_file_trimmed = nc::Split(tm_file, "/").back(); inputs_for_topology.emplace_back(top_file_trimmed, tm_file_trimmed, std::move(demand_matrix)); } std::shuffle(inputs_for_topology.begin(), inputs_for_topology.end(), rnd); inputs_for_topology.resize( std::min(inputs_for_topology.size(), static_cast<size_t>(FLAGS_tm_per_topology))); for (auto& input : inputs_for_topology) { inputs.emplace_back(input.topology_file, input.tm_file, std::move(input.demand_matrix)); } graphs.emplace_back(std::move(graph)); } return {std::move(graphs), std::move(inputs)}; } } // namespace ctr <commit_msg>updated<commit_after>#include "opt_eval.h" #include <gflags/gflags.h> #include <iostream> #include <type_traits> #include "ncode_common/src/file.h" #include "ncode_common/src/logging.h" #include "ncode_common/src/lp/demand_matrix.h" #include "ncode_common/src/net/net_gen.h" #include "ncode_common/src/perfect_hash.h" #include "ncode_common/src/strutil.h" DEFINE_string(topology_files, "", "Topology files"); DEFINE_string( tm_files, "", "Traffic matrix file(s). If empty will look for TMs named like the " "topology, but with the .demands extension"); DEFINE_double(link_capacity_scale, 1.0, "By how much to scale all links"); DEFINE_double(tm_scale, 1.0, "By how much to scale the traffic matrix"); DEFINE_double(delay_scale, 1.0, "By how much to scale the delays of all links"); DEFINE_uint64(topology_size_limit, 100000, "Topologies with size more than this will be skipped"); DEFINE_uint64(topology_delay_limit_ms, 10, "Topologies with diameter less than this limit will be skipped"); DEFINE_uint64(tm_per_topology, std::numeric_limits<uint64_t>::max(), "How many TMs to run for each topology"); DEFINE_uint64(seed, 1, "Seed used when choosing TMs for each topology"); using namespace std::chrono; namespace ctr { static std::vector<std::string> GetTopologyFiles() { std::vector<std::string> out; std::vector<std::string> split = nc::Split(FLAGS_topology_files, ","); for (const std::string& piece : split) { std::vector<std::string> files = nc::Glob(piece); out.insert(out.end(), files.begin(), files.end()); } return out; } static std::vector<std::string> GetMatrixFiles( const std::string& topology_file) { if (!FLAGS_tm_files.empty()) { std::vector<std::string> out; for (const std::string& tm_file : nc::Split(FLAGS_tm_files, ",")) { std::vector<std::string> tm_globbed = nc::Glob(tm_file); out.insert(out.end(), tm_globbed.begin(), tm_globbed.end()); } return out; } std::string matrix_location = nc::StringReplace(topology_file, ".graph", ".*.demands", true); return nc::Glob(matrix_location); } std::pair<std::vector<std::unique_ptr<nc::net::GraphStorage>>, std::vector<OptEvalInput>> GetOptEvalInputs() { std::vector<std::string> topology_files = GetTopologyFiles(); CHECK(!topology_files.empty()); // All graphs. std::vector<std::unique_ptr<nc::net::GraphStorage>> graphs; // Inputs. std::vector<OptEvalInput> inputs; // Randomness to pick tms for each topology. std::mt19937 rnd(FLAGS_seed); for (const std::string& topology_file : topology_files) { std::vector<std::string> node_order; nc::net::GraphBuilder builder = nc::net::LoadRepetitaOrDie( nc::File::ReadFileToStringOrDie(topology_file), &node_order); builder.RemoveMultipleLinks(); builder.ScaleCapacity(FLAGS_link_capacity_scale); builder.ScaleDelay(FLAGS_delay_scale); auto graph = nc::make_unique<nc::net::GraphStorage>(builder); nc::net::GraphStats stats = graph->Stats(); CHECK(!stats.sp_delay_percentiles.empty()); if (stats.sp_delay_percentiles.back() == nc::net::Delay::max()) { LOG(INFO) << "Skipping " << topology_file << " graph partitioned "; continue; } size_t node_count = graph->AllNodes().Count(); if (node_count > FLAGS_topology_size_limit) { LOG(INFO) << "Skipping " << topology_file << " / " << topology_file << " size limit " << FLAGS_topology_size_limit << " vs " << node_count; continue; } nc::net::Delay diameter = graph->Stats().sp_delay_percentiles.back(); if (diameter < milliseconds(FLAGS_topology_delay_limit_ms)) { LOG(INFO) << "Skipping " << topology_file << " / " << topology_file << " delay limit " << FLAGS_topology_delay_limit_ms << "ms vs diameter delay " << duration_cast<milliseconds>(diameter).count() << "ms"; continue; } std::vector<std::string> matrix_files = GetMatrixFiles(topology_file); if (matrix_files.empty()) { LOG(ERROR) << "No matrices for " << topology_file; continue; } std::vector<OptEvalInput> inputs_for_topology; std::string top_file_trimmed = nc::Split(topology_file, "/").back(); for (const std::string& tm_file : matrix_files) { std::unique_ptr<nc::lp::DemandMatrix> demand_matrix = nc::lp::DemandMatrix::LoadRepetitaOrDie( nc::File::ReadFileToStringOrDie(tm_file), node_order, graph.get()); if (!demand_matrix) { LOG(INFO) << "Skipping " << tm_file << " inconsistent TM"; continue; } if (demand_matrix->IsTriviallySatisfiable()) { LOG(INFO) << "Skipping " << tm_file << " trivially satisfiable"; continue; } demand_matrix = demand_matrix->Scale(FLAGS_tm_scale); std::string tm_file_trimmed = nc::Split(tm_file, "/").back(); inputs_for_topology.emplace_back(top_file_trimmed, tm_file_trimmed, std::move(demand_matrix)); } std::shuffle(inputs_for_topology.begin(), inputs_for_topology.end(), rnd); inputs_for_topology.resize( std::min(inputs_for_topology.size(), static_cast<size_t>(FLAGS_tm_per_topology))); for (auto& input : inputs_for_topology) { inputs.emplace_back(input.topology_file, input.tm_file, std::move(input.demand_matrix)); } graphs.emplace_back(std::move(graph)); } return {std::move(graphs), std::move(inputs)}; } } // namespace ctr <|endoftext|>
<commit_before>//===- UnifyFunctionExitNodes.cpp - Make all functions have a single exit -===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass is used to ensure that functions have at most one return // instruction in them. Additionally, it keeps track of which node is the new // exit node of the CFG. If there are no exit nodes in the CFG, the getExitNode // method will return a null pointer. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h" #include "llvm/Transforms/Scalar.h" #include "llvm/BasicBlock.h" #include "llvm/Function.h" #include "llvm/Instructions.h" #include "llvm/Type.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" using namespace llvm; char UnifyFunctionExitNodes::ID = 0; static RegisterPass<UnifyFunctionExitNodes> X("mergereturn", "Unify function exit nodes"); int UnifyFunctionExitNodes::stub; Pass *llvm::createUnifyFunctionExitNodesPass() { return new UnifyFunctionExitNodes(); } void UnifyFunctionExitNodes::getAnalysisUsage(AnalysisUsage &AU) const{ // We preserve the non-critical-edgeness property AU.addPreservedID(BreakCriticalEdgesID); // This is a cluster of orthogonal Transforms AU.addPreservedID(PromoteMemoryToRegisterID); AU.addPreservedID(LowerSwitchID); } // UnifyAllExitNodes - Unify all exit nodes of the CFG by creating a new // BasicBlock, and converting all returns to unconditional branches to this // new basic block. The singular exit node is returned. // // If there are no return stmts in the Function, a null pointer is returned. // bool UnifyFunctionExitNodes::runOnFunction(Function &F) { // Loop over all of the blocks in a function, tracking all of the blocks that // return. // std::vector<BasicBlock*> ReturningBlocks; std::vector<BasicBlock*> UnwindingBlocks; std::vector<BasicBlock*> UnreachableBlocks; for(Function::iterator I = F.begin(), E = F.end(); I != E; ++I) if (isa<ReturnInst>(I->getTerminator())) ReturningBlocks.push_back(I); else if (isa<UnwindInst>(I->getTerminator())) UnwindingBlocks.push_back(I); else if (isa<UnreachableInst>(I->getTerminator())) UnreachableBlocks.push_back(I); // Handle unwinding blocks first. if (UnwindingBlocks.empty()) { UnwindBlock = 0; } else if (UnwindingBlocks.size() == 1) { UnwindBlock = UnwindingBlocks.front(); } else { UnwindBlock = BasicBlock::Create("UnifiedUnwindBlock", &F); new UnwindInst(UnwindBlock); for (std::vector<BasicBlock*>::iterator I = UnwindingBlocks.begin(), E = UnwindingBlocks.end(); I != E; ++I) { BasicBlock *BB = *I; BB->getInstList().pop_back(); // Remove the unwind insn BranchInst::Create(UnwindBlock, BB); } } // Then unreachable blocks. if (UnreachableBlocks.empty()) { UnreachableBlock = 0; } else if (UnreachableBlocks.size() == 1) { UnreachableBlock = UnreachableBlocks.front(); } else { UnreachableBlock = BasicBlock::Create("UnifiedUnreachableBlock", &F); new UnreachableInst(UnreachableBlock); for (std::vector<BasicBlock*>::iterator I = UnreachableBlocks.begin(), E = UnreachableBlocks.end(); I != E; ++I) { BasicBlock *BB = *I; BB->getInstList().pop_back(); // Remove the unreachable inst. BranchInst::Create(UnreachableBlock, BB); } } // Now handle return blocks. if (ReturningBlocks.empty()) { ReturnBlock = 0; return false; // No blocks return } else if (ReturningBlocks.size() == 1) { ReturnBlock = ReturningBlocks.front(); // Already has a single return block return false; } // Otherwise, we need to insert a new basic block into the function, add a PHI // nodes (if the function returns values), and convert all of the return // instructions into unconditional branches. // BasicBlock *NewRetBlock = BasicBlock::Create("UnifiedReturnBlock", &F); SmallVector<Value *, 4> Phis; unsigned NumRetVals = ReturningBlocks[0]->getTerminator()->getNumOperands(); if (NumRetVals == 0) ReturnInst::Create(NULL, NewRetBlock); else if (const StructType *STy = dyn_cast<StructType>(F.getReturnType())) { Instruction *InsertPt = NewRetBlock->getFirstNonPHI(); for (unsigned i = 0; i < NumRetVals; ++i) { PHINode *PN = PHINode::Create(STy->getElementType(i), "UnifiedRetVal." + utostr(i), InsertPt); Phis.push_back(PN); } ReturnInst::Create(&Phis[0], NumRetVals); } else { // If the function doesn't return void... add a PHI node to the block... PHINode *PN = PHINode::Create(F.getReturnType(), "UnifiedRetVal"); NewRetBlock->getInstList().push_back(PN); Phis.push_back(PN); ReturnInst::Create(PN, NewRetBlock); } // Loop over all of the blocks, replacing the return instruction with an // unconditional branch. // for (std::vector<BasicBlock*>::iterator I = ReturningBlocks.begin(), E = ReturningBlocks.end(); I != E; ++I) { BasicBlock *BB = *I; // Add an incoming element to the PHI node for every return instruction that // is merging into this new block... if (!Phis.empty()) { for (unsigned i = 0; i < NumRetVals; ++i) cast<PHINode>(Phis[i])->addIncoming(BB->getTerminator()->getOperand(i), BB); } BB->getInstList().pop_back(); // Remove the return insn BranchInst::Create(NewRetBlock, BB); } ReturnBlock = NewRetBlock; return true; } <commit_msg>Fix insert point handling for multiple return values.<commit_after>//===- UnifyFunctionExitNodes.cpp - Make all functions have a single exit -===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass is used to ensure that functions have at most one return // instruction in them. Additionally, it keeps track of which node is the new // exit node of the CFG. If there are no exit nodes in the CFG, the getExitNode // method will return a null pointer. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h" #include "llvm/Transforms/Scalar.h" #include "llvm/BasicBlock.h" #include "llvm/Function.h" #include "llvm/Instructions.h" #include "llvm/Type.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" using namespace llvm; char UnifyFunctionExitNodes::ID = 0; static RegisterPass<UnifyFunctionExitNodes> X("mergereturn", "Unify function exit nodes"); int UnifyFunctionExitNodes::stub; Pass *llvm::createUnifyFunctionExitNodesPass() { return new UnifyFunctionExitNodes(); } void UnifyFunctionExitNodes::getAnalysisUsage(AnalysisUsage &AU) const{ // We preserve the non-critical-edgeness property AU.addPreservedID(BreakCriticalEdgesID); // This is a cluster of orthogonal Transforms AU.addPreservedID(PromoteMemoryToRegisterID); AU.addPreservedID(LowerSwitchID); } // UnifyAllExitNodes - Unify all exit nodes of the CFG by creating a new // BasicBlock, and converting all returns to unconditional branches to this // new basic block. The singular exit node is returned. // // If there are no return stmts in the Function, a null pointer is returned. // bool UnifyFunctionExitNodes::runOnFunction(Function &F) { // Loop over all of the blocks in a function, tracking all of the blocks that // return. // std::vector<BasicBlock*> ReturningBlocks; std::vector<BasicBlock*> UnwindingBlocks; std::vector<BasicBlock*> UnreachableBlocks; for(Function::iterator I = F.begin(), E = F.end(); I != E; ++I) if (isa<ReturnInst>(I->getTerminator())) ReturningBlocks.push_back(I); else if (isa<UnwindInst>(I->getTerminator())) UnwindingBlocks.push_back(I); else if (isa<UnreachableInst>(I->getTerminator())) UnreachableBlocks.push_back(I); // Handle unwinding blocks first. if (UnwindingBlocks.empty()) { UnwindBlock = 0; } else if (UnwindingBlocks.size() == 1) { UnwindBlock = UnwindingBlocks.front(); } else { UnwindBlock = BasicBlock::Create("UnifiedUnwindBlock", &F); new UnwindInst(UnwindBlock); for (std::vector<BasicBlock*>::iterator I = UnwindingBlocks.begin(), E = UnwindingBlocks.end(); I != E; ++I) { BasicBlock *BB = *I; BB->getInstList().pop_back(); // Remove the unwind insn BranchInst::Create(UnwindBlock, BB); } } // Then unreachable blocks. if (UnreachableBlocks.empty()) { UnreachableBlock = 0; } else if (UnreachableBlocks.size() == 1) { UnreachableBlock = UnreachableBlocks.front(); } else { UnreachableBlock = BasicBlock::Create("UnifiedUnreachableBlock", &F); new UnreachableInst(UnreachableBlock); for (std::vector<BasicBlock*>::iterator I = UnreachableBlocks.begin(), E = UnreachableBlocks.end(); I != E; ++I) { BasicBlock *BB = *I; BB->getInstList().pop_back(); // Remove the unreachable inst. BranchInst::Create(UnreachableBlock, BB); } } // Now handle return blocks. if (ReturningBlocks.empty()) { ReturnBlock = 0; return false; // No blocks return } else if (ReturningBlocks.size() == 1) { ReturnBlock = ReturningBlocks.front(); // Already has a single return block return false; } // Otherwise, we need to insert a new basic block into the function, add a PHI // nodes (if the function returns values), and convert all of the return // instructions into unconditional branches. // BasicBlock *NewRetBlock = BasicBlock::Create("UnifiedReturnBlock", &F); SmallVector<Value *, 4> Phis; unsigned NumRetVals = ReturningBlocks[0]->getTerminator()->getNumOperands(); if (NumRetVals == 0) ReturnInst::Create(NULL, NewRetBlock); else if (const StructType *STy = dyn_cast<StructType>(F.getReturnType())) { Instruction *InsertPt = NULL; if (NumRetVals == 0) InsertPt = NewRetBlock->getFirstNonPHI(); PHINode *PN = NULL; for (unsigned i = 0; i < NumRetVals; ++i) { if (InsertPt) PN = PHINode::Create(STy->getElementType(i), "UnifiedRetVal." + utostr(i), InsertPt); else PN = PHINode::Create(STy->getElementType(i), "UnifiedRetVal." + utostr(i), NewRetBlock); Phis.push_back(PN); InsertPt = PN; } ReturnInst::Create(&Phis[0], NumRetVals, NewRetBlock); } else { // If the function doesn't return void... add a PHI node to the block... PHINode *PN = PHINode::Create(F.getReturnType(), "UnifiedRetVal"); NewRetBlock->getInstList().push_back(PN); Phis.push_back(PN); ReturnInst::Create(PN, NewRetBlock); } // Loop over all of the blocks, replacing the return instruction with an // unconditional branch. // for (std::vector<BasicBlock*>::iterator I = ReturningBlocks.begin(), E = ReturningBlocks.end(); I != E; ++I) { BasicBlock *BB = *I; // Add an incoming element to the PHI node for every return instruction that // is merging into this new block... if (!Phis.empty()) { for (unsigned i = 0; i < NumRetVals; ++i) cast<PHINode>(Phis[i])->addIncoming(BB->getTerminator()->getOperand(i), BB); } BB->getInstList().pop_back(); // Remove the return insn BranchInst::Create(NewRetBlock, BB); } ReturnBlock = NewRetBlock; return true; } <|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/ntp/new_tab_page_handler.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/memory/scoped_ptr.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/default_apps_trial.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/ui/webui/ntp/new_tab_ui.h" #include "chrome/browser/web_resource/notification_promo.h" #include "chrome/common/pref_names.h" #include "content/public/browser/notification_service.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" static const int kIntroDisplayMax = 10; // The URL of a knowledge-base article about the new NTP. static const char kNTP4IntroURL[] = "http://www.google.com/support/chrome/bin/answer.py?answer=95451"; WebUIMessageHandler* NewTabPageHandler::Attach(WebUI* web_ui) { // Record an open of the NTP with its default page type. PrefService* prefs = Profile::FromWebUI(web_ui)->GetPrefs(); int shown_page_type = prefs->GetInteger(prefs::kNTPShownPage) >> kPageIdOffset; UMA_HISTOGRAM_ENUMERATION("NewTabPage.DefaultPageType", shown_page_type, kHistogramEnumerationMax); static bool default_apps_trial_exists = base::FieldTrialList::TrialExists(kDefaultAppsTrial_Name); if (default_apps_trial_exists) { UMA_HISTOGRAM_ENUMERATION( base::FieldTrial::MakeName("NewTabPage.DefaultPageType", kDefaultAppsTrial_Name), shown_page_type, kHistogramEnumerationMax); } return WebUIMessageHandler::Attach(web_ui); } void NewTabPageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback("closeNotificationPromo", base::Bind(&NewTabPageHandler::HandleCloseNotificationPromo, base::Unretained(this))); web_ui()->RegisterMessageCallback("notificationPromoViewed", base::Bind(&NewTabPageHandler::HandleNotificationPromoViewed, base::Unretained(this))); web_ui()->RegisterMessageCallback("pageSelected", base::Bind(&NewTabPageHandler::HandlePageSelected, base::Unretained(this))); web_ui()->RegisterMessageCallback("introMessageDismissed", base::Bind(&NewTabPageHandler::HandleIntroMessageDismissed, base::Unretained(this))); web_ui()->RegisterMessageCallback("introMessageSeen", base::Bind(&NewTabPageHandler::HandleIntroMessageSeen, base::Unretained(this))); } void NewTabPageHandler::HandleCloseNotificationPromo(const ListValue* args) { scoped_refptr<NotificationPromo> notification_promo = NotificationPromo::Create(Profile::FromWebUI(web_ui()), NULL); notification_promo->HandleClosed(); Notify(chrome::NOTIFICATION_PROMO_RESOURCE_STATE_CHANGED); } void NewTabPageHandler::HandleNotificationPromoViewed(const ListValue* args) { scoped_refptr<NotificationPromo> notification_promo = NotificationPromo::Create(Profile::FromWebUI(web_ui_), NULL); if (notification_promo->HandleViewed()) Notify(chrome::NOTIFICATION_PROMO_RESOURCE_STATE_CHANGED); } void NewTabPageHandler::HandlePageSelected(const ListValue* args) { double page_id_double; CHECK(args->GetDouble(0, &page_id_double)); int page_id = static_cast<int>(page_id_double); double index_double; CHECK(args->GetDouble(1, &index_double)); int index = static_cast<int>(index_double); PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs(); prefs->SetInteger(prefs::kNTPShownPage, page_id | index); int shown_page_type = page_id >> kPageIdOffset; UMA_HISTOGRAM_ENUMERATION("NewTabPage.SelectedPageType", shown_page_type, kHistogramEnumerationMax); static bool default_apps_trial_exists = base::FieldTrialList::TrialExists(kDefaultAppsTrial_Name); if (default_apps_trial_exists) { UMA_HISTOGRAM_ENUMERATION( base::FieldTrial::MakeName("NewTabPage.SelectedPageType", kDefaultAppsTrial_Name), shown_page_type, kHistogramEnumerationMax); } } void NewTabPageHandler::HandleIntroMessageDismissed(const ListValue* args) { PrefService* prefs = g_browser_process->local_state(); prefs->SetInteger(prefs::kNTP4IntroDisplayCount, kIntroDisplayMax + 1); Notify(chrome::NTP4_INTRO_PREF_CHANGED); } void NewTabPageHandler::HandleIntroMessageSeen(const ListValue* args) { PrefService* prefs = g_browser_process->local_state(); int intro_displays = prefs->GetInteger(prefs::kNTP4IntroDisplayCount); prefs->SetInteger(prefs::kNTP4IntroDisplayCount, intro_displays + 1); Notify(chrome::NTP4_INTRO_PREF_CHANGED); } // static void NewTabPageHandler::RegisterUserPrefs(PrefService* prefs) { // TODO(estade): should be syncable. prefs->RegisterIntegerPref(prefs::kNTPShownPage, APPS_PAGE_ID, PrefService::UNSYNCABLE_PREF); } // static void NewTabPageHandler::RegisterPrefs(PrefService* prefs) { prefs->RegisterIntegerPref(prefs::kNTP4IntroDisplayCount, 0, PrefService::UNSYNCABLE_PREF); } // static void NewTabPageHandler::GetLocalizedValues(Profile* profile, DictionaryValue* values) { values->SetInteger("most_visited_page_id", MOST_VISITED_PAGE_ID); values->SetInteger("apps_page_id", APPS_PAGE_ID); values->SetInteger("bookmarks_page_id", BOOKMARKS_PAGE_ID); PrefService* prefs = profile->GetPrefs(); int shown_page = prefs->GetInteger(prefs::kNTPShownPage); values->SetInteger("shown_page_type", shown_page & ~INDEX_MASK); values->SetInteger("shown_page_index", shown_page & INDEX_MASK); PrefService* local_state = g_browser_process->local_state(); int intro_displays = local_state->GetInteger(prefs::kNTP4IntroDisplayCount); // This preference used to exist in profile, so check the profile if it has // not been set in local state yet. if (!intro_displays) { prefs->RegisterIntegerPref(prefs::kNTP4IntroDisplayCount, 0, PrefService::UNSYNCABLE_PREF); intro_displays = prefs->GetInteger(prefs::kNTP4IntroDisplayCount); if (intro_displays) local_state->SetInteger(prefs::kNTP4IntroDisplayCount, intro_displays); } if (intro_displays <= kIntroDisplayMax) { values->SetString("ntp4_intro_message", l10n_util::GetStringUTF16(IDS_NTP4_INTRO_MESSAGE)); values->SetString("ntp4_intro_url", kNTP4IntroURL); values->SetString("learn_more", l10n_util::GetStringUTF16(IDS_LEARN_MORE)); } } // static void NewTabPageHandler::DismissIntroMessage(PrefService* prefs) { prefs->SetInteger(prefs::kNTP4IntroDisplayCount, kIntroDisplayMax + 1); // No need to send notification to update resource cache, because this method // is only called during startup before the ntp resource cache is constructed. } void NewTabPageHandler::Notify(chrome::NotificationType notification_type) { content::NotificationService* service = content::NotificationService::current(); service->Notify(notification_type, content::Source<NewTabPageHandler>(this), content::NotificationService::NoDetails()); } <commit_msg>[ntp4] Remove last remnants of bookmarks page implementation.<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/ntp/new_tab_page_handler.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/memory/scoped_ptr.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/default_apps_trial.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/ui/webui/ntp/new_tab_ui.h" #include "chrome/browser/web_resource/notification_promo.h" #include "chrome/common/pref_names.h" #include "content/public/browser/notification_service.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" static const int kIntroDisplayMax = 10; // The URL of a knowledge-base article about the new NTP. static const char kNTP4IntroURL[] = "http://www.google.com/support/chrome/bin/answer.py?answer=95451"; WebUIMessageHandler* NewTabPageHandler::Attach(WebUI* web_ui) { // Record an open of the NTP with its default page type. PrefService* prefs = Profile::FromWebUI(web_ui)->GetPrefs(); int shown_page_type = prefs->GetInteger(prefs::kNTPShownPage) >> kPageIdOffset; UMA_HISTOGRAM_ENUMERATION("NewTabPage.DefaultPageType", shown_page_type, kHistogramEnumerationMax); static bool default_apps_trial_exists = base::FieldTrialList::TrialExists(kDefaultAppsTrial_Name); if (default_apps_trial_exists) { UMA_HISTOGRAM_ENUMERATION( base::FieldTrial::MakeName("NewTabPage.DefaultPageType", kDefaultAppsTrial_Name), shown_page_type, kHistogramEnumerationMax); } return WebUIMessageHandler::Attach(web_ui); } void NewTabPageHandler::RegisterMessages() { web_ui()->RegisterMessageCallback("closeNotificationPromo", base::Bind(&NewTabPageHandler::HandleCloseNotificationPromo, base::Unretained(this))); web_ui()->RegisterMessageCallback("notificationPromoViewed", base::Bind(&NewTabPageHandler::HandleNotificationPromoViewed, base::Unretained(this))); web_ui()->RegisterMessageCallback("pageSelected", base::Bind(&NewTabPageHandler::HandlePageSelected, base::Unretained(this))); web_ui()->RegisterMessageCallback("introMessageDismissed", base::Bind(&NewTabPageHandler::HandleIntroMessageDismissed, base::Unretained(this))); web_ui()->RegisterMessageCallback("introMessageSeen", base::Bind(&NewTabPageHandler::HandleIntroMessageSeen, base::Unretained(this))); } void NewTabPageHandler::HandleCloseNotificationPromo(const ListValue* args) { scoped_refptr<NotificationPromo> notification_promo = NotificationPromo::Create(Profile::FromWebUI(web_ui()), NULL); notification_promo->HandleClosed(); Notify(chrome::NOTIFICATION_PROMO_RESOURCE_STATE_CHANGED); } void NewTabPageHandler::HandleNotificationPromoViewed(const ListValue* args) { scoped_refptr<NotificationPromo> notification_promo = NotificationPromo::Create(Profile::FromWebUI(web_ui_), NULL); if (notification_promo->HandleViewed()) Notify(chrome::NOTIFICATION_PROMO_RESOURCE_STATE_CHANGED); } void NewTabPageHandler::HandlePageSelected(const ListValue* args) { double page_id_double; CHECK(args->GetDouble(0, &page_id_double)); int page_id = static_cast<int>(page_id_double); double index_double; CHECK(args->GetDouble(1, &index_double)); int index = static_cast<int>(index_double); PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs(); prefs->SetInteger(prefs::kNTPShownPage, page_id | index); int shown_page_type = page_id >> kPageIdOffset; UMA_HISTOGRAM_ENUMERATION("NewTabPage.SelectedPageType", shown_page_type, kHistogramEnumerationMax); static bool default_apps_trial_exists = base::FieldTrialList::TrialExists(kDefaultAppsTrial_Name); if (default_apps_trial_exists) { UMA_HISTOGRAM_ENUMERATION( base::FieldTrial::MakeName("NewTabPage.SelectedPageType", kDefaultAppsTrial_Name), shown_page_type, kHistogramEnumerationMax); } } void NewTabPageHandler::HandleIntroMessageDismissed(const ListValue* args) { PrefService* prefs = g_browser_process->local_state(); prefs->SetInteger(prefs::kNTP4IntroDisplayCount, kIntroDisplayMax + 1); Notify(chrome::NTP4_INTRO_PREF_CHANGED); } void NewTabPageHandler::HandleIntroMessageSeen(const ListValue* args) { PrefService* prefs = g_browser_process->local_state(); int intro_displays = prefs->GetInteger(prefs::kNTP4IntroDisplayCount); prefs->SetInteger(prefs::kNTP4IntroDisplayCount, intro_displays + 1); Notify(chrome::NTP4_INTRO_PREF_CHANGED); } // static void NewTabPageHandler::RegisterUserPrefs(PrefService* prefs) { // TODO(estade): should be syncable. prefs->RegisterIntegerPref(prefs::kNTPShownPage, APPS_PAGE_ID, PrefService::UNSYNCABLE_PREF); } // static void NewTabPageHandler::RegisterPrefs(PrefService* prefs) { prefs->RegisterIntegerPref(prefs::kNTP4IntroDisplayCount, 0, PrefService::UNSYNCABLE_PREF); } // static void NewTabPageHandler::GetLocalizedValues(Profile* profile, DictionaryValue* values) { values->SetInteger("most_visited_page_id", MOST_VISITED_PAGE_ID); values->SetInteger("apps_page_id", APPS_PAGE_ID); PrefService* prefs = profile->GetPrefs(); int shown_page = prefs->GetInteger(prefs::kNTPShownPage); values->SetInteger("shown_page_type", shown_page & ~INDEX_MASK); values->SetInteger("shown_page_index", shown_page & INDEX_MASK); PrefService* local_state = g_browser_process->local_state(); int intro_displays = local_state->GetInteger(prefs::kNTP4IntroDisplayCount); // This preference used to exist in profile, so check the profile if it has // not been set in local state yet. if (!intro_displays) { prefs->RegisterIntegerPref(prefs::kNTP4IntroDisplayCount, 0, PrefService::UNSYNCABLE_PREF); intro_displays = prefs->GetInteger(prefs::kNTP4IntroDisplayCount); if (intro_displays) local_state->SetInteger(prefs::kNTP4IntroDisplayCount, intro_displays); } if (intro_displays <= kIntroDisplayMax) { values->SetString("ntp4_intro_message", l10n_util::GetStringUTF16(IDS_NTP4_INTRO_MESSAGE)); values->SetString("ntp4_intro_url", kNTP4IntroURL); values->SetString("learn_more", l10n_util::GetStringUTF16(IDS_LEARN_MORE)); } } // static void NewTabPageHandler::DismissIntroMessage(PrefService* prefs) { prefs->SetInteger(prefs::kNTP4IntroDisplayCount, kIntroDisplayMax + 1); // No need to send notification to update resource cache, because this method // is only called during startup before the ntp resource cache is constructed. } void NewTabPageHandler::Notify(chrome::NotificationType notification_type) { content::NotificationService* service = content::NotificationService::current(); service->Notify(notification_type, content::Source<NewTabPageHandler>(this), content::NotificationService::NoDetails()); } <|endoftext|>
<commit_before>#include <string> #include <regex> #include <optional> #include <map> #include <tuple> #include "acmacs-base/argv.hh" #include "acmacs-base/enumerate.hh" #include "acmacs-chart-2/chart.hh" #include "acmacs-chart-2/factory-import.hh" #include "hidb-5/hidb.hh" // ---------------------------------------------------------------------- using namespace acmacs::argv; struct Options : public argv { Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); } option<str> name{*this, "name", desc{"name (regex) to filter, matched against full_name"}}; option<bool> serum_circles{*this, "serum-circles", desc{"output data for drawing serum circles"}}; argument<str> chart{*this, mandatory}; }; enum class passage_t { egg, reassortant, cell }; struct SerumData { const size_t sr_no; const std::string name; const std::string full_name; const acmacs::chart::Reassortant reassortant; const acmacs::chart::Passage passage; const passage_t passage_type; std::vector<hidb::TableStat> table_data; bool most_used = false; // this name+passage-type+if-reassortant has max number of tables bool most_recent = false; // this name+passage-type+if-reassortant is in more than one table and has most recent oldest table }; static std::vector<SerumData> collect(const acmacs::chart::Chart& chart, std::optional<std::regex> name_match, const hidb::HiDb& hidb); static passage_t passage_type(const acmacs::chart::Reassortant& reassortant, const acmacs::chart::Passage& passage); static void find_most_used(std::vector<SerumData>& serum_data, std::string assay, std::string lab, std::string rbc); static bool match_assay(const hidb::TableStat& tables, std::string assay, std::string lab, std::string rbc); static void report(const std::vector<SerumData>& serum_data); static void report_for_serum_circles_json(const std::vector<SerumData>& serum_data, std::string assay, std::string lab, std::string rbc); static void report_for_serum_circles_html(const std::vector<SerumData>& serum_data, std::string assay, std::string lab, std::string rbc); // ---------------------------------------------------------------------- int main(int argc, const char* argv[]) { int exit_code = 0; try { Options opt(argc, argv); std::optional<std::regex> name_match; if (opt.name.has_value()) name_match = std::regex(opt.name->begin(), opt.name->end()); auto chart = acmacs::chart::import_from_file(opt.chart, acmacs::chart::Verify::None, report_time::no); std::string assay = chart->info()->assay(acmacs::chart::Info::Compute::Yes); if (assay == "FOCUS REDUCTION") assay = "FR"; else if (assay == "PLAQUE REDUCTION NEUTRALISATION") assay = "PRN"; const auto lab = chart->info()->lab(acmacs::chart::Info::Compute::Yes); const auto rbc = chart->info()->rbc_species(acmacs::chart::Info::Compute::Yes); auto serum_data = collect(*chart, name_match, hidb::get(chart->info()->virus_type(acmacs::chart::Info::Compute::Yes), report_time::no)); find_most_used(serum_data, assay, lab, rbc); if (opt.serum_circles) { report_for_serum_circles_json(serum_data, assay, lab, rbc); report_for_serum_circles_html(serum_data, assay, lab, rbc); } else report(serum_data); } catch (std::exception& err) { std::cerr << err.what() << std::endl; exit_code = 1; } return exit_code; } // ---------------------------------------------------------------------- std::vector<SerumData> collect(const acmacs::chart::Chart& chart, std::optional<std::regex> name_match, const hidb::HiDb& hidb) { auto sera = chart.sera(); const auto hidb_sera = hidb.sera()->find(*sera); auto hidb_tables = hidb.tables(); std::vector<SerumData> serum_data; for (auto [sr_no, serum] : acmacs::enumerate(*sera)) { if (!name_match || std::regex_search(serum->full_name(), *name_match)) { if (auto hidb_serum = hidb_sera[sr_no]; hidb_serum) serum_data.push_back({sr_no, serum->name(), serum->full_name(), serum->reassortant(), serum->passage(), passage_type(serum->reassortant(), serum->passage()), hidb_tables->stat(hidb_serum->tables())}); else std::cerr << "WARNING: not in hidb: " << serum->full_name_with_fields() << '\n'; } } return serum_data; } // collect // ---------------------------------------------------------------------- passage_t passage_type(const acmacs::chart::Reassortant& reassortant, const acmacs::chart::Passage& passage) { if (!reassortant.empty()) return passage_t::reassortant; if (passage.is_egg()) return passage_t::egg; return passage_t::cell; } // passage_type // ---------------------------------------------------------------------- void find_most_used(std::vector<SerumData>& serum_data, std::string assay, std::string lab, std::string rbc) { struct name_passage_t { std::string name; passage_t passage_type; bool operator<(const name_passage_t& rhs) const { return name == rhs.name ? passage_type < rhs.passage_type : name < rhs.name; } }; struct most_t { size_t most_used_index; size_t most_used_number; size_t most_recent_index; std::string most_recent_oldest_date; }; std::map<name_passage_t, most_t> index; for (const auto [no, entry] : acmacs::enumerate(serum_data)) { for (const auto& tables : entry.table_data) { if (match_assay(tables, assay, lab, rbc)) { if (const auto found = index.find({entry.name, entry.passage_type}); found != index.end()) { if (tables.number > found->second.most_used_number) { found->second.most_used_index = no; found->second.most_used_number = tables.number; } if (std::string{tables.oldest->date()} > found->second.most_recent_oldest_date) { found->second.most_recent_index = no; found->second.most_recent_oldest_date = std::string{tables.oldest->date()}; } } else index.emplace(name_passage_t{entry.name, entry.passage_type}, most_t{no, tables.number, no, std::string{tables.oldest->date()}}); } } } for (auto [name_passage, most_entry] : index) { // std::cerr << "DEBUG: " << name_passage.name << ' ' << static_cast<int>(name_passage.passage_type) << " most-used:" << most_entry.most_used_index << " most_recent:" << most_entry.most_recent_index << '\n'; serum_data[most_entry.most_used_index].most_used = true; serum_data[most_entry.most_recent_index].most_recent = true; } } // SerumData::find_most_used // ---------------------------------------------------------------------- bool match_assay(const hidb::TableStat& tables, std::string assay, std::string lab, std::string rbc) { return tables.assay == assay && tables.lab == lab && tables.rbc == rbc; } // match_assay // ---------------------------------------------------------------------- void report(const std::vector<SerumData>& serum_data) { for (const auto& entry : serum_data) { std::cout << std::setw(3) << std::right << entry.sr_no << ' ' << entry.full_name << " P: " << entry.passage << '\n'; for (const auto& tables : entry.table_data) { std::cout << " " << tables.title() << " tables:" << std::setw(2) << std::right << tables.number << " newest:" << tables.most_recent->date() << " oldest:" << tables.oldest->date() << '\n'; // << " newest: " << std::setw(30) << std::left << tables.most_recent->name() // << " oldest: " << tables.oldest->name() << '\n'; } } } // report // ---------------------------------------------------------------------- void report_for_serum_circles_json(const std::vector<SerumData>& serum_data, std::string assay, std::string lab, std::string rbc) { auto report = [&](const auto& entry, std::string color) { std::cout << R"({"N": "serum_circle", "serum": {"full_name": ")" << entry.full_name << R"("}, "report": true,)" << '\n' << " \"?passage\": \"" << entry.passage << "\",\n"; for (const auto& tables : entry.table_data) { // std::cerr << "DEBUG: " << tables.assay << " --- " << assay << '\n'; if (match_assay(tables, assay, lab, rbc)) { std::cout << " \"?\": \""; if (entry.most_used) std::cout << "**most-used** "; if (entry.most_recent) std::cout << "**most-recent** "; std::cout << "tables:" << tables.number << " newest:" << tables.most_recent->date() << " oldest:" << tables.oldest->date() << "\",\n"; } } const double outline_width = (entry.most_used || entry.most_recent) ? 6.0 : 2.0; const char* outline_dash = entry.most_recent ? R"(, "outline_dash": "dash1")" : ""; std::cout << R"( "empirical": {"show": true, "fill": "transparent", "outline": ")" << color << R"(", "outline_width": )" << outline_width << outline_dash << R"(},)" << '\n' << R"( "theoretical": {"show": false, "fill": "transparent", "outline": ")" << color << R"(", "outline_width": )" << outline_width << outline_dash << R"(},)" << '\n' << R"( "fallback": { "fill": "transparent", "outline": ")" << color << R"(", "outline_width": )" << outline_width << R"(, "outline_dash": "dash2", "radius": 3},)" << '\n' << R"( "mark_serum": {"fill": ")" << color << R"(", "outline": "black", "order": "raise", "?label": {"name_type": "full", "offset": [0, 1], "color": "black", "size": 12}},)" << '\n' << R"( "?mark_antigen": {"fill": ")" << color << R"(", "outline": "black", "order": "raise", "?label": {"name_type": "full", "offset": [0, 1], "color": "black", "size": 12}})" << '\n' << "},\n\n"; }; std::cout << "\"? ------ EGG ----------------------------------------------------------------------\",\n\n"; for (const auto& entry : serum_data) { if (entry.passage_type == passage_t::egg) report(entry, "${egg_color}"); } std::cout << "\"? ------ Reassortant ----------------------------------------------------------------------\",\n\n"; for (const auto& entry : serum_data) { if (entry.passage_type == passage_t::reassortant) report(entry, "${reassortant_color}"); } std::cout << "\"? ------ CELL ----------------------------------------------------------------------\",\n\n"; for (const auto& entry : serum_data) { if (entry.passage_type == passage_t::cell) report(entry, "${cell_color}"); } } // report_for_serum_circles_json // ---------------------------------------------------------------------- void report_for_serum_circles_html(const std::vector<SerumData>& serum_data, std::string assay, std::string lab, std::string rbc) { auto report = [&](const auto& entry) { std::cout << "<b>" << entry.sr_no << ' ' << entry.full_name << "</b>" << (entry.most_used ? " **most-used**" : "") << (entry.most_recent ? " **most-recent**" : "") << '\n' << "<table>\n<tr><td>titer</td><td>radius</td><td>antigen</td></tr>\n"; // for (const auto& tables : entry.table_data) { // // std::cerr << "DEBUG: " << tables.assay << " --- " << assay << '\n'; // if (match_assay(tables, assay, lab, rbc)) { // std::cout << " \"?\": \""; // if (entry.most_used) // std::cout << "**most-used** "; // if (entry.most_recent) // std::cout << "**most-recent** "; // std::cout << "tables:" << tables.number << " newest:" << tables.most_recent->date() << " oldest:" << tables.oldest->date() << "\",\n"; // } // } // const double outline_width = (entry.most_used || entry.most_recent) ? 6.0 : 2.0; // const char* outline_dash = entry.most_recent ? R"(, "outline_dash": "dash1")" : ""; // std::cout << R"( "empirical": {"show": true, "fill": "transparent", "outline": ")" << color << R"(", "outline_width": )" << outline_width << outline_dash << R"(},)" << '\n' // << R"( "theoretical": {"show": false, "fill": "transparent", "outline": ")" << color << R"(", "outline_width": )" << outline_width << outline_dash << R"(},)" << '\n' // << R"( "fallback": { "fill": "transparent", "outline": ")" << color << R"(", "outline_width": )" << outline_width << R"(, "outline_dash": "dash2", "radius": 3},)" << '\n' // << R"( "mark_serum": {"fill": ")" << color << R"(", "outline": "black", "order": "raise", "?label": {"name_type": "full", "offset": [0, 1], "color": "black", "size": 12}},)" << '\n' // << R"( "?mark_antigen": {"fill": ")" << color << R"(", "outline": "black", "order": "raise", "?label": {"name_type": "full", "offset": [0, 1], "color": "black", "size": 12}})" << '\n' // << "},\n\n"; }; std::cout << "<span class=\"passage-egg\">EGG</span><br>\n"; for (const auto& entry : serum_data) { if (entry.passage_type == passage_t::egg) report(entry); } std::cout << "<span class=\"passage-reassortant\">Reassortant</span><br>\n"; for (const auto& entry : serum_data) { if (entry.passage_type == passage_t::reassortant) report(entry); } std::cout << "<span class=\"passage-cell\">CELL</span><br>\n"; for (const auto& entry : serum_data) { if (entry.passage_type == passage_t::cell) report(entry); } } // report_for_serum_circles_html // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>whocc-sera-of-chart: --serum-circles<commit_after>#include <string> #include <regex> #include <optional> #include <map> #include <tuple> #include "acmacs-base/argv.hh" #include "acmacs-base/enumerate.hh" #include "acmacs-chart-2/chart.hh" #include "acmacs-chart-2/factory-import.hh" #include "hidb-5/hidb.hh" // ---------------------------------------------------------------------- using namespace acmacs::argv; struct Options : public argv { Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); } option<str> name{*this, "name", desc{"name (regex) to filter, matched against full_name"}}; option<bool> serum_circles{*this, "serum-circles", desc{"output data for drawing serum circles"}}; argument<str> chart{*this, mandatory}; }; enum class passage_t { egg, reassortant, cell }; struct SerumData { const size_t sr_no; const std::string name; const std::string full_name; const acmacs::chart::Reassortant reassortant; const acmacs::chart::Passage passage; const passage_t passage_type; std::vector<hidb::TableStat> table_data; bool most_used = false; // this name+passage-type+if-reassortant has max number of tables bool most_recent = false; // this name+passage-type+if-reassortant is in more than one table and has most recent oldest table }; static std::vector<SerumData> collect(const acmacs::chart::Chart& chart, std::optional<std::regex> name_match, const hidb::HiDb& hidb); static passage_t passage_type(const acmacs::chart::Reassortant& reassortant, const acmacs::chart::Passage& passage); static void find_most_used(std::vector<SerumData>& serum_data, std::string assay, std::string lab, std::string rbc); static bool match_assay(const hidb::TableStat& tables, std::string assay, std::string lab, std::string rbc); static void report(const std::vector<SerumData>& serum_data); static void report_for_serum_circles_json(const std::vector<SerumData>& serum_data, std::string assay, std::string lab, std::string rbc); static void report_for_serum_circles_html(const std::vector<SerumData>& serum_data, std::string assay, std::string lab, std::string rbc); // ---------------------------------------------------------------------- int main(int argc, const char* argv[]) { int exit_code = 0; try { Options opt(argc, argv); std::optional<std::regex> name_match; if (opt.name.has_value()) name_match = std::regex(opt.name->begin(), opt.name->end()); auto chart = acmacs::chart::import_from_file(opt.chart, acmacs::chart::Verify::None, report_time::no); std::string assay = chart->info()->assay(acmacs::chart::Info::Compute::Yes); if (assay == "FOCUS REDUCTION") assay = "FR"; else if (assay == "PLAQUE REDUCTION NEUTRALISATION") assay = "PRN"; const auto lab = chart->info()->lab(acmacs::chart::Info::Compute::Yes); const auto rbc = chart->info()->rbc_species(acmacs::chart::Info::Compute::Yes); auto serum_data = collect(*chart, name_match, hidb::get(chart->info()->virus_type(acmacs::chart::Info::Compute::Yes), report_time::no)); find_most_used(serum_data, assay, lab, rbc); if (opt.serum_circles) { report_for_serum_circles_json(serum_data, assay, lab, rbc); report_for_serum_circles_html(serum_data, assay, lab, rbc); } else report(serum_data); } catch (std::exception& err) { std::cerr << err.what() << std::endl; exit_code = 1; } return exit_code; } // ---------------------------------------------------------------------- std::vector<SerumData> collect(const acmacs::chart::Chart& chart, std::optional<std::regex> name_match, const hidb::HiDb& hidb) { auto sera = chart.sera(); const auto hidb_sera = hidb.sera()->find(*sera); auto hidb_tables = hidb.tables(); std::vector<SerumData> serum_data; for (auto [sr_no, serum] : acmacs::enumerate(*sera)) { if (!name_match || std::regex_search(serum->full_name(), *name_match)) { if (auto hidb_serum = hidb_sera[sr_no]; hidb_serum) serum_data.push_back({sr_no, serum->name(), serum->full_name(), serum->reassortant(), serum->passage(), passage_type(serum->reassortant(), serum->passage()), hidb_tables->stat(hidb_serum->tables())}); else std::cerr << "WARNING: not in hidb: " << serum->full_name_with_fields() << '\n'; } } return serum_data; } // collect // ---------------------------------------------------------------------- passage_t passage_type(const acmacs::chart::Reassortant& reassortant, const acmacs::chart::Passage& passage) { if (!reassortant.empty()) return passage_t::reassortant; if (passage.is_egg()) return passage_t::egg; return passage_t::cell; } // passage_type // ---------------------------------------------------------------------- void find_most_used(std::vector<SerumData>& serum_data, std::string assay, std::string lab, std::string rbc) { struct name_passage_t { std::string name; passage_t passage_type; bool operator<(const name_passage_t& rhs) const { return name == rhs.name ? passage_type < rhs.passage_type : name < rhs.name; } }; struct most_t { size_t most_used_index; size_t most_used_number; size_t most_recent_index; std::string most_recent_oldest_date; }; std::map<name_passage_t, most_t> index; for (const auto [no, entry] : acmacs::enumerate(serum_data)) { for (const auto& tables : entry.table_data) { if (match_assay(tables, assay, lab, rbc)) { if (const auto found = index.find({entry.name, entry.passage_type}); found != index.end()) { if (tables.number > found->second.most_used_number) { found->second.most_used_index = no; found->second.most_used_number = tables.number; } if (std::string{tables.oldest->date()} > found->second.most_recent_oldest_date) { found->second.most_recent_index = no; found->second.most_recent_oldest_date = std::string{tables.oldest->date()}; } } else index.emplace(name_passage_t{entry.name, entry.passage_type}, most_t{no, tables.number, no, std::string{tables.oldest->date()}}); } } } for (auto [name_passage, most_entry] : index) { // std::cerr << "DEBUG: " << name_passage.name << ' ' << static_cast<int>(name_passage.passage_type) << " most-used:" << most_entry.most_used_index << " most_recent:" << most_entry.most_recent_index << '\n'; serum_data[most_entry.most_used_index].most_used = true; serum_data[most_entry.most_recent_index].most_recent = true; } } // SerumData::find_most_used // ---------------------------------------------------------------------- bool match_assay(const hidb::TableStat& tables, std::string assay, std::string lab, std::string rbc) { return tables.assay == assay && tables.lab == lab && tables.rbc == rbc; } // match_assay // ---------------------------------------------------------------------- void report(const std::vector<SerumData>& serum_data) { for (const auto& entry : serum_data) { std::cout << std::setw(3) << std::right << entry.sr_no << ' ' << entry.full_name << " P: " << entry.passage << '\n'; for (const auto& tables : entry.table_data) { std::cout << " " << tables.title() << " tables:" << std::setw(2) << std::right << tables.number << " newest:" << tables.most_recent->date() << " oldest:" << tables.oldest->date() << '\n'; // << " newest: " << std::setw(30) << std::left << tables.most_recent->name() // << " oldest: " << tables.oldest->name() << '\n'; } } } // report // ---------------------------------------------------------------------- void report_for_serum_circles_json(const std::vector<SerumData>& serum_data, std::string assay, std::string lab, std::string rbc) { auto report = [&](const auto& entry, std::string color) { std::cout << R"({"N": "serum_circle", "serum": {"full_name": ")" << entry.full_name << R"("}, "report": true,)" << '\n' << " \"?passage\": \"" << entry.passage << "\",\n"; for (const auto& tables : entry.table_data) { // std::cerr << "DEBUG: " << tables.assay << " --- " << assay << '\n'; if (match_assay(tables, assay, lab, rbc)) { std::cout << " \"?\": \""; if (entry.most_used) std::cout << "**most-used** "; if (entry.most_recent) std::cout << "**most-recent** "; std::cout << "tables:" << tables.number << " newest:" << tables.most_recent->date() << " oldest:" << tables.oldest->date() << "\",\n"; } } const double outline_width = (entry.most_used || entry.most_recent) ? 6.0 : 2.0; const char* outline_dash = entry.most_recent ? R"(, "outline_dash": "dash1")" : ""; std::cout << R"( "empirical": {"show": true, "fill": "transparent", "outline": ")" << color << R"(", "outline_width": )" << outline_width << outline_dash << R"(},)" << '\n' << R"( "theoretical": {"show": false, "fill": "transparent", "outline": ")" << color << R"(", "outline_width": )" << outline_width << outline_dash << R"(},)" << '\n' << R"( "fallback": { "fill": "transparent", "outline": ")" << color << R"(", "outline_width": )" << outline_width << R"(, "outline_dash": "dash2", "radius": 3},)" << '\n' << R"( "mark_serum": {"fill": ")" << color << R"(", "outline": "black", "order": "raise", "?label": {"name_type": "full", "offset": [0, 1], "color": "black", "size": 12}},)" << '\n' << R"( "?mark_antigen": {"fill": ")" << color << R"(", "outline": "black", "order": "raise", "?label": {"name_type": "full", "offset": [0, 1], "color": "black", "size": 12}})" << '\n' << "},\n\n"; }; std::cout << "\"? ------ EGG ----------------------------------------------------------------------\",\n\n"; for (const auto& entry : serum_data) { if (entry.passage_type == passage_t::egg) report(entry, "${egg_color}"); } std::cout << "\"? ------ Reassortant ----------------------------------------------------------------------\",\n\n"; for (const auto& entry : serum_data) { if (entry.passage_type == passage_t::reassortant) report(entry, "${reassortant_color}"); } std::cout << "\"? ------ CELL ----------------------------------------------------------------------\",\n\n"; for (const auto& entry : serum_data) { if (entry.passage_type == passage_t::cell) report(entry, "${cell_color}"); } } // report_for_serum_circles_json // ---------------------------------------------------------------------- void report_for_serum_circles_html(const std::vector<SerumData>& serum_data, std::string assay, std::string lab, std::string rbc) { auto report = [&](const auto& entry) { std::cout << "<div class='serum-name'>" << entry.sr_no << ' ' << entry.full_name << "</div>\n"; for (const auto& tables : entry.table_data) { if (match_assay(tables, assay, lab, rbc)) { std::cout << "<div class='serum-tables" << (entry.most_used ? " most-used" : "") << (entry.most_recent ? " most-recent" : "") << "'><span class='number-of-tables'>tables:" << tables.number << "</span> <span class='newest'>newest:" << tables.most_recent->date() << "</span> <span class='oldest'>oldest:" << tables.oldest->date() << "</span></div>\n"; } } std::cout << "<table>\n<tr><td>titer</td><td>radius</td><td>antigen</td></tr>\n"; std::cout << "</table>\n"; }; std::cout << "<span class=\"passage-egg\">EGG</span><br>\n"; for (const auto& entry : serum_data) { if (entry.passage_type == passage_t::egg) report(entry); } std::cout << "<br>\n"; std::cout << "<span class=\"passage-reassortant\">Reassortant</span><br>\n"; for (const auto& entry : serum_data) { if (entry.passage_type == passage_t::reassortant) report(entry); } std::cout << "<br>\n"; std::cout << "<span class=\"passage-cell\">CELL</span><br>\n"; for (const auto& entry : serum_data) { if (entry.passage_type == passage_t::cell) report(entry); } std::cout << "<br>\n"; } // report_for_serum_circles_html // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>//===- UnifyFunctionExitNodes.cpp - Make all functions have a single exit -===// // // This file provides several routines that are useful for simplifying CFGs in // various ways... // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/UnifyFunctionExitNodes.h" #include "llvm/BasicBlock.h" #include "llvm/Function.h" #include "llvm/iTerminators.h" #include "llvm/iPHINode.h" #include "llvm/Type.h" using std::vector; AnalysisID UnifyFunctionExitNodes::ID(AnalysisID::create<UnifyFunctionExitNodes>()); // UnifyAllExitNodes - Unify all exit nodes of the CFG by creating a new // BasicBlock, and converting all returns to unconditional branches to this // new basic block. The singular exit node is returned. // // If there are no return stmts in the Function, a null pointer is returned. // bool UnifyFunctionExitNodes::doit(Function *M, BasicBlock *&ExitNode) { // Loop over all of the blocks in a function, tracking all of the blocks that // return. // vector<BasicBlock*> ReturningBlocks; for(Function::iterator I = M->begin(), E = M->end(); I != E; ++I) if (isa<ReturnInst>((*I)->getTerminator())) ReturningBlocks.push_back(*I); if (ReturningBlocks.empty()) { ExitNode = 0; return false; // No blocks return } else if (ReturningBlocks.size() == 1) { ExitNode = ReturningBlocks.front(); // Already has a single return block return false; } // Otherwise, we need to insert a new basic block into the function, add a PHI // node (if the function returns a value), and convert all of the return // instructions into unconditional branches. // BasicBlock *NewRetBlock = new BasicBlock("UnifiedExitNode", M); if (M->getReturnType() != Type::VoidTy) { // If the function doesn't return void... add a PHI node to the block... PHINode *PN = new PHINode(M->getReturnType()); NewRetBlock->getInstList().push_back(PN); // Add an incoming element to the PHI node for every return instruction that // is merging into this new block... for (vector<BasicBlock*>::iterator I = ReturningBlocks.begin(), E = ReturningBlocks.end(); I != E; ++I) PN->addIncoming((*I)->getTerminator()->getOperand(0), *I); // Add a return instruction to return the result of the PHI node... NewRetBlock->getInstList().push_back(new ReturnInst(PN)); } else { // If it returns void, just add a return void instruction to the block NewRetBlock->getInstList().push_back(new ReturnInst()); } // Loop over all of the blocks, replacing the return instruction with an // unconditional branch. // for (vector<BasicBlock*>::iterator I = ReturningBlocks.begin(), E = ReturningBlocks.end(); I != E; ++I) { delete (*I)->getInstList().pop_back(); // Remove the return insn (*I)->getInstList().push_back(new BranchInst(NewRetBlock)); } ExitNode = NewRetBlock; return true; } <commit_msg>Cleanup implementation a bit<commit_after>//===- UnifyFunctionExitNodes.cpp - Make all functions have a single exit -===// // // This pass is used to ensure that functions have at most one return // instruction in them. Additionally, it keeps track of which node is the new // exit node of the CFG. If there are no exit nodes in the CFG, the getExitNode // method will return a null pointer. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/UnifyFunctionExitNodes.h" #include "llvm/BasicBlock.h" #include "llvm/Function.h" #include "llvm/iTerminators.h" #include "llvm/iPHINode.h" #include "llvm/Type.h" using std::vector; AnalysisID UnifyFunctionExitNodes::ID(AnalysisID::create<UnifyFunctionExitNodes>()); // UnifyAllExitNodes - Unify all exit nodes of the CFG by creating a new // BasicBlock, and converting all returns to unconditional branches to this // new basic block. The singular exit node is returned. // // If there are no return stmts in the Function, a null pointer is returned. // bool UnifyFunctionExitNodes::runOnFunction(Function *M) { // Loop over all of the blocks in a function, tracking all of the blocks that // return. // vector<BasicBlock*> ReturningBlocks; for(Function::iterator I = M->begin(), E = M->end(); I != E; ++I) if (isa<ReturnInst>((*I)->getTerminator())) ReturningBlocks.push_back(*I); if (ReturningBlocks.empty()) { ExitNode = 0; return false; // No blocks return } else if (ReturningBlocks.size() == 1) { ExitNode = ReturningBlocks.front(); // Already has a single return block return false; } // Otherwise, we need to insert a new basic block into the function, add a PHI // node (if the function returns a value), and convert all of the return // instructions into unconditional branches. // BasicBlock *NewRetBlock = new BasicBlock("UnifiedExitNode", M); if (M->getReturnType() != Type::VoidTy) { // If the function doesn't return void... add a PHI node to the block... PHINode *PN = new PHINode(M->getReturnType()); NewRetBlock->getInstList().push_back(PN); // Add an incoming element to the PHI node for every return instruction that // is merging into this new block... for (vector<BasicBlock*>::iterator I = ReturningBlocks.begin(), E = ReturningBlocks.end(); I != E; ++I) PN->addIncoming((*I)->getTerminator()->getOperand(0), *I); // Add a return instruction to return the result of the PHI node... NewRetBlock->getInstList().push_back(new ReturnInst(PN)); } else { // If it returns void, just add a return void instruction to the block NewRetBlock->getInstList().push_back(new ReturnInst()); } // Loop over all of the blocks, replacing the return instruction with an // unconditional branch. // for (vector<BasicBlock*>::iterator I = ReturningBlocks.begin(), E = ReturningBlocks.end(); I != E; ++I) { delete (*I)->getInstList().pop_back(); // Remove the return insn (*I)->getInstList().push_back(new BranchInst(NewRetBlock)); } ExitNode = NewRetBlock; return true; } <|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. // // This code glues the RLZ library DLL with Chrome. It allows Chrome to work // with or without the DLL being present. If the DLL is not present the // functions do nothing and just return false. #include "chrome/browser/rlz/rlz.h" #include <windows.h> #include <process.h> #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/task.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/profile_manager.h" #include "chrome/browser/search_engines/template_url_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/env_vars.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/installer/util/google_update_settings.h" namespace { // The maximum length of an access points RLZ in wide chars. const DWORD kMaxRlzLength = 64; // The RLZ is a DLL that might not be present in the system. We load it // as needed but never unload it. volatile HMODULE rlz_dll = NULL; enum { ACCESS_VALUES_STALE, // Possibly new values available. ACCESS_VALUES_FRESH // The cached values are current. }; // Tracks if we have tried and succeeded sending the ping. This helps us // decide if we need to refresh the some cached strings. volatile int access_values_state = ACCESS_VALUES_STALE; extern "C" { typedef bool (*RecordProductEventFn)(RLZTracker::Product product, RLZTracker::AccessPoint point, RLZTracker::Event event_id, void* reserved); typedef bool (*GetAccessPointRlzFn)(RLZTracker::AccessPoint point, wchar_t* rlz, DWORD rlz_size, void* reserved); typedef bool (*ClearAllProductEventsFn)(RLZTracker::Product product, void* reserved); typedef bool (*SendFinancialPingFn)(RLZTracker::Product product, RLZTracker::AccessPoint* access_points, const WCHAR* product_signature, const WCHAR* product_brand, const WCHAR* product_id, const WCHAR* product_lang, bool exclude_id, void* reserved); } // extern "C". RecordProductEventFn record_event = NULL; GetAccessPointRlzFn get_access_point = NULL; ClearAllProductEventsFn clear_all_events = NULL; SendFinancialPingFn send_ping = NULL; template <typename FuncT> FuncT WireExport(HMODULE module, const char* export_name) { void* entry_point = ::GetProcAddress(module, export_name); return (module)? reinterpret_cast<FuncT>(entry_point) : NULL; } HMODULE LoadRLZLibraryInternal(int directory_key) { FilePath rlz_path; if (!PathService::Get(directory_key, &rlz_path)) return NULL; rlz_path = rlz_path.AppendASCII("rlz.dll"); return ::LoadLibraryW(rlz_path.value().c_str()); } bool LoadRLZLibrary(int directory_key) { rlz_dll = LoadRLZLibraryInternal(directory_key); if (!rlz_dll) { // As a last resort we can try the EXE directory. if (directory_key != base::DIR_EXE) rlz_dll = LoadRLZLibraryInternal(base::DIR_EXE); } if (rlz_dll) { record_event = WireExport<RecordProductEventFn>(rlz_dll, "RecordProductEvent"); get_access_point = WireExport<GetAccessPointRlzFn>(rlz_dll, "GetAccessPointRlz"); clear_all_events = WireExport<ClearAllProductEventsFn>(rlz_dll, "ClearAllProductEvents"); send_ping = WireExport<SendFinancialPingFn>(rlz_dll, "SendFinancialPing"); return (record_event && get_access_point && clear_all_events && send_ping); } return false; } bool SendFinancialPing(const wchar_t* brand, const wchar_t* lang, const wchar_t* referral, bool exclude_id) { RLZTracker::AccessPoint points[] = {RLZTracker::CHROME_OMNIBOX, RLZTracker::CHROME_HOME_PAGE, RLZTracker::NO_ACCESS_POINT}; if (!send_ping) return false; return send_ping(RLZTracker::CHROME, points, L"chrome", brand, referral, lang, exclude_id, NULL); } // This class leverages the AutocompleteEditModel notification to know when // the user first interacted with the omnibox and set a global accordingly. class OmniBoxUsageObserver : public NotificationObserver { public: OmniBoxUsageObserver() { registrar_.Add(this, NotificationType::OMNIBOX_OPENED_URL, NotificationService::AllSources()); omnibox_used_ = false; DCHECK(!instance_); instance_ = this; } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { // Try to record event now, else set the flag to try later when we // attempt the ping. if (!RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::FIRST_SEARCH)) omnibox_used_ = true; delete this; } static bool used() { return omnibox_used_; } // Deletes the single instance of OmniBoxUsageObserver. static void DeleteInstance() { delete instance_; } private: // Dtor is private so the object cannot be created on the stack. ~OmniBoxUsageObserver() { instance_ = NULL; } static bool omnibox_used_; // There should only be one instance created at a time, and instance_ points // to that instance. // NOTE: this is only non-null for the amount of time it is needed. Once the // instance_ is no longer needed (or Chrome is exiting), this is null. static OmniBoxUsageObserver* instance_; NotificationRegistrar registrar_; }; bool OmniBoxUsageObserver::omnibox_used_ = false; OmniBoxUsageObserver* OmniBoxUsageObserver::instance_ = NULL; // This task is run in the file thread, so to not block it for a long time // we use a throwaway thread to do the blocking url request. class DailyPingTask : public Task { public: virtual ~DailyPingTask() { } virtual void Run() { // We use a transient thread because we have no guarantees about // how long the RLZ lib can block us. _beginthread(PingNow, 0, NULL); } private: // Causes a ping to the server using WinInet. There is logic inside RLZ dll // that throttles it to a maximum of one ping per day. static void _cdecl PingNow(void*) { std::wstring lang; GoogleUpdateSettings::GetLanguage(&lang); if (lang.empty()) lang = L"en"; std::wstring brand; GoogleUpdateSettings::GetBrand(&brand); std::wstring referral; GoogleUpdateSettings::GetReferral(&referral); if (SendFinancialPing(brand.c_str(), lang.c_str(), referral.c_str(), is_organic(brand))) { access_values_state = ACCESS_VALUES_STALE; GoogleUpdateSettings::ClearReferral(); } } // Organic brands all start with GG, such as GGCM. static bool is_organic(const std::wstring brand) { return (brand.size() < 2) ? false : (brand.substr(0,2) == L"GG"); } }; // Performs late RLZ initialization and RLZ event recording for chrome. // This task needs to run on the UI thread. class DelayedInitTask : public Task { public: explicit DelayedInitTask(int directory_key, bool first_run) : directory_key_(directory_key), first_run_(first_run) { } virtual ~DelayedInitTask() { } virtual void Run() { // For non-interactive tests we don't do the rest of the initialization // because sometimes the very act of loading the dll causes QEMU to crash. if (::GetEnvironmentVariableW(env_vars::kHeadless, NULL, 0)) return; if (!LoadRLZLibrary(directory_key_)) return; // Do the initial event recording if is the first run or if we have an // empty rlz which means we haven't got a chance to do it. std::wstring omnibox_rlz; RLZTracker::GetAccessPointRlz(RLZTracker::CHROME_OMNIBOX, &omnibox_rlz); if (first_run_ || omnibox_rlz.empty()) { // Record the installation of chrome. RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::INSTALL); RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_HOME_PAGE, RLZTracker::INSTALL); // Record if google is the initial search provider. if (IsGoogleDefaultSearch()) { RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::SET_TO_GOOGLE); } // Record first user interaction with the omnibox. if (OmniBoxUsageObserver::used()) { RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::FIRST_SEARCH); } } // Schedule the daily RLZ ping. base::Thread* thread = g_browser_process->file_thread(); if (thread) thread->message_loop()->PostTask(FROM_HERE, new DailyPingTask()); } private: bool IsGoogleDefaultSearch() { if (!g_browser_process) return false; FilePath user_data_dir; if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) return false; ProfileManager* profile_manager = g_browser_process->profile_manager(); Profile* profile = profile_manager->GetDefaultProfile(user_data_dir); if (!profile) return false; const TemplateURL* url_template = profile->GetTemplateURLModel()->GetDefaultSearchProvider(); if (!url_template) return false; const TemplateURLRef* urlref = url_template->url(); if (!urlref) return false; return urlref->HasGoogleBaseURLs(); } int directory_key_; bool first_run_; DISALLOW_IMPLICIT_CONSTRUCTORS(DelayedInitTask); }; } // namespace bool RLZTracker::InitRlz(int directory_key) { return LoadRLZLibrary(directory_key); } bool RLZTracker::InitRlzDelayed(int directory_key, bool first_run, int delay) { // Maximum and minimum delay we would allow to be set through master // preferences. Somewhat arbitrary, may need to be adjusted in future. const int kMaxDelay = 200 * 1000; const int kMinDelay = 20 * 1000; delay *= 1000; delay = (delay < kMinDelay) ? kMinDelay : delay; delay = (delay > kMaxDelay) ? kMaxDelay : delay; if (!OmniBoxUsageObserver::used()) new OmniBoxUsageObserver(); // Schedule the delayed init items. MessageLoop::current()->PostDelayedTask(FROM_HERE, new DelayedInitTask(directory_key, first_run), delay); return true; } bool RLZTracker::RecordProductEvent(Product product, AccessPoint point, Event event) { return (record_event) ? record_event(product, point, event, NULL) : false; } bool RLZTracker::ClearAllProductEvents(Product product) { return (clear_all_events) ? clear_all_events(product, NULL) : false; } // We implement caching of the answer of get_access_point() if the request // is for CHROME_OMNIBOX. If we had a successful ping, then we update the // cached value. bool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) { static std::wstring cached_ommibox_rlz; if (!get_access_point) return false; if ((CHROME_OMNIBOX == point) && (access_values_state == ACCESS_VALUES_FRESH)) { *rlz = cached_ommibox_rlz; return true; } wchar_t str_rlz[kMaxRlzLength]; if (!get_access_point(point, str_rlz, kMaxRlzLength, NULL)) return false; if (CHROME_OMNIBOX == point) { access_values_state = ACCESS_VALUES_FRESH; cached_ommibox_rlz.assign(str_rlz); } *rlz = str_rlz; return true; } // static void RLZTracker::CleanupRlz() { OmniBoxUsageObserver::DeleteInstance(); } <commit_msg>Coverity: check module for NULL before calling GetProcAddress.<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. // // This code glues the RLZ library DLL with Chrome. It allows Chrome to work // with or without the DLL being present. If the DLL is not present the // functions do nothing and just return false. #include "chrome/browser/rlz/rlz.h" #include <windows.h> #include <process.h> #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/task.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/profile_manager.h" #include "chrome/browser/search_engines/template_url_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/env_vars.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/installer/util/google_update_settings.h" namespace { // The maximum length of an access points RLZ in wide chars. const DWORD kMaxRlzLength = 64; // The RLZ is a DLL that might not be present in the system. We load it // as needed but never unload it. volatile HMODULE rlz_dll = NULL; enum { ACCESS_VALUES_STALE, // Possibly new values available. ACCESS_VALUES_FRESH // The cached values are current. }; // Tracks if we have tried and succeeded sending the ping. This helps us // decide if we need to refresh the some cached strings. volatile int access_values_state = ACCESS_VALUES_STALE; extern "C" { typedef bool (*RecordProductEventFn)(RLZTracker::Product product, RLZTracker::AccessPoint point, RLZTracker::Event event_id, void* reserved); typedef bool (*GetAccessPointRlzFn)(RLZTracker::AccessPoint point, wchar_t* rlz, DWORD rlz_size, void* reserved); typedef bool (*ClearAllProductEventsFn)(RLZTracker::Product product, void* reserved); typedef bool (*SendFinancialPingFn)(RLZTracker::Product product, RLZTracker::AccessPoint* access_points, const WCHAR* product_signature, const WCHAR* product_brand, const WCHAR* product_id, const WCHAR* product_lang, bool exclude_id, void* reserved); } // extern "C". RecordProductEventFn record_event = NULL; GetAccessPointRlzFn get_access_point = NULL; ClearAllProductEventsFn clear_all_events = NULL; SendFinancialPingFn send_ping = NULL; template <typename FuncT> FuncT WireExport(HMODULE module, const char* export_name) { if (!module) return NULL; void* entry_point = ::GetProcAddress(module, export_name); return reinterpret_cast<FuncT>(entry_point); } HMODULE LoadRLZLibraryInternal(int directory_key) { FilePath rlz_path; if (!PathService::Get(directory_key, &rlz_path)) return NULL; rlz_path = rlz_path.AppendASCII("rlz.dll"); return ::LoadLibraryW(rlz_path.value().c_str()); } bool LoadRLZLibrary(int directory_key) { rlz_dll = LoadRLZLibraryInternal(directory_key); if (!rlz_dll) { // As a last resort we can try the EXE directory. if (directory_key != base::DIR_EXE) rlz_dll = LoadRLZLibraryInternal(base::DIR_EXE); } if (rlz_dll) { record_event = WireExport<RecordProductEventFn>(rlz_dll, "RecordProductEvent"); get_access_point = WireExport<GetAccessPointRlzFn>(rlz_dll, "GetAccessPointRlz"); clear_all_events = WireExport<ClearAllProductEventsFn>(rlz_dll, "ClearAllProductEvents"); send_ping = WireExport<SendFinancialPingFn>(rlz_dll, "SendFinancialPing"); return (record_event && get_access_point && clear_all_events && send_ping); } return false; } bool SendFinancialPing(const wchar_t* brand, const wchar_t* lang, const wchar_t* referral, bool exclude_id) { RLZTracker::AccessPoint points[] = {RLZTracker::CHROME_OMNIBOX, RLZTracker::CHROME_HOME_PAGE, RLZTracker::NO_ACCESS_POINT}; if (!send_ping) return false; return send_ping(RLZTracker::CHROME, points, L"chrome", brand, referral, lang, exclude_id, NULL); } // This class leverages the AutocompleteEditModel notification to know when // the user first interacted with the omnibox and set a global accordingly. class OmniBoxUsageObserver : public NotificationObserver { public: OmniBoxUsageObserver() { registrar_.Add(this, NotificationType::OMNIBOX_OPENED_URL, NotificationService::AllSources()); omnibox_used_ = false; DCHECK(!instance_); instance_ = this; } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { // Try to record event now, else set the flag to try later when we // attempt the ping. if (!RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::FIRST_SEARCH)) omnibox_used_ = true; delete this; } static bool used() { return omnibox_used_; } // Deletes the single instance of OmniBoxUsageObserver. static void DeleteInstance() { delete instance_; } private: // Dtor is private so the object cannot be created on the stack. ~OmniBoxUsageObserver() { instance_ = NULL; } static bool omnibox_used_; // There should only be one instance created at a time, and instance_ points // to that instance. // NOTE: this is only non-null for the amount of time it is needed. Once the // instance_ is no longer needed (or Chrome is exiting), this is null. static OmniBoxUsageObserver* instance_; NotificationRegistrar registrar_; }; bool OmniBoxUsageObserver::omnibox_used_ = false; OmniBoxUsageObserver* OmniBoxUsageObserver::instance_ = NULL; // This task is run in the file thread, so to not block it for a long time // we use a throwaway thread to do the blocking url request. class DailyPingTask : public Task { public: virtual ~DailyPingTask() { } virtual void Run() { // We use a transient thread because we have no guarantees about // how long the RLZ lib can block us. _beginthread(PingNow, 0, NULL); } private: // Causes a ping to the server using WinInet. There is logic inside RLZ dll // that throttles it to a maximum of one ping per day. static void _cdecl PingNow(void*) { std::wstring lang; GoogleUpdateSettings::GetLanguage(&lang); if (lang.empty()) lang = L"en"; std::wstring brand; GoogleUpdateSettings::GetBrand(&brand); std::wstring referral; GoogleUpdateSettings::GetReferral(&referral); if (SendFinancialPing(brand.c_str(), lang.c_str(), referral.c_str(), is_organic(brand))) { access_values_state = ACCESS_VALUES_STALE; GoogleUpdateSettings::ClearReferral(); } } // Organic brands all start with GG, such as GGCM. static bool is_organic(const std::wstring brand) { return (brand.size() < 2) ? false : (brand.substr(0,2) == L"GG"); } }; // Performs late RLZ initialization and RLZ event recording for chrome. // This task needs to run on the UI thread. class DelayedInitTask : public Task { public: explicit DelayedInitTask(int directory_key, bool first_run) : directory_key_(directory_key), first_run_(first_run) { } virtual ~DelayedInitTask() { } virtual void Run() { // For non-interactive tests we don't do the rest of the initialization // because sometimes the very act of loading the dll causes QEMU to crash. if (::GetEnvironmentVariableW(env_vars::kHeadless, NULL, 0)) return; if (!LoadRLZLibrary(directory_key_)) return; // Do the initial event recording if is the first run or if we have an // empty rlz which means we haven't got a chance to do it. std::wstring omnibox_rlz; RLZTracker::GetAccessPointRlz(RLZTracker::CHROME_OMNIBOX, &omnibox_rlz); if (first_run_ || omnibox_rlz.empty()) { // Record the installation of chrome. RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::INSTALL); RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_HOME_PAGE, RLZTracker::INSTALL); // Record if google is the initial search provider. if (IsGoogleDefaultSearch()) { RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::SET_TO_GOOGLE); } // Record first user interaction with the omnibox. if (OmniBoxUsageObserver::used()) { RLZTracker::RecordProductEvent(RLZTracker::CHROME, RLZTracker::CHROME_OMNIBOX, RLZTracker::FIRST_SEARCH); } } // Schedule the daily RLZ ping. base::Thread* thread = g_browser_process->file_thread(); if (thread) thread->message_loop()->PostTask(FROM_HERE, new DailyPingTask()); } private: bool IsGoogleDefaultSearch() { if (!g_browser_process) return false; FilePath user_data_dir; if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) return false; ProfileManager* profile_manager = g_browser_process->profile_manager(); Profile* profile = profile_manager->GetDefaultProfile(user_data_dir); if (!profile) return false; const TemplateURL* url_template = profile->GetTemplateURLModel()->GetDefaultSearchProvider(); if (!url_template) return false; const TemplateURLRef* urlref = url_template->url(); if (!urlref) return false; return urlref->HasGoogleBaseURLs(); } int directory_key_; bool first_run_; DISALLOW_IMPLICIT_CONSTRUCTORS(DelayedInitTask); }; } // namespace bool RLZTracker::InitRlz(int directory_key) { return LoadRLZLibrary(directory_key); } bool RLZTracker::InitRlzDelayed(int directory_key, bool first_run, int delay) { // Maximum and minimum delay we would allow to be set through master // preferences. Somewhat arbitrary, may need to be adjusted in future. const int kMaxDelay = 200 * 1000; const int kMinDelay = 20 * 1000; delay *= 1000; delay = (delay < kMinDelay) ? kMinDelay : delay; delay = (delay > kMaxDelay) ? kMaxDelay : delay; if (!OmniBoxUsageObserver::used()) new OmniBoxUsageObserver(); // Schedule the delayed init items. MessageLoop::current()->PostDelayedTask(FROM_HERE, new DelayedInitTask(directory_key, first_run), delay); return true; } bool RLZTracker::RecordProductEvent(Product product, AccessPoint point, Event event) { return (record_event) ? record_event(product, point, event, NULL) : false; } bool RLZTracker::ClearAllProductEvents(Product product) { return (clear_all_events) ? clear_all_events(product, NULL) : false; } // We implement caching of the answer of get_access_point() if the request // is for CHROME_OMNIBOX. If we had a successful ping, then we update the // cached value. bool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) { static std::wstring cached_ommibox_rlz; if (!get_access_point) return false; if ((CHROME_OMNIBOX == point) && (access_values_state == ACCESS_VALUES_FRESH)) { *rlz = cached_ommibox_rlz; return true; } wchar_t str_rlz[kMaxRlzLength]; if (!get_access_point(point, str_rlz, kMaxRlzLength, NULL)) return false; if (CHROME_OMNIBOX == point) { access_values_state = ACCESS_VALUES_FRESH; cached_ommibox_rlz.assign(str_rlz); } *rlz = str_rlz; return true; } // static void RLZTracker::CleanupRlz() { OmniBoxUsageObserver::DeleteInstance(); } <|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/gpu/gpu_channel.h" #if defined(OS_WIN) #include <windows.h> #endif #include "base/command_line.h" #include "base/process_util.h" #include "base/string_util.h" #include "chrome/common/child_process.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/gpu_messages.h" #include "chrome/gpu/gpu_thread.h" #include "chrome/gpu/gpu_video_service.h" #if defined(OS_POSIX) #include "ipc/ipc_channel_posix.h" #endif GpuChannel::GpuChannel(GpuThread* gpu_thread, int renderer_id) : gpu_thread_(gpu_thread), renderer_id_(renderer_id) { DCHECK(gpu_thread); const CommandLine* command_line = CommandLine::ForCurrentProcess(); log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages); } GpuChannel::~GpuChannel() { } void GpuChannel::OnChannelConnected(int32 peer_pid) { if (!renderer_process_.Open(peer_pid)) { NOTREACHED(); } } bool GpuChannel::OnMessageReceived(const IPC::Message& message) { if (log_messages_) { VLOG(1) << "received message @" << &message << " on channel @" << this << " with type " << message.type(); } if (message.routing_id() == MSG_ROUTING_CONTROL) return OnControlMessageReceived(message); // Fail silently if the GPU process has destroyed while the IPC message was // en-route. return router_.RouteMessage(message); } void GpuChannel::OnChannelError() { gpu_thread_->RemoveChannel(renderer_id_); } bool GpuChannel::Send(IPC::Message* message) { if (log_messages_) { VLOG(1) << "sending message @" << message << " on channel @" << this << " with type " << message->type(); } if (!channel_.get()) { delete message; return false; } return channel_->Send(message); } void GpuChannel::CreateViewCommandBuffer( gfx::PluginWindowHandle window, int32 render_view_id, const GPUCreateCommandBufferConfig& init_params, int32* route_id) { *route_id = MSG_ROUTING_NONE; #if defined(ENABLE_GPU) *route_id = GenerateRouteID(); scoped_ptr<GpuCommandBufferStub> stub(new GpuCommandBufferStub( this, window, NULL, gfx::Size(), init_params.allowed_extensions, init_params.attribs, 0, *route_id, renderer_id_, render_view_id)); router_.AddRoute(*route_id, stub.get()); stubs_.AddWithID(stub.release(), *route_id); #endif // ENABLE_GPU } #if defined(OS_MACOSX) void GpuChannel::AcceleratedSurfaceBuffersSwapped( int32 route_id, uint64 swap_buffers_count) { GpuCommandBufferStub* stub = stubs_.Lookup(route_id); if (stub == NULL) return; stub->AcceleratedSurfaceBuffersSwapped(swap_buffers_count); } void GpuChannel::DidDestroySurface(int32 renderer_route_id) { // Since acclerated views are created in the renderer process and then sent // to the browser process during GPU channel construction, it is possible that // this is called before a GpuCommandBufferStub for |renderer_route_id| was // put into |stubs_|. Hence, do not walk |stubs_| here but instead remember // all |renderer_route_id|s this was called for and use them later. destroyed_renderer_routes_.insert(renderer_route_id); } bool GpuChannel::IsRenderViewGone(int32 renderer_route_id) { return destroyed_renderer_routes_.count(renderer_route_id) > 0; } #endif bool GpuChannel::OnControlMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(GpuChannel, msg) IPC_MESSAGE_HANDLER(GpuChannelMsg_CreateOffscreenCommandBuffer, OnCreateOffscreenCommandBuffer) IPC_MESSAGE_HANDLER(GpuChannelMsg_DestroyCommandBuffer, OnDestroyCommandBuffer) IPC_MESSAGE_HANDLER(GpuChannelMsg_CreateVideoDecoder, OnCreateVideoDecoder) IPC_MESSAGE_HANDLER(GpuChannelMsg_DestroyVideoDecoder, OnDestroyVideoDecoder) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() DCHECK(handled); return handled; } int GpuChannel::GenerateRouteID() { static int last_id = 0; return ++last_id; } void GpuChannel::OnCreateOffscreenCommandBuffer( int32 parent_route_id, const gfx::Size& size, const GPUCreateCommandBufferConfig& init_params, uint32 parent_texture_id, int32* route_id) { #if defined(ENABLE_GPU) *route_id = GenerateRouteID(); GpuCommandBufferStub* parent_stub = NULL; if (parent_route_id != 0) parent_stub = stubs_.Lookup(parent_route_id); scoped_ptr<GpuCommandBufferStub> stub(new GpuCommandBufferStub( this, gfx::kNullPluginWindow, parent_stub, size, init_params.allowed_extensions, init_params.attribs, parent_texture_id, *route_id, 0, 0)); router_.AddRoute(*route_id, stub.get()); stubs_.AddWithID(stub.release(), *route_id); #else *route_id = MSG_ROUTING_NONE; #endif } void GpuChannel::OnDestroyCommandBuffer(int32 route_id) { #if defined(ENABLE_GPU) router_.RemoveRoute(route_id); stubs_.Remove(route_id); #endif } void GpuChannel::OnCreateVideoDecoder(int32 context_route_id, int32 decoder_host_id) { #if defined(ENABLE_GPU) VLOG(1) << "GpuChannel::OnCreateVideoDecoder"; GpuVideoService* service = GpuVideoService::GetInstance(); if (service == NULL) { // TODO(hclam): Need to send a failure message. return; } // The context ID corresponds to the command buffer used. GpuCommandBufferStub* stub = stubs_.Lookup(context_route_id); int32 decoder_id = GenerateRouteID(); // TODO(hclam): Need to be careful about the lifetime of the command buffer // decoder. bool ret = service->CreateVideoDecoder( this, &router_, decoder_host_id, decoder_id, stub->processor()->decoder()); DCHECK(ret) << "Failed to create a GpuVideoDecoder"; #endif } void GpuChannel::OnDestroyVideoDecoder(int32 decoder_id) { #if defined(ENABLE_GPU) LOG(ERROR) << "GpuChannel::OnDestroyVideoDecoder"; GpuVideoService* service = GpuVideoService::GetInstance(); if (service == NULL) return; service->DestroyVideoDecoder(&router_, decoder_id); #endif } bool GpuChannel::Init() { // Check whether we're already initialized. if (channel_.get()) return true; // Map renderer ID to a (single) channel to that process. std::string channel_name = GetChannelName(); channel_.reset(new IPC::SyncChannel( channel_name, IPC::Channel::MODE_SERVER, this, ChildProcess::current()->io_message_loop(), false, ChildProcess::current()->GetShutDownEvent())); return true; } std::string GpuChannel::GetChannelName() { return StringPrintf("%d.r%d.gpu", base::GetCurrentProcId(), renderer_id_); } #if defined(OS_POSIX) int GpuChannel::GetRendererFileDescriptor() { int fd = -1; if (channel_.get()) { fd = channel_->GetClientFileDescriptor(); } return fd; } #endif // defined(OS_POSIX) <commit_msg>Don't compile in experimental GPU video decoding IPC handling for now.<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/gpu/gpu_channel.h" #if defined(OS_WIN) #include <windows.h> #endif #include "base/command_line.h" #include "base/process_util.h" #include "base/string_util.h" #include "chrome/common/child_process.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/gpu_messages.h" #include "chrome/gpu/gpu_thread.h" #include "chrome/gpu/gpu_video_service.h" #if defined(OS_POSIX) #include "ipc/ipc_channel_posix.h" #endif GpuChannel::GpuChannel(GpuThread* gpu_thread, int renderer_id) : gpu_thread_(gpu_thread), renderer_id_(renderer_id) { DCHECK(gpu_thread); const CommandLine* command_line = CommandLine::ForCurrentProcess(); log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages); } GpuChannel::~GpuChannel() { } void GpuChannel::OnChannelConnected(int32 peer_pid) { if (!renderer_process_.Open(peer_pid)) { NOTREACHED(); } } bool GpuChannel::OnMessageReceived(const IPC::Message& message) { if (log_messages_) { VLOG(1) << "received message @" << &message << " on channel @" << this << " with type " << message.type(); } if (message.routing_id() == MSG_ROUTING_CONTROL) return OnControlMessageReceived(message); // Fail silently if the GPU process has destroyed while the IPC message was // en-route. return router_.RouteMessage(message); } void GpuChannel::OnChannelError() { gpu_thread_->RemoveChannel(renderer_id_); } bool GpuChannel::Send(IPC::Message* message) { if (log_messages_) { VLOG(1) << "sending message @" << message << " on channel @" << this << " with type " << message->type(); } if (!channel_.get()) { delete message; return false; } return channel_->Send(message); } void GpuChannel::CreateViewCommandBuffer( gfx::PluginWindowHandle window, int32 render_view_id, const GPUCreateCommandBufferConfig& init_params, int32* route_id) { *route_id = MSG_ROUTING_NONE; #if defined(ENABLE_GPU) *route_id = GenerateRouteID(); scoped_ptr<GpuCommandBufferStub> stub(new GpuCommandBufferStub( this, window, NULL, gfx::Size(), init_params.allowed_extensions, init_params.attribs, 0, *route_id, renderer_id_, render_view_id)); router_.AddRoute(*route_id, stub.get()); stubs_.AddWithID(stub.release(), *route_id); #endif // ENABLE_GPU } #if defined(OS_MACOSX) void GpuChannel::AcceleratedSurfaceBuffersSwapped( int32 route_id, uint64 swap_buffers_count) { GpuCommandBufferStub* stub = stubs_.Lookup(route_id); if (stub == NULL) return; stub->AcceleratedSurfaceBuffersSwapped(swap_buffers_count); } void GpuChannel::DidDestroySurface(int32 renderer_route_id) { // Since acclerated views are created in the renderer process and then sent // to the browser process during GPU channel construction, it is possible that // this is called before a GpuCommandBufferStub for |renderer_route_id| was // put into |stubs_|. Hence, do not walk |stubs_| here but instead remember // all |renderer_route_id|s this was called for and use them later. destroyed_renderer_routes_.insert(renderer_route_id); } bool GpuChannel::IsRenderViewGone(int32 renderer_route_id) { return destroyed_renderer_routes_.count(renderer_route_id) > 0; } #endif bool GpuChannel::OnControlMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(GpuChannel, msg) IPC_MESSAGE_HANDLER(GpuChannelMsg_CreateOffscreenCommandBuffer, OnCreateOffscreenCommandBuffer) IPC_MESSAGE_HANDLER(GpuChannelMsg_DestroyCommandBuffer, OnDestroyCommandBuffer) IPC_MESSAGE_HANDLER(GpuChannelMsg_CreateVideoDecoder, OnCreateVideoDecoder) IPC_MESSAGE_HANDLER(GpuChannelMsg_DestroyVideoDecoder, OnDestroyVideoDecoder) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() DCHECK(handled); return handled; } int GpuChannel::GenerateRouteID() { static int last_id = 0; return ++last_id; } void GpuChannel::OnCreateOffscreenCommandBuffer( int32 parent_route_id, const gfx::Size& size, const GPUCreateCommandBufferConfig& init_params, uint32 parent_texture_id, int32* route_id) { #if defined(ENABLE_GPU) *route_id = GenerateRouteID(); GpuCommandBufferStub* parent_stub = NULL; if (parent_route_id != 0) parent_stub = stubs_.Lookup(parent_route_id); scoped_ptr<GpuCommandBufferStub> stub(new GpuCommandBufferStub( this, gfx::kNullPluginWindow, parent_stub, size, init_params.allowed_extensions, init_params.attribs, parent_texture_id, *route_id, 0, 0)); router_.AddRoute(*route_id, stub.get()); stubs_.AddWithID(stub.release(), *route_id); #else *route_id = MSG_ROUTING_NONE; #endif } void GpuChannel::OnDestroyCommandBuffer(int32 route_id) { #if defined(ENABLE_GPU) router_.RemoveRoute(route_id); stubs_.Remove(route_id); #endif } void GpuChannel::OnCreateVideoDecoder(int32 context_route_id, int32 decoder_host_id) { // TODO(cevans): do NOT re-enable this until GpuVideoService has been checked // for integer overflows, including the classic "width * height" overflow. #if 0 VLOG(1) << "GpuChannel::OnCreateVideoDecoder"; GpuVideoService* service = GpuVideoService::GetInstance(); if (service == NULL) { // TODO(hclam): Need to send a failure message. return; } // The context ID corresponds to the command buffer used. GpuCommandBufferStub* stub = stubs_.Lookup(context_route_id); int32 decoder_id = GenerateRouteID(); // TODO(hclam): Need to be careful about the lifetime of the command buffer // decoder. bool ret = service->CreateVideoDecoder( this, &router_, decoder_host_id, decoder_id, stub->processor()->decoder()); DCHECK(ret) << "Failed to create a GpuVideoDecoder"; #endif } void GpuChannel::OnDestroyVideoDecoder(int32 decoder_id) { #if defined(ENABLE_GPU) LOG(ERROR) << "GpuChannel::OnDestroyVideoDecoder"; GpuVideoService* service = GpuVideoService::GetInstance(); if (service == NULL) return; service->DestroyVideoDecoder(&router_, decoder_id); #endif } bool GpuChannel::Init() { // Check whether we're already initialized. if (channel_.get()) return true; // Map renderer ID to a (single) channel to that process. std::string channel_name = GetChannelName(); channel_.reset(new IPC::SyncChannel( channel_name, IPC::Channel::MODE_SERVER, this, ChildProcess::current()->io_message_loop(), false, ChildProcess::current()->GetShutDownEvent())); return true; } std::string GpuChannel::GetChannelName() { return StringPrintf("%d.r%d.gpu", base::GetCurrentProcId(), renderer_id_); } #if defined(OS_POSIX) int GpuChannel::GetRendererFileDescriptor() { int fd = -1; if (channel_.get()) { fd = channel_->GetClientFileDescriptor(); } return fd; } #endif // defined(OS_POSIX) <|endoftext|>
<commit_before>/************************************************************************** ** ** Copyright (c) 2013 BogDan Vatra <bog_dan_ro@yahoo.com> ** 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 "androidqbspropertyprovider.h" #include "androidconfigurations.h" #include "androidconstants.h" #include "androidgdbserverkitinformation.h" #include "androidtoolchain.h" #include <qbsprojectmanager/qbsconstants.h> namespace Android { namespace Internal { // QBS Android specific settings: const QLatin1String CPP_ANDROID_SDK_PATH("cpp.androidSdkPath"); const QLatin1String CPP_ANDROID_NDK_PATH("cpp.androidNdkPath"); const QLatin1String CPP_ANDROID_TOOLCHAIN_VERSION("cpp.androidToolchainVersion"); const QLatin1String CPP_ANDROID_TOOLCHAIN_HOST("cpp.androidToolchainHost"); const QLatin1String CPP_ANDROID_TOOLCHAIN_PREFIX("cpp.androidToolchainPrefix"); const QLatin1String CPP_ANDROID_GDBSERVER("cpp.androidGdbServer"); bool AndroidQBSPropertyProvider::canHandle(const ProjectExplorer::Kit *kit) const { return AndroidGdbServerKitInformation::isAndroidKit(kit); } QVariantMap AndroidQBSPropertyProvider::properties(const ProjectExplorer::Kit *kit, const QVariantMap &defaultData) const { Q_ASSERT(AndroidGdbServerKitInformation::isAndroidKit(kit)); QVariantMap qbsProperties = defaultData; QStringList targetOSs(defaultData[QLatin1String(QbsProjectManager::Constants::QBS_TARGETOS)].toStringList()); if (!targetOSs.contains(QLatin1String("android"))) qbsProperties[QLatin1String(QbsProjectManager::Constants::QBS_TARGETOS)] = QStringList() << QLatin1String("android") << targetOSs; const AndroidConfig &config = AndroidConfigurations::instance().config(); AndroidToolChain *tc = static_cast<AndroidToolChain*>(ProjectExplorer::ToolChainKitInformation::toolChain(kit)); qbsProperties[CPP_ANDROID_SDK_PATH] = config.sdkLocation.toString(); qbsProperties[CPP_ANDROID_NDK_PATH] = config.ndkLocation.toString(); qbsProperties[CPP_ANDROID_TOOLCHAIN_VERSION] = tc->ndkToolChainVersion(); qbsProperties[CPP_ANDROID_TOOLCHAIN_HOST] = config.toolchainHost; qbsProperties[CPP_ANDROID_TOOLCHAIN_PREFIX] = AndroidConfigurations::toolchainPrefix(tc->targetAbi().architecture()); qbsProperties[CPP_ANDROID_GDBSERVER] = tc->suggestedGdbServer().toString(); #warning TODO: Find a way to extract ANDROID_ARCHITECTURE from Qt mkspec // qbsProperties[QbsProjectManager::Constants::QBS_ARCHITECTURE] = ... return qbsProperties; } } // namespace Internal } // namespace Android <commit_msg>Android: Do not use #warning<commit_after>/************************************************************************** ** ** Copyright (c) 2013 BogDan Vatra <bog_dan_ro@yahoo.com> ** 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 "androidqbspropertyprovider.h" #include "androidconfigurations.h" #include "androidconstants.h" #include "androidgdbserverkitinformation.h" #include "androidtoolchain.h" #include <qbsprojectmanager/qbsconstants.h> namespace Android { namespace Internal { // QBS Android specific settings: const QLatin1String CPP_ANDROID_SDK_PATH("cpp.androidSdkPath"); const QLatin1String CPP_ANDROID_NDK_PATH("cpp.androidNdkPath"); const QLatin1String CPP_ANDROID_TOOLCHAIN_VERSION("cpp.androidToolchainVersion"); const QLatin1String CPP_ANDROID_TOOLCHAIN_HOST("cpp.androidToolchainHost"); const QLatin1String CPP_ANDROID_TOOLCHAIN_PREFIX("cpp.androidToolchainPrefix"); const QLatin1String CPP_ANDROID_GDBSERVER("cpp.androidGdbServer"); bool AndroidQBSPropertyProvider::canHandle(const ProjectExplorer::Kit *kit) const { return AndroidGdbServerKitInformation::isAndroidKit(kit); } QVariantMap AndroidQBSPropertyProvider::properties(const ProjectExplorer::Kit *kit, const QVariantMap &defaultData) const { Q_ASSERT(AndroidGdbServerKitInformation::isAndroidKit(kit)); QVariantMap qbsProperties = defaultData; QStringList targetOSs(defaultData[QLatin1String(QbsProjectManager::Constants::QBS_TARGETOS)].toStringList()); if (!targetOSs.contains(QLatin1String("android"))) qbsProperties[QLatin1String(QbsProjectManager::Constants::QBS_TARGETOS)] = QStringList() << QLatin1String("android") << targetOSs; const AndroidConfig &config = AndroidConfigurations::instance().config(); AndroidToolChain *tc = static_cast<AndroidToolChain*>(ProjectExplorer::ToolChainKitInformation::toolChain(kit)); qbsProperties[CPP_ANDROID_SDK_PATH] = config.sdkLocation.toString(); qbsProperties[CPP_ANDROID_NDK_PATH] = config.ndkLocation.toString(); qbsProperties[CPP_ANDROID_TOOLCHAIN_VERSION] = tc->ndkToolChainVersion(); qbsProperties[CPP_ANDROID_TOOLCHAIN_HOST] = config.toolchainHost; qbsProperties[CPP_ANDROID_TOOLCHAIN_PREFIX] = AndroidConfigurations::toolchainPrefix(tc->targetAbi().architecture()); qbsProperties[CPP_ANDROID_GDBSERVER] = tc->suggestedGdbServer().toString(); // TODO: Find a way to extract ANDROID_ARCHITECTURE from Qt mkspec // qbsProperties[QbsProjectManager::Constants::QBS_ARCHITECTURE] = ... return qbsProperties; } } // namespace Internal } // namespace Android <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qmlprofilerviewmanager.h" #include "qmlprofilertraceview.h" #include "qmlprofilereventview.h" #include "qmlprofilertool.h" #include "qmlprofilerstatemanager.h" #include "qmlprofilermodelmanager.h" #include "qmlprofilerstatewidget.h" #include "qv8profilereventview.h" #include <utils/qtcassert.h> #include <utils/fancymainwindow.h> #include <analyzerbase/analyzermanager.h> #include <QDockWidget> using namespace Analyzer; namespace QmlProfiler { namespace Internal { class QmlProfilerViewManager::QmlProfilerViewManagerPrivate { public: QmlProfilerViewManagerPrivate(QmlProfilerViewManager *qq) { Q_UNUSED(qq); } QmlProfilerTraceView *traceView; QmlProfilerEventsWidget *eventsView; QV8ProfilerEventsWidget *v8profilerView; QmlProfilerStateManager *profilerState; QmlProfilerModelManager *profilerModelManager; QmlProfilerTool *profilerTool; }; QmlProfilerViewManager::QmlProfilerViewManager(QObject *parent, QmlProfilerTool *profilerTool, QmlProfilerModelManager *modelManager, QmlProfilerStateManager *profilerState) : QObject(parent), d(new QmlProfilerViewManagerPrivate(this)) { setObjectName(QLatin1String("QML Profiler View Manager")); d->traceView = 0; d->eventsView = 0; d->v8profilerView = 0; d->profilerState = profilerState; d->profilerModelManager = modelManager; d->profilerTool = profilerTool; createViews(); } QmlProfilerViewManager::~QmlProfilerViewManager() { delete d; } //////////////////////////////////////////////////////////// // Views void QmlProfilerViewManager::createViews() { QTC_ASSERT(d->profilerModelManager, return); QTC_ASSERT(d->profilerState, return); Utils::FancyMainWindow *mw = AnalyzerManager::mainWindow(); d->traceView = new QmlProfilerTraceView(mw, d->profilerTool, this, d->profilerModelManager, d->profilerState); connect(d->traceView, SIGNAL(gotoSourceLocation(QString,int,int)), this, SIGNAL(gotoSourceLocation(QString,int,int))); d->traceView->reset(); d->eventsView = new QmlProfilerEventsWidget(mw, d->profilerTool, this, d->profilerModelManager); connect(d->eventsView, SIGNAL(gotoSourceLocation(QString,int,int)), this, SIGNAL(gotoSourceLocation(QString,int,int))); connect(d->eventsView, SIGNAL(eventSelectedByHash(QString)), d->traceView, SLOT(selectNextEventByHash(QString))); connect(d->traceView, SIGNAL(gotoSourceLocation(QString,int,int)), d->eventsView, SLOT(selectBySourceLocation(QString,int,int))); d->v8profilerView = new QV8ProfilerEventsWidget(mw, d->profilerTool, this, d->profilerModelManager); connect(d->traceView, SIGNAL(gotoSourceLocation(QString,int,int)), d->v8profilerView, SLOT(selectBySourceLocation(QString,int,int))); connect(d->v8profilerView, SIGNAL(gotoSourceLocation(QString,int,int)), d->traceView, SLOT(selectNextEventByLocation(QString,int,int))); connect(d->v8profilerView, SIGNAL(gotoSourceLocation(QString,int,int)), d->eventsView, SLOT(selectBySourceLocation(QString,int,int))); connect(d->eventsView, SIGNAL(gotoSourceLocation(QString,int,int)), d->v8profilerView, SLOT(selectBySourceLocation(QString,int,int))); QDockWidget *eventsDock = AnalyzerManager::createDockWidget (d->profilerTool, tr("Events"), d->eventsView, Qt::BottomDockWidgetArea); QDockWidget *timelineDock = AnalyzerManager::createDockWidget (d->profilerTool, tr("Timeline"), d->traceView, Qt::BottomDockWidgetArea); QDockWidget *v8profilerDock = AnalyzerManager::createDockWidget( d->profilerTool, tr("JavaScript"), d->v8profilerView, Qt::BottomDockWidgetArea); eventsDock->show(); timelineDock->show(); v8profilerDock->show(); mw->splitDockWidget(mw->toolBarDockWidget(), timelineDock, Qt::Vertical); mw->tabifyDockWidget(timelineDock, eventsDock); mw->tabifyDockWidget(eventsDock, v8profilerDock); new QmlProfilerStateWidget(d->profilerState, d->profilerModelManager, d->eventsView); new QmlProfilerStateWidget(d->profilerState, d->profilerModelManager, d->traceView); new QmlProfilerStateWidget(d->profilerState, d->profilerModelManager, d->v8profilerView); } bool QmlProfilerViewManager::hasValidSelection() const { return d->traceView->hasValidSelection(); } qint64 QmlProfilerViewManager::selectionStart() const { return d->traceView->selectionStart(); } qint64 QmlProfilerViewManager::selectionEnd() const { return d->traceView->selectionEnd(); } bool QmlProfilerViewManager::hasGlobalStats() const { return d->eventsView->hasGlobalStats(); } void QmlProfilerViewManager::getStatisticsInRange(qint64 rangeStart, qint64 rangeEnd) { d->eventsView->getStatisticsInRange(rangeStart, rangeEnd); } void QmlProfilerViewManager::clear() { d->traceView->clearDisplay(); d->eventsView->clear(); d->v8profilerView->clear(); } } // namespace Internal } // namespace QmlProfiler <commit_msg>QmlProfiler: send gotoSourceLocation also from JS profiler<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qmlprofilerviewmanager.h" #include "qmlprofilertraceview.h" #include "qmlprofilereventview.h" #include "qmlprofilertool.h" #include "qmlprofilerstatemanager.h" #include "qmlprofilermodelmanager.h" #include "qmlprofilerstatewidget.h" #include "qv8profilereventview.h" #include <utils/qtcassert.h> #include <utils/fancymainwindow.h> #include <analyzerbase/analyzermanager.h> #include <QDockWidget> using namespace Analyzer; namespace QmlProfiler { namespace Internal { class QmlProfilerViewManager::QmlProfilerViewManagerPrivate { public: QmlProfilerViewManagerPrivate(QmlProfilerViewManager *qq) { Q_UNUSED(qq); } QmlProfilerTraceView *traceView; QmlProfilerEventsWidget *eventsView; QV8ProfilerEventsWidget *v8profilerView; QmlProfilerStateManager *profilerState; QmlProfilerModelManager *profilerModelManager; QmlProfilerTool *profilerTool; }; QmlProfilerViewManager::QmlProfilerViewManager(QObject *parent, QmlProfilerTool *profilerTool, QmlProfilerModelManager *modelManager, QmlProfilerStateManager *profilerState) : QObject(parent), d(new QmlProfilerViewManagerPrivate(this)) { setObjectName(QLatin1String("QML Profiler View Manager")); d->traceView = 0; d->eventsView = 0; d->v8profilerView = 0; d->profilerState = profilerState; d->profilerModelManager = modelManager; d->profilerTool = profilerTool; createViews(); } QmlProfilerViewManager::~QmlProfilerViewManager() { delete d; } //////////////////////////////////////////////////////////// // Views void QmlProfilerViewManager::createViews() { QTC_ASSERT(d->profilerModelManager, return); QTC_ASSERT(d->profilerState, return); Utils::FancyMainWindow *mw = AnalyzerManager::mainWindow(); d->traceView = new QmlProfilerTraceView(mw, d->profilerTool, this, d->profilerModelManager, d->profilerState); connect(d->traceView, SIGNAL(gotoSourceLocation(QString,int,int)), this, SIGNAL(gotoSourceLocation(QString,int,int))); d->traceView->reset(); d->eventsView = new QmlProfilerEventsWidget(mw, d->profilerTool, this, d->profilerModelManager); connect(d->eventsView, SIGNAL(gotoSourceLocation(QString,int,int)), this, SIGNAL(gotoSourceLocation(QString,int,int))); connect(d->eventsView, SIGNAL(eventSelectedByHash(QString)), d->traceView, SLOT(selectNextEventByHash(QString))); connect(d->traceView, SIGNAL(gotoSourceLocation(QString,int,int)), d->eventsView, SLOT(selectBySourceLocation(QString,int,int))); d->v8profilerView = new QV8ProfilerEventsWidget(mw, d->profilerTool, this, d->profilerModelManager); connect(d->v8profilerView, SIGNAL(gotoSourceLocation(QString,int,int)), this, SIGNAL(gotoSourceLocation(QString,int,int))); connect(d->traceView, SIGNAL(gotoSourceLocation(QString,int,int)), d->v8profilerView, SLOT(selectBySourceLocation(QString,int,int))); connect(d->v8profilerView, SIGNAL(gotoSourceLocation(QString,int,int)), d->traceView, SLOT(selectNextEventByLocation(QString,int,int))); connect(d->v8profilerView, SIGNAL(gotoSourceLocation(QString,int,int)), d->eventsView, SLOT(selectBySourceLocation(QString,int,int))); connect(d->eventsView, SIGNAL(gotoSourceLocation(QString,int,int)), d->v8profilerView, SLOT(selectBySourceLocation(QString,int,int))); QDockWidget *eventsDock = AnalyzerManager::createDockWidget (d->profilerTool, tr("Events"), d->eventsView, Qt::BottomDockWidgetArea); QDockWidget *timelineDock = AnalyzerManager::createDockWidget (d->profilerTool, tr("Timeline"), d->traceView, Qt::BottomDockWidgetArea); QDockWidget *v8profilerDock = AnalyzerManager::createDockWidget( d->profilerTool, tr("JavaScript"), d->v8profilerView, Qt::BottomDockWidgetArea); eventsDock->show(); timelineDock->show(); v8profilerDock->show(); mw->splitDockWidget(mw->toolBarDockWidget(), timelineDock, Qt::Vertical); mw->tabifyDockWidget(timelineDock, eventsDock); mw->tabifyDockWidget(eventsDock, v8profilerDock); new QmlProfilerStateWidget(d->profilerState, d->profilerModelManager, d->eventsView); new QmlProfilerStateWidget(d->profilerState, d->profilerModelManager, d->traceView); new QmlProfilerStateWidget(d->profilerState, d->profilerModelManager, d->v8profilerView); } bool QmlProfilerViewManager::hasValidSelection() const { return d->traceView->hasValidSelection(); } qint64 QmlProfilerViewManager::selectionStart() const { return d->traceView->selectionStart(); } qint64 QmlProfilerViewManager::selectionEnd() const { return d->traceView->selectionEnd(); } bool QmlProfilerViewManager::hasGlobalStats() const { return d->eventsView->hasGlobalStats(); } void QmlProfilerViewManager::getStatisticsInRange(qint64 rangeStart, qint64 rangeEnd) { d->eventsView->getStatisticsInRange(rangeStart, rangeEnd); } void QmlProfilerViewManager::clear() { d->traceView->clearDisplay(); d->eventsView->clear(); d->v8profilerView->clear(); } } // namespace Internal } // namespace QmlProfiler <|endoftext|>
<commit_before>/************************************************************************** ** ** Copyright (C) 2011 - 2013 Research In Motion ** ** Contact: Research In Motion (blackberry-qt@qnx.com) ** Contact: KDAB (info@kdab.com) ** ** 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 "blackberryconfigurationmanager.h" #include "blackberrycertificate.h" #include "blackberryconfiguration.h" #include "qnxutils.h" #include <coreplugin/icore.h> #include <utils/persistentsettings.h> #include <utils/hostosinfo.h> #include <projectexplorer/kit.h> #include <projectexplorer/kitmanager.h> #include <projectexplorer/kitinformation.h> #include <projectexplorer/toolchainmanager.h> #include <qtsupport/qtversionmanager.h> #include <qtsupport/qtkitinformation.h> #include <QMessageBox> #include <QFileInfo> using namespace ProjectExplorer; namespace Qnx { namespace Internal { namespace { const QLatin1String SettingsGroup("BlackBerryConfiguration"); const QLatin1String NDKLocationKey("NDKLocation"); // For 10.1 NDK support (< QTC 3.0) const QLatin1String NDKEnvFileKey("NDKEnvFile"); const QLatin1String CertificateGroup("Certificates"); const QLatin1String ManualNDKsGroup("ManualNDKs"); const QLatin1String ActiveNDKsGroup("ActiveNDKs"); } BlackBerryConfigurationManager::BlackBerryConfigurationManager(QObject *parent) :QObject(parent) { connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()), this, SLOT(saveSettings())); } void BlackBerryConfigurationManager::loadCertificates() { QSettings *settings = Core::ICore::settings(); settings->beginGroup(SettingsGroup); settings->beginGroup(CertificateGroup); foreach (const QString &certificateId, settings->childGroups()) { settings->beginGroup(certificateId); BlackBerryCertificate *cert = new BlackBerryCertificate(settings->value(QLatin1String(Qnx::Constants::QNX_KEY_PATH)).toString(), settings->value(QLatin1String(Qnx::Constants::QNX_KEY_AUTHOR)).toString()); cert->setParent(this); if (settings->value(QLatin1String(Qnx::Constants::QNX_KEY_ACTIVE)).toBool()) m_activeCertificate = cert; m_certificates << cert; settings->endGroup(); } settings->endGroup(); settings->endGroup(); } void BlackBerryConfigurationManager::loadManualConfigurations() { QSettings *settings = Core::ICore::settings(); settings->beginGroup(SettingsGroup); settings->beginGroup(ManualNDKsGroup); foreach (const QString &manualNdk, settings->childGroups()) { settings->beginGroup(manualNdk); QString ndkEnvPath = settings->value(NDKEnvFileKey).toString(); // For 10.1 NDK support (< QTC 3.0): // Since QTC 3.0 BBConfigurations are based on the bbndk-env file // to support multiple targets per NDK if (ndkEnvPath.isEmpty()) { QString ndkPath = settings->value(NDKLocationKey).toString(); ndkEnvPath = QnxUtils::envFilePath(ndkPath); } BlackBerryConfiguration *config = new BlackBerryConfiguration(Utils::FileName::fromString(ndkEnvPath), false); if (!addConfiguration(config)) delete config; settings->endGroup(); } settings->endGroup(); settings->endGroup(); } void BlackBerryConfigurationManager::loadAutoDetectedConfigurations() { QStringList activePaths = activeConfigurationNdkEnvPaths(); foreach (const NdkInstallInformation &ndkInfo, QnxUtils::installedNdks()) { QString envFilePath = QnxUtils::envFilePath(ndkInfo.path, ndkInfo.version); BlackBerryConfiguration *config = new BlackBerryConfiguration(Utils::FileName::fromString(envFilePath), true, ndkInfo.name); if (!addConfiguration(config)) { delete config; continue; } // Activate targets foreach (const QString activeNdkEnvPath, activePaths) { if (config->ndkEnvFile().toString() == activeNdkEnvPath) config->activate(); } } // If no target was/is activated, activate one since it's needed by // device connection and CSK code. if (activeConfigurations().isEmpty()) m_configs.first()->activate(); } QStringList BlackBerryConfigurationManager::activeConfigurationNdkEnvPaths() { QStringList actives; QSettings *settings = Core::ICore::settings(); settings->beginGroup(SettingsGroup); settings->beginGroup(ActiveNDKsGroup); foreach (const QString &activeNdkEnvPath, settings->childGroups()) { settings->beginGroup(activeNdkEnvPath); actives.append(settings->value(NDKEnvFileKey).toString()); settings->endGroup(); } settings->endGroup(); settings->endGroup(); return actives; } void BlackBerryConfigurationManager::saveCertificates() { QSettings *settings = Core::ICore::settings(); settings->beginGroup(SettingsGroup); settings->beginGroup(CertificateGroup); settings->remove(QString()); foreach (const BlackBerryCertificate *cert, m_certificates) { settings->beginGroup(cert->id()); settings->setValue(QLatin1String(Qnx::Constants::QNX_KEY_PATH), cert->fileName()); settings->setValue(QLatin1String(Qnx::Constants::QNX_KEY_AUTHOR), cert->author()); if (cert == m_activeCertificate) settings->setValue(QLatin1String(Qnx::Constants::QNX_KEY_ACTIVE), true); settings->endGroup(); } settings->endGroup(); settings->endGroup(); } void BlackBerryConfigurationManager::saveManualConfigurations() { if (manualConfigurations().isEmpty()) return; QSettings *settings = Core::ICore::settings(); settings->beginGroup(SettingsGroup); settings->beginGroup(ManualNDKsGroup); foreach (BlackBerryConfiguration *config, manualConfigurations()) { settings->beginGroup(config->displayName()); settings->setValue(NDKEnvFileKey, config->ndkEnvFile().toString()); settings->endGroup(); } settings->endGroup(); settings->endGroup(); } void BlackBerryConfigurationManager::saveActiveConfigurationNdkEnvPath() { if (activeConfigurations().isEmpty()) return; QSettings *settings = Core::ICore::settings(); settings->beginGroup(SettingsGroup); settings->beginGroup(ActiveNDKsGroup); settings->clear(); foreach (BlackBerryConfiguration *config, activeConfigurations()) { settings->beginGroup(config->displayName()); settings->setValue(NDKEnvFileKey, config->ndkEnvFile().toString()); settings->endGroup(); } settings->endGroup(); settings->endGroup(); } // Remove no longer available/valid 'auto detected' BlackBerry kits and qt versions void BlackBerryConfigurationManager::clearInvalidConfigurations() { // Deregister invalid auto deteted BlackBerry Kits foreach (ProjectExplorer::Kit *kit, ProjectExplorer::KitManager::instance()->kits()) { if (!kit->isAutoDetected()) continue; if (ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(kit) == Constants::QNX_BB_OS_TYPE && !kit->isValid()) ProjectExplorer::KitManager::instance()->deregisterKit(kit); } // Remove invalid auto detected BlackBerry qtVerions foreach (QtSupport::BaseQtVersion *qtVersion, QtSupport::QtVersionManager::versions()) { if (!qtVersion->isAutodetected()) continue; if (qtVersion->platformName() == QLatin1String(Constants::QNX_BB_PLATFORM_NAME) && !qtVersion->isValid()) QtSupport::QtVersionManager::removeVersion(qtVersion); } } bool BlackBerryConfigurationManager::addConfiguration(BlackBerryConfiguration *config) { foreach (BlackBerryConfiguration *c, m_configs) { if (c->ndkPath() == config->ndkPath() && c->targetName() == config->targetName()) { if (!config->isAutoDetected()) QMessageBox::warning(0, tr("NDK Already known"), tr("The NDK already has a configuration."), QMessageBox::Ok); return false; } } if (config->isValid()) { m_configs.append(config); return true; } return false; } void BlackBerryConfigurationManager::removeConfiguration(BlackBerryConfiguration *config) { if (!config) return; if (config->isActive()) config->deactivate(); clearConfigurationSettings(config); m_configs.removeAt(m_configs.indexOf(config)); delete config; } QList<BlackBerryConfiguration *> BlackBerryConfigurationManager::configurations() const { return m_configs; } QList<BlackBerryConfiguration *> BlackBerryConfigurationManager::manualConfigurations() const { QList<BlackBerryConfiguration*> manuals; foreach (BlackBerryConfiguration *config, m_configs) { if (!config->isAutoDetected()) manuals << config; } return manuals; } QList<BlackBerryConfiguration *> BlackBerryConfigurationManager::activeConfigurations() const { QList<BlackBerryConfiguration*> actives; foreach (BlackBerryConfiguration *config, m_configs) { if (config->isActive()) actives << config; } return actives; } BlackBerryConfiguration *BlackBerryConfigurationManager::configurationFromEnvFile(const Utils::FileName &envFile) const { foreach (BlackBerryConfiguration *config, m_configs) { if (config->ndkEnvFile() == envFile) return config; } return 0; } void BlackBerryConfigurationManager::syncCertificates(QList<BlackBerryCertificate*> certificates, BlackBerryCertificate *activeCertificate) { m_activeCertificate = activeCertificate; foreach (BlackBerryCertificate *cert, certificates) { if (!certificates.contains(cert)) removeCertificate(cert); } foreach (BlackBerryCertificate *cert, certificates) addCertificate(cert); } void BlackBerryConfigurationManager::addCertificate(BlackBerryCertificate *certificate) { if (m_certificates.contains(certificate)) return; if (m_certificates.isEmpty()) m_activeCertificate = certificate; certificate->setParent(this); m_certificates << certificate; } void BlackBerryConfigurationManager::removeCertificate(BlackBerryCertificate *certificate) { if (m_activeCertificate == certificate) m_activeCertificate = 0; m_certificates.removeAll(certificate); delete certificate; } QList<BlackBerryCertificate*> BlackBerryConfigurationManager::certificates() const { return m_certificates; } BlackBerryCertificate * BlackBerryConfigurationManager::activeCertificate() { return m_activeCertificate; } // Returns a valid qnxEnv map from a valid configuration; // Needed by other classes to get blackberry process path (keys registration, debug token...) QMultiMap<QString, QString> BlackBerryConfigurationManager::defaultQnxEnv() { foreach (BlackBerryConfiguration *config, m_configs) { if (config->isActive() && !config->qnxEnv().isEmpty()) return config->qnxEnv(); } return QMultiMap<QString, QString>(); } void BlackBerryConfigurationManager::loadSettings() { clearInvalidConfigurations(); loadAutoDetectedConfigurations(); loadManualConfigurations(); loadCertificates(); emit settingsLoaded(); } void BlackBerryConfigurationManager::clearConfigurationSettings(BlackBerryConfiguration *config) { if (!config) return; QSettings *settings = Core::ICore::settings(); settings->beginGroup(SettingsGroup); settings->beginGroup(ManualNDKsGroup); foreach (const QString &manualNdk, settings->childGroups()) { if (manualNdk == config->displayName()) { settings->remove(manualNdk); break; } } settings->endGroup(); settings->endGroup(); } void BlackBerryConfigurationManager::saveSettings() { saveActiveConfigurationNdkEnvPath(); saveManualConfigurations(); saveCertificates(); } BlackBerryConfigurationManager &BlackBerryConfigurationManager::instance() { if (m_instance == 0) m_instance = new BlackBerryConfigurationManager(); return *m_instance; } BlackBerryConfigurationManager::~BlackBerryConfigurationManager() { qDeleteAll(m_configs); } QString BlackBerryConfigurationManager::barsignerCskPath() const { return QnxUtils::dataDirPath() + QLatin1String("/barsigner.csk"); } QString BlackBerryConfigurationManager::barsignerDbPath() const { return QnxUtils::dataDirPath() + QLatin1String("/barsigner.db"); } QString BlackBerryConfigurationManager::defaultKeystorePath() const { return QnxUtils::dataDirPath() + QLatin1String("/author.p12"); } QString BlackBerryConfigurationManager::defaultDebugTokenPath() const { return QnxUtils::dataDirPath() + QLatin1String("/debugtoken.bar"); } BlackBerryConfigurationManager* BlackBerryConfigurationManager::m_instance = 0; } // namespace Internal } // namespace Qnx <commit_msg>Qnx: Don't crash on startup.<commit_after>/************************************************************************** ** ** Copyright (C) 2011 - 2013 Research In Motion ** ** Contact: Research In Motion (blackberry-qt@qnx.com) ** Contact: KDAB (info@kdab.com) ** ** 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 "blackberryconfigurationmanager.h" #include "blackberrycertificate.h" #include "blackberryconfiguration.h" #include "qnxutils.h" #include <coreplugin/icore.h> #include <utils/persistentsettings.h> #include <utils/hostosinfo.h> #include <projectexplorer/kit.h> #include <projectexplorer/kitmanager.h> #include <projectexplorer/kitinformation.h> #include <projectexplorer/toolchainmanager.h> #include <qtsupport/qtversionmanager.h> #include <qtsupport/qtkitinformation.h> #include <QMessageBox> #include <QFileInfo> using namespace ProjectExplorer; namespace Qnx { namespace Internal { namespace { const QLatin1String SettingsGroup("BlackBerryConfiguration"); const QLatin1String NDKLocationKey("NDKLocation"); // For 10.1 NDK support (< QTC 3.0) const QLatin1String NDKEnvFileKey("NDKEnvFile"); const QLatin1String CertificateGroup("Certificates"); const QLatin1String ManualNDKsGroup("ManualNDKs"); const QLatin1String ActiveNDKsGroup("ActiveNDKs"); } BlackBerryConfigurationManager::BlackBerryConfigurationManager(QObject *parent) :QObject(parent) { connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()), this, SLOT(saveSettings())); } void BlackBerryConfigurationManager::loadCertificates() { QSettings *settings = Core::ICore::settings(); settings->beginGroup(SettingsGroup); settings->beginGroup(CertificateGroup); foreach (const QString &certificateId, settings->childGroups()) { settings->beginGroup(certificateId); BlackBerryCertificate *cert = new BlackBerryCertificate(settings->value(QLatin1String(Qnx::Constants::QNX_KEY_PATH)).toString(), settings->value(QLatin1String(Qnx::Constants::QNX_KEY_AUTHOR)).toString()); cert->setParent(this); if (settings->value(QLatin1String(Qnx::Constants::QNX_KEY_ACTIVE)).toBool()) m_activeCertificate = cert; m_certificates << cert; settings->endGroup(); } settings->endGroup(); settings->endGroup(); } void BlackBerryConfigurationManager::loadManualConfigurations() { QSettings *settings = Core::ICore::settings(); settings->beginGroup(SettingsGroup); settings->beginGroup(ManualNDKsGroup); foreach (const QString &manualNdk, settings->childGroups()) { settings->beginGroup(manualNdk); QString ndkEnvPath = settings->value(NDKEnvFileKey).toString(); // For 10.1 NDK support (< QTC 3.0): // Since QTC 3.0 BBConfigurations are based on the bbndk-env file // to support multiple targets per NDK if (ndkEnvPath.isEmpty()) { QString ndkPath = settings->value(NDKLocationKey).toString(); ndkEnvPath = QnxUtils::envFilePath(ndkPath); } BlackBerryConfiguration *config = new BlackBerryConfiguration(Utils::FileName::fromString(ndkEnvPath), false); if (!addConfiguration(config)) delete config; settings->endGroup(); } settings->endGroup(); settings->endGroup(); } void BlackBerryConfigurationManager::loadAutoDetectedConfigurations() { QStringList activePaths = activeConfigurationNdkEnvPaths(); foreach (const NdkInstallInformation &ndkInfo, QnxUtils::installedNdks()) { QString envFilePath = QnxUtils::envFilePath(ndkInfo.path, ndkInfo.version); BlackBerryConfiguration *config = new BlackBerryConfiguration(Utils::FileName::fromString(envFilePath), true, ndkInfo.name); if (!addConfiguration(config)) { delete config; continue; } // Activate targets foreach (const QString activeNdkEnvPath, activePaths) { if (config->ndkEnvFile().toString() == activeNdkEnvPath) config->activate(); } } // If no target was/is activated, activate one since it's needed by // device connection and CSK code. if (activeConfigurations().isEmpty() && !m_configs.isEmpty()) m_configs.first()->activate(); } QStringList BlackBerryConfigurationManager::activeConfigurationNdkEnvPaths() { QStringList actives; QSettings *settings = Core::ICore::settings(); settings->beginGroup(SettingsGroup); settings->beginGroup(ActiveNDKsGroup); foreach (const QString &activeNdkEnvPath, settings->childGroups()) { settings->beginGroup(activeNdkEnvPath); actives.append(settings->value(NDKEnvFileKey).toString()); settings->endGroup(); } settings->endGroup(); settings->endGroup(); return actives; } void BlackBerryConfigurationManager::saveCertificates() { QSettings *settings = Core::ICore::settings(); settings->beginGroup(SettingsGroup); settings->beginGroup(CertificateGroup); settings->remove(QString()); foreach (const BlackBerryCertificate *cert, m_certificates) { settings->beginGroup(cert->id()); settings->setValue(QLatin1String(Qnx::Constants::QNX_KEY_PATH), cert->fileName()); settings->setValue(QLatin1String(Qnx::Constants::QNX_KEY_AUTHOR), cert->author()); if (cert == m_activeCertificate) settings->setValue(QLatin1String(Qnx::Constants::QNX_KEY_ACTIVE), true); settings->endGroup(); } settings->endGroup(); settings->endGroup(); } void BlackBerryConfigurationManager::saveManualConfigurations() { if (manualConfigurations().isEmpty()) return; QSettings *settings = Core::ICore::settings(); settings->beginGroup(SettingsGroup); settings->beginGroup(ManualNDKsGroup); foreach (BlackBerryConfiguration *config, manualConfigurations()) { settings->beginGroup(config->displayName()); settings->setValue(NDKEnvFileKey, config->ndkEnvFile().toString()); settings->endGroup(); } settings->endGroup(); settings->endGroup(); } void BlackBerryConfigurationManager::saveActiveConfigurationNdkEnvPath() { if (activeConfigurations().isEmpty()) return; QSettings *settings = Core::ICore::settings(); settings->beginGroup(SettingsGroup); settings->beginGroup(ActiveNDKsGroup); settings->clear(); foreach (BlackBerryConfiguration *config, activeConfigurations()) { settings->beginGroup(config->displayName()); settings->setValue(NDKEnvFileKey, config->ndkEnvFile().toString()); settings->endGroup(); } settings->endGroup(); settings->endGroup(); } // Remove no longer available/valid 'auto detected' BlackBerry kits and qt versions void BlackBerryConfigurationManager::clearInvalidConfigurations() { // Deregister invalid auto deteted BlackBerry Kits foreach (ProjectExplorer::Kit *kit, ProjectExplorer::KitManager::instance()->kits()) { if (!kit->isAutoDetected()) continue; if (ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(kit) == Constants::QNX_BB_OS_TYPE && !kit->isValid()) ProjectExplorer::KitManager::instance()->deregisterKit(kit); } // Remove invalid auto detected BlackBerry qtVerions foreach (QtSupport::BaseQtVersion *qtVersion, QtSupport::QtVersionManager::versions()) { if (!qtVersion->isAutodetected()) continue; if (qtVersion->platformName() == QLatin1String(Constants::QNX_BB_PLATFORM_NAME) && !qtVersion->isValid()) QtSupport::QtVersionManager::removeVersion(qtVersion); } } bool BlackBerryConfigurationManager::addConfiguration(BlackBerryConfiguration *config) { foreach (BlackBerryConfiguration *c, m_configs) { if (c->ndkPath() == config->ndkPath() && c->targetName() == config->targetName()) { if (!config->isAutoDetected()) QMessageBox::warning(0, tr("NDK Already known"), tr("The NDK already has a configuration."), QMessageBox::Ok); return false; } } if (config->isValid()) { m_configs.append(config); return true; } return false; } void BlackBerryConfigurationManager::removeConfiguration(BlackBerryConfiguration *config) { if (!config) return; if (config->isActive()) config->deactivate(); clearConfigurationSettings(config); m_configs.removeAt(m_configs.indexOf(config)); delete config; } QList<BlackBerryConfiguration *> BlackBerryConfigurationManager::configurations() const { return m_configs; } QList<BlackBerryConfiguration *> BlackBerryConfigurationManager::manualConfigurations() const { QList<BlackBerryConfiguration*> manuals; foreach (BlackBerryConfiguration *config, m_configs) { if (!config->isAutoDetected()) manuals << config; } return manuals; } QList<BlackBerryConfiguration *> BlackBerryConfigurationManager::activeConfigurations() const { QList<BlackBerryConfiguration*> actives; foreach (BlackBerryConfiguration *config, m_configs) { if (config->isActive()) actives << config; } return actives; } BlackBerryConfiguration *BlackBerryConfigurationManager::configurationFromEnvFile(const Utils::FileName &envFile) const { foreach (BlackBerryConfiguration *config, m_configs) { if (config->ndkEnvFile() == envFile) return config; } return 0; } void BlackBerryConfigurationManager::syncCertificates(QList<BlackBerryCertificate*> certificates, BlackBerryCertificate *activeCertificate) { m_activeCertificate = activeCertificate; foreach (BlackBerryCertificate *cert, certificates) { if (!certificates.contains(cert)) removeCertificate(cert); } foreach (BlackBerryCertificate *cert, certificates) addCertificate(cert); } void BlackBerryConfigurationManager::addCertificate(BlackBerryCertificate *certificate) { if (m_certificates.contains(certificate)) return; if (m_certificates.isEmpty()) m_activeCertificate = certificate; certificate->setParent(this); m_certificates << certificate; } void BlackBerryConfigurationManager::removeCertificate(BlackBerryCertificate *certificate) { if (m_activeCertificate == certificate) m_activeCertificate = 0; m_certificates.removeAll(certificate); delete certificate; } QList<BlackBerryCertificate*> BlackBerryConfigurationManager::certificates() const { return m_certificates; } BlackBerryCertificate * BlackBerryConfigurationManager::activeCertificate() { return m_activeCertificate; } // Returns a valid qnxEnv map from a valid configuration; // Needed by other classes to get blackberry process path (keys registration, debug token...) QMultiMap<QString, QString> BlackBerryConfigurationManager::defaultQnxEnv() { foreach (BlackBerryConfiguration *config, m_configs) { if (config->isActive() && !config->qnxEnv().isEmpty()) return config->qnxEnv(); } return QMultiMap<QString, QString>(); } void BlackBerryConfigurationManager::loadSettings() { clearInvalidConfigurations(); loadAutoDetectedConfigurations(); loadManualConfigurations(); loadCertificates(); emit settingsLoaded(); } void BlackBerryConfigurationManager::clearConfigurationSettings(BlackBerryConfiguration *config) { if (!config) return; QSettings *settings = Core::ICore::settings(); settings->beginGroup(SettingsGroup); settings->beginGroup(ManualNDKsGroup); foreach (const QString &manualNdk, settings->childGroups()) { if (manualNdk == config->displayName()) { settings->remove(manualNdk); break; } } settings->endGroup(); settings->endGroup(); } void BlackBerryConfigurationManager::saveSettings() { saveActiveConfigurationNdkEnvPath(); saveManualConfigurations(); saveCertificates(); } BlackBerryConfigurationManager &BlackBerryConfigurationManager::instance() { if (m_instance == 0) m_instance = new BlackBerryConfigurationManager(); return *m_instance; } BlackBerryConfigurationManager::~BlackBerryConfigurationManager() { qDeleteAll(m_configs); } QString BlackBerryConfigurationManager::barsignerCskPath() const { return QnxUtils::dataDirPath() + QLatin1String("/barsigner.csk"); } QString BlackBerryConfigurationManager::barsignerDbPath() const { return QnxUtils::dataDirPath() + QLatin1String("/barsigner.db"); } QString BlackBerryConfigurationManager::defaultKeystorePath() const { return QnxUtils::dataDirPath() + QLatin1String("/author.p12"); } QString BlackBerryConfigurationManager::defaultDebugTokenPath() const { return QnxUtils::dataDirPath() + QLatin1String("/debugtoken.bar"); } BlackBerryConfigurationManager* BlackBerryConfigurationManager::m_instance = 0; } // namespace Internal } // namespace Qnx <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #include "remotelinuxprocesslist.h" #include "linuxdeviceconfiguration.h" #include <utils/qtcassert.h> #include <utils/ssh/sshremoteprocessrunner.h> #include <QtCore/QByteArray> #include <QtCore/QString> using namespace Utils; namespace RemoteLinux { namespace Internal { namespace { enum State { Inactive, Listing, Killing }; const char Delimiter[] = "-----"; } // anonymous namespace class AbstractRemoteLinuxProcessListPrivate { public: AbstractRemoteLinuxProcessListPrivate(const LinuxDeviceConfiguration::ConstPtr &devConf) : deviceConfiguration(devConf), process(SshRemoteProcessRunner::create(devConf->sshParameters())), state(Inactive) { } const LinuxDeviceConfiguration::ConstPtr deviceConfiguration; const SshRemoteProcessRunner::Ptr process; QList<AbstractRemoteLinuxProcessList::RemoteProcess> remoteProcesses; QByteArray remoteStdout; QByteArray remoteStderr; QString errorMsg; State state; }; } // namespace Internal using namespace Internal; AbstractRemoteLinuxProcessList::AbstractRemoteLinuxProcessList(const LinuxDeviceConfiguration::ConstPtr &devConfig, QObject *parent) : QAbstractTableModel(parent), d(new AbstractRemoteLinuxProcessListPrivate(devConfig)) { } LinuxDeviceConfiguration::ConstPtr AbstractRemoteLinuxProcessList::deviceConfiguration() const { return d->deviceConfiguration; } AbstractRemoteLinuxProcessList::~AbstractRemoteLinuxProcessList() { delete d; } void AbstractRemoteLinuxProcessList::update() { QTC_ASSERT(d->state == Inactive, return); beginResetModel(); d->remoteProcesses.clear(); d->state = Listing; startProcess(listProcessesCommandLine()); } void AbstractRemoteLinuxProcessList::killProcess(int row) { QTC_ASSERT(row >= 0 && row < d->remoteProcesses.count(), return); QTC_ASSERT(d->state == Inactive, return); d->state = Killing; startProcess(killProcessCommandLine(d->remoteProcesses.at(row))); } int AbstractRemoteLinuxProcessList::pidAt(int row) const { return d->remoteProcesses.at(row).pid; } int AbstractRemoteLinuxProcessList::rowCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : d->remoteProcesses.count(); } int AbstractRemoteLinuxProcessList::columnCount(const QModelIndex &) const { return 2; } QVariant AbstractRemoteLinuxProcessList::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation != Qt::Horizontal || role != Qt::DisplayRole || section < 0 || section >= columnCount()) return QVariant(); return section == 0? tr("PID") : tr("Command Line"); } QVariant AbstractRemoteLinuxProcessList::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= rowCount(index.parent()) || index.column() >= columnCount() || role != Qt::DisplayRole) return QVariant(); const RemoteProcess &proc = d->remoteProcesses.at(index.row()); if (index.column() == 0) return proc.pid; else return proc.cmdLine; } void AbstractRemoteLinuxProcessList::handleRemoteStdOut(const QByteArray &output) { if (d->state == Listing) d->remoteStdout += output; } void AbstractRemoteLinuxProcessList::handleRemoteStdErr(const QByteArray &output) { if (d->state != Inactive) d->remoteStderr += output; } void AbstractRemoteLinuxProcessList::handleConnectionError() { QTC_ASSERT(d->state != Inactive, return); emit error(tr("Connection failure: %1").arg(d->process->connection()->errorString())); beginResetModel(); d->remoteProcesses.clear(); endResetModel(); setFinished(); } void AbstractRemoteLinuxProcessList::handleRemoteProcessFinished(int exitStatus) { QTC_ASSERT(d->state != Inactive, return); switch (exitStatus) { case SshRemoteProcess::FailedToStart: d->errorMsg = tr("Error: Remote process failed to start: %1") .arg(d->process->process()->errorString()); break; case SshRemoteProcess::KilledBySignal: d->errorMsg = tr("Error: Remote process crashed: %1") .arg(d->process->process()->errorString()); break; case SshRemoteProcess::ExitedNormally: if (d->process->process()->exitCode() == 0) { if (d->state == Listing) d->remoteProcesses = buildProcessList(QString::fromUtf8(d->remoteStdout)); } else { d->errorMsg = tr("Remote process failed."); } break; default: Q_ASSERT_X(false, Q_FUNC_INFO, "Invalid exit status"); } if (!d->errorMsg.isEmpty()) { if (!d->remoteStderr.isEmpty()) d->errorMsg += tr("\nRemote stderr was: %1").arg(QString::fromUtf8(d->remoteStderr)); emit error(d->errorMsg); } else if (d->state == Killing) { emit processKilled(); } if (d->state == Listing) endResetModel(); setFinished(); } void AbstractRemoteLinuxProcessList::startProcess(const QString &cmdLine) { connect(d->process.data(), SIGNAL(connectionError(Utils::SshError)), SLOT(handleConnectionError())); connect(d->process.data(), SIGNAL(processOutputAvailable(QByteArray)), SLOT(handleRemoteStdOut(QByteArray))); connect(d->process.data(), SIGNAL(processErrorOutputAvailable(QByteArray)), SLOT(handleRemoteStdErr(QByteArray))); connect(d->process.data(), SIGNAL(processClosed(int)), SLOT(handleRemoteProcessFinished(int))); d->remoteStdout.clear(); d->remoteStderr.clear(); d->errorMsg.clear(); d->process->run(cmdLine.toUtf8()); } void AbstractRemoteLinuxProcessList::setFinished() { disconnect(d->process.data(), 0, this, 0); d->state = Inactive; } GenericRemoteLinuxProcessList::GenericRemoteLinuxProcessList(const LinuxDeviceConfiguration::ConstPtr &devConfig, QObject *parent) : AbstractRemoteLinuxProcessList(devConfig, parent) { } QString GenericRemoteLinuxProcessList::listProcessesCommandLine() const { return QString::fromLocal8Bit("for dir in `ls -d /proc/[0123456789]*`; " "do echo $dir%1`cat $dir/cmdline`%1`cat $dir/stat`; done").arg(Delimiter); } QString GenericRemoteLinuxProcessList::killProcessCommandLine(const RemoteProcess &process) const { return QLatin1String("kill -9 ") + QString::number(process.pid); } QList<AbstractRemoteLinuxProcessList::RemoteProcess> GenericRemoteLinuxProcessList::buildProcessList(const QString &listProcessesReply) const { QList<RemoteProcess> processes; const QStringList &lines = listProcessesReply.split(QLatin1Char('\n')); foreach (const QString &line, lines) { const QStringList elements = line.split(QString::fromLocal8Bit(Delimiter)); if (elements.count() < 3) { qDebug("%s: Expected three list elements, got %d.", Q_FUNC_INFO, elements.count()); continue; } bool ok; const int pid = elements.first().mid(6).toInt(&ok); if (!ok) { qDebug("%s: Expected number in %s.", Q_FUNC_INFO, qPrintable(elements.first())); continue; } QString command = elements.at(1); if (command.isEmpty()) { const QString &statString = elements.at(2); const int openParenPos = statString.indexOf(QLatin1Char('(')); const int closedParenPos = statString.indexOf(QLatin1Char(')'), openParenPos); if (openParenPos == -1 || closedParenPos == -1) continue; command = QLatin1Char('[') + statString.mid(openParenPos + 1, closedParenPos - openParenPos - 1) + QLatin1Char(']'); } int insertPos; for (insertPos = 0; insertPos < processes.count(); ++insertPos) { if (pid < processes.at(insertPos).pid) break; } processes.insert(insertPos, RemoteProcess(pid, command)); } return processes; } } // namespace RemoteLinux <commit_msg>RemoteLinux: Fix remote processes listing.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #include "remotelinuxprocesslist.h" #include "linuxdeviceconfiguration.h" #include <utils/qtcassert.h> #include <utils/ssh/sshremoteprocessrunner.h> #include <QtCore/QByteArray> #include <QtCore/QString> using namespace Utils; namespace RemoteLinux { namespace Internal { namespace { enum State { Inactive, Listing, Killing }; const char Delimiter[] = "x-----"; } // anonymous namespace class AbstractRemoteLinuxProcessListPrivate { public: AbstractRemoteLinuxProcessListPrivate(const LinuxDeviceConfiguration::ConstPtr &devConf) : deviceConfiguration(devConf), process(SshRemoteProcessRunner::create(devConf->sshParameters())), state(Inactive) { } const LinuxDeviceConfiguration::ConstPtr deviceConfiguration; const SshRemoteProcessRunner::Ptr process; QList<AbstractRemoteLinuxProcessList::RemoteProcess> remoteProcesses; QByteArray remoteStdout; QByteArray remoteStderr; QString errorMsg; State state; }; } // namespace Internal using namespace Internal; AbstractRemoteLinuxProcessList::AbstractRemoteLinuxProcessList(const LinuxDeviceConfiguration::ConstPtr &devConfig, QObject *parent) : QAbstractTableModel(parent), d(new AbstractRemoteLinuxProcessListPrivate(devConfig)) { } LinuxDeviceConfiguration::ConstPtr AbstractRemoteLinuxProcessList::deviceConfiguration() const { return d->deviceConfiguration; } AbstractRemoteLinuxProcessList::~AbstractRemoteLinuxProcessList() { delete d; } void AbstractRemoteLinuxProcessList::update() { QTC_ASSERT(d->state == Inactive, return); beginResetModel(); d->remoteProcesses.clear(); d->state = Listing; startProcess(listProcessesCommandLine()); } void AbstractRemoteLinuxProcessList::killProcess(int row) { QTC_ASSERT(row >= 0 && row < d->remoteProcesses.count(), return); QTC_ASSERT(d->state == Inactive, return); d->state = Killing; startProcess(killProcessCommandLine(d->remoteProcesses.at(row))); } int AbstractRemoteLinuxProcessList::pidAt(int row) const { return d->remoteProcesses.at(row).pid; } int AbstractRemoteLinuxProcessList::rowCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : d->remoteProcesses.count(); } int AbstractRemoteLinuxProcessList::columnCount(const QModelIndex &) const { return 2; } QVariant AbstractRemoteLinuxProcessList::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation != Qt::Horizontal || role != Qt::DisplayRole || section < 0 || section >= columnCount()) return QVariant(); return section == 0? tr("PID") : tr("Command Line"); } QVariant AbstractRemoteLinuxProcessList::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= rowCount(index.parent()) || index.column() >= columnCount() || role != Qt::DisplayRole) return QVariant(); const RemoteProcess &proc = d->remoteProcesses.at(index.row()); if (index.column() == 0) return proc.pid; else return proc.cmdLine; } void AbstractRemoteLinuxProcessList::handleRemoteStdOut(const QByteArray &output) { if (d->state == Listing) d->remoteStdout += output; } void AbstractRemoteLinuxProcessList::handleRemoteStdErr(const QByteArray &output) { if (d->state != Inactive) d->remoteStderr += output; } void AbstractRemoteLinuxProcessList::handleConnectionError() { QTC_ASSERT(d->state != Inactive, return); emit error(tr("Connection failure: %1").arg(d->process->connection()->errorString())); beginResetModel(); d->remoteProcesses.clear(); endResetModel(); setFinished(); } void AbstractRemoteLinuxProcessList::handleRemoteProcessFinished(int exitStatus) { QTC_ASSERT(d->state != Inactive, return); switch (exitStatus) { case SshRemoteProcess::FailedToStart: d->errorMsg = tr("Error: Remote process failed to start: %1") .arg(d->process->process()->errorString()); break; case SshRemoteProcess::KilledBySignal: d->errorMsg = tr("Error: Remote process crashed: %1") .arg(d->process->process()->errorString()); break; case SshRemoteProcess::ExitedNormally: if (d->process->process()->exitCode() == 0) { if (d->state == Listing) { d->remoteProcesses = buildProcessList(QString::fromUtf8(d->remoteStdout.data(), d->remoteStdout.count())); } } else { d->errorMsg = tr("Remote process failed."); } break; default: Q_ASSERT_X(false, Q_FUNC_INFO, "Invalid exit status"); } if (!d->errorMsg.isEmpty()) { if (!d->remoteStderr.isEmpty()) d->errorMsg += tr("\nRemote stderr was: %1").arg(QString::fromUtf8(d->remoteStderr)); emit error(d->errorMsg); } else if (d->state == Killing) { emit processKilled(); } if (d->state == Listing) endResetModel(); setFinished(); } void AbstractRemoteLinuxProcessList::startProcess(const QString &cmdLine) { connect(d->process.data(), SIGNAL(connectionError(Utils::SshError)), SLOT(handleConnectionError())); connect(d->process.data(), SIGNAL(processOutputAvailable(QByteArray)), SLOT(handleRemoteStdOut(QByteArray))); connect(d->process.data(), SIGNAL(processErrorOutputAvailable(QByteArray)), SLOT(handleRemoteStdErr(QByteArray))); connect(d->process.data(), SIGNAL(processClosed(int)), SLOT(handleRemoteProcessFinished(int))); d->remoteStdout.clear(); d->remoteStderr.clear(); d->errorMsg.clear(); d->process->run(cmdLine.toUtf8()); } void AbstractRemoteLinuxProcessList::setFinished() { disconnect(d->process.data(), 0, this, 0); d->state = Inactive; } GenericRemoteLinuxProcessList::GenericRemoteLinuxProcessList(const LinuxDeviceConfiguration::ConstPtr &devConfig, QObject *parent) : AbstractRemoteLinuxProcessList(devConfig, parent) { } QString GenericRemoteLinuxProcessList::listProcessesCommandLine() const { return QString::fromLocal8Bit("for dir in `ls -d /proc/[0123456789]*`; " "do printf \"${dir}%1\";cat $dir/cmdline; printf '%1';cat $dir/stat;printf '\\n'; done") .arg(Delimiter); } QString GenericRemoteLinuxProcessList::killProcessCommandLine(const RemoteProcess &process) const { return QLatin1String("kill -9 ") + QString::number(process.pid); } QList<AbstractRemoteLinuxProcessList::RemoteProcess> GenericRemoteLinuxProcessList::buildProcessList(const QString &listProcessesReply) const { QList<RemoteProcess> processes; const QStringList &lines = listProcessesReply.split(QLatin1Char('\n'), QString::SkipEmptyParts); foreach (const QString &line, lines) { const QStringList elements = line.split(QString::fromLocal8Bit(Delimiter)); if (elements.count() < 3) { qDebug("%s: Expected three list elements, got %d.", Q_FUNC_INFO, elements.count()); continue; } bool ok; const int pid = elements.first().mid(6).toInt(&ok); if (!ok) { qDebug("%s: Expected number in %s.", Q_FUNC_INFO, qPrintable(elements.first())); continue; } QString command = elements.at(1); command.replace(QLatin1Char('\0'), QLatin1Char(' ')); if (command.isEmpty()) { const QString &statString = elements.at(2); const int openParenPos = statString.indexOf(QLatin1Char('(')); const int closedParenPos = statString.indexOf(QLatin1Char(')'), openParenPos); if (openParenPos == -1 || closedParenPos == -1) continue; command = QLatin1Char('[') + statString.mid(openParenPos + 1, closedParenPos - openParenPos - 1) + QLatin1Char(']'); } int insertPos; for (insertPos = 0; insertPos < processes.count(); ++insertPos) { if (pid < processes.at(insertPos).pid) break; } processes.insert(insertPos, RemoteProcess(pid, command)); } return processes; } } // namespace RemoteLinux <|endoftext|>
<commit_before>#include "p2ppipe.h" #include "utils.h" #include "crypto/sha2.h" #include <thread> #include <chrono> #include <string.h> #include <unistd.h> #include <sys/time.h> #include <stdio.h> #include <cstddef> #ifdef WIN32 #include <winsock2.h> #include <ws2tcpip.h> #else // WIN32 #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <netdb.h> #include <fcntl.h> #endif // !WIN32 void P2PPipe::send_message(const char* command, unsigned char* headerAndData, size_t datalen) { prepare_message(command, headerAndData, datalen); maybe_do_send_bytes((char*)headerAndData, sizeof(struct bitcoin_msg_header) + datalen); } static std::string statefulMessages[] = {"sendheaders", "feefilter" /*, "sendcmpct" - but gets its own processing */}; void P2PPipe::send_hashed_message(const unsigned char* headerAndData, size_t totallen) { if (!strncmp(((struct bitcoin_msg_header*)headerAndData)->command, "version", strlen("version"))) { std::vector<unsigned char> message(headerAndData, headerAndData + totallen); bool insert = !statefulMessagesSent.count("version"); if (!insert) { const unsigned char* oldMessage = statefulMessagesSent["version"].data(); uint32_t oldMsgLength, newMsgLength; memcpy(&oldMsgLength, &((struct bitcoin_msg_header*)oldMessage )->length, sizeof(oldMsgLength)); memcpy(&newMsgLength, &((struct bitcoin_msg_header*)headerAndData)->length, sizeof(newMsgLength)); insert = oldMsgLength != newMsgLength; if (!insert && le32toh(newMsgLength) >= sizeof(struct bitcoin_version_start)) { struct bitcoin_version_start oldVersion, newVersion; memcpy(&oldVersion, oldMessage + sizeof(struct bitcoin_msg_header), sizeof(oldVersion)); memcpy(&newVersion, headerAndData + sizeof(struct bitcoin_msg_header), sizeof(newVersion)); insert = oldVersion.protocol_version != newVersion.protocol_version || oldVersion.services != newVersion.services || memcmp(oldVersion.addr_recv, newVersion.addr_recv, sizeof(oldVersion.addr_recv) - 2) || memcmp(oldVersion.addr_from, newVersion.addr_from, sizeof(oldVersion.addr_from) - 2) || oldVersion.user_agent_length != newVersion.user_agent_length; } } if (insert) { statefulMessagesSent["version"] = std::move(message); disconnect_from_outside("new outbound version"); } return; } if (is_connected()) maybe_do_send_bytes((char*)headerAndData, totallen); assert(totallen >= sizeof(struct bitcoin_msg_header)); for (size_t i = 0; i < sizeof(statefulMessages) / sizeof(std::string); i++) if (!strncmp(((struct bitcoin_msg_header*)headerAndData)->command, statefulMessages[i].c_str(), statefulMessages[i].length())) statefulMessagesSent[statefulMessages[i]] = std::vector<unsigned char>(headerAndData, headerAndData + totallen); if (!strncmp(((struct bitcoin_msg_header*)headerAndData)->command, "sendcmpct", strlen("sendcmpct")) && totallen >= sizeof(struct bitcoin_msg_header) + 9) { uint64_t cmpctVersion; memcpy(&cmpctVersion, headerAndData + sizeof(struct bitcoin_msg_header) + 1, sizeof(cmpctVersion)); cmpctVersion = le64toh(cmpctVersion); statefulMessagesSent[std::string("sendcmpct") + std::to_string(cmpctVersion)] = std::vector<unsigned char>(headerAndData, headerAndData + totallen); } } void P2PPipe::on_disconnect() { connected = 0; read_msg.reset(); read_pos = 0; } void P2PPipe::net_process(const std::function<void(std::string)>& disconnect) { connected = 0; if (statefulMessagesSent.count("version")) { // Postpend Bent Pipe info to version std::vector<unsigned char> message(statefulMessagesSent["version"]); if (message.size() >= sizeof(struct bitcoin_version_start) + sizeof(struct bitcoin_msg_header)) { uint8_t ua_length = message[sizeof(struct bitcoin_msg_header) + offsetof(struct bitcoin_version_start, user_agent_length)]; if (ua_length <= 100 && message.size() > sizeof(struct bitcoin_version_start) + sizeof(struct bitcoin_msg_header) + ua_length) { const char* ua_postpend = "FIBREBentPipe:42/"; message.insert(message.begin() + sizeof(struct bitcoin_msg_header) + sizeof(struct bitcoin_version_start) + ua_length, (unsigned char*)ua_postpend, (unsigned char*) ua_postpend + 17); message[sizeof(struct bitcoin_msg_header) + offsetof(struct bitcoin_version_start, user_agent_length)] = ua_length + 17; } } send_message("version", message.data(), message.size() - sizeof(struct bitcoin_msg_header)); } else { std::vector<unsigned char> version_msg(generate_version()); send_message("version", &version_msg[0], version_msg.size() - sizeof(struct bitcoin_msg_header)); } while (true) { struct bitcoin_msg_header header; if (read_all((char*)&header, sizeof(header)) != sizeof(header)) return disconnect("failed to read message header"); if (header.magic != BITCOIN_MAGIC) return disconnect("invalid magic bytes"); header.length = le32toh(header.length); if (header.length > 5000000) return disconnect("got message too large"); auto msg = std::make_shared<std::vector<unsigned char> > (sizeof(header) + uint32_t(header.length)); memcpy(msg->data(), &header, sizeof(header)); bool check_msg_hash = check_block_msghash || (strncmp(header.command, "block", strlen("block")) && strncmp(header.command, "blocktxn", strlen("blocktxn")) && strncmp(header.command, "cmpctblock", strlen("cmpctblock"))); if (check_msg_hash) { uint32_t hash[8]; double_sha256_init(hash); uint32_t steps = header.length / 64; for (uint32_t i = 0; i < steps; i++) { unsigned char* writepos = &((*msg)[sizeof(header) + i*64]); if (read_all((char*)writepos, 64) != 64) return disconnect("failed to read message"); double_sha256_step(writepos, 64, hash); } unsigned char* writepos = &((*msg)[sizeof(header) + steps*64]); if (read_all((char*)writepos, header.length - steps*64) != ssize_t(header.length - steps*64)) return disconnect("failed to read message"); double_sha256_done(writepos, header.length - steps*64, header.length, hash); if (memcmp((char*)hash, header.checksum, sizeof(header.checksum))) return disconnect("got invalid message checksum"); } else if (read_all((char*)&(*msg)[sizeof(header)], header.length) != ssize_t(header.length)) return disconnect("failed to read message"); if (!strncmp(header.command, "version", strlen("version"))) { if (connected != 0) return disconnect("got invalid version"); connected = 1; if (header.length < sizeof(struct bitcoin_version_start)) return disconnect("got short version"); struct bitcoin_version_start their_version; memcpy(&their_version, &(*msg)[sizeof(header)], sizeof(their_version)); struct bitcoin_msg_header new_header; send_message("verack", (unsigned char*)&new_header, 0); STAMPOUT(); printf("Connected to bitcoind with version %u\n", le32toh(their_version.protocol_version)); provide_msg(*msg); continue; } else if (!strncmp(header.command, "verack", strlen("verack"))) { if (connected != 1) return disconnect("got invalid verack"); STAMPOUT(); printf("Finished connect handshake with bitcoind\n"); connected = 2; for (auto it = statefulMessagesSent.rbegin(); it != statefulMessagesSent.rend(); it++) { auto &p = *it; if (p.first != "version") { std::string cmpct("sendcmpct"); if (!p.first.compare(0, cmpct.length(), cmpct)) send_message("sendcmpct", p.second.data(), p.second.size() - sizeof(struct bitcoin_msg_header)); else send_message(p.first.c_str(), p.second.data(), p.second.size() - sizeof(struct bitcoin_msg_header)); } } continue; } if (connected != 2) return disconnect("got non-version, non-verack before version+verack"); if (!strncmp(header.command, "ping", strlen("ping"))) { std::vector<unsigned char> resp(sizeof(struct bitcoin_msg_header) + header.length); resp.insert(resp.begin() + sizeof(struct bitcoin_msg_header), msg->begin() + sizeof(header), msg->end()); send_message("pong", &resp[0], header.length); } else if (!strncmp(header.command, "pong", strlen("pong"))) { if (msg->size() != 8 + sizeof(header)) return disconnect("got pong without nonce"); uint64_t nonce; memcpy(&nonce, &(*msg)[sizeof(read_header)], 8); pong_received(nonce); } else provide_msg(*msg); } } void P2PPipe::send_ping(uint64_t nonce) { std::vector<unsigned char> msg(sizeof(struct bitcoin_msg_header) + 8); memcpy(&msg[sizeof(struct bitcoin_msg_header)], &nonce, 8); send_message("ping", &msg[0], 8); } bool P2PPipe::is_connected() const { return connected == 2; } <commit_msg>version-bump pipe to indicate fixed cmpctblock handling<commit_after>#include "p2ppipe.h" #include "utils.h" #include "crypto/sha2.h" #include <thread> #include <chrono> #include <string.h> #include <unistd.h> #include <sys/time.h> #include <stdio.h> #include <cstddef> #ifdef WIN32 #include <winsock2.h> #include <ws2tcpip.h> #else // WIN32 #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <netdb.h> #include <fcntl.h> #endif // !WIN32 void P2PPipe::send_message(const char* command, unsigned char* headerAndData, size_t datalen) { prepare_message(command, headerAndData, datalen); maybe_do_send_bytes((char*)headerAndData, sizeof(struct bitcoin_msg_header) + datalen); } static std::string statefulMessages[] = {"sendheaders", "feefilter" /*, "sendcmpct" - but gets its own processing */}; void P2PPipe::send_hashed_message(const unsigned char* headerAndData, size_t totallen) { if (!strncmp(((struct bitcoin_msg_header*)headerAndData)->command, "version", strlen("version"))) { std::vector<unsigned char> message(headerAndData, headerAndData + totallen); bool insert = !statefulMessagesSent.count("version"); if (!insert) { const unsigned char* oldMessage = statefulMessagesSent["version"].data(); uint32_t oldMsgLength, newMsgLength; memcpy(&oldMsgLength, &((struct bitcoin_msg_header*)oldMessage )->length, sizeof(oldMsgLength)); memcpy(&newMsgLength, &((struct bitcoin_msg_header*)headerAndData)->length, sizeof(newMsgLength)); insert = oldMsgLength != newMsgLength; if (!insert && le32toh(newMsgLength) >= sizeof(struct bitcoin_version_start)) { struct bitcoin_version_start oldVersion, newVersion; memcpy(&oldVersion, oldMessage + sizeof(struct bitcoin_msg_header), sizeof(oldVersion)); memcpy(&newVersion, headerAndData + sizeof(struct bitcoin_msg_header), sizeof(newVersion)); insert = oldVersion.protocol_version != newVersion.protocol_version || oldVersion.services != newVersion.services || memcmp(oldVersion.addr_recv, newVersion.addr_recv, sizeof(oldVersion.addr_recv) - 2) || memcmp(oldVersion.addr_from, newVersion.addr_from, sizeof(oldVersion.addr_from) - 2) || oldVersion.user_agent_length != newVersion.user_agent_length; } } if (insert) { statefulMessagesSent["version"] = std::move(message); disconnect_from_outside("new outbound version"); } return; } if (is_connected()) maybe_do_send_bytes((char*)headerAndData, totallen); assert(totallen >= sizeof(struct bitcoin_msg_header)); for (size_t i = 0; i < sizeof(statefulMessages) / sizeof(std::string); i++) if (!strncmp(((struct bitcoin_msg_header*)headerAndData)->command, statefulMessages[i].c_str(), statefulMessages[i].length())) statefulMessagesSent[statefulMessages[i]] = std::vector<unsigned char>(headerAndData, headerAndData + totallen); if (!strncmp(((struct bitcoin_msg_header*)headerAndData)->command, "sendcmpct", strlen("sendcmpct")) && totallen >= sizeof(struct bitcoin_msg_header) + 9) { uint64_t cmpctVersion; memcpy(&cmpctVersion, headerAndData + sizeof(struct bitcoin_msg_header) + 1, sizeof(cmpctVersion)); cmpctVersion = le64toh(cmpctVersion); statefulMessagesSent[std::string("sendcmpct") + std::to_string(cmpctVersion)] = std::vector<unsigned char>(headerAndData, headerAndData + totallen); } } void P2PPipe::on_disconnect() { connected = 0; read_msg.reset(); read_pos = 0; } void P2PPipe::net_process(const std::function<void(std::string)>& disconnect) { connected = 0; if (statefulMessagesSent.count("version")) { // Postpend Bent Pipe info to version std::vector<unsigned char> message(statefulMessagesSent["version"]); if (message.size() >= sizeof(struct bitcoin_version_start) + sizeof(struct bitcoin_msg_header)) { uint8_t ua_length = message[sizeof(struct bitcoin_msg_header) + offsetof(struct bitcoin_version_start, user_agent_length)]; if (ua_length <= 100 && message.size() > sizeof(struct bitcoin_version_start) + sizeof(struct bitcoin_msg_header) + ua_length) { const char* ua_postpend = "FIBREBentPipe:43/"; message.insert(message.begin() + sizeof(struct bitcoin_msg_header) + sizeof(struct bitcoin_version_start) + ua_length, (unsigned char*)ua_postpend, (unsigned char*) ua_postpend + 17); message[sizeof(struct bitcoin_msg_header) + offsetof(struct bitcoin_version_start, user_agent_length)] = ua_length + 17; } } send_message("version", message.data(), message.size() - sizeof(struct bitcoin_msg_header)); } else { std::vector<unsigned char> version_msg(generate_version()); send_message("version", &version_msg[0], version_msg.size() - sizeof(struct bitcoin_msg_header)); } while (true) { struct bitcoin_msg_header header; if (read_all((char*)&header, sizeof(header)) != sizeof(header)) return disconnect("failed to read message header"); if (header.magic != BITCOIN_MAGIC) return disconnect("invalid magic bytes"); header.length = le32toh(header.length); if (header.length > 5000000) return disconnect("got message too large"); auto msg = std::make_shared<std::vector<unsigned char> > (sizeof(header) + uint32_t(header.length)); memcpy(msg->data(), &header, sizeof(header)); bool check_msg_hash = check_block_msghash || (strncmp(header.command, "block", strlen("block")) && strncmp(header.command, "blocktxn", strlen("blocktxn")) && strncmp(header.command, "cmpctblock", strlen("cmpctblock"))); if (check_msg_hash) { uint32_t hash[8]; double_sha256_init(hash); uint32_t steps = header.length / 64; for (uint32_t i = 0; i < steps; i++) { unsigned char* writepos = &((*msg)[sizeof(header) + i*64]); if (read_all((char*)writepos, 64) != 64) return disconnect("failed to read message"); double_sha256_step(writepos, 64, hash); } unsigned char* writepos = &((*msg)[sizeof(header) + steps*64]); if (read_all((char*)writepos, header.length - steps*64) != ssize_t(header.length - steps*64)) return disconnect("failed to read message"); double_sha256_done(writepos, header.length - steps*64, header.length, hash); if (memcmp((char*)hash, header.checksum, sizeof(header.checksum))) return disconnect("got invalid message checksum"); } else if (read_all((char*)&(*msg)[sizeof(header)], header.length) != ssize_t(header.length)) return disconnect("failed to read message"); if (!strncmp(header.command, "version", strlen("version"))) { if (connected != 0) return disconnect("got invalid version"); connected = 1; if (header.length < sizeof(struct bitcoin_version_start)) return disconnect("got short version"); struct bitcoin_version_start their_version; memcpy(&their_version, &(*msg)[sizeof(header)], sizeof(their_version)); struct bitcoin_msg_header new_header; send_message("verack", (unsigned char*)&new_header, 0); STAMPOUT(); printf("Connected to bitcoind with version %u\n", le32toh(their_version.protocol_version)); provide_msg(*msg); continue; } else if (!strncmp(header.command, "verack", strlen("verack"))) { if (connected != 1) return disconnect("got invalid verack"); STAMPOUT(); printf("Finished connect handshake with bitcoind\n"); connected = 2; for (auto it = statefulMessagesSent.rbegin(); it != statefulMessagesSent.rend(); it++) { auto &p = *it; if (p.first != "version") { std::string cmpct("sendcmpct"); if (!p.first.compare(0, cmpct.length(), cmpct)) send_message("sendcmpct", p.second.data(), p.second.size() - sizeof(struct bitcoin_msg_header)); else send_message(p.first.c_str(), p.second.data(), p.second.size() - sizeof(struct bitcoin_msg_header)); } } continue; } if (connected != 2) return disconnect("got non-version, non-verack before version+verack"); if (!strncmp(header.command, "ping", strlen("ping"))) { std::vector<unsigned char> resp(sizeof(struct bitcoin_msg_header) + header.length); resp.insert(resp.begin() + sizeof(struct bitcoin_msg_header), msg->begin() + sizeof(header), msg->end()); send_message("pong", &resp[0], header.length); } else if (!strncmp(header.command, "pong", strlen("pong"))) { if (msg->size() != 8 + sizeof(header)) return disconnect("got pong without nonce"); uint64_t nonce; memcpy(&nonce, &(*msg)[sizeof(read_header)], 8); pong_received(nonce); } else provide_msg(*msg); } } void P2PPipe::send_ping(uint64_t nonce) { std::vector<unsigned char> msg(sizeof(struct bitcoin_msg_header) + 8); memcpy(&msg[sizeof(struct bitcoin_msg_header)], &nonce, 8); send_message("ping", &msg[0], 8); } bool P2PPipe::is_connected() const { return connected == 2; } <|endoftext|>
<commit_before><commit_msg>Switch specular-color to CIE 1931 10 degree observer<commit_after><|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////////// // AboutDialog.cpp // // Copyright 2011 Johannes Marbach. All rights reserved. // See the LICENSE file for details. #include <config.h> #include "AboutDialog.h" namespace jRadio { // Constructor & destructor AboutDialog::AboutDialog(Gtk::Window& parent) { set_transient_for(parent); // Setup parent window // Insert program info set_program_name(PACKAGE_NAME); set_version(PACKAGE_VERSION); set_copyright("© 2011 Johannes Marbach"); set_comments("An easy to use web radio player."); set_license_type (Gtk::LICENSE_LGPL_3_0); std::vector<Glib::ustring> authors; authors.push_back("Johannes Marbach"); set_authors(authors); } AboutDialog::~AboutDialog() { } } // namespace jRadio <commit_msg>Adjusted license in about dialog<commit_after>////////////////////////////////////////////////////////////////////////////// // AboutDialog.cpp // // Copyright 2011 Johannes Marbach. All rights reserved. // See the LICENSE file for details. #include <config.h> #include "AboutDialog.h" #include <iostream> #include <fstream> namespace jRadio { // Constructor & destructor AboutDialog::AboutDialog(Gtk::Window& parent) { set_transient_for(parent); // Setup parent window // Insert program info set_program_name(PACKAGE_NAME); set_version(PACKAGE_VERSION); set_copyright("© 2011 Johannes Marbach"); set_comments("An easy to use web radio player."); set_license_type (Gtk::LICENSE_CUSTOM); std::ifstream license("LICENSE"); if (license.is_open()) { std::stringstream licenseStream; licenseStream << license.rdbuf(); license.close(); set_license (licenseStream.str()); } std::vector<Glib::ustring> authors; authors.push_back("Johannes Marbach"); set_authors(authors); } AboutDialog::~AboutDialog() { } } // namespace jRadio <|endoftext|>