commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
5a2dc432b1ee3bab1d47306d84acef4ad32b2f2a
src/assert.cpp
src/assert.cpp
/* Copyright (c) 2007-2015, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #ifdef TORRENT_PRODUCTION_ASSERTS #include <boost/atomic.hpp> #endif #if (defined TORRENT_DEBUG && TORRENT_USE_ASSERTS) \ || defined TORRENT_ASIO_DEBUGGING \ || defined TORRENT_PROFILE_CALLS \ || defined TORRENT_RELEASE_ASSERTS \ || defined TORRENT_DEBUG_BUFFERS #ifdef __APPLE__ #include <AvailabilityMacros.h> #endif #include <string> #include <cstring> #include <stdlib.h> #include <stdarg.h> // uClibc++ doesn't have cxxabi.h #if defined __GNUC__ && __GNUC__ >= 3 \ && !defined __UCLIBCXX_MAJOR__ #include <cxxabi.h> std::string demangle(char const* name) { // in case this string comes // this is needed on linux char const* start = strchr(name, '('); if (start != 0) { ++start; } else { // this is needed on macos x start = strstr(name, "0x"); if (start != 0) { start = strchr(start, ' '); if (start != 0) ++start; else start = name; } else start = name; } char const* end = strchr(start, '+'); if (end) while (*(end-1) == ' ') --end; std::string in; if (end == 0) in.assign(start); else in.assign(start, end); size_t len; int status; char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status); if (unmangled == 0) return in; std::string ret(unmangled); free(unmangled); return ret; } #elif defined WIN32 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // XP #include "windows.h" #include "dbghelp.h" std::string demangle(char const* name) { char demangled_name[256]; if (UnDecorateSymbolName(name, demangled_name, sizeof(demangled_name), UNDNAME_NO_THROW_SIGNATURES) == 0) demangled_name[0] = 0; return demangled_name; } #else std::string demangle(char const* name) { return name; } #endif #include <stdlib.h> #include <stdio.h> #include <signal.h> #include "libtorrent/version.hpp" #if TORRENT_USE_EXECINFO #include <execinfo.h> TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) { void* stack[50]; int size = backtrace(stack, 50); char** symbols = backtrace_symbols(stack, size); for (int i = 1; i < size && len > 0; ++i) { int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str()); out += ret; len -= ret; if (i - 1 == max_depth && max_depth > 0) break; } free(symbols); } // visual studio 9 and up appears to support this #elif defined WIN32 && _MSC_VER >= 1500 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // XP #include "windows.h" #include "libtorrent/utf8.hpp" #include "winbase.h" #include "dbghelp.h" TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) { typedef USHORT (WINAPI *RtlCaptureStackBackTrace_t)( __in ULONG FramesToSkip, __in ULONG FramesToCapture, __out PVOID *BackTrace, __out_opt PULONG BackTraceHash); static RtlCaptureStackBackTrace_t RtlCaptureStackBackTrace = 0; if (RtlCaptureStackBackTrace == 0) { // we don't actually have to free this library, everyone has it loaded HMODULE lib = LoadLibrary(TEXT("kernel32.dll")); RtlCaptureStackBackTrace = (RtlCaptureStackBackTrace_t)GetProcAddress(lib, "RtlCaptureStackBackTrace"); if (RtlCaptureStackBackTrace == 0) { out[0] = 0; return; } } int i; void* stack[50]; int size = CaptureStackBackTrace(0, 50, stack, 0); SYMBOL_INFO* symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR), 1); symbol->MaxNameLen = MAX_SYM_NAME; symbol->SizeOfStruct = sizeof(SYMBOL_INFO); HANDLE p = GetCurrentProcess(); static bool sym_initialized = false; if (!sym_initialized) { sym_initialized = true; SymInitialize(p, NULL, true); } for (i = 0; i < size && len > 0; ++i) { int ret; if (SymFromAddr(p, uintptr_t(stack[i]), 0, symbol)) ret = snprintf(out, len, "%d: %s\n", i, symbol->Name); else ret = snprintf(out, len, "%d: <unknown>\n", i); out += ret; len -= ret; if (i == max_depth && max_depth > 0) break; } free(symbol); } #else TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) { out[0] = 0; strncat(out, "<not supported>", len); } #endif #endif #if TORRENT_USE_ASSERTS || defined TORRENT_ASIO_DEBUGGING #ifdef TORRENT_PRODUCTION_ASSERTS char const* libtorrent_assert_log = "asserts.log"; // the number of asserts we've printed to the log boost::atomic<int> assert_counter(0); #endif TORRENT_FORMAT(1,2) TORRENT_EXPORT void assert_print(char const* fmt, ...) { #ifdef TORRENT_PRODUCTION_ASSERTS if (assert_counter > 500) return; FILE* out = fopen(libtorrent_assert_log, "a+"); if (out == 0) out = stderr; #else FILE* out = stderr; #endif va_list va; va_start(va, fmt); vfprintf(out, fmt, va); va_end(va); #ifdef TORRENT_PRODUCTION_ASSERTS if (out != stderr) fclose(out); #endif } TORRENT_NO_RETURN TORRENT_EXPORT void assert_fail(char const* expr, int line , char const* file, char const* function, char const* value, int kind) { #ifdef TORRENT_PRODUCTION_ASSERTS // no need to flood the assert log with infinite number of asserts if (assert_counter.fetch_add(1) + 1 > 500) return; #endif char stack[8192]; stack[0] = '\0'; print_backtrace(stack, sizeof(stack), 0); char const* message = "assertion failed. Please file a bugreport at " "https://github.com/arvidn/libtorrent/issues\n" "Please include the following information:\n\n" "version: " LIBTORRENT_VERSION "\n" LIBTORRENT_REVISION "\n"; switch (kind) { case 1: message = "A precondition of a libtorrent function has been violated.\n" "This indicates a bug in the client application using libtorrent\n"; } assert_print("%s\n" #ifdef TORRENT_PRODUCTION_ASSERTS "#: %d\n" #endif "file: '%s'\n" "line: %d\n" "function: %s\n" "expression: %s\n" "%s%s\n" "stack:\n" "%s\n" , message #ifdef TORRENT_PRODUCTION_ASSERTS , assert_counter.load() #endif , file, line, function, expr , value ? value : "", value ? "\n" : "" , stack); // if production asserts are defined, don't abort, just print the error #ifndef TORRENT_PRODUCTION_ASSERTS // send SIGINT to the current process // to break into the debugger raise(SIGINT); abort(); #endif } #else TORRENT_FORMAT(1,2) TORRENT_EXPORT void assert_print(char const*, ...) {} TORRENT_EXPORT void assert_fail(char const*, int, char const* , char const*, char const*, int) {} #endif
/* Copyright (c) 2007-2015, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #ifdef TORRENT_PRODUCTION_ASSERTS #include <boost/atomic.hpp> #endif #if (defined TORRENT_DEBUG && TORRENT_USE_ASSERTS) \ || defined TORRENT_ASIO_DEBUGGING \ || defined TORRENT_PROFILE_CALLS \ || defined TORRENT_RELEASE_ASSERTS \ || defined TORRENT_DEBUG_BUFFERS #ifdef __APPLE__ #include <AvailabilityMacros.h> #endif #include <string> #include <cstring> #include <stdlib.h> #include <stdarg.h> // uClibc++ doesn't have cxxabi.h #if defined __GNUC__ && __GNUC__ >= 3 \ && !defined __UCLIBCXX_MAJOR__ #include <cxxabi.h> std::string demangle(char const* name) { // in case this string comes // this is needed on linux char const* start = strchr(name, '('); if (start != 0) { ++start; } else { // this is needed on macos x start = strstr(name, "0x"); if (start != 0) { start = strchr(start, ' '); if (start != 0) ++start; else start = name; } else start = name; } char const* end = strchr(start, '+'); if (end) while (*(end-1) == ' ') --end; std::string in; if (end == 0) in.assign(start); else in.assign(start, end); size_t len; int status; char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status); if (unmangled == 0) return in; std::string ret(unmangled); free(unmangled); return ret; } #elif defined WIN32 #include "windows.h" #include "dbghelp.h" std::string demangle(char const* name) { char demangled_name[256]; if (UnDecorateSymbolName(name, demangled_name, sizeof(demangled_name), UNDNAME_NO_THROW_SIGNATURES) == 0) demangled_name[0] = 0; return demangled_name; } #else std::string demangle(char const* name) { return name; } #endif #include <stdlib.h> #include <stdio.h> #include <signal.h> #include "libtorrent/version.hpp" #if TORRENT_USE_EXECINFO #include <execinfo.h> TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) { void* stack[50]; int size = backtrace(stack, 50); char** symbols = backtrace_symbols(stack, size); for (int i = 1; i < size && len > 0; ++i) { int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str()); out += ret; len -= ret; if (i - 1 == max_depth && max_depth > 0) break; } free(symbols); } // visual studio 9 and up appears to support this #elif defined WIN32 && _MSC_VER >= 1500 #include "windows.h" #include "libtorrent/utf8.hpp" #include "winbase.h" #include "dbghelp.h" TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) { typedef USHORT (WINAPI *RtlCaptureStackBackTrace_t)( __in ULONG FramesToSkip, __in ULONG FramesToCapture, __out PVOID *BackTrace, __out_opt PULONG BackTraceHash); static RtlCaptureStackBackTrace_t RtlCaptureStackBackTrace = 0; if (RtlCaptureStackBackTrace == 0) { // we don't actually have to free this library, everyone has it loaded HMODULE lib = LoadLibrary(TEXT("kernel32.dll")); RtlCaptureStackBackTrace = (RtlCaptureStackBackTrace_t)GetProcAddress(lib, "RtlCaptureStackBackTrace"); if (RtlCaptureStackBackTrace == 0) { out[0] = 0; return; } } int i; void* stack[50]; int size = CaptureStackBackTrace(0, 50, stack, 0); SYMBOL_INFO* symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR), 1); symbol->MaxNameLen = MAX_SYM_NAME; symbol->SizeOfStruct = sizeof(SYMBOL_INFO); HANDLE p = GetCurrentProcess(); static bool sym_initialized = false; if (!sym_initialized) { sym_initialized = true; SymInitialize(p, NULL, true); } for (i = 0; i < size && len > 0; ++i) { int ret; if (SymFromAddr(p, uintptr_t(stack[i]), 0, symbol)) ret = snprintf(out, len, "%d: %s\n", i, symbol->Name); else ret = snprintf(out, len, "%d: <unknown>\n", i); out += ret; len -= ret; if (i == max_depth && max_depth > 0) break; } free(symbol); } #else TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) { out[0] = 0; strncat(out, "<not supported>", len); } #endif #endif #if TORRENT_USE_ASSERTS || defined TORRENT_ASIO_DEBUGGING #ifdef TORRENT_PRODUCTION_ASSERTS char const* libtorrent_assert_log = "asserts.log"; // the number of asserts we've printed to the log boost::atomic<int> assert_counter(0); #endif TORRENT_FORMAT(1,2) TORRENT_EXPORT void assert_print(char const* fmt, ...) { #ifdef TORRENT_PRODUCTION_ASSERTS if (assert_counter > 500) return; FILE* out = fopen(libtorrent_assert_log, "a+"); if (out == 0) out = stderr; #else FILE* out = stderr; #endif va_list va; va_start(va, fmt); vfprintf(out, fmt, va); va_end(va); #ifdef TORRENT_PRODUCTION_ASSERTS if (out != stderr) fclose(out); #endif } TORRENT_NO_RETURN TORRENT_EXPORT void assert_fail(char const* expr, int line , char const* file, char const* function, char const* value, int kind) { #ifdef TORRENT_PRODUCTION_ASSERTS // no need to flood the assert log with infinite number of asserts if (assert_counter.fetch_add(1) + 1 > 500) return; #endif char stack[8192]; stack[0] = '\0'; print_backtrace(stack, sizeof(stack), 0); char const* message = "assertion failed. Please file a bugreport at " "https://github.com/arvidn/libtorrent/issues\n" "Please include the following information:\n\n" "version: " LIBTORRENT_VERSION "\n" LIBTORRENT_REVISION "\n"; switch (kind) { case 1: message = "A precondition of a libtorrent function has been violated.\n" "This indicates a bug in the client application using libtorrent\n"; } assert_print("%s\n" #ifdef TORRENT_PRODUCTION_ASSERTS "#: %d\n" #endif "file: '%s'\n" "line: %d\n" "function: %s\n" "expression: %s\n" "%s%s\n" "stack:\n" "%s\n" , message #ifdef TORRENT_PRODUCTION_ASSERTS , assert_counter.load() #endif , file, line, function, expr , value ? value : "", value ? "\n" : "" , stack); // if production asserts are defined, don't abort, just print the error #ifndef TORRENT_PRODUCTION_ASSERTS // send SIGINT to the current process // to break into the debugger raise(SIGINT); abort(); #endif } #else TORRENT_FORMAT(1,2) TORRENT_EXPORT void assert_print(char const*, ...) {} TORRENT_EXPORT void assert_fail(char const*, int, char const* , char const*, char const*, int) {} #endif
remove windows version from code file
remove windows version from code file because it should be in the build files
C++
bsd-3-clause
jpetso/libtorrent,jpetso/libtorrent,jpetso/libtorrent,jpetso/libtorrent
2b338b71c09f971b55114d8d4d553be63c513486
include/s2s/decode.hpp
include/s2s/decode.hpp
#include "dynet/nodes.h" #include "dynet/exec.h" #include "dynet/dynet.h" #include "dynet/training.h" #include "dynet/timing.h" #include "dynet/rnn.h" #include "dynet/gru.h" #include "dynet/lstm.h" #include "dynet/fast-lstm.h" #include "dynet/dict.h" #include "dynet/expr.h" #include <iostream> #include <fstream> #include <sstream> #include <type_traits> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/program_options.hpp> #include "s2s/encdec.hpp" #include "s2s/define.hpp" #include "s2s/comp.hpp" #include "s2s/preprocess.hpp" #include "s2s/metrics.hpp" namespace s2s { void greedy_decode(const batch& one_batch, std::vector<std::vector<unsigned int > >& osent, encoder_decoder *encdec, dynet::ComputationGraph &cg, dicts &d, const s2s_options &opts){ //unsigned slen = sents.size(); std::vector<dynet::expr::Expression> i_enc = encdec->encoder(one_batch, cg); osent.push_back(std::vector<unsigned int>(d.target_start_id, one_batch.src.at(0).size())); dynet::expr::Expression i_feed; for (int t = 1; t < opts.max_length; ++t) { dynet::Expression i_att_t = encdec->decoder_attention(cg, osent[t-1], i_feed, i_enc[0]); std::vector<dynet::Expression> i_out_t = encdec->decoder_output(cg, i_att_t, i_enc[1]); i_feed = i_out_t[1]; Expression predict = softmax(i_out_t[0]); std::vector<dynet::Tensor> results = cg.incremental_forward(predict).batch_elems(); std::vector<unsigned int> osent_col; for(unsigned int i=0; results.size(); i++){ auto output = as_vector(results.at(i)); int w_id = 0; double w_prob = output[w_id]; for(unsigned int j=0; j<output.size(); j++){ if(output[j] > w_prob){ w_id = j; w_prob = output[j]; } } osent_col.push_back(w_id); } osent.push_back(osent_col); } } void beam_decode(){ } std::string print_sents(std::vector<std::vector<unsigned int > >& osent, dicts& d){ std::string sents = ""; std::vector<std::vector<unsigned int> > sents_conved; sents_conved.resize(osent.size()); for(unsigned int col_id = 0; col_id < osent.size(); col_id++){ for(unsigned int sid = 0; osent.at(col_id).size(); sid++){ sents_conved[sid].push_back(osent.at(col_id).at(sid)); } } for(const auto sent : sents_conved){ for(const auto wid : sent){ std::string word = d.d_trg.convert(wid); sents += word; if(wid == d.target_end_id){ break; } sents += " "; } sents += "\n"; } return sents; } };
#include "dynet/nodes.h" #include "dynet/exec.h" #include "dynet/dynet.h" #include "dynet/training.h" #include "dynet/timing.h" #include "dynet/rnn.h" #include "dynet/gru.h" #include "dynet/lstm.h" #include "dynet/fast-lstm.h" #include "dynet/dict.h" #include "dynet/expr.h" #include <iostream> #include <fstream> #include <sstream> #include <type_traits> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/program_options.hpp> #include "s2s/encdec.hpp" #include "s2s/define.hpp" #include "s2s/comp.hpp" #include "s2s/metrics.hpp" namespace s2s { void greedy_decode(const batch& one_batch, std::vector<std::vector<unsigned int > >& osent, encoder_decoder *encdec, dynet::ComputationGraph &cg, dicts &d, const s2s_options &opts){ //unsigned slen = sents.size(); std::vector<dynet::expr::Expression> i_enc = encdec->encoder(one_batch, cg); osent.push_back(std::vector<unsigned int>(d.target_start_id, one_batch.src.at(0).size())); dynet::expr::Expression i_feed; for (int t = 1; t < opts.max_length; ++t) { dynet::Expression i_att_t = encdec->decoder_attention(cg, osent[t-1], i_feed, i_enc[0]); std::vector<dynet::Expression> i_out_t = encdec->decoder_output(cg, i_att_t, i_enc[1]); i_feed = i_out_t[1]; Expression predict = softmax(i_out_t[0]); std::vector<dynet::Tensor> results = cg.incremental_forward(predict).batch_elems(); std::vector<unsigned int> osent_col; for(unsigned int i=0; results.size(); i++){ auto output = as_vector(results.at(i)); int w_id = 0; double w_prob = output[w_id]; for(unsigned int j=0; j<output.size(); j++){ if(output[j] > w_prob){ w_id = j; w_prob = output[j]; } } osent_col.push_back(w_id); } osent.push_back(osent_col); } } void beam_decode(){ } std::string print_sents(std::vector<std::vector<unsigned int > >& osent, dicts& d){ std::string sents = ""; std::vector<std::vector<unsigned int> > sents_conved; sents_conved.resize(osent.size()); for(unsigned int col_id = 0; col_id < osent.size(); col_id++){ for(unsigned int sid = 0; osent.at(col_id).size(); sid++){ sents_conved[sid].push_back(osent.at(col_id).at(sid)); } } for(const auto sent : sents_conved){ for(const auto wid : sent){ std::string word = d.d_trg.convert(wid); sents += word; if(wid == d.target_end_id){ break; } sents += " "; } sents += "\n"; } return sents; } };
include bug fixed.
include bug fixed.
C++
mit
kamigaito/seq2seq-baseline-dynet,kamigaito/seq2seq-baseline-dynet
2b974df956116b37f9774fc477a7c522448717e6
src/ast/loc.hh
src/ast/loc.hh
/* * Copyright (C) 2007-2011, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file ast/loc.hh ** \brief Definition of ast::loc. */ #ifndef AST_LOC_HH # define AST_LOC_HH # include <libport/symbol.hh> # include <parser/location.hh> # include <kernel/config.h> // If you have an error from here, it probably means that you used // LOCATION_HERE without first calling DECLARE_LOCATION_FILE (alone, // visible from the scopes using LOCATION_HERE). # define DECLARE_LOCATION_FILE \ static /* const */ ::libport::Symbol \ _DECLARE_LOCATION_FILE_is_missing = \ ::ast::declare_location_file(__SRCDIR__, __FILE__); # define LOCATION_HERE \ ::ast::loc(&_DECLARE_LOCATION_FILE_is_missing, __LINE__) namespace ast { typedef yy::location loc; /// A Symbol that represents the current source file. /// Also add it to the urbi::system_files_get. ::libport::Symbol declare_location_file(const std::string& srcdir, std::string file); } #endif // !AST_LOC_HH
/* * Copyright (C) 2007-2012, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file ast/loc.hh ** \brief Definition of ast::loc. */ #ifndef AST_LOC_HH # define AST_LOC_HH # include <libport/symbol.hh> # include <parser/location.hh> // If you have an error from here, it probably means that you used // LOCATION_HERE without first calling DECLARE_LOCATION_FILE (alone, // visible from the scopes using LOCATION_HERE). # define DECLARE_LOCATION_FILE \ static /* const */ ::libport::Symbol \ _DECLARE_LOCATION_FILE_is_missing = \ ::ast::declare_location_file(__SRCDIR__, __FILE__); # define LOCATION_HERE \ ::ast::loc(&_DECLARE_LOCATION_FILE_is_missing, __LINE__) namespace ast { typedef yy::location loc; /// A Symbol that represents the current source file. /// Also add it to the urbi::system_files_get. ::libport::Symbol declare_location_file(const std::string& srcdir, std::string file); } #endif // !AST_LOC_HH
remove gratuitous dependency.
remove gratuitous dependency. * src/ast/loc.hh: here.
C++
bsd-3-clause
urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi
52730422d16e987776866a0cc319012695213956
src/lunar_shared_type.cpp
src/lunar_shared_type.cpp
#include "lunar_shared_type.hpp" namespace lunar { extern "C" { /* * memory layout of shared type: * +--------------------------------------+ <- malloc and free here * | reference count | * | (64 bits) | * +--------------------------------------+ <- make_shared_type() returns a pointer pointing here * | | * | data | * // (variable length) // * | | */ void* make_shared_type(size_t size) { uint64_t *ptr = (uint64_t*)malloc(size + sizeof(uint64_t)); *ptr = 1; return ptr + 1; } void incref_shared_type(void *p) { uint64_t *ptr = (uint64_t*)p; __sync_fetch_and_add(&ptr[-1], 1); } void deref_shared_type(void *p) { uint64_t *ptr = (uint64_t*)p; uint64_t cnt = __sync_fetch_and_add(&ptr[-1], -1); if (cnt == 0) free(ptr - 1); } } }
#include "lunar_shared_type.hpp" #include <stdint.h> namespace lunar { extern "C" { /* * memory layout of shared type: * +--------------------------------------+ <- malloc and free here * | reference count | * | (64 bits) | * +--------------------------------------+ <- make_shared_type() returns a pointer pointing here * | | * | data | * // (variable length) // * | | */ void* make_shared_type(size_t size) { uint64_t *ptr = (uint64_t*)malloc(size + sizeof(uint64_t)); *ptr = 1; return ptr + 1; } void incref_shared_type(void *p) { uint64_t *ptr = (uint64_t*)p; __sync_fetch_and_add(&ptr[-1], 1); } void deref_shared_type(void *p) { uint64_t *ptr = (uint64_t*)p; uint64_t cnt = __sync_fetch_and_add(&ptr[-1], -1); if (cnt == 0) free(ptr - 1); } } }
fix for Linux
fix for Linux
C++
bsd-3-clause
ytakano/tsukuyomi,ytakano/tsukuyomi
674c0e2fa0bfb1eed7ba12b3e773160e191e0f97
src/base64.cpp
src/base64.cpp
/* * Copyright (c) 1996 by Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ /* * Portions Copyright (c) 1995 by International Business Machines, Inc. * * International Business Machines, Inc. (hereinafter called IBM) grants * permission under its copyrights to use, copy, modify, and distribute this * Software with or without fee, provided that the above copyright notice and * all paragraphs of this notice appear in all copies, and that the name of IBM * not be used in connection with the marketing of any product incorporating * the Software or modifications thereof, without specific, written prior * permission. * * To the extent it has a right to do so, IBM grants an immunity from suit * under its patents, if any, for the use, sale or manufacture of products to * the extent that such products are used for performing Domain Name System * dynamic updates in TCP/IP networks by means of the Software. No immunity is * granted for any product per se or for any other function of any product. * * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES. */ #include <sys/types.h> #if 0 #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <arpa/nameser.h> #include <ctype.h> #include <resolv.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #endif #include <cctype> #include <cstring> #include "base64.hpp" namespace cryptolens_io { namespace v20180502 { static const char Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static const char Pad64 = '='; /* (From RFC1521 and draft-ietf-dnssec-secext-03.txt) The following encoding technique is taken from RFC 1521 by Borenstein and Freed. It is reproduced here in a slightly edited form for convenience. A 65-character subset of US-ASCII is used, enabling 6 bits to be represented per printable character. (The extra 65th character, "=", is used to signify a special processing function.) The encoding process represents 24-bit groups of input bits as output strings of 4 encoded characters. Proceeding from left to right, a 24-bit input group is formed by concatenating 3 8-bit input groups. These 24 bits are then treated as 4 concatenated 6-bit groups, each of which is translated into a single digit in the base64 alphabet. Each 6-bit group is used as an index into an array of 64 printable characters. The character referenced by the index is placed in the output string. Table 1: The Base64 Alphabet Value Encoding Value Encoding Value Encoding Value Encoding 0 A 17 R 34 i 51 z 1 B 18 S 35 j 52 0 2 C 19 T 36 k 53 1 3 D 20 U 37 l 54 2 4 E 21 V 38 m 55 3 5 F 22 W 39 n 56 4 6 G 23 X 40 o 57 5 7 H 24 Y 41 p 58 6 8 I 25 Z 42 q 59 7 9 J 26 a 43 r 60 8 10 K 27 b 44 s 61 9 11 L 28 c 45 t 62 + 12 M 29 d 46 u 63 / 13 N 30 e 47 v 14 O 31 f 48 w (pad) = 15 P 32 g 49 x 16 Q 33 h 50 y Special processing is performed if fewer than 24 bits are available at the end of the data being encoded. A full encoding quantum is always completed at the end of a quantity. When fewer than 24 input bits are available in an input group, zero bits are added (on the right) to form an integral number of 6-bit groups. Padding at the end of the data is performed using the '=' character. Since all base64 input is an integral number of octets, only the ------------------------------------------------- following cases can arise: (1) the final quantum of encoding input is an integral multiple of 24 bits; here, the final unit of encoded output will be an integral multiple of 4 characters with no "=" padding, (2) the final quantum of encoding input is exactly 8 bits; here, the final unit of encoded output will be two characters followed by two "=" padding characters, or (3) the final quantum of encoding input is exactly 16 bits; here, the final unit of encoded output will be three characters followed by one "=" padding character. */ #if 0 int b64_ntop(src, srclength, target, targsize) u_char const *src; size_t srclength; char *target; size_t targsize; { size_t datalength = 0; u_char input[3]; u_char output[4]; int i; while (2 < srclength) { input[0] = *src++; input[1] = *src++; input[2] = *src++; srclength -= 3; output[0] = input[0] >> 2; output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4); output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6); output[3] = input[2] & 0x3f; if (datalength + 4 > targsize) return (-1); target[datalength++] = Base64[output[0]]; target[datalength++] = Base64[output[1]]; target[datalength++] = Base64[output[2]]; target[datalength++] = Base64[output[3]]; } /* Now we worry about padding. */ if (0 != srclength) { /* Get what's left. */ input[0] = input[1] = input[2] = '\0'; for (i = 0; i < srclength; i++) input[i] = *src++; output[0] = input[0] >> 2; output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4); output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6); if (datalength + 4 > targsize) return (-1); target[datalength++] = Base64[output[0]]; target[datalength++] = Base64[output[1]]; if (srclength == 1) target[datalength++] = Pad64; else target[datalength++] = Base64[output[2]]; target[datalength++] = Pad64; } if (datalength >= targsize) return (-1); target[datalength] = '\0'; /* Returned value doesn't count \0. */ return (datalength); } /* skips all whitespace anywhere. converts characters, four at a time, starting at (or after) src from base - 64 numbers into three 8 bit bytes in the target area. it returns the number of data bytes stored at the target, or -1 on error. */ #endif int b64_pton(char const *src, unsigned char *target, size_t targsize) { int tarindex, state, ch; u_char nextbyte; const char *pos; state = 0; tarindex = 0; while ((ch = (unsigned char)*src++) != '\0') { if (isspace(ch)) /* Skip whitespace anywhere. */ continue; if (ch == Pad64) break; pos = strchr(Base64, ch); if (pos == 0) /* A non-base64 character. */ return (-1); switch (state) { case 0: if (target) { if (tarindex >= targsize) return (-1); target[tarindex] = (pos - Base64) << 2; } state = 1; break; case 1: if (target) { if (tarindex >= targsize) return (-1); target[tarindex] |= (pos - Base64) >> 4; nextbyte = ((pos - Base64) & 0x0f) << 4; if (tarindex + 1 < targsize) target[tarindex+1] = nextbyte; else if (nextbyte) return (-1); } tarindex++; state = 2; break; case 2: if (target) { if (tarindex >= targsize) return (-1); target[tarindex] |= (pos - Base64) >> 2; nextbyte = ((pos - Base64) & 0x03) << 6; if (tarindex + 1 < targsize) target[tarindex+1] = nextbyte; else if (nextbyte) return (-1); } tarindex++; state = 3; break; case 3: if (target) { if (tarindex >= targsize) return (-1); target[tarindex] |= (pos - Base64); } tarindex++; state = 0; break; } } /* * We are done decoding Base-64 chars. Let's see if we ended * on a byte boundary, and/or with erroneous trailing characters. */ if (ch == Pad64) { /* We got a pad char. */ ch = (unsigned char)*src++; /* Skip it, get next. */ switch (state) { case 0: /* Invalid = in first position */ case 1: /* Invalid = in second position */ return (-1); case 2: /* Valid, means one byte of info */ /* Skip any number of spaces. */ for (; ch != '\0'; ch = (unsigned char)*src++) if (!isspace(ch)) break; /* Make sure there is another trailing = sign. */ if (ch != Pad64) return (-1); ch = (unsigned char)*src++; /* Skip the = */ /* Fall through to "single trailing =" case. */ /* FALLTHROUGH */ case 3: /* Valid, means two bytes of info */ /* * We know this char is an =. Is there anything but * whitespace after it? */ for (; ch != '\0'; ch = (unsigned char)*src++) if (!isspace(ch)) return (-1); /* * Now make sure for cases 2 and 3 that the "extra" * bits that slopped past the last full byte were * zeros. If we don't check them, they become a * subliminal channel. */ if (target && tarindex < targsize && target[tarindex] != 0) return (-1); } } else { /* * We ended by seeing the end of the string. Make sure we * have no partial bytes lying around. */ if (state != 0) return (-1); } return (tarindex); } optional<std::string> b64_decode(std::string const& b64) { int len = b64_pton(b64.c_str(), NULL, 0); if (len == -1) { return nullopt; } std::string s(len, '\0'); b64_pton(b64.c_str(), (unsigned char*)s.c_str(), len); return make_optional(std::move(s)); } } // namespace v20180502 using namespace ::cryptolens_io::v20180502; } // namespace cryptolens_io
/* * Copyright (c) 1996 by Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ /* * Portions Copyright (c) 1995 by International Business Machines, Inc. * * International Business Machines, Inc. (hereinafter called IBM) grants * permission under its copyrights to use, copy, modify, and distribute this * Software with or without fee, provided that the above copyright notice and * all paragraphs of this notice appear in all copies, and that the name of IBM * not be used in connection with the marketing of any product incorporating * the Software or modifications thereof, without specific, written prior * permission. * * To the extent it has a right to do so, IBM grants an immunity from suit * under its patents, if any, for the use, sale or manufacture of products to * the extent that such products are used for performing Domain Name System * dynamic updates in TCP/IP networks by means of the Software. No immunity is * granted for any product per se or for any other function of any product. * * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES. */ #include <sys/types.h> #if 0 #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <arpa/nameser.h> #include <ctype.h> #include <resolv.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #endif #include <cctype> #include <cstring> #include "base64.hpp" namespace cryptolens_io { namespace v20180502 { static const char Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static const char Pad64 = '='; /* (From RFC1521 and draft-ietf-dnssec-secext-03.txt) The following encoding technique is taken from RFC 1521 by Borenstein and Freed. It is reproduced here in a slightly edited form for convenience. A 65-character subset of US-ASCII is used, enabling 6 bits to be represented per printable character. (The extra 65th character, "=", is used to signify a special processing function.) The encoding process represents 24-bit groups of input bits as output strings of 4 encoded characters. Proceeding from left to right, a 24-bit input group is formed by concatenating 3 8-bit input groups. These 24 bits are then treated as 4 concatenated 6-bit groups, each of which is translated into a single digit in the base64 alphabet. Each 6-bit group is used as an index into an array of 64 printable characters. The character referenced by the index is placed in the output string. Table 1: The Base64 Alphabet Value Encoding Value Encoding Value Encoding Value Encoding 0 A 17 R 34 i 51 z 1 B 18 S 35 j 52 0 2 C 19 T 36 k 53 1 3 D 20 U 37 l 54 2 4 E 21 V 38 m 55 3 5 F 22 W 39 n 56 4 6 G 23 X 40 o 57 5 7 H 24 Y 41 p 58 6 8 I 25 Z 42 q 59 7 9 J 26 a 43 r 60 8 10 K 27 b 44 s 61 9 11 L 28 c 45 t 62 + 12 M 29 d 46 u 63 / 13 N 30 e 47 v 14 O 31 f 48 w (pad) = 15 P 32 g 49 x 16 Q 33 h 50 y Special processing is performed if fewer than 24 bits are available at the end of the data being encoded. A full encoding quantum is always completed at the end of a quantity. When fewer than 24 input bits are available in an input group, zero bits are added (on the right) to form an integral number of 6-bit groups. Padding at the end of the data is performed using the '=' character. Since all base64 input is an integral number of octets, only the ------------------------------------------------- following cases can arise: (1) the final quantum of encoding input is an integral multiple of 24 bits; here, the final unit of encoded output will be an integral multiple of 4 characters with no "=" padding, (2) the final quantum of encoding input is exactly 8 bits; here, the final unit of encoded output will be two characters followed by two "=" padding characters, or (3) the final quantum of encoding input is exactly 16 bits; here, the final unit of encoded output will be three characters followed by one "=" padding character. */ #if 0 int b64_ntop(src, srclength, target, targsize) u_char const *src; size_t srclength; char *target; size_t targsize; { size_t datalength = 0; u_char input[3]; u_char output[4]; int i; while (2 < srclength) { input[0] = *src++; input[1] = *src++; input[2] = *src++; srclength -= 3; output[0] = input[0] >> 2; output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4); output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6); output[3] = input[2] & 0x3f; if (datalength + 4 > targsize) return (-1); target[datalength++] = Base64[output[0]]; target[datalength++] = Base64[output[1]]; target[datalength++] = Base64[output[2]]; target[datalength++] = Base64[output[3]]; } /* Now we worry about padding. */ if (0 != srclength) { /* Get what's left. */ input[0] = input[1] = input[2] = '\0'; for (i = 0; i < srclength; i++) input[i] = *src++; output[0] = input[0] >> 2; output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4); output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6); if (datalength + 4 > targsize) return (-1); target[datalength++] = Base64[output[0]]; target[datalength++] = Base64[output[1]]; if (srclength == 1) target[datalength++] = Pad64; else target[datalength++] = Base64[output[2]]; target[datalength++] = Pad64; } if (datalength >= targsize) return (-1); target[datalength] = '\0'; /* Returned value doesn't count \0. */ return (datalength); } /* skips all whitespace anywhere. converts characters, four at a time, starting at (or after) src from base - 64 numbers into three 8 bit bytes in the target area. it returns the number of data bytes stored at the target, or -1 on error. */ #endif int b64_pton(char const *src, unsigned char *target, size_t targsize) { int tarindex, state, ch; unsigned char nextbyte; const char *pos; state = 0; tarindex = 0; while ((ch = (unsigned char)*src++) != '\0') { if (isspace(ch)) /* Skip whitespace anywhere. */ continue; if (ch == Pad64) break; pos = strchr(Base64, ch); if (pos == 0) /* A non-base64 character. */ return (-1); switch (state) { case 0: if (target) { if (tarindex >= targsize) return (-1); target[tarindex] = (pos - Base64) << 2; } state = 1; break; case 1: if (target) { if (tarindex >= targsize) return (-1); target[tarindex] |= (pos - Base64) >> 4; nextbyte = ((pos - Base64) & 0x0f) << 4; if (tarindex + 1 < targsize) target[tarindex+1] = nextbyte; else if (nextbyte) return (-1); } tarindex++; state = 2; break; case 2: if (target) { if (tarindex >= targsize) return (-1); target[tarindex] |= (pos - Base64) >> 2; nextbyte = ((pos - Base64) & 0x03) << 6; if (tarindex + 1 < targsize) target[tarindex+1] = nextbyte; else if (nextbyte) return (-1); } tarindex++; state = 3; break; case 3: if (target) { if (tarindex >= targsize) return (-1); target[tarindex] |= (pos - Base64); } tarindex++; state = 0; break; } } /* * We are done decoding Base-64 chars. Let's see if we ended * on a byte boundary, and/or with erroneous trailing characters. */ if (ch == Pad64) { /* We got a pad char. */ ch = (unsigned char)*src++; /* Skip it, get next. */ switch (state) { case 0: /* Invalid = in first position */ case 1: /* Invalid = in second position */ return (-1); case 2: /* Valid, means one byte of info */ /* Skip any number of spaces. */ for (; ch != '\0'; ch = (unsigned char)*src++) if (!isspace(ch)) break; /* Make sure there is another trailing = sign. */ if (ch != Pad64) return (-1); ch = (unsigned char)*src++; /* Skip the = */ /* Fall through to "single trailing =" case. */ /* FALLTHROUGH */ case 3: /* Valid, means two bytes of info */ /* * We know this char is an =. Is there anything but * whitespace after it? */ for (; ch != '\0'; ch = (unsigned char)*src++) if (!isspace(ch)) return (-1); /* * Now make sure for cases 2 and 3 that the "extra" * bits that slopped past the last full byte were * zeros. If we don't check them, they become a * subliminal channel. */ if (target && tarindex < targsize && target[tarindex] != 0) return (-1); } } else { /* * We ended by seeing the end of the string. Make sure we * have no partial bytes lying around. */ if (state != 0) return (-1); } return (tarindex); } optional<std::string> b64_decode(std::string const& b64) { int len = b64_pton(b64.c_str(), NULL, 0); if (len == -1) { return nullopt; } std::string s(len, '\0'); b64_pton(b64.c_str(), (unsigned char*)s.c_str(), len); return make_optional(std::move(s)); } } // namespace v20180502 using namespace ::cryptolens_io::v20180502; } // namespace cryptolens_io
Fix portability issue with base64 decoder
Fix portability issue with base64 decoder
C++
bsd-2-clause
SerialKeyManager/SKM-Client-API-CPP,SerialKeyManager/SKM-Client-API-CPP
caf397aa886de9e86836632df2f776899006f817
src/nixsection.cc
src/nixsection.cc
#include "nixsection.h" #include "mex.h" #include <nix.hpp> #include "nixgen.h" #include "handle.h" #include "arguments.h" #include "struct.h" #include "nix2mx.h" namespace nixsection { static mxArray* array_from_value(nix::Value v) { mxArray *res; nix::DataType dtype = v.type(); switch (dtype) { case nix::DataType::Bool: res = make_mx_array(v.get<bool>()); break; case nix::DataType::String: res = make_mx_array(v.get<std::string>()); break; case nix::DataType::Double: res = make_mx_array(v.get<double>()); break; case nix::DataType::Int32: res = make_mx_array(v.get<std::int32_t>()); break; case nix::DataType::UInt32: res = make_mx_array(v.get<std::uint32_t>()); break; case nix::DataType::Int64: res = make_mx_array(v.get<std::int64_t>()); break; case nix::DataType::UInt64: res = make_mx_array(v.get<std::uint64_t>()); break; default: res = make_mx_array(v.get<std::string>()); } return res; } void describe(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); struct_builder sb({ 1 }, { "name", "id", "type", "repository", "mapping" }); sb.set(section.name()); sb.set(section.id()); sb.set(section.type()); sb.set(section.repository()); sb.set(section.mapping()); output.set(0, sb.array()); } void link(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); nix::Section linked = section.link(); handle lh = handle(linked); output.set(0, lh); } void parent(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); nix::Section parent = section.parent(); handle lh = handle(parent); output.set(0, lh); } void has_section(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); output.set(0, nixgen::has_entity(section.hasSection(input.str(2)), { "hasSection" })); } void open_section(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); nix::Section sec = section.getSection(input.str(2)); handle h = handle(sec); output.set(0, h); } void list_sections(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); std::vector<nix::Section> sections = section.sections(); struct_builder sb({ sections.size() }, { "name", "id", "type" }); for (const auto &b : sections) { sb.set(b.name()); sb.set(b.id()); sb.set(b.type()); sb.next(); } output.set(0, sb.array()); } void sections(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); std::vector<nix::Section> sections = section.sections(); const mwSize size = static_cast<mwSize>(sections.size()); mxArray *lst = mxCreateCellArray(1, &size); for (int i = 0; i < sections.size(); i++) { mxSetCell(lst, i, make_mx_array(handle(sections[i]))); } output.set(0, lst); } void has_property(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); output.set(0, nixgen::has_entity(section.hasProperty(input.str(2)), { "hasProperty" })); } void list_properties(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); std::vector<nix::Property> properties = section.properties(); const mwSize size = static_cast<mwSize>(properties.size()); mxArray *lst = mxCreateCellArray(1, &size); for (int i = 0; i < properties.size(); i++) { nix::Property pr = properties[i]; std::vector<nix::Value> values = pr.values(); const mwSize vsize = static_cast<mwSize>(values.size()); mxArray *mx_values = mxCreateCellArray(1, &size); for (int j = 0; j < values.size(); j++) { mxSetCell(mx_values, j, array_from_value(values[j])); } struct_builder sb({ 1 }, { "name", "id", "definition", "mapping", "unit", "values" }); sb.set(pr.name()); sb.set(pr.id()); sb.set(pr.definition()); sb.set(pr.mapping()); sb.set(pr.unit()); sb.set(mx_values); mxSetCell(lst, i, sb.array()); } output.set(0, lst); } } // namespace nixfile
#include "nixsection.h" #include "mex.h" #include <nix.hpp> #include "nixgen.h" #include "handle.h" #include "arguments.h" #include "struct.h" #include "nix2mx.h" namespace nixsection { static mxArray* array_from_value(nix::Value v) { mxArray *res; nix::DataType dtype = v.type(); switch (dtype) { case nix::DataType::Bool: res = make_mx_array(v.get<bool>()); break; case nix::DataType::String: res = make_mx_array(v.get<std::string>()); break; case nix::DataType::Double: res = make_mx_array(v.get<double>()); break; case nix::DataType::Int32: res = make_mx_array(v.get<std::int32_t>()); break; case nix::DataType::UInt32: res = make_mx_array(v.get<std::uint32_t>()); break; case nix::DataType::Int64: res = make_mx_array(v.get<std::int64_t>()); break; case nix::DataType::UInt64: res = make_mx_array(v.get<std::uint64_t>()); break; default: res = make_mx_array(v.get<std::string>()); } return res; } void describe(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); struct_builder sb({ 1 }, { "name", "id", "type", "repository", "mapping" }); sb.set(section.name()); sb.set(section.id()); sb.set(section.type()); sb.set(section.repository()); sb.set(section.mapping()); output.set(0, sb.array()); } void link(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); nix::Section linked = section.link(); handle lh = handle(linked); output.set(0, lh); } void parent(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); nix::Section parent = section.parent(); handle lh = handle(parent); output.set(0, lh); } void has_section(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); output.set(0, nixgen::has_entity(section.hasSection(input.str(2)), { "hasSection" })); } void open_section(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); nix::Section sec = section.getSection(input.str(2)); handle h = handle(sec); output.set(0, h); } void list_sections(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); std::vector<nix::Section> sections = section.sections(); struct_builder sb({ sections.size() }, { "name", "id", "type" }); for (const auto &b : sections) { sb.set(b.name()); sb.set(b.id()); sb.set(b.type()); sb.next(); } output.set(0, sb.array()); } void sections(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); std::vector<nix::Section> sections = section.sections(); const mwSize size = static_cast<mwSize>(sections.size()); mxArray *lst = mxCreateCellArray(1, &size); for (int i = 0; i < sections.size(); i++) { mxSetCell(lst, i, make_mx_array(handle(sections[i]))); } output.set(0, lst); } void has_property(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); output.set(0, nixgen::has_entity(section.hasProperty(input.str(2)), { "hasProperty" })); } void list_properties(const extractor &input, infusor &output) { nix::Section section = input.entity<nix::Section>(1); std::vector<nix::Property> properties = section.properties(); const mwSize size = static_cast<mwSize>(properties.size()); mxArray *lst = mxCreateCellArray(1, &size); for (int i = 0; i < properties.size(); i++) { nix::Property pr = properties[i]; std::vector<nix::Value> values = pr.values(); const mwSize val_size = static_cast<mwSize>(values.size()); mxArray *mx_values = mxCreateCellArray(1, &val_size); for (int j = 0; j < values.size(); j++) { mxSetCell(mx_values, j, array_from_value(values[j])); } struct_builder sb({ 1 }, { "name", "id", "definition", "mapping", "unit", "values" }); sb.set(pr.name()); sb.set(pr.id()); sb.set(pr.definition()); sb.set(pr.mapping()); sb.set(pr.unit()); sb.set(mx_values); mxSetCell(lst, i, sb.array()); } output.set(0, lst); } } // namespace nixfile
fix value array size
nixsection: fix value array size Used section's size not value's
C++
bsd-3-clause
mpsonntag/nix-mx,mpsonntag/nix-mx
1aeb85c65cd1240b99ca3764821266c2f0187cc4
src/node-midi.cpp
src/node-midi.cpp
#include <v8.h> #include <node.h> #include <node_object_wrap.h> #include <queue> #include <uv.h> #include "lib/RtMidi/RtMidi.h" #include "lib/RtMidi/RtMidi.cpp" using namespace node; class NodeMidiOutput : ObjectWrap { private: RtMidiOut* out; public: static v8::Persistent<v8::FunctionTemplate> s_ct; static void Init(v8::Handle<v8::Object> target) { v8::HandleScope scope; v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New); s_ct = v8::Persistent<v8::FunctionTemplate>::New(t); s_ct->InstanceTemplate()->SetInternalFieldCount(1); s_ct->SetClassName(v8::String::NewSymbol("NodeMidiOutput")); NODE_SET_PROTOTYPE_METHOD(s_ct, "getPortCount", GetPortCount); NODE_SET_PROTOTYPE_METHOD(s_ct, "getPortName", GetPortName); NODE_SET_PROTOTYPE_METHOD(s_ct, "openPort", OpenPort); NODE_SET_PROTOTYPE_METHOD(s_ct, "openVirtualPort", OpenVirtualPort); NODE_SET_PROTOTYPE_METHOD(s_ct, "closePort", ClosePort); NODE_SET_PROTOTYPE_METHOD(s_ct, "sendMessage", SendMessage); target->Set(v8::String::NewSymbol("output"), s_ct->GetFunction()); } NodeMidiOutput() { out = new RtMidiOut(); } ~NodeMidiOutput() { delete out; } static v8::Handle<v8::Value> New(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = new NodeMidiOutput(); output->Wrap(args.This()); return args.This(); } static v8::Handle<v8::Value> GetPortCount(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); v8::Local<v8::Integer> result = v8::Uint32::New(output->out->getPortCount()); return scope.Close(result); } static v8::Handle<v8::Value> GetPortName(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); if (args.Length() == 0 || !args[0]->IsUint32()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an integer"))); } unsigned int portNumber = args[0]->Uint32Value(); v8::Local<v8::String> result = v8::String::New(output->out->getPortName(portNumber).c_str()); return scope.Close(result); } static v8::Handle<v8::Value> OpenPort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); if (args.Length() == 0 || !args[0]->IsUint32()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an integer"))); } unsigned int portNumber = args[0]->Uint32Value(); output->out->openPort(portNumber); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> OpenVirtualPort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be a string"))); } std::string name(*v8::String::AsciiValue(args[0])); output->out->openVirtualPort(name); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> ClosePort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); output->out->closePort(); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> SendMessage(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); if (args.Length() == 0 || !args[0]->IsArray()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an array"))); } v8::Local<v8::Object> message = args[0]->ToObject(); size_t messageLength = message->Get(v8::String::New("length"))->Int32Value(); std::vector<unsigned char> messageOutput; for (size_t i = 0; i != messageLength; ++i) { messageOutput.push_back(message->Get(v8::Integer::New(i))->Int32Value()); } output->out->sendMessage(&messageOutput); return scope.Close(v8::Undefined()); } }; static v8::Persistent<v8::String> emit_symbol; class NodeMidiInput : public ObjectWrap { private: RtMidiIn* in; public: uv_async_t message_async; pthread_mutex_t message_mutex; struct MidiMessage { double deltaTime; std::vector<unsigned char> message; }; std::queue<MidiMessage*> message_queue; static v8::Persistent<v8::FunctionTemplate> s_ct; static void Init(v8::Handle<v8::Object> target) { v8::HandleScope scope; v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New); s_ct = v8::Persistent<v8::FunctionTemplate>::New(t); s_ct->InstanceTemplate()->SetInternalFieldCount(1); emit_symbol = v8::Persistent<v8::String>::New(v8::String::NewSymbol("emit")); s_ct->SetClassName(v8::String::NewSymbol("NodeMidiInput")); NODE_SET_PROTOTYPE_METHOD(s_ct, "getPortCount", GetPortCount); NODE_SET_PROTOTYPE_METHOD(s_ct, "getPortName", GetPortName); NODE_SET_PROTOTYPE_METHOD(s_ct, "openPort", OpenPort); NODE_SET_PROTOTYPE_METHOD(s_ct, "openVirtualPort", OpenVirtualPort); NODE_SET_PROTOTYPE_METHOD(s_ct, "closePort", ClosePort); NODE_SET_PROTOTYPE_METHOD(s_ct, "ignoreTypes", IgnoreTypes); target->Set(v8::String::NewSymbol("input"), s_ct->GetFunction()); } NodeMidiInput() { in = new RtMidiIn(); pthread_mutex_init(&message_mutex, NULL); } ~NodeMidiInput() { in->closePort(); // not sure im doing the right thing here for uv the two next lines // ev_async_stop(EV_DEFAULT_UC_ message_async); delete &message_async; delete in; pthread_mutex_destroy(&message_mutex); } static void EmitMessage(uv_async_t *w, int status) { assert(status == 0); v8::HandleScope scope; NodeMidiInput *input = static_cast<NodeMidiInput*>(w->data); pthread_mutex_lock(&input->message_mutex); while (!input->message_queue.empty()) { MidiMessage* message = input->message_queue.front(); v8::Local<v8::Value> args[3]; args[0]= v8::String::New("message"); args[1] = v8::Local<v8::Value>::New(v8::Number::New(message->deltaTime)); size_t count = message->message.size(); v8::Local<v8::Array> data = v8::Array::New(count); for (size_t i = 0; i < count; ++i) { data->Set(v8::Number::New(i), v8::Integer::New(message->message[i])); } args[2] = v8::Local<v8::Value>::New(data); v8::Local<v8::Value> emit_v = input->handle_->Get(emit_symbol); if (emit_v->IsFunction()) { v8::Local<v8::Function> emit=v8::Local<v8::Function>::Cast(emit_v); v8::TryCatch tc; emit->Call(input->handle_,3,args); if (tc.HasCaught()){ node::FatalException(tc); } } input->message_queue.pop(); delete message; } pthread_mutex_unlock(&input->message_mutex); } static void Callback(double deltaTime, std::vector<unsigned char> *message, void *userData) { NodeMidiInput *input = static_cast<NodeMidiInput*>(userData); MidiMessage* data = new MidiMessage(); data->deltaTime = deltaTime; data->message = *message; pthread_mutex_lock(&input->message_mutex); input->message_queue.push(data); pthread_mutex_unlock(&input->message_mutex); uv_async_send(&input->message_async); } static v8::Handle<v8::Value> New(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = new NodeMidiInput(); input->message_async.data = input; uv_async_init(uv_default_loop(), &input->message_async, NodeMidiInput::EmitMessage); uv_unref(uv_default_loop()); input->Wrap(args.This()); return args.This(); } static v8::Handle<v8::Value> GetPortCount(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); v8::Local<v8::Integer> result = v8::Uint32::New(input->in->getPortCount()); return scope.Close(result); } static v8::Handle<v8::Value> GetPortName(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); if (args.Length() == 0 || !args[0]->IsUint32()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an integer"))); } unsigned int portNumber = args[0]->Uint32Value(); v8::Local<v8::String> result = v8::String::New(input->in->getPortName(portNumber).c_str()); return scope.Close(result); } static v8::Handle<v8::Value> OpenPort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); if (args.Length() == 0 || !args[0]->IsUint32()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an integer"))); } unsigned int portNumber = args[0]->Uint32Value(); input->Ref(); input->in->setCallback(&NodeMidiInput::Callback, ObjectWrap::Unwrap<NodeMidiInput>(args.This())); input->in->openPort(portNumber); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> OpenVirtualPort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be a string"))); } std::string name(*v8::String::AsciiValue(args[0])); input->Ref(); input->in->setCallback(&NodeMidiInput::Callback, ObjectWrap::Unwrap<NodeMidiInput>(args.This())); input->in->openVirtualPort(name); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> ClosePort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); input->Unref(); input->in->closePort(); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> IgnoreTypes(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); if (args.Length() != 3 || !args[0]->IsBoolean() || !args[1]->IsBoolean() || !args[2]->IsBoolean()) { return ThrowException(v8::Exception::TypeError( v8::String::New("Arguments must be boolean"))); } bool filter_sysex = args[0]->BooleanValue(); bool filter_timing = args[1]->BooleanValue(); bool filter_sensing = args[2]->BooleanValue(); input->in->ignoreTypes(filter_sysex, filter_timing, filter_sensing); return scope.Close(v8::Undefined()); } }; v8::Persistent<v8::FunctionTemplate> NodeMidiOutput::s_ct; v8::Persistent<v8::FunctionTemplate> NodeMidiInput::s_ct; extern "C" { void init (v8::Handle<v8::Object> target) { NodeMidiOutput::Init(target); NodeMidiInput::Init(target); } NODE_MODULE(nodemidi, init); }
#include <v8.h> #include <node.h> #include <node_object_wrap.h> #include <queue> #include <uv.h> #include "lib/RtMidi/RtMidi.h" #include "lib/RtMidi/RtMidi.cpp" using namespace node; class NodeMidiOutput : ObjectWrap { private: RtMidiOut* out; public: static v8::Persistent<v8::FunctionTemplate> s_ct; static void Init(v8::Handle<v8::Object> target) { v8::HandleScope scope; v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New); s_ct = v8::Persistent<v8::FunctionTemplate>::New(t); s_ct->InstanceTemplate()->SetInternalFieldCount(1); s_ct->SetClassName(v8::String::NewSymbol("NodeMidiOutput")); NODE_SET_PROTOTYPE_METHOD(s_ct, "getPortCount", GetPortCount); NODE_SET_PROTOTYPE_METHOD(s_ct, "getPortName", GetPortName); NODE_SET_PROTOTYPE_METHOD(s_ct, "openPort", OpenPort); NODE_SET_PROTOTYPE_METHOD(s_ct, "openVirtualPort", OpenVirtualPort); NODE_SET_PROTOTYPE_METHOD(s_ct, "closePort", ClosePort); NODE_SET_PROTOTYPE_METHOD(s_ct, "sendMessage", SendMessage); target->Set(v8::String::NewSymbol("output"), s_ct->GetFunction()); } NodeMidiOutput() { out = new RtMidiOut(); } ~NodeMidiOutput() { delete out; } static v8::Handle<v8::Value> New(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = new NodeMidiOutput(); output->Wrap(args.This()); return args.This(); } static v8::Handle<v8::Value> GetPortCount(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); v8::Local<v8::Integer> result = v8::Uint32::New(output->out->getPortCount()); return scope.Close(result); } static v8::Handle<v8::Value> GetPortName(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); if (args.Length() == 0 || !args[0]->IsUint32()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an integer"))); } unsigned int portNumber = args[0]->Uint32Value(); v8::Local<v8::String> result = v8::String::New(output->out->getPortName(portNumber).c_str()); return scope.Close(result); } static v8::Handle<v8::Value> OpenPort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); if (args.Length() == 0 || !args[0]->IsUint32()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an integer"))); } unsigned int portNumber = args[0]->Uint32Value(); if (portNumber >= output->out->getPortCount()) { return ThrowException(v8::Exception::RangeError( v8::String::New("Invalid MIDI port number"))); } output->out->openPort(portNumber); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> OpenVirtualPort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be a string"))); } std::string name(*v8::String::AsciiValue(args[0])); output->out->openVirtualPort(name); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> ClosePort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); output->out->closePort(); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> SendMessage(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiOutput* output = ObjectWrap::Unwrap<NodeMidiOutput>(args.This()); if (args.Length() == 0 || !args[0]->IsArray()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an array"))); } v8::Local<v8::Object> message = args[0]->ToObject(); size_t messageLength = message->Get(v8::String::New("length"))->Int32Value(); std::vector<unsigned char> messageOutput; for (size_t i = 0; i != messageLength; ++i) { messageOutput.push_back(message->Get(v8::Integer::New(i))->Int32Value()); } output->out->sendMessage(&messageOutput); return scope.Close(v8::Undefined()); } }; static v8::Persistent<v8::String> emit_symbol; class NodeMidiInput : public ObjectWrap { private: RtMidiIn* in; public: uv_async_t message_async; pthread_mutex_t message_mutex; struct MidiMessage { double deltaTime; std::vector<unsigned char> message; }; std::queue<MidiMessage*> message_queue; static v8::Persistent<v8::FunctionTemplate> s_ct; static void Init(v8::Handle<v8::Object> target) { v8::HandleScope scope; v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New); s_ct = v8::Persistent<v8::FunctionTemplate>::New(t); s_ct->InstanceTemplate()->SetInternalFieldCount(1); emit_symbol = NODE_PSYMBOL("emit"); s_ct->SetClassName(v8::String::NewSymbol("NodeMidiInput")); NODE_SET_PROTOTYPE_METHOD(s_ct, "getPortCount", GetPortCount); NODE_SET_PROTOTYPE_METHOD(s_ct, "getPortName", GetPortName); NODE_SET_PROTOTYPE_METHOD(s_ct, "openPort", OpenPort); NODE_SET_PROTOTYPE_METHOD(s_ct, "openVirtualPort", OpenVirtualPort); NODE_SET_PROTOTYPE_METHOD(s_ct, "closePort", ClosePort); NODE_SET_PROTOTYPE_METHOD(s_ct, "ignoreTypes", IgnoreTypes); target->Set(v8::String::NewSymbol("input"), s_ct->GetFunction()); } NodeMidiInput() { in = new RtMidiIn(); pthread_mutex_init(&message_mutex, NULL); } ~NodeMidiInput() { in->closePort(); delete &message_async; delete in; pthread_mutex_destroy(&message_mutex); } static void EmitMessage(uv_async_t *w, int status) { assert(status == 0); v8::HandleScope scope; NodeMidiInput *input = static_cast<NodeMidiInput*>(w->data); pthread_mutex_lock(&input->message_mutex); while (!input->message_queue.empty()) { MidiMessage* message = input->message_queue.front(); v8::Local<v8::Value> args[3]; args[0]= v8::String::New("message"); args[1] = v8::Local<v8::Value>::New(v8::Number::New(message->deltaTime)); size_t count = message->message.size(); v8::Local<v8::Array> data = v8::Array::New(count); for (size_t i = 0; i < count; ++i) { data->Set(v8::Number::New(i), v8::Integer::New(message->message[i])); } args[2] = v8::Local<v8::Value>::New(data); v8::Local<v8::Value> emit_v = input->handle_->Get(emit_symbol); if (emit_v->IsFunction()) { v8::Local<v8::Function> emit=v8::Local<v8::Function>::Cast(emit_v); v8::TryCatch tc; emit->Call(input->handle_,3,args); if (tc.HasCaught()){ std::cerr << '\n' << "node_midi: unexpected error" << "\n\n"; node::FatalException(tc); } } input->message_queue.pop(); delete message; } pthread_mutex_unlock(&input->message_mutex); } static void Callback(double deltaTime, std::vector<unsigned char> *message, void *userData) { NodeMidiInput *input = static_cast<NodeMidiInput*>(userData); MidiMessage* data = new MidiMessage(); data->deltaTime = deltaTime; data->message = *message; pthread_mutex_lock(&input->message_mutex); input->message_queue.push(data); pthread_mutex_unlock(&input->message_mutex); uv_async_send(&input->message_async); } static v8::Handle<v8::Value> New(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = new NodeMidiInput(); input->message_async.data = input; uv_async_init(uv_default_loop(), &input->message_async, NodeMidiInput::EmitMessage); uv_unref(uv_default_loop()); input->Wrap(args.This()); return args.This(); } static v8::Handle<v8::Value> GetPortCount(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); v8::Local<v8::Integer> result = v8::Uint32::New(input->in->getPortCount()); return scope.Close(result); } static v8::Handle<v8::Value> GetPortName(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); if (args.Length() == 0 || !args[0]->IsUint32()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an integer"))); } unsigned int portNumber = args[0]->Uint32Value(); v8::Local<v8::String> result = v8::String::New(input->in->getPortName(portNumber).c_str()); return scope.Close(result); } static v8::Handle<v8::Value> OpenPort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); if (args.Length() == 0 || !args[0]->IsUint32()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be an integer"))); } unsigned int portNumber = args[0]->Uint32Value(); if (portNumber >= input->in->getPortCount()) { return ThrowException(v8::Exception::RangeError( v8::String::New("Invalid MIDI port number"))); } input->Ref(); input->in->setCallback(&NodeMidiInput::Callback, ObjectWrap::Unwrap<NodeMidiInput>(args.This())); input->in->openPort(portNumber); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> OpenVirtualPort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); if (args.Length() == 0 || !args[0]->IsString()) { return ThrowException(v8::Exception::TypeError( v8::String::New("First argument must be a string"))); } std::string name(*v8::String::AsciiValue(args[0])); input->Ref(); input->in->setCallback(&NodeMidiInput::Callback, ObjectWrap::Unwrap<NodeMidiInput>(args.This())); input->in->openVirtualPort(name); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> ClosePort(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); input->Unref(); input->in->closePort(); return scope.Close(v8::Undefined()); } static v8::Handle<v8::Value> IgnoreTypes(const v8::Arguments& args) { v8::HandleScope scope; NodeMidiInput* input = ObjectWrap::Unwrap<NodeMidiInput>(args.This()); if (args.Length() != 3 || !args[0]->IsBoolean() || !args[1]->IsBoolean() || !args[2]->IsBoolean()) { return ThrowException(v8::Exception::TypeError( v8::String::New("Arguments must be boolean"))); } bool filter_sysex = args[0]->BooleanValue(); bool filter_timing = args[1]->BooleanValue(); bool filter_sensing = args[2]->BooleanValue(); input->in->ignoreTypes(filter_sysex, filter_timing, filter_sensing); return scope.Close(v8::Undefined()); } }; v8::Persistent<v8::FunctionTemplate> NodeMidiOutput::s_ct; v8::Persistent<v8::FunctionTemplate> NodeMidiInput::s_ct; extern "C" { void init (v8::Handle<v8::Object> target) { NodeMidiOutput::Init(target); NodeMidiInput::Init(target); } NODE_MODULE(nodemidi, init) }
check port number before trying to open
check port number before trying to open Conflicts: src/node-midi.cpp
C++
mit
szymonkaliski/node-midi,drewish/node-midi,Cycling74/node-midi,szymonkaliski/node-midi,drewish/node-midi,justinlatimer/node-midi,Cycling74/node-midi,Cycling74/node-midi,drewish/node-midi,julianduque/node-midi,szymonkaliski/node-midi,drewish/node-midi,justinlatimer/node-midi,brandly/node-midi,julianduque/node-midi,julianduque/node-midi,Cycling74/node-midi,julianduque/node-midi,brandly/node-midi,brandly/node-midi,drewish/node-midi,szymonkaliski/node-midi,Cycling74/node-midi,szymonkaliski/node-midi,julianduque/node-midi,brandly/node-midi,Cycling74/node-midi,justinlatimer/node-midi,brandly/node-midi
a9bddf581b98ac0041e05529726e2016b33e4f45
include/wtl/string.hpp
include/wtl/string.hpp
#pragma once #ifndef WTL_STRING_HPP_ #define WTL_STRING_HPP_ #include <string> #include <vector> namespace wtl { template <class T> inline T sto(const std::string& s) {return s;} template <> inline const char* sto(const std::string& s) {return s.c_str();} template <> inline bool sto<bool>(const std::string&) {return true;} template <> inline int sto<int>(const std::string& s) {return std::stoi(s);} template <> inline long sto<long>(const std::string& s) {return std::stol(s);} template <> inline long long sto<long long>(const std::string& s) {return std::stoll(s);} template <> inline unsigned sto<unsigned>(const std::string& s) {return static_cast<unsigned>(std::stoul(s));} template <> inline unsigned long sto<unsigned long>(const std::string& s) {return std::stoul(s);} template <> inline unsigned long long sto<unsigned long long>(const std::string& s) {return std::stoull(s);} template <> inline double sto<double>(const std::string& s) {return std::stod(s);} template <class T> inline void split(const std::string& src, const std::string& delimiter, T* dst) { if (src.empty()) return; for (size_t start = 0, pos = 0; pos != src.npos; start = pos + 1u) { pos = src.find_first_of(delimiter, start); dst->push_back(sto<typename T::value_type>(src.substr(start, pos - start))); } } template <class T = std::string> inline std::vector<T> split(const std::string& src, const std::string& delimiter=" \t\n") { std::vector<T> dst; split(src, delimiter, &dst); return dst; } inline std::string rstrip(const std::string& s, const std::string& chars=" ") { return s.substr(0u, s.find_last_not_of(chars) + 1u); } inline std::string lstrip(const std::string& s, const std::string& chars=" ") { return s.substr(s.find_first_not_of(chars)); } inline std::string strip(const std::string& s, const std::string& chars=" ") { return rstrip(lstrip(s, chars), chars); } inline bool startswith(const std::string& str, const std::string& prefix) { return (str.size() >= prefix.size()) && (str.compare(0, prefix.size(), prefix) == 0); } inline bool endswith(const std::string& str, const std::string& suffix) { size_t str_size = str.size(); return (str_size >= suffix.size()) && (str.compare(str_size -= suffix.size(), suffix.size(), suffix) == 0); } inline std::string replace_all(const std::string& patt, const std::string& repl, const std::string& src) { std::string result; std::string::size_type pos_before(0); std::string::size_type pos(0); std::string::size_type len(patt.size()); while ((pos = src.find(patt, pos)) != std::string::npos) { result.append(src, pos_before, pos-pos_before); result.append(repl); pos += len; pos_before = pos; } result.append(src, pos_before, src.size()-pos_before); return result; } } // namespace wtl #endif // WTL_STRING_HPP_
#pragma once #ifndef WTL_STRING_HPP_ #define WTL_STRING_HPP_ #include <string> #include <vector> namespace wtl { template <class T> inline T sto(const std::string& s) {return s;} template <> inline const char* sto(const std::string& s) {return s.c_str();} template <> inline bool sto<bool>(const std::string&) {return true;} template <> inline int sto<int>(const std::string& s) {return std::stoi(s);} template <> inline long sto<long>(const std::string& s) {return std::stol(s);} template <> inline long long sto<long long>(const std::string& s) {return std::stoll(s);} template <> inline unsigned sto<unsigned>(const std::string& s) {return static_cast<unsigned>(std::stoul(s));} template <> inline unsigned long sto<unsigned long>(const std::string& s) {return std::stoul(s);} template <> inline unsigned long long sto<unsigned long long>(const std::string& s) {return std::stoull(s);} template <> inline double sto<double>(const std::string& s) {return std::stod(s);} template <class T> inline void split(const std::string& src, const std::string& delimiter, T* dst) { if (src.empty()) return; for (size_t start = 0, pos = 0; pos != src.npos; start = pos + 1u) { pos = src.find_first_of(delimiter, start); dst->push_back(sto<typename T::value_type>(src.substr(start, pos - start))); } } template <class T = std::string> inline std::vector<T> split(const std::string& src, const std::string& delimiter=" \t\n") { std::vector<T> dst; split(src, delimiter, &dst); return dst; } inline std::string rstrip(const std::string& s, const std::string& chars=" ") { return s.substr(0u, s.find_last_not_of(chars) + 1u); } inline std::string lstrip(const std::string& s, const std::string& chars=" ") { return s.substr(s.find_first_not_of(chars)); } inline std::string strip(const std::string& s, const std::string& chars=" ") { return rstrip(lstrip(s, chars), chars); } inline bool startswith(const std::string& str, const std::string& prefix) { return (str.size() >= prefix.size()) && (str.compare(0, prefix.size(), prefix) == 0); } inline bool endswith(const std::string& str, const std::string& suffix) { size_t str_size = str.size(); return (str_size >= suffix.size()) && (str.compare(str_size -= suffix.size(), suffix.size(), suffix) == 0); } // Use std::replace() in <algorithm> for single char substitution inline void replace(std::string* s, const std::string& patt, const std::string& repl) { const auto pattsize = patt.size(); std::string::size_type pos = 0u; while ((pos = s->find(patt, pos)) != std::string::npos) { s->replace(pos, pattsize, repl); pos += pattsize; } } inline std::string replace(std::string s, const std::string& patt, const std::string& repl) { replace(&s, patt, repl); return s; } } // namespace wtl #endif // WTL_STRING_HPP_
Rename and refactor replace() in string.hpp
:boom: Rename and refactor replace() in string.hpp
C++
mit
heavywatal/cxxwtils
bda8a2ad95ff26ef4b9b1844272a6907464c9a94
src/ntpclient.cpp
src/ntpclient.cpp
// Copyright (c) 2018 alex v // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "ntpclient.h" #include "random.h" #include "timedata.h" #include "util.h" using namespace boost; using namespace boost::asio; int64_t CNtpClient::getTimestamp() { time_t timeRecv = -1; io_service io_service; LogPrint("ntp", "[NTP] Opening socket to NTP server %s.\n", sHostName); try { ip::udp::resolver resolver(io_service); ip::udp::resolver::query query(boost::asio::ip::udp::v4(), sHostName, "ntp"); ip::udp::endpoint receiver_endpoint = *resolver.resolve(query); ip::udp::socket socket(io_service); socket.open(ip::udp::v4()); boost::array<unsigned char, 48> sendBuf = {{010,0,0,0,0,0,0,0,0}}; socket.send_to(boost::asio::buffer(sendBuf), receiver_endpoint); boost::array<unsigned long, 1024> recvBuf; ip::udp::endpoint sender_endpoint; try { fd_set fileDescriptorSet; struct timeval timeStruct; // set the timeout to 10 seconds timeStruct.tv_sec = GetArg("-ntptimeout", 10); timeStruct.tv_usec = 0; FD_ZERO(&fileDescriptorSet); int nativeSocket = socket.native(); FD_SET(nativeSocket,&fileDescriptorSet); select(nativeSocket+1,&fileDescriptorSet,NULL,NULL,&timeStruct); if(!FD_ISSET(nativeSocket,&fileDescriptorSet)) { LogPrint("ntp", "[NTP] Could not read socket from NTP server %s (Read timeout)\n", sHostName); } else { socket.receive_from(boost::asio::buffer(recvBuf), sender_endpoint); timeRecv = ntohl((time_t)recvBuf[4]); timeRecv-= 2208988800U; // Substract 01/01/1970 == 2208988800U LogPrint("ntp", "[NTP] Received timestamp: %ll \n", (uint64_t)timeRecv); } } catch (std::exception& e) { LogPrintf("[NTP] Could not read clock from NTP server %s (%s)\n", sHostName, e.what()); } } catch (std::exception& e) { LogPrintf("[NTP] Could not open socket to NTP server %s (%s)\n", sHostName, e.what()); } return (int64_t)timeRecv; } bool NtpClockSync() { LogPrintf("[NTP] Starting clock sync...\n"); std::vector<std::string> vNtpServers; std::vector<int64_t> vResults; if (mapMultiArgs["-ntpservers"].size() > 0) { vNtpServers = mapMultiArgs["-ntpservers"]; } else { vNtpServers = vDefaultNtpServers; } string sReport = ""; string sPrevServer = ""; int64_t nPrevMeasure = -1; random_shuffle(vNtpServers.begin(), vNtpServers.end(), GetRandInt); for(unsigned int i = 0; i < vNtpServers.size(); i++) { string s = vNtpServers[i]; CNtpClient ntpClient(s); int64_t nTimestamp = ntpClient.getTimestamp(); if(nTimestamp > -1) { int64_t nClockDrift = GetTimeNow() - nTimestamp; // We push if its the first entry if(vResults.size() == 0) { vResults.push_back(nClockDrift); string sign = ""; if(nClockDrift > 0) sign = "+"; else if (nClockDrift < 0) sign = "-"; sReport += s + "[" + sign + to_string(nClockDrift) + "sec.] "; } // or if we have two cached values, ensuring size of the vector is odd else if (nPrevMeasure != -1) { vResults.push_back(nClockDrift); string sign = ""; if(nClockDrift > 0) sign = "+"; else if (nClockDrift < 0) sign = "-"; sReport += s + "[" + sign + to_string(nClockDrift) + "sec.] "; vResults.push_back(nPrevMeasure); sign = ""; if(nPrevMeasure > 0) sign = "+"; else if (nPrevMeasure < 0) sign = "-"; sReport += sPrevServer + "[" + sign + to_string(nPrevMeasure) + "sec.] "; nPrevMeasure = -1; sPrevServer = ""; } else { nPrevMeasure = nClockDrift; sPrevServer = s; } if (vResults.size() >= 5) break; } } assert(vResults.size() % 2 == 1 || vResults.size() == 0); unsigned int nMin = GetArg("-ntpminmeasures", MINIMUM_NTP_MEASURE); if (vResults.size() >= nMin) { LogPrintf("[NTP] Measured: %s\n", sReport); static CMedianFilter<int64_t> vNtpTimeOffsets(vResults.size(), 0); for(unsigned int i = 0; i < vResults.size(); i++) { vNtpTimeOffsets.input(vResults[i]); } SetNtpTimeOffset(vNtpTimeOffsets.median()); LogPrintf("[NTP] Calculated offset from median: %d\n", GetNtpTimeOffset()); return true; } else { return false; } }
// Copyright (c) 2018 alex v // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "ntpclient.h" #include "random.h" #include "timedata.h" #include "util.h" using namespace boost; using namespace boost::asio; int64_t CNtpClient::getTimestamp() { time_t timeRecv = -1; io_service io_service; LogPrint("ntp", "[NTP] Opening socket to NTP server %s.\n", sHostName); try { ip::udp::resolver resolver(io_service); ip::udp::resolver::query query(boost::asio::ip::udp::v4(), sHostName, "ntp"); ip::udp::endpoint receiver_endpoint = *resolver.resolve(query); ip::udp::socket socket(io_service); socket.open(ip::udp::v4()); boost::array<unsigned char, 48> sendBuf = {{010,0,0,0,0,0,0,0,0}}; socket.send_to(boost::asio::buffer(sendBuf), receiver_endpoint); boost::array<unsigned long, 1024> recvBuf; ip::udp::endpoint sender_endpoint; try { fd_set fileDescriptorSet; struct timeval timeStruct; // set the timeout to 10 seconds timeStruct.tv_sec = GetArg("-ntptimeout", 10); timeStruct.tv_usec = 0; FD_ZERO(&fileDescriptorSet); int nativeSocket = socket.native(); FD_SET(nativeSocket,&fileDescriptorSet); select(nativeSocket+1,&fileDescriptorSet,NULL,NULL,&timeStruct); if(!FD_ISSET(nativeSocket,&fileDescriptorSet)) { LogPrint("ntp", "[NTP] Could not read socket from NTP server %s (Read timeout)\n", sHostName); } else { socket.receive_from(boost::asio::buffer(recvBuf), sender_endpoint); timeRecv = ntohl((time_t)recvBuf[4]); timeRecv-= 2208988800U; // Substract 01/01/1970 == 2208988800U LogPrint("ntp", "[NTP] Received timestamp: %ll \n", (uint64_t)timeRecv); } } catch (std::exception& e) { LogPrintf("[NTP] Could not read clock from NTP server %s (%s)\n", sHostName, e.what()); } } catch (std::exception& e) { LogPrintf("[NTP] Could not open socket to NTP server %s (%s)\n", sHostName, e.what()); } return (int64_t)timeRecv; } bool NtpClockSync() { LogPrintf("[NTP] Starting clock sync...\n"); std::vector<std::string> vNtpServers; std::vector<int64_t> vResults; if (mapMultiArgs["-ntpservers"].size() > 0) { vNtpServers = mapMultiArgs["-ntpservers"]; } else { vNtpServers = vDefaultNtpServers; } string sReport = ""; string sPrevServer = ""; int64_t nPrevMeasure = -1; random_shuffle(vNtpServers.begin(), vNtpServers.end(), GetRandInt); unsigned int nMeasureCount = 0; for(unsigned int i = 0; i < vNtpServers.size(); i++) { string s = vNtpServers[i]; CNtpClient ntpClient(s); int64_t nTimestamp = ntpClient.getTimestamp(); if(nTimestamp > -1) { int64_t nClockDrift = GetTimeNow() - nTimestamp; nMeasureCount++; // We push if its the first entry if(nMeasureCount == 1) { vResults.push_back(nClockDrift); string sign = ""; if(nClockDrift > 0) sign = "+"; else if (nClockDrift < 0) sign = "-"; sReport += s + "[" + sign + to_string(nClockDrift) + "sec.] "; } // or if n.measure is odd, including prev measure too else if (nMeasureCount % 2 == 1) { vResults.push_back(nClockDrift); string sign = ""; if(nClockDrift > 0) sign = "+"; else if (nClockDrift < 0) sign = "-"; sReport += s + "[" + sign + to_string(nClockDrift) + "sec.] "; vResults.push_back(nPrevMeasure); sign = ""; if(nPrevMeasure > 0) sign = "+"; else if (nPrevMeasure < 0) sign = "-"; sReport += sPrevServer + "[" + sign + to_string(nPrevMeasure) + "sec.] "; } else { nPrevMeasure = nClockDrift; sPrevServer = s; } if (vResults.size() >= 5) break; } } assert(vResults.size() % 2 == 1 || vResults.size() == 0); unsigned int nMin = GetArg("-ntpminmeasures", MINIMUM_NTP_MEASURE); if (vResults.size() >= nMin) { LogPrintf("[NTP] Measured: %s\n", sReport); static CMedianFilter<int64_t> vNtpTimeOffsets(vResults.size(), 0); for(unsigned int i = 0; i < vResults.size(); i++) { vNtpTimeOffsets.input(vResults[i]); } SetNtpTimeOffset(vNtpTimeOffsets.median()); LogPrintf("[NTP] Calculated offset from median: %d\n", GetNtpTimeOffset()); return true; } else { return false; } }
Rewrite logic
Rewrite logic
C++
mit
navcoindev/navcoin-core,navcoindev/navcoin-core,navcoindev/navcoin-core,navcoindev/navcoin-core,navcoindev/navcoin-core,navcoindev/navcoin-core
6193600cd4f68ec9bdcfe2a5e22dc9c9b1eb5f8c
src/binding.cc
src/binding.cc
#include <math.h> #include <sstream> #include <string> #include "nan.h" #include "point.h" #include "hunk.h" #include "patch.h" using namespace v8; static Nan::Persistent<String> row_string; static Nan::Persistent<String> column_string; static Nan::Maybe<Point> PointFromJS(Nan::MaybeLocal<Object> maybe_object) { Local<Object> object; if (!maybe_object.ToLocal(&object)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } Nan::MaybeLocal<Integer> maybe_row = Nan::To<Integer>(object->Get(Nan::New(row_string))); Local<Integer> js_row; if (!maybe_row.ToLocal(&js_row)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } Nan::MaybeLocal<Integer> maybe_column = Nan::To<Integer>(object->Get(Nan::New(column_string))); Local<Integer> js_column; if (!maybe_column.ToLocal(&js_column)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } unsigned row, column; if (isfinite(js_row->NumberValue())) { row = static_cast<unsigned>(js_row->Int32Value()); } else { row = UINT_MAX; } if (isfinite(js_column->NumberValue())) { column = static_cast<unsigned>(js_column->Int32Value()); } else { column = UINT_MAX; } return Nan::Just(Point(row, column)); } class PointWrapper : public Nan::ObjectWrap { public: static void Init() { Local<FunctionTemplate> constructor_template = Nan::New<FunctionTemplate>(New); constructor_template->SetClassName(Nan::New<String>("Point").ToLocalChecked()); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(constructor_template->InstanceTemplate(), Nan::New(row_string), GetRow); Nan::SetAccessor(constructor_template->InstanceTemplate(), Nan::New(column_string), GetColumn); constructor.Reset(constructor_template->GetFunction()); } static Local<Value> FromPoint(Point point) { Local<Object> result; if (Nan::New(constructor)->NewInstance(Nan::GetCurrentContext()).ToLocal(&result)) { (new PointWrapper(point))->Wrap(result); return result; } else { return Nan::Null(); } } private: PointWrapper(Point point) : point{point} {} static void New(const Nan::FunctionCallbackInfo<Value> &info) {} static void GetRow(v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { PointWrapper *wrapper = Nan::ObjectWrap::Unwrap<PointWrapper>(info.This()); Point &point = wrapper->point; info.GetReturnValue().Set(Nan::New(point.row)); } static void GetColumn(v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { PointWrapper *wrapper = Nan::ObjectWrap::Unwrap<PointWrapper>(info.This()); Point &point = wrapper->point; info.GetReturnValue().Set(Nan::New(point.column)); } static Nan::Persistent<v8::Function> constructor; Point point; }; class HunkWrapper : public Nan::ObjectWrap { public: static void Init() { Local<FunctionTemplate> constructor_template = Nan::New<FunctionTemplate>(New); constructor_template->SetClassName(Nan::New<String>("Hunk").ToLocalChecked()); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); const auto &instance_template = constructor_template->InstanceTemplate(); Nan::SetAccessor(instance_template, Nan::New("oldStart").ToLocalChecked(), GetOldStart); Nan::SetAccessor(instance_template, Nan::New("newStart").ToLocalChecked(), GetNewStart); Nan::SetAccessor(instance_template, Nan::New("oldEnd").ToLocalChecked(), GetOldEnd); Nan::SetAccessor(instance_template, Nan::New("newEnd").ToLocalChecked(), GetNewEnd); const auto &prototype_template = constructor_template->PrototypeTemplate(); prototype_template->Set(Nan::New<String>("toString").ToLocalChecked(), Nan::New<FunctionTemplate>(ToString)); constructor.Reset(constructor_template->GetFunction()); } static Local<Value> FromHunk(Hunk hunk) { Local<Object> result; if (Nan::NewInstance(Nan::New(constructor)).ToLocal(&result)) { (new HunkWrapper(hunk))->Wrap(result); return result; } else { return Nan::Null(); } } private: HunkWrapper(Hunk hunk) : hunk{hunk} {} static void New(const Nan::FunctionCallbackInfo<Value> &info) {} static void GetOldStart(v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { Hunk &hunk = Nan::ObjectWrap::Unwrap<HunkWrapper>(info.This())->hunk; info.GetReturnValue().Set(PointWrapper::FromPoint(hunk.old_start)); } static void GetNewStart(v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { Hunk &hunk = Nan::ObjectWrap::Unwrap<HunkWrapper>(info.This())->hunk; info.GetReturnValue().Set(PointWrapper::FromPoint(hunk.new_start)); } static void GetOldEnd(v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { Hunk &hunk = Nan::ObjectWrap::Unwrap<HunkWrapper>(info.This())->hunk; info.GetReturnValue().Set(PointWrapper::FromPoint(hunk.old_end)); } static void GetNewEnd(v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { Hunk &hunk = Nan::ObjectWrap::Unwrap<HunkWrapper>(info.This())->hunk; info.GetReturnValue().Set(PointWrapper::FromPoint(hunk.new_end)); } static void ToString(const Nan::FunctionCallbackInfo<Value> &info) { Hunk &hunk = Nan::ObjectWrap::Unwrap<HunkWrapper>(info.This())->hunk; std::stringstream result; result << hunk; info.GetReturnValue().Set(Nan::New<String>(result.str()).ToLocalChecked()); } static Nan::Persistent<v8::Function> constructor; Hunk hunk; }; class PatchWrapper : public Nan::ObjectWrap { public: static void Init(Local<Object> exports, Local<Object> module) { Local<FunctionTemplate> constructor_template = Nan::New<FunctionTemplate>(New); constructor_template->SetClassName(Nan::New<String>("Patch").ToLocalChecked()); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); const auto &prototype_template = constructor_template->PrototypeTemplate(); prototype_template->Set(Nan::New("splice").ToLocalChecked(), Nan::New<FunctionTemplate>(Splice)); prototype_template->Set(Nan::New("getHunks").ToLocalChecked(), Nan::New<FunctionTemplate>(GetHunks)); prototype_template->Set(Nan::New("getHunksInOldRange").ToLocalChecked(), Nan::New<FunctionTemplate>(GetHunksInOldRange)); prototype_template->Set(Nan::New("getHunksInNewRange").ToLocalChecked(), Nan::New<FunctionTemplate>(GetHunksInNewRange)); prototype_template->Set(Nan::New("translateOldPosition").ToLocalChecked(), Nan::New<FunctionTemplate>(TranslateOldPosition)); prototype_template->Set(Nan::New("translateNewPosition").ToLocalChecked(), Nan::New<FunctionTemplate>(TranslateNewPosition)); prototype_template->Set(Nan::New("serialize").ToLocalChecked(), Nan::New<FunctionTemplate>(Serialize)); prototype_template->Set(Nan::New("printDotGraph").ToLocalChecked(), Nan::New<FunctionTemplate>(PrintDotGraph)); constructor.Reset(constructor_template->GetFunction()); Local<Function> constructor_local = Nan::New(constructor); constructor_local->Set(Nan::New("deserialize").ToLocalChecked(), Nan::New<FunctionTemplate>(Deserialize)->GetFunction()); module->Set(Nan::New("exports").ToLocalChecked(), constructor_local); } private: PatchWrapper() : patch{} {} PatchWrapper(const std::vector<uint8_t> &data) : patch{data} {} static void New(const Nan::FunctionCallbackInfo<Value> &info) { PatchWrapper *patch = new PatchWrapper(); patch->Wrap(info.This()); } static void Splice(const Nan::FunctionCallbackInfo<Value> &info) { Patch &patch = Nan::ObjectWrap::Unwrap<PatchWrapper>(info.This())->patch; Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0])); Nan::Maybe<Point> deletion_extent = PointFromJS(Nan::To<Object>(info[1])); Nan::Maybe<Point> insertion_extent = PointFromJS(Nan::To<Object>(info[2])); if (start.IsJust() && deletion_extent.IsJust() && insertion_extent.IsJust()) { if (!patch.Splice(start.FromJust(), deletion_extent.FromJust(), insertion_extent.FromJust())) { Nan::ThrowError("Can't splice into a frozen patch"); } } } static void GetHunks(const Nan::FunctionCallbackInfo<Value> &info) { Patch &patch = Nan::ObjectWrap::Unwrap<PatchWrapper>(info.This())->patch; Local<Array> js_result = Nan::New<Array>(); size_t i = 0; for (Hunk hunk : patch.GetHunks()) { js_result->Set(i++, HunkWrapper::FromHunk(hunk)); } info.GetReturnValue().Set(js_result); } static void GetHunksInOldRange(const Nan::FunctionCallbackInfo<Value> &info) { Patch &patch = Nan::ObjectWrap::Unwrap<PatchWrapper>(info.This())->patch; Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0])); Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[1])); if (start.IsJust() && end.IsJust()) { Local<Array> js_result = Nan::New<Array>(); size_t i = 0; for (Hunk hunk : patch.GetHunksInOldRange(start.FromJust(), end.FromJust())) { js_result->Set(i++, HunkWrapper::FromHunk(hunk)); } info.GetReturnValue().Set(js_result); } } static void GetHunksInNewRange(const Nan::FunctionCallbackInfo<Value> &info) { Patch &patch = Nan::ObjectWrap::Unwrap<PatchWrapper>(info.This())->patch; Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0])); Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[1])); if (start.IsJust() && end.IsJust()) { Local<Array> js_result = Nan::New<Array>(); size_t i = 0; for (Hunk hunk : patch.GetHunksInNewRange(start.FromJust(), end.FromJust())) { js_result->Set(i++, HunkWrapper::FromHunk(hunk)); } info.GetReturnValue().Set(js_result); } } static void TranslateOldPosition(const Nan::FunctionCallbackInfo<Value> &info) { Patch &patch = Nan::ObjectWrap::Unwrap<PatchWrapper>(info.This())->patch; Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0])); if (start.IsJust()) { Point result = patch.TranslateOldPosition(start.FromJust()); info.GetReturnValue().Set(PointWrapper::FromPoint(result)); } } static void TranslateNewPosition(const Nan::FunctionCallbackInfo<Value> &info) { Patch &patch = Nan::ObjectWrap::Unwrap<PatchWrapper>(info.This())->patch; Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0])); if (start.IsJust()) { Point result = patch.TranslateNewPosition(start.FromJust()); info.GetReturnValue().Set(PointWrapper::FromPoint(result)); } } static void Serialize(const Nan::FunctionCallbackInfo<Value> &info) { Patch &patch = Nan::ObjectWrap::Unwrap<PatchWrapper>(info.This())->patch; auto &serialization_vector = SerializationVector(); serialization_vector.clear(); patch.Serialize(&serialization_vector); Local<Object> result; auto maybe_result = Nan::CopyBuffer( reinterpret_cast<char *>(serialization_vector.data()), serialization_vector.size() ); if (maybe_result.ToLocal(&result)) { info.GetReturnValue().Set(result); } } static void Deserialize(const Nan::FunctionCallbackInfo<Value> &info) { Local<Object> result; if (Nan::NewInstance(Nan::New(constructor)).ToLocal(&result)) { Local<Uint8Array> typed_array = Local<Uint8Array>::Cast(info[0]); if (typed_array->IsUint8Array()) { auto buffer = typed_array->Buffer(); auto contents = buffer->GetContents(); auto &serialization_vector = SerializationVector(); auto *data = reinterpret_cast<const uint8_t *>(contents.Data()); serialization_vector.assign(data, data + contents.ByteLength()); PatchWrapper *wrapper = new PatchWrapper(serialization_vector); wrapper->Wrap(result); info.GetReturnValue().Set(result); } } } static inline std::vector<uint8_t> &SerializationVector() { static std::vector<uint8_t> result; return result; } static void PrintDotGraph(const Nan::FunctionCallbackInfo<Value> &info) { Patch &patch = Nan::ObjectWrap::Unwrap<PatchWrapper>(info.This())->patch; patch.PrintDotGraph(); } static Nan::Persistent<v8::Function> constructor; Patch patch; }; Nan::Persistent<v8::Function> PointWrapper::constructor; Nan::Persistent<v8::Function> HunkWrapper::constructor; Nan::Persistent<v8::Function> PatchWrapper::constructor; void Init(Local<Object> exports, Local<Object> module) { row_string.Reset(Nan::Persistent<String>(Nan::New("row").ToLocalChecked())); column_string.Reset(Nan::Persistent<String>(Nan::New("column").ToLocalChecked())); PointWrapper::Init(); HunkWrapper::Init(); PatchWrapper::Init(exports, module); } NODE_MODULE(atom_patch, Init)
#include <cmath> #include <sstream> #include <string> #include "nan.h" #include "point.h" #include "hunk.h" #include "patch.h" using namespace v8; static Nan::Persistent<String> row_string; static Nan::Persistent<String> column_string; static Nan::Maybe<Point> PointFromJS(Nan::MaybeLocal<Object> maybe_object) { Local<Object> object; if (!maybe_object.ToLocal(&object)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } Nan::MaybeLocal<Integer> maybe_row = Nan::To<Integer>(object->Get(Nan::New(row_string))); Local<Integer> js_row; if (!maybe_row.ToLocal(&js_row)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } Nan::MaybeLocal<Integer> maybe_column = Nan::To<Integer>(object->Get(Nan::New(column_string))); Local<Integer> js_column; if (!maybe_column.ToLocal(&js_column)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } unsigned row, column; if (std::isfinite(js_row->NumberValue())) { row = static_cast<unsigned>(js_row->Int32Value()); } else { row = UINT_MAX; } if (std::isfinite(js_column->NumberValue())) { column = static_cast<unsigned>(js_column->Int32Value()); } else { column = UINT_MAX; } return Nan::Just(Point(row, column)); } class PointWrapper : public Nan::ObjectWrap { public: static void Init() { Local<FunctionTemplate> constructor_template = Nan::New<FunctionTemplate>(New); constructor_template->SetClassName(Nan::New<String>("Point").ToLocalChecked()); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(constructor_template->InstanceTemplate(), Nan::New(row_string), GetRow); Nan::SetAccessor(constructor_template->InstanceTemplate(), Nan::New(column_string), GetColumn); constructor.Reset(constructor_template->GetFunction()); } static Local<Value> FromPoint(Point point) { Local<Object> result; if (Nan::New(constructor)->NewInstance(Nan::GetCurrentContext()).ToLocal(&result)) { (new PointWrapper(point))->Wrap(result); return result; } else { return Nan::Null(); } } private: PointWrapper(Point point) : point(point) {} static void New(const Nan::FunctionCallbackInfo<Value> &info) {} static void GetRow(v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { PointWrapper *wrapper = Nan::ObjectWrap::Unwrap<PointWrapper>(info.This()); Point &point = wrapper->point; info.GetReturnValue().Set(Nan::New(point.row)); } static void GetColumn(v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { PointWrapper *wrapper = Nan::ObjectWrap::Unwrap<PointWrapper>(info.This()); Point &point = wrapper->point; info.GetReturnValue().Set(Nan::New(point.column)); } static Nan::Persistent<v8::Function> constructor; Point point; }; class HunkWrapper : public Nan::ObjectWrap { public: static void Init() { Local<FunctionTemplate> constructor_template = Nan::New<FunctionTemplate>(New); constructor_template->SetClassName(Nan::New<String>("Hunk").ToLocalChecked()); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); const auto &instance_template = constructor_template->InstanceTemplate(); Nan::SetAccessor(instance_template, Nan::New("oldStart").ToLocalChecked(), GetOldStart); Nan::SetAccessor(instance_template, Nan::New("newStart").ToLocalChecked(), GetNewStart); Nan::SetAccessor(instance_template, Nan::New("oldEnd").ToLocalChecked(), GetOldEnd); Nan::SetAccessor(instance_template, Nan::New("newEnd").ToLocalChecked(), GetNewEnd); const auto &prototype_template = constructor_template->PrototypeTemplate(); prototype_template->Set(Nan::New<String>("toString").ToLocalChecked(), Nan::New<FunctionTemplate>(ToString)); constructor.Reset(constructor_template->GetFunction()); } static Local<Value> FromHunk(Hunk hunk) { Local<Object> result; if (Nan::NewInstance(Nan::New(constructor)).ToLocal(&result)) { (new HunkWrapper(hunk))->Wrap(result); return result; } else { return Nan::Null(); } } private: HunkWrapper(Hunk hunk) : hunk(hunk) {} static void New(const Nan::FunctionCallbackInfo<Value> &info) {} static void GetOldStart(v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { Hunk &hunk = Nan::ObjectWrap::Unwrap<HunkWrapper>(info.This())->hunk; info.GetReturnValue().Set(PointWrapper::FromPoint(hunk.old_start)); } static void GetNewStart(v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { Hunk &hunk = Nan::ObjectWrap::Unwrap<HunkWrapper>(info.This())->hunk; info.GetReturnValue().Set(PointWrapper::FromPoint(hunk.new_start)); } static void GetOldEnd(v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { Hunk &hunk = Nan::ObjectWrap::Unwrap<HunkWrapper>(info.This())->hunk; info.GetReturnValue().Set(PointWrapper::FromPoint(hunk.old_end)); } static void GetNewEnd(v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { Hunk &hunk = Nan::ObjectWrap::Unwrap<HunkWrapper>(info.This())->hunk; info.GetReturnValue().Set(PointWrapper::FromPoint(hunk.new_end)); } static void ToString(const Nan::FunctionCallbackInfo<Value> &info) { Hunk &hunk = Nan::ObjectWrap::Unwrap<HunkWrapper>(info.This())->hunk; std::stringstream result; result << hunk; info.GetReturnValue().Set(Nan::New<String>(result.str()).ToLocalChecked()); } static Nan::Persistent<v8::Function> constructor; Hunk hunk; }; class PatchWrapper : public Nan::ObjectWrap { public: static void Init(Local<Object> exports, Local<Object> module) { Local<FunctionTemplate> constructor_template = Nan::New<FunctionTemplate>(New); constructor_template->SetClassName(Nan::New<String>("Patch").ToLocalChecked()); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); const auto &prototype_template = constructor_template->PrototypeTemplate(); prototype_template->Set(Nan::New("splice").ToLocalChecked(), Nan::New<FunctionTemplate>(Splice)); prototype_template->Set(Nan::New("getHunks").ToLocalChecked(), Nan::New<FunctionTemplate>(GetHunks)); prototype_template->Set(Nan::New("getHunksInOldRange").ToLocalChecked(), Nan::New<FunctionTemplate>(GetHunksInOldRange)); prototype_template->Set(Nan::New("getHunksInNewRange").ToLocalChecked(), Nan::New<FunctionTemplate>(GetHunksInNewRange)); prototype_template->Set(Nan::New("translateOldPosition").ToLocalChecked(), Nan::New<FunctionTemplate>(TranslateOldPosition)); prototype_template->Set(Nan::New("translateNewPosition").ToLocalChecked(), Nan::New<FunctionTemplate>(TranslateNewPosition)); prototype_template->Set(Nan::New("serialize").ToLocalChecked(), Nan::New<FunctionTemplate>(Serialize)); prototype_template->Set(Nan::New("printDotGraph").ToLocalChecked(), Nan::New<FunctionTemplate>(PrintDotGraph)); constructor.Reset(constructor_template->GetFunction()); Local<Function> constructor_local = Nan::New(constructor); constructor_local->Set(Nan::New("deserialize").ToLocalChecked(), Nan::New<FunctionTemplate>(Deserialize)->GetFunction()); module->Set(Nan::New("exports").ToLocalChecked(), constructor_local); } private: PatchWrapper() : patch{} {} PatchWrapper(const std::vector<uint8_t> &data) : patch(data) {} static void New(const Nan::FunctionCallbackInfo<Value> &info) { PatchWrapper *patch = new PatchWrapper(); patch->Wrap(info.This()); } static void Splice(const Nan::FunctionCallbackInfo<Value> &info) { Patch &patch = Nan::ObjectWrap::Unwrap<PatchWrapper>(info.This())->patch; Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0])); Nan::Maybe<Point> deletion_extent = PointFromJS(Nan::To<Object>(info[1])); Nan::Maybe<Point> insertion_extent = PointFromJS(Nan::To<Object>(info[2])); if (start.IsJust() && deletion_extent.IsJust() && insertion_extent.IsJust()) { if (!patch.Splice(start.FromJust(), deletion_extent.FromJust(), insertion_extent.FromJust())) { Nan::ThrowError("Can't splice into a frozen patch"); } } } static void GetHunks(const Nan::FunctionCallbackInfo<Value> &info) { Patch &patch = Nan::ObjectWrap::Unwrap<PatchWrapper>(info.This())->patch; Local<Array> js_result = Nan::New<Array>(); size_t i = 0; for (Hunk hunk : patch.GetHunks()) { js_result->Set(i++, HunkWrapper::FromHunk(hunk)); } info.GetReturnValue().Set(js_result); } static void GetHunksInOldRange(const Nan::FunctionCallbackInfo<Value> &info) { Patch &patch = Nan::ObjectWrap::Unwrap<PatchWrapper>(info.This())->patch; Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0])); Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[1])); if (start.IsJust() && end.IsJust()) { Local<Array> js_result = Nan::New<Array>(); size_t i = 0; for (Hunk hunk : patch.GetHunksInOldRange(start.FromJust(), end.FromJust())) { js_result->Set(i++, HunkWrapper::FromHunk(hunk)); } info.GetReturnValue().Set(js_result); } } static void GetHunksInNewRange(const Nan::FunctionCallbackInfo<Value> &info) { Patch &patch = Nan::ObjectWrap::Unwrap<PatchWrapper>(info.This())->patch; Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0])); Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[1])); if (start.IsJust() && end.IsJust()) { Local<Array> js_result = Nan::New<Array>(); size_t i = 0; for (Hunk hunk : patch.GetHunksInNewRange(start.FromJust(), end.FromJust())) { js_result->Set(i++, HunkWrapper::FromHunk(hunk)); } info.GetReturnValue().Set(js_result); } } static void TranslateOldPosition(const Nan::FunctionCallbackInfo<Value> &info) { Patch &patch = Nan::ObjectWrap::Unwrap<PatchWrapper>(info.This())->patch; Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0])); if (start.IsJust()) { Point result = patch.TranslateOldPosition(start.FromJust()); info.GetReturnValue().Set(PointWrapper::FromPoint(result)); } } static void TranslateNewPosition(const Nan::FunctionCallbackInfo<Value> &info) { Patch &patch = Nan::ObjectWrap::Unwrap<PatchWrapper>(info.This())->patch; Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[0])); if (start.IsJust()) { Point result = patch.TranslateNewPosition(start.FromJust()); info.GetReturnValue().Set(PointWrapper::FromPoint(result)); } } static void Serialize(const Nan::FunctionCallbackInfo<Value> &info) { Patch &patch = Nan::ObjectWrap::Unwrap<PatchWrapper>(info.This())->patch; auto &serialization_vector = SerializationVector(); serialization_vector.clear(); patch.Serialize(&serialization_vector); Local<Object> result; auto maybe_result = Nan::CopyBuffer( reinterpret_cast<char *>(serialization_vector.data()), serialization_vector.size() ); if (maybe_result.ToLocal(&result)) { info.GetReturnValue().Set(result); } } static void Deserialize(const Nan::FunctionCallbackInfo<Value> &info) { Local<Object> result; if (Nan::NewInstance(Nan::New(constructor)).ToLocal(&result)) { Local<Uint8Array> typed_array = Local<Uint8Array>::Cast(info[0]); if (typed_array->IsUint8Array()) { auto buffer = typed_array->Buffer(); auto contents = buffer->GetContents(); auto &serialization_vector = SerializationVector(); auto *data = reinterpret_cast<const uint8_t *>(contents.Data()); serialization_vector.assign(data, data + contents.ByteLength()); PatchWrapper *wrapper = new PatchWrapper(serialization_vector); wrapper->Wrap(result); info.GetReturnValue().Set(result); } } } static inline std::vector<uint8_t> &SerializationVector() { static std::vector<uint8_t> result; return result; } static void PrintDotGraph(const Nan::FunctionCallbackInfo<Value> &info) { Patch &patch = Nan::ObjectWrap::Unwrap<PatchWrapper>(info.This())->patch; patch.PrintDotGraph(); } static Nan::Persistent<v8::Function> constructor; Patch patch; }; Nan::Persistent<v8::Function> PointWrapper::constructor; Nan::Persistent<v8::Function> HunkWrapper::constructor; Nan::Persistent<v8::Function> PatchWrapper::constructor; void Init(Local<Object> exports, Local<Object> module) { row_string.Reset(Nan::Persistent<String>(Nan::New("row").ToLocalChecked())); column_string.Reset(Nan::Persistent<String>(Nan::New("column").ToLocalChecked())); PointWrapper::Init(); HunkWrapper::Init(); PatchWrapper::Init(exports, module); } NODE_MODULE(atom_patch, Init)
Fix compiler errors on travis
Fix compiler errors on travis
C++
mit
atom/atom-patch,atom/superstring,atom/superstring,atom/superstring,atom/superstring,atom/atom-patch,atom/atom-patch,atom/superstring,atom/atom-patch,nathansobo/atom-patch
ddde3819d664a986e3c530e08f0c29e5c7c2bfa9
scene/gui/texture_rect.cpp
scene/gui/texture_rect.cpp
/*************************************************************************/ /* texture_rect.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "texture_rect.h" #include "core/core_string_names.h" #include "servers/visual_server.h" void TextureRect::_notification(int p_what) { if (p_what == NOTIFICATION_DRAW) { if (texture.is_null()) { return; } Size2 size; Point2 offset; Rect2 region; bool tile = false; switch (stretch_mode) { case STRETCH_SCALE_ON_EXPAND: { size = expand ? get_size() : texture->get_size(); } break; case STRETCH_SCALE: { size = get_size(); } break; case STRETCH_TILE: { size = get_size(); tile = true; } break; case STRETCH_KEEP: { size = texture->get_size(); } break; case STRETCH_KEEP_CENTERED: { offset = (get_size() - texture->get_size()) / 2; size = texture->get_size(); } break; case STRETCH_KEEP_ASPECT_CENTERED: case STRETCH_KEEP_ASPECT: { size = get_size(); int tex_width = texture->get_width() * size.height / texture->get_height(); int tex_height = size.height; if (tex_width > size.width) { tex_width = size.width; tex_height = texture->get_height() * tex_width / texture->get_width(); } if (stretch_mode == STRETCH_KEEP_ASPECT_CENTERED) { offset.x += (size.width - tex_width) / 2; offset.y += (size.height - tex_height) / 2; } size.width = tex_width; size.height = tex_height; } break; case STRETCH_KEEP_ASPECT_COVERED: { size = get_size(); Size2 tex_size = texture->get_size(); Size2 scale_size(size.width / tex_size.width, size.height / tex_size.height); float scale = scale_size.width > scale_size.height ? scale_size.width : scale_size.height; Size2 scaled_tex_size = tex_size * scale; region.position = ((scaled_tex_size - size) / scale).abs() / 2.0f; region.size = size / scale; } break; } size.width *= hflip ? -1.0f : 1.0f; size.height *= vflip ? -1.0f : 1.0f; if (region.has_no_area()) { draw_texture_rect(texture, Rect2(offset, size), tile); } else { draw_texture_rect_region(texture, Rect2(offset, size), region); } } } Size2 TextureRect::get_minimum_size() const { if (!expand && !texture.is_null()) { return texture->get_size(); } else { return Size2(); } } void TextureRect::_bind_methods() { ClassDB::bind_method(D_METHOD("set_texture", "texture"), &TextureRect::set_texture); ClassDB::bind_method(D_METHOD("get_texture"), &TextureRect::get_texture); ClassDB::bind_method(D_METHOD("set_expand", "enable"), &TextureRect::set_expand); ClassDB::bind_method(D_METHOD("has_expand"), &TextureRect::has_expand); ClassDB::bind_method(D_METHOD("set_flip_h", "enable"), &TextureRect::set_flip_h); ClassDB::bind_method(D_METHOD("is_flipped_h"), &TextureRect::is_flipped_h); ClassDB::bind_method(D_METHOD("set_flip_v", "enable"), &TextureRect::set_flip_v); ClassDB::bind_method(D_METHOD("is_flipped_v"), &TextureRect::is_flipped_v); ClassDB::bind_method(D_METHOD("set_stretch_mode", "stretch_mode"), &TextureRect::set_stretch_mode); ClassDB::bind_method(D_METHOD("get_stretch_mode"), &TextureRect::get_stretch_mode); ClassDB::bind_method(D_METHOD("_texture_changed"), &TextureRect::_texture_changed); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "expand"), "set_expand", "has_expand"); ADD_PROPERTY(PropertyInfo(Variant::INT, "stretch_mode", PROPERTY_HINT_ENUM, "Scale On Expand (Compat),Scale,Tile,Keep,Keep Centered,Keep Aspect,Keep Aspect Centered,Keep Aspect Covered"), "set_stretch_mode", "get_stretch_mode"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_h"), "set_flip_h", "is_flipped_h"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_v"), "set_flip_v", "is_flipped_v"); BIND_ENUM_CONSTANT(STRETCH_SCALE_ON_EXPAND); BIND_ENUM_CONSTANT(STRETCH_SCALE); BIND_ENUM_CONSTANT(STRETCH_TILE); BIND_ENUM_CONSTANT(STRETCH_KEEP); BIND_ENUM_CONSTANT(STRETCH_KEEP_CENTERED); BIND_ENUM_CONSTANT(STRETCH_KEEP_ASPECT); BIND_ENUM_CONSTANT(STRETCH_KEEP_ASPECT_CENTERED); BIND_ENUM_CONSTANT(STRETCH_KEEP_ASPECT_COVERED); } void TextureRect::_texture_changed() { if (texture.is_valid()) { update(); minimum_size_changed(); } } void TextureRect::set_texture(const Ref<Texture> &p_tex) { if (p_tex == texture) { return; } if (texture.is_valid()) { texture->disconnect(CoreStringNames::get_singleton()->changed, this, "_texture_changed"); } texture = p_tex; if (texture.is_valid()) { texture->connect(CoreStringNames::get_singleton()->changed, this, "_texture_changed"); } update(); minimum_size_changed(); } Ref<Texture> TextureRect::get_texture() const { return texture; } void TextureRect::set_expand(bool p_expand) { expand = p_expand; update(); minimum_size_changed(); } bool TextureRect::has_expand() const { return expand; } void TextureRect::set_stretch_mode(StretchMode p_mode) { stretch_mode = p_mode; update(); } TextureRect::StretchMode TextureRect::get_stretch_mode() const { return stretch_mode; } void TextureRect::set_flip_h(bool p_flip) { hflip = p_flip; update(); } bool TextureRect::is_flipped_h() const { return hflip; } void TextureRect::set_flip_v(bool p_flip) { vflip = p_flip; update(); } bool TextureRect::is_flipped_v() const { return vflip; } TextureRect::TextureRect() { expand = false; hflip = false; vflip = false; set_mouse_filter(MOUSE_FILTER_PASS); stretch_mode = STRETCH_SCALE_ON_EXPAND; } TextureRect::~TextureRect() { }
/*************************************************************************/ /* texture_rect.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "texture_rect.h" #include "core/core_string_names.h" #include "servers/visual_server.h" void TextureRect::_notification(int p_what) { if (p_what == NOTIFICATION_DRAW) { if (texture.is_null()) { return; } Size2 size; Point2 offset; Rect2 region; bool tile = false; switch (stretch_mode) { case STRETCH_SCALE_ON_EXPAND: { size = expand ? get_size() : texture->get_size(); } break; case STRETCH_SCALE: { size = get_size(); } break; case STRETCH_TILE: { size = get_size(); tile = true; } break; case STRETCH_KEEP: { size = texture->get_size(); } break; case STRETCH_KEEP_CENTERED: { offset = (get_size() - texture->get_size()) / 2; size = texture->get_size(); } break; case STRETCH_KEEP_ASPECT_CENTERED: case STRETCH_KEEP_ASPECT: { size = get_size(); int tex_width = texture->get_width() * size.height / texture->get_height(); int tex_height = size.height; if (tex_width > size.width) { tex_width = size.width; tex_height = texture->get_height() * tex_width / texture->get_width(); } if (stretch_mode == STRETCH_KEEP_ASPECT_CENTERED) { offset.x += (size.width - tex_width) / 2; offset.y += (size.height - tex_height) / 2; } size.width = tex_width; size.height = tex_height; } break; case STRETCH_KEEP_ASPECT_COVERED: { size = get_size(); Size2 tex_size = texture->get_size(); Size2 scale_size(size.width / tex_size.width, size.height / tex_size.height); float scale = scale_size.width > scale_size.height ? scale_size.width : scale_size.height; Size2 scaled_tex_size = tex_size * scale; region.position = ((scaled_tex_size - size) / scale).abs() / 2.0f; region.size = size / scale; } break; } Ref<AtlasTexture> p_atlas = texture; if (p_atlas.is_valid() && region.has_no_area()) { Size2 scale_size(size.width / texture->get_width(), size.height / texture->get_height()); offset.width += hflip ? p_atlas->get_margin().get_position().width * scale_size.width * 2 : 0; offset.height += vflip ? p_atlas->get_margin().get_position().height * scale_size.height * 2 : 0; } size.width *= hflip ? -1.0f : 1.0f; size.height *= vflip ? -1.0f : 1.0f; if (region.has_no_area()) { draw_texture_rect(texture, Rect2(offset, size), tile); } else { draw_texture_rect_region(texture, Rect2(offset, size), region); } } } Size2 TextureRect::get_minimum_size() const { if (!expand && !texture.is_null()) { return texture->get_size(); } else { return Size2(); } } void TextureRect::_bind_methods() { ClassDB::bind_method(D_METHOD("set_texture", "texture"), &TextureRect::set_texture); ClassDB::bind_method(D_METHOD("get_texture"), &TextureRect::get_texture); ClassDB::bind_method(D_METHOD("set_expand", "enable"), &TextureRect::set_expand); ClassDB::bind_method(D_METHOD("has_expand"), &TextureRect::has_expand); ClassDB::bind_method(D_METHOD("set_flip_h", "enable"), &TextureRect::set_flip_h); ClassDB::bind_method(D_METHOD("is_flipped_h"), &TextureRect::is_flipped_h); ClassDB::bind_method(D_METHOD("set_flip_v", "enable"), &TextureRect::set_flip_v); ClassDB::bind_method(D_METHOD("is_flipped_v"), &TextureRect::is_flipped_v); ClassDB::bind_method(D_METHOD("set_stretch_mode", "stretch_mode"), &TextureRect::set_stretch_mode); ClassDB::bind_method(D_METHOD("get_stretch_mode"), &TextureRect::get_stretch_mode); ClassDB::bind_method(D_METHOD("_texture_changed"), &TextureRect::_texture_changed); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "expand"), "set_expand", "has_expand"); ADD_PROPERTY(PropertyInfo(Variant::INT, "stretch_mode", PROPERTY_HINT_ENUM, "Scale On Expand (Compat),Scale,Tile,Keep,Keep Centered,Keep Aspect,Keep Aspect Centered,Keep Aspect Covered"), "set_stretch_mode", "get_stretch_mode"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_h"), "set_flip_h", "is_flipped_h"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_v"), "set_flip_v", "is_flipped_v"); BIND_ENUM_CONSTANT(STRETCH_SCALE_ON_EXPAND); BIND_ENUM_CONSTANT(STRETCH_SCALE); BIND_ENUM_CONSTANT(STRETCH_TILE); BIND_ENUM_CONSTANT(STRETCH_KEEP); BIND_ENUM_CONSTANT(STRETCH_KEEP_CENTERED); BIND_ENUM_CONSTANT(STRETCH_KEEP_ASPECT); BIND_ENUM_CONSTANT(STRETCH_KEEP_ASPECT_CENTERED); BIND_ENUM_CONSTANT(STRETCH_KEEP_ASPECT_COVERED); } void TextureRect::_texture_changed() { if (texture.is_valid()) { update(); minimum_size_changed(); } } void TextureRect::set_texture(const Ref<Texture> &p_tex) { if (p_tex == texture) { return; } if (texture.is_valid()) { texture->disconnect(CoreStringNames::get_singleton()->changed, this, "_texture_changed"); } texture = p_tex; if (texture.is_valid()) { texture->connect(CoreStringNames::get_singleton()->changed, this, "_texture_changed"); } update(); minimum_size_changed(); } Ref<Texture> TextureRect::get_texture() const { return texture; } void TextureRect::set_expand(bool p_expand) { expand = p_expand; update(); minimum_size_changed(); } bool TextureRect::has_expand() const { return expand; } void TextureRect::set_stretch_mode(StretchMode p_mode) { stretch_mode = p_mode; update(); } TextureRect::StretchMode TextureRect::get_stretch_mode() const { return stretch_mode; } void TextureRect::set_flip_h(bool p_flip) { hflip = p_flip; update(); } bool TextureRect::is_flipped_h() const { return hflip; } void TextureRect::set_flip_v(bool p_flip) { vflip = p_flip; update(); } bool TextureRect::is_flipped_v() const { return vflip; } TextureRect::TextureRect() { expand = false; hflip = false; vflip = false; set_mouse_filter(MOUSE_FILTER_PASS); stretch_mode = STRETCH_SCALE_ON_EXPAND; } TextureRect::~TextureRect() { }
Fix TextureRect::flip_* when used with atlas texture
Fix TextureRect::flip_* when used with atlas texture Fix #37526 (cherry picked from commit fb2d2dd5d01f7f695728658b2f3e8af89bf992d9)
C++
mit
ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot
d90458a933dadee3a9802b115d8541ff8ff3aee9
src/osd/OSDMap.cc
src/osd/OSDMap.cc
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <[email protected]> * * This 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. See file COPYING. * */ #include "OSDMap.h" #include "common/config.h" void OSDMap::print(ostream& out) const { out << "epoch " << get_epoch() << "\n" << "fsid " << get_fsid() << "\n" << "created " << get_created() << "\n" << "modifed " << get_modified() << "\n"; out << "flags"; if (test_flag(CEPH_OSDMAP_NEARFULL)) out << " nearfull"; if (test_flag(CEPH_OSDMAP_FULL)) out << " full"; if (test_flag(CEPH_OSDMAP_PAUSERD)) out << " pauserd"; if (test_flag(CEPH_OSDMAP_PAUSEWR)) out << " pausewr"; if (test_flag(CEPH_OSDMAP_PAUSEREC)) out << " pauserec"; out << "\n" << std::endl; for (map<int,pg_pool_t>::const_iterator p = pools.begin(); p != pools.end(); ++p) { std::string name("<unknown>"); map<int32_t,string>::const_iterator pni = pool_name.find(p->first); if (pni != pool_name.end()) name = pni->second; out << "pg_pool " << p->first << " '" << name << "' " << p->second << "\n"; for (map<snapid_t,pool_snap_info_t>::const_iterator q = p->second.snaps.begin(); q != p->second.snaps.end(); q++) out << "\tsnap " << q->second.snapid << " '" << q->second.name << "' " << q->second.stamp << "\n"; if (!p->second.removed_snaps.empty()) out << "\tremoved_snaps " << p->second.removed_snaps << "\n"; } out << std::endl; out << "max_osd " << get_max_osd() << "\n"; for (int i=0; i<get_max_osd(); i++) { if (exists(i)) { out << "osd" << i; out << (is_up(i) ? " up ":" down"); out << (is_in(i) ? " in ":" out"); if (is_in(i)) out << " weight " << get_weightf(i); const osd_info_t& info(get_info(i)); out << " " << info; if (is_up(i)) out << " " << get_addr(i) << " " << get_cluster_addr(i) << " " << get_hb_addr(i); out << "\n"; } } out << std::endl; for (map<pg_t,vector<int> >::const_iterator p = pg_temp.begin(); p != pg_temp.end(); p++) out << "pg_temp " << p->first << " " << p->second << "\n"; for (hash_map<entity_addr_t,utime_t>::const_iterator p = blacklist.begin(); p != blacklist.end(); p++) out << "blacklist " << p->first << " expires " << p->second << "\n"; // ignore pg_swap_primary } void OSDMap::print_summary(ostream& out) const { out << "e" << get_epoch() << ": " << get_num_osds() << " osds: " << get_num_up_osds() << " up, " << get_num_in_osds() << " in"; if (test_flag(CEPH_OSDMAP_FULL)) out << " full"; else if (test_flag(CEPH_OSDMAP_NEARFULL)) out << " nearfull"; } void OSDMap::build_simple(epoch_t e, ceph_fsid_t &fsid, int nosd, int ndom, int pg_bits, int pgp_bits, int lpg_bits) { dout(10) << "build_simple on " << num_osd << " osds with " << pg_bits << " pg bits per osd, " << lpg_bits << " lpg bits" << dendl; epoch = e; set_fsid(fsid); created = modified = g_clock.now(); set_max_osd(nosd); // pgp_num <= pg_num if (pgp_bits > pg_bits) pgp_bits = pg_bits; // crush map map<int, const char*> rulesets; rulesets[CEPH_DATA_RULE] = "data"; rulesets[CEPH_METADATA_RULE] = "metadata"; rulesets[CEPH_RBD_RULE] = "rbd"; for (map<int,const char*>::iterator p = rulesets.begin(); p != rulesets.end(); p++) { int pool = ++pool_max; pools[pool].v.type = CEPH_PG_TYPE_REP; pools[pool].v.size = 2; pools[pool].v.crush_ruleset = p->first; pools[pool].v.object_hash = CEPH_STR_HASH_RJENKINS; pools[pool].v.pg_num = nosd << pg_bits; pools[pool].v.pgp_num = nosd << pgp_bits; pools[pool].v.lpg_num = lpg_bits ? (1 << (lpg_bits-1)) : 0; pools[pool].v.lpgp_num = lpg_bits ? (1 << (lpg_bits-1)) : 0; pools[pool].v.last_change = epoch; pool_name[pool] = p->second; } build_simple_crush_map(crush, rulesets, nosd, ndom); for (int i=0; i<nosd; i++) { set_state(i, 0); set_weight(i, CEPH_OSD_OUT); } } void OSDMap::build_simple_crush_map(CrushWrapper& crush, map<int, const char*>& rulesets, int nosd, int ndom) { // new crush.create(); crush.set_type_name(1, "domain"); crush.set_type_name(2, "pool"); int minrep = g_conf.osd_min_rep; int maxrep = g_conf.osd_max_rep; assert(maxrep >= minrep); if (!ndom) ndom = MAX(maxrep, g_conf.osd_max_raid_width); if (ndom > 1 && nosd >= ndom*3 && nosd > 8) { int ritems[ndom]; int rweights[ndom]; int nper = ((nosd - 1) / ndom) + 1; dout(0) << ndom << " failure domains, " << nper << " osds each" << dendl; int o = 0; for (int i=0; i<ndom; i++) { int items[nper], weights[nper]; int j; rweights[i] = 0; for (j=0; j<nper; j++, o++) { if (o == nosd) break; dout(20) << "added osd" << o << dendl; items[j] = o; weights[j] = 0x10000; //w[j] = weights[o] ? (0x10000 - (int)(weights[o] * 0x10000)):0x10000; //rweights[i] += w[j]; rweights[i] += 0x10000; } crush_bucket *domain = crush_make_bucket(CRUSH_BUCKET_STRAW, CRUSH_HASH_DEFAULT, 1, j, items, weights); ritems[i] = crush_add_bucket(crush.crush, 0, domain); dout(20) << "added domain bucket i " << ritems[i] << " of size " << j << dendl; char bname[10]; snprintf(bname, sizeof(bname), "dom%d", i); crush.set_item_name(ritems[i], bname); } // root crush_bucket *root = crush_make_bucket(CRUSH_BUCKET_STRAW, CRUSH_HASH_DEFAULT, 2, ndom, ritems, rweights); int rootid = crush_add_bucket(crush.crush, 0, root); crush.set_item_name(rootid, "root"); // rules for (map<int,const char*>::iterator p = rulesets.begin(); p != rulesets.end(); p++) { int ruleset = p->first; crush_rule *rule = crush_make_rule(3, ruleset, CEPH_PG_TYPE_REP, minrep, maxrep); crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, rootid, 0); crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSE_LEAF_FIRSTN, CRUSH_CHOOSE_N, 1); // choose N domains crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0); int rno = crush_add_rule(crush.crush, rule, -1); crush.set_rule_name(rno, p->second); } } else { // one bucket int items[nosd]; int weights[nosd]; for (int i=0; i<nosd; i++) { items[i] = i; weights[i] = 0x10000; } crush_bucket *b = crush_make_bucket(CRUSH_BUCKET_STRAW, CRUSH_HASH_DEFAULT, 1, nosd, items, weights); int rootid = crush_add_bucket(crush.crush, 0, b); crush.set_item_name(rootid, "root"); // replication for (map<int,const char*>::iterator p = rulesets.begin(); p != rulesets.end(); p++) { int ruleset = p->first; crush_rule *rule = crush_make_rule(3, ruleset, CEPH_PG_TYPE_REP, g_conf.osd_min_rep, maxrep); crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, rootid, 0); crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSE_FIRSTN, CRUSH_CHOOSE_N, 0); crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0); int rno = crush_add_rule(crush.crush, rule, -1); crush.set_rule_name(rno, p->second); } } crush.finalize(); dout(20) << "crush max_devices " << crush.crush->max_devices << dendl; }
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <[email protected]> * * This 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. See file COPYING. * */ #include "OSDMap.h" #include "common/config.h" void OSDMap::print(ostream& out) const { out << "epoch " << get_epoch() << "\n" << "fsid " << get_fsid() << "\n" << "created " << get_created() << "\n" << "modifed " << get_modified() << "\n"; out << "flags"; if (test_flag(CEPH_OSDMAP_NEARFULL)) out << " nearfull"; if (test_flag(CEPH_OSDMAP_FULL)) out << " full"; if (test_flag(CEPH_OSDMAP_PAUSERD)) out << " pauserd"; if (test_flag(CEPH_OSDMAP_PAUSEWR)) out << " pausewr"; if (test_flag(CEPH_OSDMAP_PAUSEREC)) out << " pauserec"; out << "\n" << std::endl; for (map<int,pg_pool_t>::const_iterator p = pools.begin(); p != pools.end(); ++p) { std::string name("<unknown>"); map<int32_t,string>::const_iterator pni = pool_name.find(p->first); if (pni != pool_name.end()) name = pni->second; out << "pg_pool " << p->first << " '" << name << "' " << p->second << "\n"; for (map<snapid_t,pool_snap_info_t>::const_iterator q = p->second.snaps.begin(); q != p->second.snaps.end(); q++) out << "\tsnap " << q->second.snapid << " '" << q->second.name << "' " << q->second.stamp << "\n"; if (!p->second.removed_snaps.empty()) out << "\tremoved_snaps " << p->second.removed_snaps << "\n"; } out << std::endl; out << "max_osd " << get_max_osd() << "\n"; for (int i=0; i<get_max_osd(); i++) { if (exists(i)) { out << "osd" << i; out << (is_up(i) ? " up ":" down"); out << (is_in(i) ? " in ":" out"); if (is_in(i)) out << " weight " << get_weightf(i); const osd_info_t& info(get_info(i)); out << " " << info; if (is_up(i)) out << " " << get_addr(i) << " " << get_cluster_addr(i) << " " << get_hb_addr(i); out << "\n"; } } out << std::endl; for (map<pg_t,vector<int> >::const_iterator p = pg_temp.begin(); p != pg_temp.end(); p++) out << "pg_temp " << p->first << " " << p->second << "\n"; for (hash_map<entity_addr_t,utime_t>::const_iterator p = blacklist.begin(); p != blacklist.end(); p++) out << "blacklist " << p->first << " expires " << p->second << "\n"; // ignore pg_swap_primary } void OSDMap::print_summary(ostream& out) const { out << "e" << get_epoch() << ": " << get_num_osds() << " osds: " << get_num_up_osds() << " up, " << get_num_in_osds() << " in"; if (test_flag(CEPH_OSDMAP_FULL)) out << " full"; else if (test_flag(CEPH_OSDMAP_NEARFULL)) out << " nearfull"; } void OSDMap::build_simple(epoch_t e, ceph_fsid_t &fsid, int nosd, int ndom, int pg_bits, int pgp_bits, int lpg_bits) { dout(10) << "build_simple on " << num_osd << " osds with " << pg_bits << " pg bits per osd, " << lpg_bits << " lpg bits" << dendl; epoch = e; set_fsid(fsid); created = modified = g_clock.now(); set_max_osd(nosd); // pgp_num <= pg_num if (pgp_bits > pg_bits) pgp_bits = pg_bits; // crush map map<int, const char*> rulesets; rulesets[CEPH_DATA_RULE] = "data"; rulesets[CEPH_METADATA_RULE] = "metadata"; rulesets[CEPH_RBD_RULE] = "rbd"; for (map<int,const char*>::iterator p = rulesets.begin(); p != rulesets.end(); p++) { int pool = ++pool_max; pools[pool].v.type = CEPH_PG_TYPE_REP; pools[pool].v.size = 2; pools[pool].v.crush_ruleset = p->first; pools[pool].v.object_hash = CEPH_STR_HASH_RJENKINS; pools[pool].v.pg_num = nosd << pg_bits; pools[pool].v.pgp_num = nosd << pgp_bits; pools[pool].v.lpg_num = lpg_bits ? (1 << (lpg_bits-1)) : 0; pools[pool].v.lpgp_num = lpg_bits ? (1 << (lpg_bits-1)) : 0; pools[pool].v.last_change = epoch; pool_name[pool] = p->second; } build_simple_crush_map(crush, rulesets, nosd, ndom); for (int i=0; i<nosd; i++) { set_state(i, 0); set_weight(i, CEPH_OSD_OUT); } } void OSDMap::build_simple_crush_map(CrushWrapper& crush, map<int, const char*>& rulesets, int nosd, int ndom) { // new crush.create(); crush.set_type_name(0, "osd"); crush.set_type_name(1, "domain"); crush.set_type_name(2, "pool"); int minrep = g_conf.osd_min_rep; int maxrep = g_conf.osd_max_rep; assert(maxrep >= minrep); if (!ndom) ndom = MAX(maxrep, g_conf.osd_max_raid_width); if (ndom > 1 && nosd >= ndom*3 && nosd > 8) { int ritems[ndom]; int rweights[ndom]; int nper = ((nosd - 1) / ndom) + 1; dout(0) << ndom << " failure domains, " << nper << " osds each" << dendl; int o = 0; for (int i=0; i<ndom; i++) { int items[nper], weights[nper]; int j; rweights[i] = 0; for (j=0; j<nper; j++, o++) { if (o == nosd) break; dout(20) << "added osd" << o << dendl; items[j] = o; weights[j] = 0x10000; //w[j] = weights[o] ? (0x10000 - (int)(weights[o] * 0x10000)):0x10000; //rweights[i] += w[j]; rweights[i] += 0x10000; } crush_bucket *domain = crush_make_bucket(CRUSH_BUCKET_STRAW, CRUSH_HASH_DEFAULT, 1, j, items, weights); ritems[i] = crush_add_bucket(crush.crush, 0, domain); dout(20) << "added domain bucket i " << ritems[i] << " of size " << j << dendl; char bname[10]; snprintf(bname, sizeof(bname), "dom%d", i); crush.set_item_name(ritems[i], bname); } // root crush_bucket *root = crush_make_bucket(CRUSH_BUCKET_STRAW, CRUSH_HASH_DEFAULT, 2, ndom, ritems, rweights); int rootid = crush_add_bucket(crush.crush, 0, root); crush.set_item_name(rootid, "root"); // rules for (map<int,const char*>::iterator p = rulesets.begin(); p != rulesets.end(); p++) { int ruleset = p->first; crush_rule *rule = crush_make_rule(3, ruleset, CEPH_PG_TYPE_REP, minrep, maxrep); crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, rootid, 0); crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSE_LEAF_FIRSTN, CRUSH_CHOOSE_N, 1); // choose N domains crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0); int rno = crush_add_rule(crush.crush, rule, -1); crush.set_rule_name(rno, p->second); } } else { // one bucket int items[nosd]; int weights[nosd]; for (int i=0; i<nosd; i++) { items[i] = i; weights[i] = 0x10000; } crush_bucket *b = crush_make_bucket(CRUSH_BUCKET_STRAW, CRUSH_HASH_DEFAULT, 1, nosd, items, weights); int rootid = crush_add_bucket(crush.crush, 0, b); crush.set_item_name(rootid, "root"); // replication for (map<int,const char*>::iterator p = rulesets.begin(); p != rulesets.end(); p++) { int ruleset = p->first; crush_rule *rule = crush_make_rule(3, ruleset, CEPH_PG_TYPE_REP, g_conf.osd_min_rep, maxrep); crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, rootid, 0); crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSE_FIRSTN, CRUSH_CHOOSE_N, 0); crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0); int rno = crush_add_rule(crush.crush, rule, -1); crush.set_rule_name(rno, p->second); } } crush.finalize(); dout(20) << "crush max_devices " << crush.crush->max_devices << dendl; }
set type 0 to 'osd'
osdmap: set type 0 to 'osd' Signed-off-by: Sage Weil <[email protected]>
C++
lgpl-2.1
ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph
9e223c3ab59cab896e7d7993b47a12e5fed6eb4c
src/metric/map_metric.hpp
src/metric/map_metric.hpp
#ifndef LIGHTGBM_METRIC_MAP_METRIC_HPP_ #define LIGHTGBM_METRIC_MAP_METRIC_HPP_ #include <LightGBM/utils/common.h> #include <LightGBM/utils/log.h> #include <LightGBM/metric.h> #include <LightGBM/utils/openmp_wrapper.h> #include <sstream> #include <vector> namespace LightGBM { class MapMetric:public Metric { public: explicit MapMetric(const MetricConfig& config) { // get eval position for (auto k : config.eval_at) { eval_at_.push_back(static_cast<data_size_t>(k)); } // get number of threads #pragma omp parallel #pragma omp master { num_threads_ = omp_get_num_threads(); } } ~MapMetric() { } void Init(const Metadata& metadata, data_size_t num_data) override { std::stringstream str_buf; for (auto k : eval_at_) { name_.emplace_back(std::string("map@") + std::to_string(k)); } num_data_ = num_data; // get label label_ = metadata.label(); // get query boundaries query_boundaries_ = metadata.query_boundaries(); if (query_boundaries_ == nullptr) { Log::Fatal("For MAP metric, there should be query information"); } num_queries_ = metadata.num_queries(); Log::Info("total groups: %d , total data: %d", num_queries_, num_data_); // get query weights query_weights_ = metadata.query_weights(); if (query_weights_ == nullptr) { sum_query_weights_ = static_cast<double>(num_queries_); } else { sum_query_weights_ = 0.0f; for (data_size_t i = 0; i < num_queries_; ++i) { sum_query_weights_ += query_weights_[i]; } } npos_per_query_.resize(num_queries_, 0); for (data_size_t i = 0; i < num_queries_; ++i) { for (data_size_t j = query_boundaries_[i]; j < query_boundaries_[i + 1]; ++j) { if (label_[j] > 0.5f) { ++npos_per_query_[i]; } } } } const std::vector<std::string>& GetName() const override { return name_; } double factor_to_bigger_better() const override { return 1.0f; } void CalMapAtK(std::vector<int> ks, data_size_t npos, const label_t* label, const double* score, data_size_t num_data, std::vector<double>* out) const { // get sorted indices by score std::vector<data_size_t> sorted_idx; for (data_size_t i = 0; i < num_data; ++i) { sorted_idx.emplace_back(i); } std::sort(sorted_idx.begin(), sorted_idx.end(), [score](data_size_t a, data_size_t b) {return score[a] > score[b]; }); int num_hit = 0; double sum_ap = 0.0f; data_size_t cur_left = 0; for (size_t i = 0; i < ks.size(); ++i) { data_size_t cur_k = static_cast<data_size_t>(ks[i]); if (cur_k > num_data) { cur_k = num_data; } for (data_size_t j = cur_left; j < cur_k; ++j) { data_size_t idx = sorted_idx[j]; if (label[idx] > 0.5f) { ++num_hit; sum_ap += static_cast<double>(num_hit) / (j + 1.0f); } } if (npos > 0) { (*out)[i] = sum_ap / std::min(npos, cur_k); } else { (*out)[i] = 1.0f; } cur_left = cur_k; } } std::vector<double> Eval(const double* score, const ObjectiveFunction*) const override { // some buffers for multi-threading sum up std::vector<std::vector<double>> result_buffer_; for (int i = 0; i < num_threads_; ++i) { result_buffer_.emplace_back(eval_at_.size(), 0.0f); } std::vector<double> tmp_map(eval_at_.size(), 0.0f); if (query_weights_ == nullptr) { #pragma omp parallel for schedule(guided) firstprivate(tmp_map) for (data_size_t i = 0; i < num_queries_; ++i) { const int tid = omp_get_thread_num(); CalMapAtK(eval_at_, npos_per_query_[i], label_ + query_boundaries_[i], score + query_boundaries_[i], query_boundaries_[i + 1] - query_boundaries_[i], &tmp_map); for (size_t j = 0; j < eval_at_.size(); ++j) { result_buffer_[tid][j] += tmp_map[j]; } } } else { #pragma omp parallel for schedule(guided) firstprivate(tmp_map) for (data_size_t i = 0; i < num_queries_; ++i) { const int tid = omp_get_thread_num(); CalMapAtK(eval_at_, npos_per_query_[i], label_ + query_boundaries_[i], score + query_boundaries_[i], query_boundaries_[i + 1] - query_boundaries_[i], &tmp_map); for (size_t j = 0; j < eval_at_.size(); ++j) { result_buffer_[tid][j] += tmp_map[j] * query_weights_[i]; } } } // Get final average MAP std::vector<double> result(eval_at_.size(), 0.0f); for (size_t j = 0; j < result.size(); ++j) { for (int i = 0; i < num_threads_; ++i) { result[j] += result_buffer_[i][j]; } result[j] /= sum_query_weights_; } return result; } private: /*! \brief Number of data */ data_size_t num_data_; /*! \brief Pointer of label */ const label_t* label_; /*! \brief Query boundaries information */ const data_size_t* query_boundaries_; /*! \brief Number of queries */ data_size_t num_queries_; /*! \brief Weights of queries */ const label_t* query_weights_; /*! \brief Sum weights of queries */ double sum_query_weights_; /*! \brief Evaluate position of Nmap */ std::vector<data_size_t> eval_at_; /*! \brief Number of threads */ int num_threads_; std::vector<std::string> name_; std::vector<data_size_t> npos_per_query_; }; } // namespace LightGBM #endif // LIGHTGBM_METRIC_MAP_METRIC_HPP_
#ifndef LIGHTGBM_METRIC_MAP_METRIC_HPP_ #define LIGHTGBM_METRIC_MAP_METRIC_HPP_ #include <LightGBM/utils/common.h> #include <LightGBM/utils/log.h> #include <LightGBM/metric.h> #include <LightGBM/utils/openmp_wrapper.h> #include <sstream> #include <vector> namespace LightGBM { class MapMetric:public Metric { public: explicit MapMetric(const MetricConfig& config) { // get eval position for (auto k : config.eval_at) { eval_at_.push_back(static_cast<data_size_t>(k)); } // get number of threads #pragma omp parallel #pragma omp master { num_threads_ = omp_get_num_threads(); } } ~MapMetric() { } void Init(const Metadata& metadata, data_size_t num_data) override { for (auto k : eval_at_) { name_.emplace_back(std::string("map@") + std::to_string(k)); } num_data_ = num_data; // get label label_ = metadata.label(); // get query boundaries query_boundaries_ = metadata.query_boundaries(); if (query_boundaries_ == nullptr) { Log::Fatal("For MAP metric, there should be query information"); } num_queries_ = metadata.num_queries(); Log::Info("total groups: %d , total data: %d", num_queries_, num_data_); // get query weights query_weights_ = metadata.query_weights(); if (query_weights_ == nullptr) { sum_query_weights_ = static_cast<double>(num_queries_); } else { sum_query_weights_ = 0.0f; for (data_size_t i = 0; i < num_queries_; ++i) { sum_query_weights_ += query_weights_[i]; } } npos_per_query_.resize(num_queries_, 0); for (data_size_t i = 0; i < num_queries_; ++i) { for (data_size_t j = query_boundaries_[i]; j < query_boundaries_[i + 1]; ++j) { if (label_[j] > 0.5f) { ++npos_per_query_[i]; } } } } const std::vector<std::string>& GetName() const override { return name_; } double factor_to_bigger_better() const override { return 1.0f; } void CalMapAtK(std::vector<int> ks, data_size_t npos, const label_t* label, const double* score, data_size_t num_data, std::vector<double>* out) const { // get sorted indices by score std::vector<data_size_t> sorted_idx; for (data_size_t i = 0; i < num_data; ++i) { sorted_idx.emplace_back(i); } std::sort(sorted_idx.begin(), sorted_idx.end(), [score](data_size_t a, data_size_t b) {return score[a] > score[b]; }); int num_hit = 0; double sum_ap = 0.0f; data_size_t cur_left = 0; for (size_t i = 0; i < ks.size(); ++i) { data_size_t cur_k = static_cast<data_size_t>(ks[i]); if (cur_k > num_data) { cur_k = num_data; } for (data_size_t j = cur_left; j < cur_k; ++j) { data_size_t idx = sorted_idx[j]; if (label[idx] > 0.5f) { ++num_hit; sum_ap += static_cast<double>(num_hit) / (j + 1.0f); } } if (npos > 0) { (*out)[i] = sum_ap / std::min(npos, cur_k); } else { (*out)[i] = 1.0f; } cur_left = cur_k; } } std::vector<double> Eval(const double* score, const ObjectiveFunction*) const override { // some buffers for multi-threading sum up std::vector<std::vector<double>> result_buffer_; for (int i = 0; i < num_threads_; ++i) { result_buffer_.emplace_back(eval_at_.size(), 0.0f); } std::vector<double> tmp_map(eval_at_.size(), 0.0f); if (query_weights_ == nullptr) { #pragma omp parallel for schedule(guided) firstprivate(tmp_map) for (data_size_t i = 0; i < num_queries_; ++i) { const int tid = omp_get_thread_num(); CalMapAtK(eval_at_, npos_per_query_[i], label_ + query_boundaries_[i], score + query_boundaries_[i], query_boundaries_[i + 1] - query_boundaries_[i], &tmp_map); for (size_t j = 0; j < eval_at_.size(); ++j) { result_buffer_[tid][j] += tmp_map[j]; } } } else { #pragma omp parallel for schedule(guided) firstprivate(tmp_map) for (data_size_t i = 0; i < num_queries_; ++i) { const int tid = omp_get_thread_num(); CalMapAtK(eval_at_, npos_per_query_[i], label_ + query_boundaries_[i], score + query_boundaries_[i], query_boundaries_[i + 1] - query_boundaries_[i], &tmp_map); for (size_t j = 0; j < eval_at_.size(); ++j) { result_buffer_[tid][j] += tmp_map[j] * query_weights_[i]; } } } // Get final average MAP std::vector<double> result(eval_at_.size(), 0.0f); for (size_t j = 0; j < result.size(); ++j) { for (int i = 0; i < num_threads_; ++i) { result[j] += result_buffer_[i][j]; } result[j] /= sum_query_weights_; } return result; } private: /*! \brief Number of data */ data_size_t num_data_; /*! \brief Pointer of label */ const label_t* label_; /*! \brief Query boundaries information */ const data_size_t* query_boundaries_; /*! \brief Number of queries */ data_size_t num_queries_; /*! \brief Weights of queries */ const label_t* query_weights_; /*! \brief Sum weights of queries */ double sum_query_weights_; /*! \brief Evaluate position of Nmap */ std::vector<data_size_t> eval_at_; /*! \brief Number of threads */ int num_threads_; std::vector<std::string> name_; std::vector<data_size_t> npos_per_query_; }; } // namespace LightGBM #endif // LIGHTGBM_METRIC_MAP_METRIC_HPP_
remove a unused variable.
remove a unused variable.
C++
mit
microsoft/LightGBM,henry0312/LightGBM,microsoft/LightGBM,Laurae2/LightGBM,microsoft/LightGBM,henry0312/LightGBM,henry0312/LightGBM,henry0312/LightGBM,microsoft/LightGBM,microsoft/LightGBM,Laurae2/LightGBM,henry0312/LightGBM,Laurae2/LightGBM,Laurae2/LightGBM,Laurae2/LightGBM
b4568a97dabaec27d12e78458db283610587ccc5
src/pito/pito.cpp
src/pito/pito.cpp
#include <rbutil/conf/cmd/command_line.hpp> #include <pito/interceptor/application.hpp> #include <pito/config.hpp> #include <iostream> #define PITO_PROGRAM_VERSION "0.9.1" namespace pito { namespace jail = interceptor::jail; namespace cmd_line = rb::util::conf::cmd; using rb::util::conf::value; bool verbose = false; inline int main(int argc, char *argv[]) { { using cmd_line::options_description; // TODO: make all arguments from second positional and inclusive the // new argv/argc options_description options; bool showHelp = false; bool silent = false; options.add_options() ("v,verbose", verbose, "increase verbosity") .help("h,help", "pito " PITO_PROGRAM_VERSION "\nusage: pito [arguments] <wrapper library name> <program> [program arguments]") ("s,silent", silent, "don't say anything") ("l,library-dir", value(jail::preload), "pito library directory") ; try { int nPositionals = silent ? cmd_line::parser(argc, argv, options)().n_positionals() : cmd_line::parser(argc, argv, options)(std::cerr).n_positionals(); if (nPositionals < 2) { if (! silent) { if (1 == nPositionals) std::cout << "missing <program> argument, see --help" << std::endl; else std::cout << "missing <wrapper library name> and <program> arguments, see --help" << std::endl; } return 1; } } catch (cmd_line::invalid_arguments& ) { return 1; } std::string libraryFileName = "libpito_"; libraryFileName.append(argv[1]); interceptor::search_for_preload_library(libraryFileName, jail::preload, jail::preload); if (jail::preload.empty()) { if (! silent) std::cerr << "library " << libraryFileName << " could not be found at" " install location or in $" PITO_LD_LIBRARY_PATH << std::endl; } else { if (verbose) std::cerr << "load interceptor library (" << jail::preload << ")" << std::endl; jail::enforce_environment(); // consider setting argv[2] based on path and use execv execvp(argv[2], argv + 2); } return 1; } } } int main(int argc, char *argv[]) { return pito::main(argc, argv); }
#include <rbutil/conf/cmd/command_line.hpp> #include <pito/interceptor/application.hpp> #include <pito/config.hpp> #include <iostream> #define PITO_PROGRAM_VERSION "0.9.1" namespace pito { namespace jail = interceptor::jail; namespace cmd_line = rb::util::conf::cmd; using rb::util::conf::value; bool verbose = false; inline int main(int argc, char *argv[]) { { using cmd_line::options_description; // TODO: make all arguments from second positional and inclusive the // new argv/argc options_description options; bool showHelp = false; bool silent = false; options.add_options() ("v,verbose", verbose, "increase verbosity") .help("pito " PITO_PROGRAM_VERSION "\nusage: pito [arguments] " "<wrapper library name> <program> [program arguments]") ("s,silent", silent, "don't say anything") ("l,library-dir", value(jail::preload), "pito library directory") ; try { int nPositionals = silent ? cmd_line::parser(argc, argv, options)().n_positionals() : cmd_line::parser(argc, argv, options)(std::cerr).n_positionals(); if (nPositionals < 2) { if (! silent) { if (1 == nPositionals) std::cout << "missing <program> argument, see --help" << std::endl; else std::cout << "missing <wrapper library name> and <program> arguments, see --help" << std::endl; } return 1; } } catch (cmd_line::invalid_arguments& ) { return 1; } std::string libraryFileName = "libpito_"; libraryFileName.append(argv[1]); interceptor::search_for_preload_library(libraryFileName, jail::preload, jail::preload); if (jail::preload.empty()) { if (! silent) std::cerr << "library " << libraryFileName << " could not be found at" " install location or in $" PITO_LD_LIBRARY_PATH << std::endl; } else { if (verbose) std::cerr << "load interceptor library (" << jail::preload << ")" << std::endl; jail::enforce_environment(); // consider setting argv[2] based on path and use execv execvp(argv[2], argv + 2); } return 1; } } } int main(int argc, char *argv[]) { return pito::main(argc, argv); }
use default help
use default help git-svn-id: 45c2c4a2387ab509d51a0462740e0050158f91df@158 10163329-09b4-48c1-bceb-0bacdf617a99
C++
mit
ohjames/pito,ohjames/pito,ohjames/pito
fb1e8e4f5296d374e0aafdccaddbed91b7327b1b
src/prefix_key.cc
src/prefix_key.cc
#include <ncurses.h> #include "show_message.hh" #include "prefix_key.hh" char prefix_key_times_ten; static boost::optional< std::shared_ptr<change> > handle(contents& contents, boost::optional<int> op, int n) { int orig = op ? op.get() : 0; char c = getch(); if(c == prefix_key_times_ten && orig != 0) { c = getch(); while(c == prefix_key_times_ten) { orig *= 10; c = getch(); } } orig *= 10; const auto& x = global_normal_map.find(c); if(x == global_normal_map.end()) { show_message(std::string("Unbound key: ") + std::to_string(c)); return boost::none; } return x->second(contents, orig + n); } boost::optional< std::shared_ptr<change> > prefix_key_1(contents& contents, boost::optional<int> op) { return handle(contents,op,1); } boost::optional< std::shared_ptr<change> > prefix_key_2(contents& contents, boost::optional<int> op) { return handle(contents,op,2); } boost::optional< std::shared_ptr<change> > prefix_key_3(contents& contents, boost::optional<int> op) { return handle(contents,op,3); } boost::optional< std::shared_ptr<change> > prefix_key_4(contents& contents, boost::optional<int> op) { return handle(contents,op,4); } boost::optional< std::shared_ptr<change> > prefix_key_5(contents& contents, boost::optional<int> op) { return handle(contents,op,5); } boost::optional< std::shared_ptr<change> > prefix_key_6(contents& contents, boost::optional<int> op) { return handle(contents,op,6); } boost::optional< std::shared_ptr<change> > prefix_key_7(contents& contents, boost::optional<int> op) { return handle(contents,op,7); } boost::optional< std::shared_ptr<change> > prefix_key_8(contents& contents, boost::optional<int> op) { return handle(contents,op,8); } boost::optional< std::shared_ptr<change> > prefix_key_9(contents& contents, boost::optional<int> op) { return handle(contents,op,9); }
#include <ncurses.h> #include "show_message.hh" #include "prefix_key.hh" char prefix_key_times_ten; static boost::optional< std::shared_ptr<change> > handle(contents& contents, boost::optional<int> op, int n) { int total = n + (op ? op.get() : 0) * 10; show_message(std::to_string(total) + "-"); char c = getch(); while(c == prefix_key_times_ten) { total *= 10; show_message(std::to_string(total) + "-"); c = getch(); } auto x = global_normal_map.find(c); if(x == global_normal_map.end()) { show_message(std::string("Unbound key: ") + std::to_string(c)); return boost::none; } showing_message = false; return x->second(contents, total); } boost::optional< std::shared_ptr<change> > prefix_key_1(contents& contents, boost::optional<int> op) { return handle(contents,op,1); } boost::optional< std::shared_ptr<change> > prefix_key_2(contents& contents, boost::optional<int> op) { return handle(contents,op,2); } boost::optional< std::shared_ptr<change> > prefix_key_3(contents& contents, boost::optional<int> op) { return handle(contents,op,3); } boost::optional< std::shared_ptr<change> > prefix_key_4(contents& contents, boost::optional<int> op) { return handle(contents,op,4); } boost::optional< std::shared_ptr<change> > prefix_key_5(contents& contents, boost::optional<int> op) { return handle(contents,op,5); } boost::optional< std::shared_ptr<change> > prefix_key_6(contents& contents, boost::optional<int> op) { return handle(contents,op,6); } boost::optional< std::shared_ptr<change> > prefix_key_7(contents& contents, boost::optional<int> op) { return handle(contents,op,7); } boost::optional< std::shared_ptr<change> > prefix_key_8(contents& contents, boost::optional<int> op) { return handle(contents,op,8); } boost::optional< std::shared_ptr<change> > prefix_key_9(contents& contents, boost::optional<int> op) { return handle(contents,op,9); }
Fix ``prefix_key.cc::handle()`` to be simpler and actually work as intended
Fix ``prefix_key.cc::handle()`` to be simpler and actually work as intended
C++
mpl-2.0
czipperz/vick,czipperz/vick
0784d1f389d707e29c50f4479f692b942181174c
src/nvtt/tests/stress.cpp
src/nvtt/tests/stress.cpp
// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <[email protected]> // // 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 <nvtt/nvtt.h> #include <stdio.h> // printf #include <stdlib.h> // rand? #include <time.h> // clock int main(int argc, char *argv[]) { nvtt::InputOptions inputOptions; inputOptions.setTextureLayout(nvtt::TextureType_2D, 1024, 1024); int * data = (int *)malloc(1024 * 1024 * 4); for (int i = 0; i < 1024 * 1024; i++) { data[i] = rand(); } inputOptions.setMipmapData(data, 1024, 1024); inputOptions.setMipmapGeneration(false); nvtt::CompressionOptions compressionOptions; nvtt::OutputOptions outputOptions; nvtt::Compressor compressor; for (int i = 0; i < 1000; i++) { clock_t start = clock(); compressor.process(inputOptions, compressionOptions, outputOptions); clock_t end = clock(); printf("time taken: %.3f seconds\n", float(end-start) / CLOCKS_PER_SEC); } return 0; }
// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <[email protected]> // // 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 <nvtt/nvtt.h> #include <stdio.h> // printf #include <stdlib.h> // rand #include <time.h> // clock #include <string.h> // memcpy, memcmp #include <assert.h> #define FRAME_COUNT 1000 #define WIDTH 1024 #define HEIGHT 1024 #define INPUT_SIZE (WIDTH*HEIGHT) #define OUTPUT_SIZE (WIDTH*HEIGHT/16*2) static int s_input[INPUT_SIZE]; static int s_reference[OUTPUT_SIZE]; static int s_output[OUTPUT_SIZE]; static int s_frame = 0; struct MyOutputHandler : public nvtt::OutputHandler { MyOutputHandler() : m_ptr(NULL) {} virtual void beginImage(int size, int width, int height, int depth, int face, int miplevel) { assert(size == OUTPUT_SIZE); assert(width == WIDTH); assert(height == HEIGHT); assert(depth == 1); assert(face == 0); assert(miplevel == 0); m_ptr = (unsigned char *)s_output; if (s_frame == 1) { // Save first result as reference. memcpy(s_reference, s_output, sizeof(int) * OUTPUT_SIZE); } else if (s_frame > 1) { // Compare against reference. if (memcmp(s_output, s_reference, sizeof(int) * OUTPUT_SIZE) != 0) { printf("Compressed image different to original.\n"); exit(EXIT_FAILURE); } } } virtual bool writeData(const void * data, int size) { memcpy(m_ptr, data, size); m_ptr += size; return true; } unsigned char * m_ptr; }; int main(int argc, char *argv[]) { nvtt::InputOptions inputOptions; inputOptions.setTextureLayout(nvtt::TextureType_2D, 1024, 1024); for (int i = 0; i < 1024 * 1024; i++) { s_input[i] = rand(); } inputOptions.setMipmapData(s_input, 1024, 1024); inputOptions.setMipmapGeneration(false); nvtt::CompressionOptions compressionOptions; nvtt::OutputOptions outputOptions; outputOptions.setOutputHeader(false); MyOutputHandler outputHandler; outputOptions.setOutputHandler(&outputHandler); nvtt::Compressor compressor; for (s_frame = 0; s_frame < FRAME_COUNT; s_frame++) { clock_t start = clock(); printf("compressing frame %d:\n", s_frame); compressor.process(inputOptions, compressionOptions, outputOptions); clock_t end = clock(); printf("time taken: %.3f seconds\n", float(end-start) / CLOCKS_PER_SEC); } return EXIT_SUCCESS; }
Improve stress test to detect errors in the output.
Improve stress test to detect errors in the output. git-svn-id: bd2008fbba0f7d30fd6598b54f2cd88503fdd2e4@442 95f4ed2b-212e-0410-8b90-d31948207fce
C++
mit
salamanderrake/nvidia-texture-tools,hymerman/nvidia-texture-tools,casseveritt/nvidia-texture-tools,salamanderrake/nvidia-texture-tools,svn2github/nvidia-texture-tools,casseveritt/nvidia-texture-tools,svn2github/nvidia-texture-tools,svn2github/nvidia-texture-tools,hymerman/nvidia-texture-tools,salamanderrake/nvidia-texture-tools,casseveritt/nvidia-texture-tools,svn2github/nvidia-texture-tools,hymerman/nvidia-texture-tools,salamanderrake/nvidia-texture-tools,hymerman/nvidia-texture-tools
a1a8f6c5917103afe08ed7298e33e285f6d76ff9
src/physics/fem_physics.C
src/physics/fem_physics.C
// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh/dof_map.h" #include "libmesh/elem.h" #include "libmesh/equation_systems.h" #include "libmesh/fe_base.h" #include "libmesh/fem_context.h" #include "libmesh/fem_system.h" #include "libmesh/libmesh_logging.h" #include "libmesh/mesh_base.h" #include "libmesh/numeric_vector.h" #include "libmesh/parallel.h" #include "libmesh/quadrature.h" #include "libmesh/sparse_matrix.h" #include "libmesh/time_solver.h" #include "libmesh/unsteady_solver.h" // For eulerian_residual namespace libMesh { bool FEMPhysics::eulerian_residual (bool request_jacobian, DiffContext &/*c*/) { // Only calculate a mesh movement residual if it's necessary if (!_mesh_sys) return request_jacobian; libmesh_not_implemented(); #if 0 FEMContext &context = libmesh_cast_ref<FEMContext&>(c); // This function only supports fully coupled mesh motion for now libmesh_assert_equal_to (_mesh_sys, this); unsigned int n_qpoints = (context.get_element_qrule())->n_points(); const unsigned int n_x_dofs = (_mesh_x_var == libMesh::invalid_uint) ? 0 : context.dof_indices_var[_mesh_x_var].size(); const unsigned int n_y_dofs = (_mesh_y_var == libMesh::invalid_uint) ? 0 : context.dof_indices_var[_mesh_y_var].size(); const unsigned int n_z_dofs = (_mesh_z_var == libMesh::invalid_uint) ? 0 : context.dof_indices_var[_mesh_z_var].size(); const unsigned int mesh_xyz_var = n_x_dofs ? _mesh_x_var : (n_y_dofs ? _mesh_y_var : (n_z_dofs ? _mesh_z_var : libMesh::invalid_uint)); // If we're our own _mesh_sys, we'd better be in charge of // at least one coordinate, and we'd better have the same // FE type for all coordinates we are in charge of libmesh_assert_not_equal_to (mesh_xyz_var, libMesh::invalid_uint); libmesh_assert(!n_x_dofs || context.element_fe_var[_mesh_x_var] == context.element_fe_var[mesh_xyz_var]); libmesh_assert(!n_y_dofs || context.element_fe_var[_mesh_y_var] == context.element_fe_var[mesh_xyz_var]); libmesh_assert(!n_z_dofs || context.element_fe_var[_mesh_z_var] == context.element_fe_var[mesh_xyz_var]); const std::vector<std::vector<Real> > &psi = context.element_fe_var[mesh_xyz_var]->get_phi(); for (unsigned int var = 0; var != context.n_vars(); ++var) { // Mesh motion only affects time-evolving variables if (this->is_time_evolving(var)) continue; // The mesh coordinate variables themselves are Lagrangian, // not Eulerian, and no convective term is desired. if (/*_mesh_sys == this && */ (var == _mesh_x_var || var == _mesh_y_var || var == _mesh_z_var)) continue; // Some of this code currently relies on the assumption that // we can pull mesh coordinate data from our own system if (_mesh_sys != this) libmesh_not_implemented(); // This residual should only be called by unsteady solvers: // if the mesh is steady, there's no mesh convection term! UnsteadySolver *unsteady; if (this->time_solver->is_steady()) return request_jacobian; else unsteady = libmesh_cast_ptr<UnsteadySolver*>(this->time_solver.get()); const std::vector<Real> &JxW = context.element_fe_var[var]->get_JxW(); const std::vector<std::vector<Real> > &phi = context.element_fe_var[var]->get_phi(); const std::vector<std::vector<RealGradient> > &dphi = context.element_fe_var[var]->get_dphi(); const unsigned int n_u_dofs = context.dof_indices_var[var].size(); DenseSubVector<Number> &Fu = *context.elem_subresiduals[var]; DenseSubMatrix<Number> &Kuu = *context.elem_subjacobians[var][var]; DenseSubMatrix<Number> *Kux = n_x_dofs ? context.elem_subjacobians[var][_mesh_x_var] : NULL; DenseSubMatrix<Number> *Kuy = n_y_dofs ? context.elem_subjacobians[var][_mesh_y_var] : NULL; DenseSubMatrix<Number> *Kuz = n_z_dofs ? context.elem_subjacobians[var][_mesh_z_var] : NULL; std::vector<Real> delta_x(n_x_dofs, 0.); std::vector<Real> delta_y(n_y_dofs, 0.); std::vector<Real> delta_z(n_z_dofs, 0.); for (unsigned int i = 0; i != n_x_dofs; ++i) { unsigned int j = context.dof_indices_var[_mesh_x_var][i]; delta_x[i] = libmesh_real(this->current_solution(j)) - libmesh_real(unsteady->old_nonlinear_solution(j)); } for (unsigned int i = 0; i != n_y_dofs; ++i) { unsigned int j = context.dof_indices_var[_mesh_y_var][i]; delta_y[i] = libmesh_real(this->current_solution(j)) - libmesh_real(unsteady->old_nonlinear_solution(j)); } for (unsigned int i = 0; i != n_z_dofs; ++i) { unsigned int j = context.dof_indices_var[_mesh_z_var][i]; delta_z[i] = libmesh_real(this->current_solution(j)) - libmesh_real(unsteady->old_nonlinear_solution(j)); } for (unsigned int qp = 0; qp != n_qpoints; ++qp) { Gradient grad_u = context.interior_gradient(var, qp); RealGradient convection(0.); for (unsigned int i = 0; i != n_x_dofs; ++i) convection(0) += delta_x[i] * psi[i][qp]; for (unsigned int i = 0; i != n_y_dofs; ++i) convection(1) += delta_y[i] * psi[i][qp]; for (unsigned int i = 0; i != n_z_dofs; ++i) convection(2) += delta_z[i] * psi[i][qp]; for (unsigned int i = 0; i != n_u_dofs; ++i) { Number JxWxPhiI = JxW[qp] * phi[i][qp]; Fu(i) += (convection * grad_u) * JxWxPhiI; if (request_jacobian) { Number JxWxPhiI = JxW[qp] * phi[i][qp]; for (unsigned int j = 0; j != n_u_dofs; ++j) Kuu(i,j) += JxWxPhiI * (convection * dphi[j][qp]); Number JxWxPhiIoverDT = JxWxPhiI/this->deltat; Number JxWxPhiIxDUDXoverDT = JxWxPhiIoverDT * grad_u(0); for (unsigned int j = 0; j != n_x_dofs; ++j) (*Kux)(i,j) += JxWxPhiIxDUDXoverDT * psi[j][qp]; Number JxWxPhiIxDUDYoverDT = JxWxPhiIoverDT * grad_u(1); for (unsigned int j = 0; j != n_y_dofs; ++j) (*Kuy)(i,j) += JxWxPhiIxDUDYoverDT * psi[j][qp]; Number JxWxPhiIxDUDZoverDT = JxWxPhiIoverDT * grad_u(2); for (unsigned int j = 0; j != n_z_dofs; ++j) (*Kuz)(i,j) += JxWxPhiIxDUDZoverDT * psi[j][qp]; } } } } #endif // 0 return request_jacobian; } bool FEMPhysics::mass_residual (bool request_jacobian, DiffContext &c) { FEMContext &context = libmesh_cast_ref<FEMContext&>(c); unsigned int n_qpoints = (context.get_element_qrule())->n_points(); for (unsigned int var = 0; var != context.n_vars(); ++var) { if (!this->is_time_evolving(var)) continue; const std::vector<Real> &JxW = context.element_fe_var[var]->get_JxW(); const std::vector<std::vector<Real> > &phi = context.element_fe_var[var]->get_phi(); const unsigned int n_dofs = libmesh_cast_int<unsigned int> (context.dof_indices_var[var].size()); DenseSubVector<Number> &Fu = *context.elem_subresiduals[var]; DenseSubMatrix<Number> &Kuu = *context.elem_subjacobians[var][var]; for (unsigned int qp = 0; qp != n_qpoints; ++qp) { Number u = context.interior_value(var, qp); Number JxWxU = JxW[qp] * u; for (unsigned int i = 0; i != n_dofs; ++i) { Fu(i) += JxWxU * phi[i][qp]; if (request_jacobian && context.elem_solution_derivative) { libmesh_assert_equal_to (context.elem_solution_derivative, 1.0); Number JxWxPhiI = JxW[qp] * phi[i][qp]; Kuu(i,i) += JxWxPhiI * phi[i][qp]; for (unsigned int j = i+1; j < n_dofs; ++j) { Number Kij = JxWxPhiI * phi[j][qp]; Kuu(i,j) += Kij; Kuu(j,i) += Kij; } } } } } return request_jacobian; } } // namespace libMesh
// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh/dof_map.h" #include "libmesh/elem.h" #include "libmesh/equation_systems.h" #include "libmesh/fe_base.h" #include "libmesh/fem_context.h" #include "libmesh/fem_system.h" #include "libmesh/libmesh_logging.h" #include "libmesh/mesh_base.h" #include "libmesh/numeric_vector.h" #include "libmesh/parallel.h" #include "libmesh/quadrature.h" #include "libmesh/sparse_matrix.h" #include "libmesh/time_solver.h" #include "libmesh/unsteady_solver.h" // For eulerian_residual namespace libMesh { bool FEMPhysics::eulerian_residual (bool request_jacobian, DiffContext &/*c*/) { // Only calculate a mesh movement residual if it's necessary if (!_mesh_sys) return request_jacobian; libmesh_not_implemented(); #if 0 FEMContext &context = libmesh_cast_ref<FEMContext&>(c); // This function only supports fully coupled mesh motion for now libmesh_assert_equal_to (_mesh_sys, this); unsigned int n_qpoints = (context.get_element_qrule())->n_points(); const unsigned int n_x_dofs = (_mesh_x_var == libMesh::invalid_uint) ? 0 : context.dof_indices_var[_mesh_x_var].size(); const unsigned int n_y_dofs = (_mesh_y_var == libMesh::invalid_uint) ? 0 : context.dof_indices_var[_mesh_y_var].size(); const unsigned int n_z_dofs = (_mesh_z_var == libMesh::invalid_uint) ? 0 : context.dof_indices_var[_mesh_z_var].size(); const unsigned int mesh_xyz_var = n_x_dofs ? _mesh_x_var : (n_y_dofs ? _mesh_y_var : (n_z_dofs ? _mesh_z_var : libMesh::invalid_uint)); // If we're our own _mesh_sys, we'd better be in charge of // at least one coordinate, and we'd better have the same // FE type for all coordinates we are in charge of libmesh_assert_not_equal_to (mesh_xyz_var, libMesh::invalid_uint); libmesh_assert(!n_x_dofs || context.element_fe_var[_mesh_x_var] == context.element_fe_var[mesh_xyz_var]); libmesh_assert(!n_y_dofs || context.element_fe_var[_mesh_y_var] == context.element_fe_var[mesh_xyz_var]); libmesh_assert(!n_z_dofs || context.element_fe_var[_mesh_z_var] == context.element_fe_var[mesh_xyz_var]); const std::vector<std::vector<Real> > &psi = context.element_fe_var[mesh_xyz_var]->get_phi(); for (unsigned int var = 0; var != context.n_vars(); ++var) { // Mesh motion only affects time-evolving variables if (this->is_time_evolving(var)) continue; // The mesh coordinate variables themselves are Lagrangian, // not Eulerian, and no convective term is desired. if (/*_mesh_sys == this && */ (var == _mesh_x_var || var == _mesh_y_var || var == _mesh_z_var)) continue; // Some of this code currently relies on the assumption that // we can pull mesh coordinate data from our own system if (_mesh_sys != this) libmesh_not_implemented(); // This residual should only be called by unsteady solvers: // if the mesh is steady, there's no mesh convection term! UnsteadySolver *unsteady; if (this->time_solver->is_steady()) return request_jacobian; else unsteady = libmesh_cast_ptr<UnsteadySolver*>(this->time_solver.get()); const std::vector<Real> &JxW = context.element_fe_var[var]->get_JxW(); const std::vector<std::vector<Real> > &phi = context.element_fe_var[var]->get_phi(); const std::vector<std::vector<RealGradient> > &dphi = context.element_fe_var[var]->get_dphi(); const unsigned int n_u_dofs = context.dof_indices_var[var].size(); DenseSubVector<Number> &Fu = *context.elem_subresiduals[var]; DenseSubMatrix<Number> &Kuu = *context.elem_subjacobians[var][var]; DenseSubMatrix<Number> *Kux = n_x_dofs ? context.elem_subjacobians[var][_mesh_x_var] : NULL; DenseSubMatrix<Number> *Kuy = n_y_dofs ? context.elem_subjacobians[var][_mesh_y_var] : NULL; DenseSubMatrix<Number> *Kuz = n_z_dofs ? context.elem_subjacobians[var][_mesh_z_var] : NULL; std::vector<Real> delta_x(n_x_dofs, 0.); std::vector<Real> delta_y(n_y_dofs, 0.); std::vector<Real> delta_z(n_z_dofs, 0.); for (unsigned int i = 0; i != n_x_dofs; ++i) { unsigned int j = context.dof_indices_var[_mesh_x_var][i]; delta_x[i] = libmesh_real(this->current_solution(j)) - libmesh_real(unsteady->old_nonlinear_solution(j)); } for (unsigned int i = 0; i != n_y_dofs; ++i) { unsigned int j = context.dof_indices_var[_mesh_y_var][i]; delta_y[i] = libmesh_real(this->current_solution(j)) - libmesh_real(unsteady->old_nonlinear_solution(j)); } for (unsigned int i = 0; i != n_z_dofs; ++i) { unsigned int j = context.dof_indices_var[_mesh_z_var][i]; delta_z[i] = libmesh_real(this->current_solution(j)) - libmesh_real(unsteady->old_nonlinear_solution(j)); } for (unsigned int qp = 0; qp != n_qpoints; ++qp) { Gradient grad_u = context.interior_gradient(var, qp); RealGradient convection(0.); for (unsigned int i = 0; i != n_x_dofs; ++i) convection(0) += delta_x[i] * psi[i][qp]; for (unsigned int i = 0; i != n_y_dofs; ++i) convection(1) += delta_y[i] * psi[i][qp]; for (unsigned int i = 0; i != n_z_dofs; ++i) convection(2) += delta_z[i] * psi[i][qp]; for (unsigned int i = 0; i != n_u_dofs; ++i) { Number JxWxPhiI = JxW[qp] * phi[i][qp]; Fu(i) += (convection * grad_u) * JxWxPhiI; if (request_jacobian) { Number JxWxPhiI = JxW[qp] * phi[i][qp]; for (unsigned int j = 0; j != n_u_dofs; ++j) Kuu(i,j) += JxWxPhiI * (convection * dphi[j][qp]); Number JxWxPhiIoverDT = JxWxPhiI/this->deltat; Number JxWxPhiIxDUDXoverDT = JxWxPhiIoverDT * grad_u(0); for (unsigned int j = 0; j != n_x_dofs; ++j) (*Kux)(i,j) += JxWxPhiIxDUDXoverDT * psi[j][qp]; Number JxWxPhiIxDUDYoverDT = JxWxPhiIoverDT * grad_u(1); for (unsigned int j = 0; j != n_y_dofs; ++j) (*Kuy)(i,j) += JxWxPhiIxDUDYoverDT * psi[j][qp]; Number JxWxPhiIxDUDZoverDT = JxWxPhiIoverDT * grad_u(2); for (unsigned int j = 0; j != n_z_dofs; ++j) (*Kuz)(i,j) += JxWxPhiIxDUDZoverDT * psi[j][qp]; } } } } #endif // 0 return request_jacobian; } bool FEMPhysics::mass_residual (bool request_jacobian, DiffContext &c) { FEMContext &context = libmesh_cast_ref<FEMContext&>(c); unsigned int n_qpoints = (context.get_element_qrule())->n_points(); for (unsigned int var = 0; var != context.n_vars(); ++var) { if (!this->is_time_evolving(var)) continue; FEBase* elem_fe = NULL; context.get_element_fe( var, elem_fe ); const std::vector<Real> &JxW = elem_fe->get_JxW(); const std::vector<std::vector<Real> > &phi = elem_fe->get_phi(); const unsigned int n_dofs = libmesh_cast_int<unsigned int> (context.get_dof_indices(var).size()); DenseSubVector<Number> &Fu = context.get_elem_residual(var); DenseSubMatrix<Number> &Kuu = context.get_elem_jacobian( var, var ); for (unsigned int qp = 0; qp != n_qpoints; ++qp) { Number u = context.interior_value(var, qp); Number JxWxU = JxW[qp] * u; for (unsigned int i = 0; i != n_dofs; ++i) { Fu(i) += JxWxU * phi[i][qp]; if (request_jacobian && context.elem_solution_derivative) { libmesh_assert_equal_to (context.elem_solution_derivative, 1.0); Number JxWxPhiI = JxW[qp] * phi[i][qp]; Kuu(i,i) += JxWxPhiI * phi[i][qp]; for (unsigned int j = i+1; j < n_dofs; ++j) { Number Kij = JxWxPhiI * phi[j][qp]; Kuu(i,j) += Kij; Kuu(j,i) += Kij; } } } } } return request_jacobian; } } // namespace libMesh
Use accessor API for FEMContext.
Use accessor API for FEMContext.
C++
lgpl-2.1
Mbewu/libmesh,Mbewu/libmesh,Mbewu/libmesh,Mbewu/libmesh,Mbewu/libmesh,Mbewu/libmesh,Mbewu/libmesh,Mbewu/libmesh,Mbewu/libmesh
7216540843d8919da305792d4f4bfbf509c17e61
fast_akaze/akaze/akaze.cpp
fast_akaze/akaze/akaze.cpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2008, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ /* OpenCV wrapper of reference implementation of [1] Fast Explicit Diffusion for Accelerated Features in Nonlinear Scale Spaces. Pablo F. Alcantarilla, J. Nuevo and Adrien Bartoli. In British Machine Vision Conference (BMVC), Bristol, UK, September 2013 http://www.robesafe.com/personal/pablo.alcantarilla/papers/Alcantarilla13bmvc.pdf @author Eugene Khvedchenya <[email protected]> */ #include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include "../features2d_akaze2.hpp" /* Define AKAZE2; use it instead of <opencv2/features2d.hpp> */ #include "AKAZEFeatures.h" #include <iostream> namespace cv { using namespace std; class AKAZE_Impl2 : public AKAZE2 { public: AKAZE_Impl2(int _descriptor_type, int _descriptor_size, int _descriptor_channels, float _threshold, int _octaves, int _sublevels, int _diffusivity) : descriptor(_descriptor_type) , descriptor_channels(_descriptor_channels) , descriptor_size(_descriptor_size) , threshold(_threshold) , octaves(_octaves) , sublevels(_sublevels) , diffusivity(_diffusivity) { } virtual ~AKAZE_Impl2() { } void setDescriptorType(int dtype) { descriptor = dtype; } int getDescriptorType() const { return descriptor; } void setDescriptorSize(int dsize) { descriptor_size = dsize; } int getDescriptorSize() const { return descriptor_size; } void setDescriptorChannels(int dch) { descriptor_channels = dch; } int getDescriptorChannels() const { return descriptor_channels; } void setThreshold(double threshold_) { threshold = (float)threshold_; } double getThreshold() const { return threshold; } void setNOctaves(int octaves_) { octaves = octaves_; } int getNOctaves() const { return octaves; } void setNOctaveLayers(int octaveLayers_) { sublevels = octaveLayers_; } int getNOctaveLayers() const { return sublevels; } void setDiffusivity(int diff_) { diffusivity = diff_; } int getDiffusivity() const { return diffusivity; } // returns the descriptor size in bytes int descriptorSize() const { switch (descriptor) { case DESCRIPTOR_KAZE: case DESCRIPTOR_KAZE_UPRIGHT: return 64; case DESCRIPTOR_MLDB: case DESCRIPTOR_MLDB_UPRIGHT: // We use the full length binary descriptor -> 486 bits if (descriptor_size == 0) { int t = (6 + 36 + 120) * descriptor_channels; return (int)ceil(t / 8.); } else { // We use the random bit selection length binary descriptor return (int)ceil(descriptor_size / 8.); } default: return -1; } } // returns the descriptor type int descriptorType() const { switch (descriptor) { case DESCRIPTOR_KAZE: case DESCRIPTOR_KAZE_UPRIGHT: return CV_32F; case DESCRIPTOR_MLDB: case DESCRIPTOR_MLDB_UPRIGHT: return CV_8U; default: return -1; } } // returns the default norm type int defaultNorm() const { switch (descriptor) { case DESCRIPTOR_KAZE: case DESCRIPTOR_KAZE_UPRIGHT: return NORM_L2; case DESCRIPTOR_MLDB: case DESCRIPTOR_MLDB_UPRIGHT: return NORM_HAMMING; default: return -1; } } void detectAndCompute(InputArray image, InputArray mask, std::vector<KeyPoint>& keypoints, OutputArray descriptors, bool useProvidedKeypoints) { Mat img = image.getMat(); if (img.type() != CV_8UC1) cvtColor(image, img, COLOR_BGR2GRAY); Mat img1_32; if ( img.depth() == CV_32F ) img1_32 = img; else if ( img.depth() == CV_8U ) img.convertTo(img1_32, CV_32F, 1.0 / 255.0, 0); else if ( img.depth() == CV_16U ) img.convertTo(img1_32, CV_32F, 1.0 / 65535.0, 0); CV_Assert( ! img1_32.empty() ); AKAZEOptionsV2 options; options.descriptor = descriptor; options.descriptor_channels = descriptor_channels; options.descriptor_size = descriptor_size; options.img_width = img.cols; options.img_height = img.rows; options.dthreshold = threshold; options.omax = octaves; options.nsublevels = sublevels; options.diffusivity = diffusivity; AKAZEFeaturesV2 impl(options); impl.Create_Nonlinear_Scale_Space(img1_32); if (!useProvidedKeypoints) { impl.Feature_Detection(keypoints); } if (!mask.empty()) { KeyPointsFilter::runByPixelsMask(keypoints, mask.getMat()); } if( descriptors.needed() ) { Mat& desc = descriptors.getMatRef(); impl.Compute_Descriptors(keypoints, desc); CV_Assert((!desc.rows || desc.cols == descriptorSize())); CV_Assert((!desc.rows || (desc.type() == descriptorType()))); } } void write(FileStorage& fs) const { fs << "descriptor" << descriptor; fs << "descriptor_channels" << descriptor_channels; fs << "descriptor_size" << descriptor_size; fs << "threshold" << threshold; fs << "octaves" << octaves; fs << "sublevels" << sublevels; fs << "diffusivity" << diffusivity; } void read(const FileNode& fn) { descriptor = (int)fn["descriptor"]; descriptor_channels = (int)fn["descriptor_channels"]; descriptor_size = (int)fn["descriptor_size"]; threshold = (float)fn["threshold"]; octaves = (int)fn["octaves"]; sublevels = (int)fn["sublevels"]; diffusivity = (int)fn["diffusivity"]; } int descriptor; int descriptor_channels; int descriptor_size; float threshold; int octaves; int sublevels; int diffusivity; }; Ptr<AKAZE2> AKAZE2::create(int descriptor_type, int descriptor_size, int descriptor_channels, float threshold, int octaves, int sublevels, int diffusivity) { return makePtr<AKAZE_Impl2>(descriptor_type, descriptor_size, descriptor_channels, threshold, octaves, sublevels, diffusivity); } }
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2008, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ /* OpenCV wrapper of reference implementation of [1] Fast Explicit Diffusion for Accelerated Features in Nonlinear Scale Spaces. Pablo F. Alcantarilla, J. Nuevo and Adrien Bartoli. In British Machine Vision Conference (BMVC), Bristol, UK, September 2013 http://www.robesafe.com/personal/pablo.alcantarilla/papers/Alcantarilla13bmvc.pdf @author Eugene Khvedchenya <[email protected]> */ #include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include "../features2d_akaze2.hpp" /* Define AKAZE2; use it instead of <opencv2/features2d.hpp> */ #include "AKAZEFeatures.h" #include <iostream> namespace cv { using namespace std; class AKAZE_Impl2 : public AKAZE2 { public: AKAZE_Impl2(int _descriptor_type, int _descriptor_size, int _descriptor_channels, float _threshold, int _octaves, int _sublevels, int _diffusivity) : descriptor(_descriptor_type) , descriptor_channels(_descriptor_channels) , descriptor_size(_descriptor_size) , threshold(_threshold) , octaves(_octaves) , sublevels(_sublevels) , diffusivity(_diffusivity) { cout << "AKAZE_Impl2 constructor called" << endl; } virtual ~AKAZE_Impl2() { } void setDescriptorType(int dtype) { descriptor = dtype; } int getDescriptorType() const { return descriptor; } void setDescriptorSize(int dsize) { descriptor_size = dsize; } int getDescriptorSize() const { return descriptor_size; } void setDescriptorChannels(int dch) { descriptor_channels = dch; } int getDescriptorChannels() const { return descriptor_channels; } void setThreshold(double threshold_) { threshold = (float)threshold_; } double getThreshold() const { return threshold; } void setNOctaves(int octaves_) { octaves = octaves_; } int getNOctaves() const { return octaves; } void setNOctaveLayers(int octaveLayers_) { sublevels = octaveLayers_; } int getNOctaveLayers() const { return sublevels; } void setDiffusivity(int diff_) { diffusivity = diff_; } int getDiffusivity() const { return diffusivity; } // returns the descriptor size in bytes int descriptorSize() const { switch (descriptor) { case DESCRIPTOR_KAZE: case DESCRIPTOR_KAZE_UPRIGHT: return 64; case DESCRIPTOR_MLDB: case DESCRIPTOR_MLDB_UPRIGHT: // We use the full length binary descriptor -> 486 bits if (descriptor_size == 0) { int t = (6 + 36 + 120) * descriptor_channels; return (int)ceil(t / 8.); } else { // We use the random bit selection length binary descriptor return (int)ceil(descriptor_size / 8.); } default: return -1; } } // returns the descriptor type int descriptorType() const { switch (descriptor) { case DESCRIPTOR_KAZE: case DESCRIPTOR_KAZE_UPRIGHT: return CV_32F; case DESCRIPTOR_MLDB: case DESCRIPTOR_MLDB_UPRIGHT: return CV_8U; default: return -1; } } // returns the default norm type int defaultNorm() const { switch (descriptor) { case DESCRIPTOR_KAZE: case DESCRIPTOR_KAZE_UPRIGHT: return NORM_L2; case DESCRIPTOR_MLDB: case DESCRIPTOR_MLDB_UPRIGHT: return NORM_HAMMING; default: return -1; } } void detectAndCompute(InputArray image, InputArray mask, std::vector<KeyPoint>& keypoints, OutputArray descriptors, bool useProvidedKeypoints) { Mat img = image.getMat(); if (img.type() != CV_8UC1) cvtColor(image, img, COLOR_BGR2GRAY); Mat img1_32; if ( img.depth() == CV_32F ) img1_32 = img; else if ( img.depth() == CV_8U ) img.convertTo(img1_32, CV_32F, 1.0 / 255.0, 0); else if ( img.depth() == CV_16U ) img.convertTo(img1_32, CV_32F, 1.0 / 65535.0, 0); CV_Assert( ! img1_32.empty() ); AKAZEOptionsV2 options; options.descriptor = descriptor; options.descriptor_channels = descriptor_channels; options.descriptor_size = descriptor_size; options.img_width = img.cols; options.img_height = img.rows; options.dthreshold = threshold; options.omax = octaves; options.nsublevels = sublevels; options.diffusivity = diffusivity; AKAZEFeaturesV2 impl(options); impl.Create_Nonlinear_Scale_Space(img1_32); if (!useProvidedKeypoints) { impl.Feature_Detection(keypoints); } if (!mask.empty()) { KeyPointsFilter::runByPixelsMask(keypoints, mask.getMat()); } if( descriptors.needed() ) { Mat& desc = descriptors.getMatRef(); impl.Compute_Descriptors(keypoints, desc); CV_Assert((!desc.rows || desc.cols == descriptorSize())); CV_Assert((!desc.rows || (desc.type() == descriptorType()))); } } void write(FileStorage& fs) const { fs << "descriptor" << descriptor; fs << "descriptor_channels" << descriptor_channels; fs << "descriptor_size" << descriptor_size; fs << "threshold" << threshold; fs << "octaves" << octaves; fs << "sublevels" << sublevels; fs << "diffusivity" << diffusivity; } void read(const FileNode& fn) { descriptor = (int)fn["descriptor"]; descriptor_channels = (int)fn["descriptor_channels"]; descriptor_size = (int)fn["descriptor_size"]; threshold = (float)fn["threshold"]; octaves = (int)fn["octaves"]; sublevels = (int)fn["sublevels"]; diffusivity = (int)fn["diffusivity"]; } int descriptor; int descriptor_channels; int descriptor_size; float threshold; int octaves; int sublevels; int diffusivity; }; Ptr<AKAZE2> AKAZE2::create(int descriptor_type, int descriptor_size, int descriptor_channels, float threshold, int octaves, int sublevels, int diffusivity) { return makePtr<AKAZE_Impl2>(descriptor_type, descriptor_size, descriptor_channels, threshold, octaves, sublevels, diffusivity); } }
Add a debug message in AKAZE_Impl2::AKAZE_Impl2
Add a debug message in AKAZE_Impl2::AKAZE_Impl2 The message confirms AKAZE2 is really called.
C++
bsd-3-clause
h2suzuki/fast_akaze,h2suzuki/fast_akaze
9e4adbdaf7f590125181eb2e7cde6235118fcd35
test/multithread.cc
test/multithread.cc
#include <mcx/memcached.h> #include <muduo/base/Atomic.h> #include <muduo/base/Logging.h> #include <muduo/base/Thread.h> #include <muduo/base/CountDownLatch.h> #include <muduo/net/EventLoop.h> #include <boost/bind.hpp> #include <stdio.h> using namespace mcx; using namespace muduo; using namespace muduo::net; EventLoop* g_loop = NULL; Memcached* g_mc = NULL; struct Stat { AtomicInt32 requesting; AtomicInt32 done_ok; AtomicInt32 not_found; AtomicInt32 done_failed; void print() { LOG_INFO << " requesting=" << requesting.get() << " done_ok=" << done_ok.get() << " not_found=" << not_found.get() << " done_failed=" << done_failed.get(); } }; Stat g_stat; void onGetDone(const std::string& key, const GetResult& result, int id) { LOG_TRACE << "onGetDone: id=" << id << " key=" << key << " value=[" << result.value() << "] status=[" << result.status().toString() << "]"; //if (key == "abc") { // assert(result.value() == "value-of-abc"); //} if (result.status().ok() || result.status().isNotFound()) { g_stat.done_ok.increment(); if (result.status().isNotFound()) { g_stat.not_found.increment(); } } else { g_stat.done_failed.increment(); LOG_ERROR << "onGetDone: id=" << id << " key=" << key << " value=[" << result.value() << "] status=[" << result.status().toString() << "]"; } } void onMultiGetDone(const MultiGetResult& result, int id) { MultiGetResult::const_iterator it (result.begin()); MultiGetResult::const_iterator ite(result.end()); for (; it != ite; ++it) { LOG_TRACE << __func__ << ": id=" << id << " key=" << it->first << " value=[" << it->second.value() << "]" << " status=[" << it->second.status().toString() << "]"; if (it->second.status().ok()) { assert(it->second.value() == it->first); } else { LOG_ERROR << "onMultiGetDone: id=" << id << " key=" << it->first << " status=[" << it->second.status().toString() << "]"; } } } void onStoreDone(const std::string& key, const Status& status, int id) { LOG_TRACE << "onStoreDone: id=" << id << " key=" << key << " status=[" << status.toString() << "]"; if (status.ok() || status.isNotFound()) { g_stat.done_ok.increment(); } else { LOG_ERROR << "onStoreDone: id=" << id << " key=" << key << " status=[" << status.toString() << "]"; } } void onRemoveDone(const std::string& key, const Status& status, int id) { LOG_INFO << "onRemoveDone: id=" << id << " key=" << key << " status=[" << status.toString() << "]"; } void request(CountDownLatch* latch) { EventLoop loop; g_loop = &loop; Memcached m("10.108.72.141", 11511); m.initialize(&loop); m.setTimeout(1000); g_mc = &m; latch->countDown(); loop.loop(); LOG_INFO << "exiting ..."; g_mc = NULL; g_loop = NULL; } std::string toString(int i) { char buf[12] = {}; snprintf(buf, sizeof(buf), "%d", i); return buf; } int main(int argc, char* argv[]) { int batch_count = 5;(void)batch_count; CountDownLatch latch(1); Thread thread(boost::bind(&request, &latch), "mc-request-th"); thread.start(); latch.wait(); sleep(1); g_loop->runEvery(1.0, boost::bind(&Stat::print, &g_stat)); Memcached* m = g_mc; std::vector<std::string> keys; for (int i = 0; ; ) { char buf[12] = {}; snprintf(buf, sizeof(buf), "%d", i); //m->store(buf, buf, boost::bind(&onStoreDone, _1, _2, i++)); //i++; //keys.clear(); // m->store(toString(i), toString(i), boost::bind(&onStoreDone, _1, _2, i)); //for (int j = 0; j < batch_count; ++j) { // if (i - j >= 0) { // keys.push_back(toString(i-j)); // } //} //m->mget(keys, boost::bind(&onMultiGetDone, _1, i++)); m->get(toString(i), boost::bind(&onGetDone, _1, _2, i)); i++; g_stat.requesting.increment(); if (g_stat.requesting.get() > g_stat.done_ok.get() + g_stat.done_failed.get() + 30000) { usleep(10); } } LOG_INFO << "do request ..."; sleep(10); LOG_INFO << "exiting ..."; return 0; }
#include <mcx/memcached.h> #include <muduo/base/Atomic.h> #include <muduo/base/Logging.h> #include <muduo/base/Thread.h> #include <muduo/base/CountDownLatch.h> #include <muduo/net/EventLoop.h> #include <boost/bind.hpp> #include <stdio.h> using namespace mcx; using namespace muduo; using namespace muduo::net; EventLoop* g_loop = NULL; Memcached* g_mc = NULL; struct Stat { AtomicInt32 requesting; AtomicInt32 done_ok; AtomicInt32 not_found; AtomicInt32 done_failed; void print() { LOG_INFO << " requesting=" << requesting.get() << " done_ok=" << done_ok.get() << " not_found=" << not_found.get() << " done_failed=" << done_failed.get(); } }; static Stat g_stat; void onGetDone(const std::string& key, const GetResult& result, int id) { LOG_TRACE << "onGetDone: id=" << id << " key=" << key << " value=[" << result.value() << "] status=[" << result.status().toString() << "]"; //if (key == "abc") { // assert(result.value() == "value-of-abc"); //} if (result.status().ok() || result.status().isNotFound()) { g_stat.done_ok.increment(); if (result.status().isNotFound()) { g_stat.not_found.increment(); } } else { g_stat.done_failed.increment(); LOG_ERROR << "onGetDone: id=" << id << " key=" << key << " value=[" << result.value() << "] status=[" << result.status().toString() << "]"; } } void onMultiGetDone(const MultiGetResult& result, int id) { MultiGetResult::const_iterator it (result.begin()); MultiGetResult::const_iterator ite(result.end()); for (; it != ite; ++it) { LOG_TRACE << __func__ << ": id=" << id << " key=" << it->first << " value=[" << it->second.value() << "]" << " status=[" << it->second.status().toString() << "]"; if (it->second.status().ok()) { assert(it->second.value() == it->first); } else { LOG_ERROR << "onMultiGetDone: id=" << id << " key=" << it->first << " status=[" << it->second.status().toString() << "]"; } } } void onStoreDone(const std::string& key, const Status& status, int id) { LOG_TRACE << "onStoreDone: id=" << id << " key=" << key << " status=[" << status.toString() << "]"; if (status.ok() || status.isNotFound()) { g_stat.done_ok.increment(); } else { LOG_ERROR << "onStoreDone: id=" << id << " key=" << key << " status=[" << status.toString() << "]"; } } void onRemoveDone(const std::string& key, const Status& status, int id) { LOG_INFO << "onRemoveDone: id=" << id << " key=" << key << " status=[" << status.toString() << "]"; } void request(CountDownLatch* latch) { EventLoop loop; g_loop = &loop; Memcached m("10.108.72.141", 11511); m.initialize(&loop); m.setTimeout(1000); g_mc = &m; latch->countDown(); loop.loop(); LOG_INFO << "exiting ..."; g_mc = NULL; g_loop = NULL; } std::string toString(int i) { char buf[12] = {}; snprintf(buf, sizeof(buf), "%d", i); return buf; } int main(int argc, char* argv[]) { bool test_get = true; bool test_store = true; bool test_mget = false; //TODO getopt int batch_count = 5;(void)batch_count; CountDownLatch latch(1); Thread thread(boost::bind(&request, &latch), "mc-request-th"); thread.start(); latch.wait(); sleep(1); g_loop->runEvery(1.0, boost::bind(&Stat::print, &g_stat)); Memcached* m = g_mc; std::vector<std::string> keys; for (int i = 0; ; ) { std::string index = toString(i); if (test_store) { m->store(index, index, boost::bind(&onStoreDone, _1, _2, i)); } if (test_mget) { keys.clear(); for (int j = 0; j < batch_count; ++j) { if (i - j >= 0) { keys.push_back(toString(i-j)); } } } m->mget(keys, boost::bind(&onMultiGetDone, _1, i++)); if (test_get) { m->get(index, boost::bind(&onGetDone, _1, _2, i)); } i++; g_stat.requesting.increment(); if (g_stat.requesting.get() > g_stat.done_ok.get() + g_stat.done_failed.get() + 30000) { usleep(10); } } LOG_INFO << "do request ..."; sleep(10); LOG_INFO << "exiting ..."; return 0; }
Add test_get test_store test_mget flags
Add test_get test_store test_mget flags
C++
bsd-3-clause
zieckey/mcx,zieckey/mcx,zieckey/mcx
94e4b671f3859745f39bfdd9bb36a7cec32c67d0
include/chaiscript/dispatchkit/dispatchkit.hpp
include/chaiscript/dispatchkit/dispatchkit.hpp
// This file is distributed under the BSD License. // See "license.txt" for details. // Copyright 2009, Jonathan Turner ([email protected]) // and Jason Turner ([email protected]) // http://www.chaiscript.com #ifndef __dispatchkit_hpp__ #define __dispatchkit_hpp__ #include <typeinfo> #include <string> #include <map> #include <set> #include <boost/shared_ptr.hpp> #include <boost/lexical_cast.hpp> #include <stdexcept> #include <vector> #include <iostream> #include <deque> #include "boxed_value.hpp" #include "type_info.hpp" #include "proxy_functions.hpp" #include "proxy_constructors.hpp" namespace chaiscript { class Module { public: Module &add(const Type_Info &ti, const std::string &name) { m_typeinfos.push_back(std::make_pair(ti, name)); return *this; } Module &add(const Proxy_Function &f, const std::string &name) { m_funcs.push_back(std::make_pair(f, name)); return *this; } template<typename T> void apply(T &t) const { apply(m_typeinfos.begin(), m_typeinfos.end(), t); apply(m_funcs.begin(), m_funcs.end(), t); } private: std::vector<std::pair<Type_Info, std::string> > m_typeinfos; std::vector<std::pair<Proxy_Function, std::string> > m_funcs; template<typename T, typename InItr> void apply(InItr begin, InItr end, T &t) const { while (begin != end) { t.add(begin->first, begin->second); ++begin; } } }; typedef boost::shared_ptr<Module> ModulePtr; /** * A Proxy_Function implementation that is able to take * a vector of Proxy_Functions and perform a dispatch on them. It is * used specifically in the case of dealing with Function object variables */ class Dispatch_Function : public Proxy_Function_Base { public: Dispatch_Function(const std::vector<std::pair<std::string, Proxy_Function > > &t_funcs) : m_funcs(t_funcs) { } virtual bool operator==(const Proxy_Function_Base &) const { return false; } virtual ~Dispatch_Function() {} virtual Boxed_Value operator()(const std::vector<Boxed_Value> &params) { return dispatch(m_funcs.begin(), m_funcs.end(), params); } virtual std::vector<Type_Info> get_param_types() const { return std::vector<Type_Info>(); } virtual int get_arity() const { return -1; } virtual bool call_match(const std::vector<Boxed_Value> &vals) const { typedef std::vector<std::pair<std::string, Proxy_Function > > function_vec; function_vec::const_iterator begin = m_funcs.begin(); function_vec::const_iterator end = m_funcs.end(); while (begin != end) { if (begin->second->call_match(vals)) { return true; } else { ++begin; } } return false; } virtual std::string annotation() const { return ""; } private: std::vector<std::pair<std::string, Proxy_Function > > m_funcs; }; /** * Exception thrown in the case that a multi method dispatch fails * because no matching function was found * at runtime due to either an arity_error, a guard_error or a bad_boxed_cast * exception */ struct reserved_word_error : std::runtime_error { reserved_word_error(const std::string &word) throw() : std::runtime_error("Reserved word not allowed in object name: " + word) { } virtual ~reserved_word_error() throw() {} }; /** * Main class for the dispatchkit. Handles management * of the object stack, functions and registered types. */ class Dispatch_Engine { public: typedef std::map<std::string, chaiscript::Type_Info> Type_Name_Map; typedef std::map<std::string, Boxed_Value> Scope; typedef boost::shared_ptr<std::pair<std::map<std::string, Boxed_Value>, std::deque<Scope> > > Stack; Dispatch_Engine() : m_scopes(new Stack::element_type()), m_place_holder(boost::shared_ptr<Placeholder_Object>(new Placeholder_Object())) { m_scopes->second.push_back(Scope()); } /** * Add a new named Proxy_Function to the system */ bool add(const Proxy_Function &f, const std::string &name) { validate_object_name(name); return add_function(f, name); } /** * Add a module's worth of registrations to the system */ void add(const ModulePtr &m) { m->apply(*this); } /** * Set the value of an object, by name. If the object * is not available in the current scope it is created */ void add(const Boxed_Value &obj, const std::string &name) { validate_object_name(name); for (int i = m_scopes->second.size()-1; i >= 0; --i) { std::map<std::string, Boxed_Value>::const_iterator itr = (m_scopes->second)[i].find(name); if (itr != (m_scopes->second)[i].end()) { m_scopes->first.erase(name); (m_scopes->second)[i][name] = Boxed_Value(obj); return; } } add_object(name, obj); } /** * Adds a named object to the current scope */ void add_object(const std::string &name, const Boxed_Value &obj) { m_scopes->first.erase(name); validate_object_name(name); m_scopes->second.back()[name] = Boxed_Value(obj); } /** * Adds a new scope to the stack */ void new_scope() { m_scopes->second.push_back(Scope()); } /** * Pops the current scope from the stack */ void pop_scope() { if (m_scopes->second.size() > 1) { Scope &scope(m_scopes->second.back()); for (Scope::const_iterator itr = scope.begin(); itr != scope.end(); ++itr) { m_scopes->first.erase(itr->first); } m_scopes->second.pop_back(); } else { throw std::range_error("Unable to pop global stack"); } } /** * Returns the current stack */ Stack get_stack() { return m_scopes; } /** * Swaps out the stack with a new stack * \returns the old stack * \param[in] s The new stack */ Stack set_stack(const Stack &s) { Stack old = m_scopes; m_scopes = s; return old; } Stack new_stack() { Stack s(new Stack::element_type()); s->second.push_back(Scope()); return s; } /** * Searches the current stack for an object of the given name * includes a special overload for the _ place holder object to * ensure that it is always in scope. */ Boxed_Value get_object(const std::string &name) const { if (name == "_") { return m_place_holder; } std::map<std::string, Boxed_Value> &cache = m_scopes->first; std::map<std::string, Boxed_Value>::const_iterator itr = cache.find(name); if (itr != cache.end()) { return itr->second; } for (int i = m_scopes->second.size()-1; i >= 0; --i) { std::map<std::string, Boxed_Value>::const_iterator itr = (m_scopes->second)[i].find(name); if (itr != (m_scopes->second)[i].end()) { cache[name] = itr->second; return itr->second; } } std::vector<std::pair<std::string, std::multimap<std::string, Proxy_Function >::mapped_type> > funcs = get_function(name); if (funcs.empty()) { throw std::range_error("Object not known: " + name); } else { Boxed_Value f(Proxy_Function(new Dispatch_Function(funcs))); cache[name] = f; return f; } } /** * Registers a new named type */ void add(const Type_Info &ti, const std::string &name) { m_types.insert(std::make_pair(name, ti)); } /** * Returns the type info for a named type */ Type_Info get_type(const std::string &name) const { Type_Name_Map::const_iterator itr = m_types.find(name); if (itr != m_types.end()) { return itr->second; } throw std::range_error("Type Not Known"); } /** * Returns the registered name of a known type_info object * compares the "bare_type_info" for the broadest possible * match */ std::string get_type_name(const Type_Info &ti) const { for (Type_Name_Map::const_iterator itr = m_types.begin(); itr != m_types.end(); ++itr) { if (itr->second.m_bare_type_info == ti.m_bare_type_info) { return itr->first; } } return ti.m_bare_type_info->name(); } /** * Return all registered types */ std::vector<std::pair<std::string, Type_Info> > get_types() const { return std::vector<std::pair<std::string, Type_Info> >(m_types.begin(), m_types.end()); } /** * Return a function by name */ std::vector<std::pair<std::string, std::multimap<std::string, Proxy_Function >::mapped_type> > get_function(const std::string &t_name) const { std::pair<std::multimap<std::string, Proxy_Function >::const_iterator, std::multimap<std::string, Proxy_Function >::const_iterator> range = m_functions.equal_range(t_name); return std::vector<std::pair<std::string, std::multimap<std::string, Proxy_Function >::mapped_type> >(range.first, range.second); } /** * Return true if a function exists */ bool function_exists(const std::string &name) const { return m_functions.find(name) != m_functions.end(); } /** * Get a vector of all registered functions */ std::vector<std::pair<std::string, Proxy_Function > > get_functions() const { return std::vector<std::pair<std::string, Proxy_Function > >(m_functions.begin(), m_functions.end()); } void add_reserved_word(const std::string &name) { m_reserved_words.insert(name); } Boxed_Value call_function(const std::string &t_name, const std::vector<Boxed_Value> &params) { std::pair<std::multimap<std::string, Proxy_Function >::const_iterator, std::multimap<std::string, Proxy_Function >::const_iterator> range = m_functions.equal_range(t_name); return dispatch(range.first, range.second, params); } private: /** * Throw a reserved_word exception if the name is not allowed */ void validate_object_name(const std::string &name) { if (m_reserved_words.find(name) != m_reserved_words.end()) { throw reserved_word_error(name); } } /** * Implementation detail for adding a function. Returns * true if the function was added, false if a function with the * same signature and name already exists. */ bool add_function(const Proxy_Function &f, const std::string &t_name) { std::pair<std::multimap<std::string, Proxy_Function >::const_iterator, std::multimap<std::string, Proxy_Function >::const_iterator> range = m_functions.equal_range(t_name); while (range.first != range.second) { if ((*f) == *(range.first->second)) { return false; } ++range.first; } m_functions.insert(std::make_pair(t_name, f)); return true; } Stack m_scopes; std::multimap<std::string, Proxy_Function > m_functions; Type_Name_Map m_types; Boxed_Value m_place_holder; std::set<std::string> m_reserved_words; }; /** * Dump object info to stdout */ void dump_object(Boxed_Value o, const Dispatch_Engine &e) { Type_Info ti = o.get_type_info(); std::cout << (ti.m_is_const?"const ":"") << e.get_type_name(ti) << std::endl; } /** * Dump type info to stdout */ void dump_type(const Type_Info &type, const Dispatch_Engine &e) { std::cout << (type.m_is_const?"const ":"") << e.get_type_name(type); } /** * Dump function to stdout */ void dump_function(const std::pair<const std::string, Proxy_Function > &f, const Dispatch_Engine &e) { std::vector<Type_Info> params = f.second->get_param_types(); std::string annotation = f.second->annotation(); if (annotation.size() > 0) { std::cout << annotation; } dump_type(params.front(), e); std::cout << " " << f.first << "("; for (std::vector<Type_Info>::const_iterator itr = params.begin() + 1; itr != params.end(); ) { dump_type(*itr, e); ++itr; if (itr != params.end()) { std::cout << ", "; } } std::cout << ") " << std::endl; } /** * Dump all system info to stdout */ void dump_system(const Dispatch_Engine &s) { std::cout << "Registered Types: " << std::endl; std::vector<std::pair<std::string, Type_Info> > types = s.get_types(); for (std::vector<std::pair<std::string, Type_Info> >::const_iterator itr = types.begin(); itr != types.end(); ++itr) { std::cout << itr->first << ": "; std::cout << itr->second.m_bare_type_info->name(); std::cout << std::endl; } std::cout << std::endl; std::vector<std::pair<std::string, Proxy_Function > > funcs = s.get_functions(); std::cout << "Functions: " << std::endl; for (std::vector<std::pair<std::string, Proxy_Function > >::const_iterator itr = funcs.begin(); itr != funcs.end(); ++itr) { dump_function(*itr, s); } std::cout << std::endl; } /** * return true if the Boxed_Value matches the registered type by name */ bool is_type(const Dispatch_Engine &e, const std::string &user_typename, Boxed_Value r) { try { return e.get_type(user_typename) == r.get_type_info(); } catch (const std::range_error &) { return false; } } std::string type_name(const Dispatch_Engine &e, Boxed_Value obj) { return e.get_type_name(obj.get_type_info()); } } #endif
// This file is distributed under the BSD License. // See "license.txt" for details. // Copyright 2009, Jonathan Turner ([email protected]) // and Jason Turner ([email protected]) // http://www.chaiscript.com #ifndef __dispatchkit_hpp__ #define __dispatchkit_hpp__ #include <typeinfo> #include <string> #include <map> #include <set> #include <boost/shared_ptr.hpp> #include <boost/lexical_cast.hpp> #include <stdexcept> #include <vector> #include <iostream> #include <deque> #include "boxed_value.hpp" #include "type_info.hpp" #include "proxy_functions.hpp" #include "proxy_constructors.hpp" namespace chaiscript { class Module { public: Module &add(const Type_Info &ti, const std::string &name) { m_typeinfos.push_back(std::make_pair(ti, name)); return *this; } Module &add(const Proxy_Function &f, const std::string &name) { m_funcs.push_back(std::make_pair(f, name)); return *this; } template<typename T> void apply(T &t) const { apply(m_typeinfos.begin(), m_typeinfos.end(), t); apply(m_funcs.begin(), m_funcs.end(), t); } private: std::vector<std::pair<Type_Info, std::string> > m_typeinfos; std::vector<std::pair<Proxy_Function, std::string> > m_funcs; template<typename T, typename InItr> void apply(InItr begin, InItr end, T &t) const { while (begin != end) { t.add(begin->first, begin->second); ++begin; } } }; typedef boost::shared_ptr<Module> ModulePtr; /** * A Proxy_Function implementation that is able to take * a vector of Proxy_Functions and perform a dispatch on them. It is * used specifically in the case of dealing with Function object variables */ class Dispatch_Function : public Proxy_Function_Base { public: Dispatch_Function(const std::vector<std::pair<std::string, Proxy_Function > > &t_funcs) : m_funcs(t_funcs) { } virtual bool operator==(const Proxy_Function_Base &) const { return false; } virtual ~Dispatch_Function() {} virtual Boxed_Value operator()(const std::vector<Boxed_Value> &params) { return dispatch(m_funcs.begin(), m_funcs.end(), params); } virtual std::vector<Type_Info> get_param_types() const { return std::vector<Type_Info>(); } virtual int get_arity() const { return -1; } virtual bool call_match(const std::vector<Boxed_Value> &vals) const { typedef std::vector<std::pair<std::string, Proxy_Function > > function_vec; function_vec::const_iterator begin = m_funcs.begin(); function_vec::const_iterator end = m_funcs.end(); while (begin != end) { if (begin->second->call_match(vals)) { return true; } else { ++begin; } } return false; } virtual std::string annotation() const { return ""; } private: std::vector<std::pair<std::string, Proxy_Function > > m_funcs; }; /** * Exception thrown in the case that a multi method dispatch fails * because no matching function was found * at runtime due to either an arity_error, a guard_error or a bad_boxed_cast * exception */ struct reserved_word_error : std::runtime_error { reserved_word_error(const std::string &word) throw() : std::runtime_error("Reserved word not allowed in object name: " + word) { } virtual ~reserved_word_error() throw() {} }; /** * Main class for the dispatchkit. Handles management * of the object stack, functions and registered types. */ class Dispatch_Engine { public: typedef std::map<std::string, chaiscript::Type_Info> Type_Name_Map; typedef std::map<std::string, Boxed_Value> Scope; typedef boost::shared_ptr<std::pair<std::map<std::string, Boxed_Value>, std::deque<Scope> > > Stack; Dispatch_Engine() : m_scopes(new Stack::element_type()), m_place_holder(boost::shared_ptr<Placeholder_Object>(new Placeholder_Object())) { m_scopes->second.push_back(Scope()); } /** * Add a new named Proxy_Function to the system */ bool add(const Proxy_Function &f, const std::string &name) { validate_object_name(name); m_scopes->first.erase(name); return add_function(f, name); } /** * Add a module's worth of registrations to the system */ void add(const ModulePtr &m) { m->apply(*this); } /** * Set the value of an object, by name. If the object * is not available in the current scope it is created */ void add(const Boxed_Value &obj, const std::string &name) { validate_object_name(name); for (int i = m_scopes->second.size()-1; i >= 0; --i) { std::map<std::string, Boxed_Value>::const_iterator itr = (m_scopes->second)[i].find(name); if (itr != (m_scopes->second)[i].end()) { m_scopes->first.erase(name); (m_scopes->second)[i][name] = Boxed_Value(obj); return; } } add_object(name, obj); } /** * Adds a named object to the current scope */ void add_object(const std::string &name, const Boxed_Value &obj) { m_scopes->first.erase(name); validate_object_name(name); m_scopes->second.back()[name] = Boxed_Value(obj); } /** * Adds a new scope to the stack */ void new_scope() { m_scopes->second.push_back(Scope()); } /** * Pops the current scope from the stack */ void pop_scope() { if (m_scopes->second.size() > 1) { Scope &scope(m_scopes->second.back()); for (Scope::const_iterator itr = scope.begin(); itr != scope.end(); ++itr) { m_scopes->first.erase(itr->first); } m_scopes->second.pop_back(); } else { throw std::range_error("Unable to pop global stack"); } } /** * Returns the current stack */ Stack get_stack() { return m_scopes; } /** * Swaps out the stack with a new stack * \returns the old stack * \param[in] s The new stack */ Stack set_stack(const Stack &s) { Stack old = m_scopes; m_scopes = s; return old; } Stack new_stack() { Stack s(new Stack::element_type()); s->second.push_back(Scope()); return s; } /** * Searches the current stack for an object of the given name * includes a special overload for the _ place holder object to * ensure that it is always in scope. */ Boxed_Value get_object(const std::string &name) const { if (name == "_") { return m_place_holder; } std::map<std::string, Boxed_Value> &cache = m_scopes->first; std::map<std::string, Boxed_Value>::const_iterator itr = cache.find(name); if (itr != cache.end()) { return itr->second; } for (int i = m_scopes->second.size()-1; i >= 0; --i) { std::map<std::string, Boxed_Value>::const_iterator itr = (m_scopes->second)[i].find(name); if (itr != (m_scopes->second)[i].end()) { cache[name] = itr->second; return itr->second; } } std::vector<std::pair<std::string, std::multimap<std::string, Proxy_Function >::mapped_type> > funcs = get_function(name); if (funcs.empty()) { throw std::range_error("Object not known: " + name); } else { Boxed_Value f(Proxy_Function(new Dispatch_Function(funcs))); cache[name] = f; return f; } } /** * Registers a new named type */ void add(const Type_Info &ti, const std::string &name) { m_types.insert(std::make_pair(name, ti)); } /** * Returns the type info for a named type */ Type_Info get_type(const std::string &name) const { Type_Name_Map::const_iterator itr = m_types.find(name); if (itr != m_types.end()) { return itr->second; } throw std::range_error("Type Not Known"); } /** * Returns the registered name of a known type_info object * compares the "bare_type_info" for the broadest possible * match */ std::string get_type_name(const Type_Info &ti) const { for (Type_Name_Map::const_iterator itr = m_types.begin(); itr != m_types.end(); ++itr) { if (itr->second.m_bare_type_info == ti.m_bare_type_info) { return itr->first; } } return ti.m_bare_type_info->name(); } /** * Return all registered types */ std::vector<std::pair<std::string, Type_Info> > get_types() const { return std::vector<std::pair<std::string, Type_Info> >(m_types.begin(), m_types.end()); } /** * Return a function by name */ std::vector<std::pair<std::string, std::multimap<std::string, Proxy_Function >::mapped_type> > get_function(const std::string &t_name) const { std::pair<std::multimap<std::string, Proxy_Function >::const_iterator, std::multimap<std::string, Proxy_Function >::const_iterator> range = m_functions.equal_range(t_name); return std::vector<std::pair<std::string, std::multimap<std::string, Proxy_Function >::mapped_type> >(range.first, range.second); } /** * Return true if a function exists */ bool function_exists(const std::string &name) const { return m_functions.find(name) != m_functions.end(); } /** * Get a vector of all registered functions */ std::vector<std::pair<std::string, Proxy_Function > > get_functions() const { return std::vector<std::pair<std::string, Proxy_Function > >(m_functions.begin(), m_functions.end()); } void add_reserved_word(const std::string &name) { m_reserved_words.insert(name); } Boxed_Value call_function(const std::string &t_name, const std::vector<Boxed_Value> &params) { std::pair<std::multimap<std::string, Proxy_Function >::const_iterator, std::multimap<std::string, Proxy_Function >::const_iterator> range = m_functions.equal_range(t_name); return dispatch(range.first, range.second, params); } private: /** * Throw a reserved_word exception if the name is not allowed */ void validate_object_name(const std::string &name) { if (m_reserved_words.find(name) != m_reserved_words.end()) { throw reserved_word_error(name); } } /** * Implementation detail for adding a function. Returns * true if the function was added, false if a function with the * same signature and name already exists. */ bool add_function(const Proxy_Function &f, const std::string &t_name) { std::pair<std::multimap<std::string, Proxy_Function >::const_iterator, std::multimap<std::string, Proxy_Function >::const_iterator> range = m_functions.equal_range(t_name); while (range.first != range.second) { if ((*f) == *(range.first->second)) { return false; } ++range.first; } m_functions.insert(std::make_pair(t_name, f)); return true; } Stack m_scopes; std::multimap<std::string, Proxy_Function > m_functions; Type_Name_Map m_types; Boxed_Value m_place_holder; std::set<std::string> m_reserved_words; }; /** * Dump object info to stdout */ void dump_object(Boxed_Value o, const Dispatch_Engine &e) { Type_Info ti = o.get_type_info(); std::cout << (ti.m_is_const?"const ":"") << e.get_type_name(ti) << std::endl; } /** * Dump type info to stdout */ void dump_type(const Type_Info &type, const Dispatch_Engine &e) { std::cout << (type.m_is_const?"const ":"") << e.get_type_name(type); } /** * Dump function to stdout */ void dump_function(const std::pair<const std::string, Proxy_Function > &f, const Dispatch_Engine &e) { std::vector<Type_Info> params = f.second->get_param_types(); std::string annotation = f.second->annotation(); if (annotation.size() > 0) { std::cout << annotation; } dump_type(params.front(), e); std::cout << " " << f.first << "("; for (std::vector<Type_Info>::const_iterator itr = params.begin() + 1; itr != params.end(); ) { dump_type(*itr, e); ++itr; if (itr != params.end()) { std::cout << ", "; } } std::cout << ") " << std::endl; } /** * Dump all system info to stdout */ void dump_system(const Dispatch_Engine &s) { std::cout << "Registered Types: " << std::endl; std::vector<std::pair<std::string, Type_Info> > types = s.get_types(); for (std::vector<std::pair<std::string, Type_Info> >::const_iterator itr = types.begin(); itr != types.end(); ++itr) { std::cout << itr->first << ": "; std::cout << itr->second.m_bare_type_info->name(); std::cout << std::endl; } std::cout << std::endl; std::vector<std::pair<std::string, Proxy_Function > > funcs = s.get_functions(); std::cout << "Functions: " << std::endl; for (std::vector<std::pair<std::string, Proxy_Function > >::const_iterator itr = funcs.begin(); itr != funcs.end(); ++itr) { dump_function(*itr, s); } std::cout << std::endl; } /** * return true if the Boxed_Value matches the registered type by name */ bool is_type(const Dispatch_Engine &e, const std::string &user_typename, Boxed_Value r) { try { return e.get_type(user_typename) == r.get_type_info(); } catch (const std::range_error &) { return false; } } std::string type_name(const Dispatch_Engine &e, Boxed_Value obj) { return e.get_type_name(obj.get_type_info()); } } #endif
Make sure to invalidate the cache when a new function name is added
Make sure to invalidate the cache when a new function name is added
C++
bsd-3-clause
bradparks/ChaiScript__cplusplus_scripting_language,bradparks/ChaiScript__cplusplus_scripting_language,bradparks/ChaiScript__cplusplus_scripting_language,kamilzubair/ChaiScript,lefticus/ChaiScript,kamilzubair/ChaiScript,kamilzubair/ChaiScript,lefticus/ChaiScript,lefticus/ChaiScript
b658853124f85d0350c294dd37f2d0d574d50e97
src/bridge.cpp
src/bridge.cpp
/* * D-Bus AT-SPI, Qt Adaptor * * Copyright 2008-2011 Nokia Corporation and/or its subsidiary(-ies). * Copyright 2008, 2009 Codethink Ltd. * * 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, see <http://www.gnu.org/licenses/>. */ #include "bridge.h" #include "adaptor.h" #include "accessible.h" #include "application.h" #include "cache.h" #include "constant_mappings.h" #include "dbusconnection.h" #include "struct_marshallers.h" #include "generated/dec_proxy.h" #include "generated/event_adaptor.h" #include <QEvent> #include <QKeyEvent> #define QSPI_DEC_NAME "/org/a11y/atspi/Registry" #define QSPI_DEC_OBJECT_PATH "/org/a11y/atspi/registry/deviceeventcontroller" QSpiAccessibleBridge* QSpiAccessibleBridge::self = 0; QSpiAccessibleBridge::QSpiAccessibleBridge() : cache(0), initialized(false) { Q_ASSERT(self == 0); self = this; dbusConnection = new DBusConnection(); if (!dBusConnection().isConnected()) { qWarning() << "Could not connect to dbus."; } qSpiInitializeStructTypes(); qSpiInitializeConstantMappings(); /* Create the cache of accessible objects */ cache = new QSpiDBusCache(dBusConnection(), this); dec = new DeviceEventControllerProxy(this); bool reg = dBusConnection().registerObject(QSPI_DEC_OBJECT_PATH, this, QDBusConnection::ExportAdaptors); qDebug() << "Registered DEC: " << reg; QAccessibleInterface* i = QAccessible::queryAccessibleInterface(qApp); QSpiAdaptor* applicationAccessible = new QSpiApplication(dbusConnection->connection(), i); adaptors.insert(QString(QSPI_OBJECT_PATH_ROOT), applicationAccessible); connect(applicationAccessible, SIGNAL(windowActivated(QObject*)), this, SLOT(windowActivated(QObject*))); } void QSpiAccessibleBridge::windowActivated(QObject* window) { QSpiAdaptor* a = spiBridge->objectToAccessible(window); QSpiAccessible* acc = static_cast<QSpiAccessible*>(a); acc->windowActivated(); } QSpiAccessibleBridge::~QSpiAccessibleBridge() { delete dbusConnection; } // Qt currently doesn't delete plugins. QDBusConnection QSpiAccessibleBridge::dBusConnection() const { return dbusConnection->connection(); } void QSpiAccessibleBridge::setRootObject(QAccessibleInterface *interface) { initialized = true; // the interface we get will be for the QApplication object. // we already cache it in the constructor. Q_ASSERT(interface->object() == qApp); } QSpiObjectReference QSpiAccessibleBridge::getRootReference() const { return QSpiObjectReference(dBusConnection(), QDBusObjectPath(QSPI_OBJECT_PATH_ROOT)); } void QSpiAccessibleBridge::notifyAccessibilityUpdate(int reason, QAccessibleInterface *interface, int index) { Q_ASSERT(interface && interface->isValid()); if (!initialized) return; // this gets deleted, so create one if we don't have it yet QSpiAdaptor* accessible = interfaceToAccessible(interface, index, false); //Q_ASSERT(accessible->associatedInterface()->object() == interface->object()); if (accessible->associatedInterface()->object() == interface->object()) { qWarning() << "Creating accessible with different object than the original interface!"; } switch (reason) { case QAccessible::ObjectCreated: qDebug() << "created" << interface->object(); // make sure we don't duplicate this. seems to work for qml loaders. notifyAboutCreation(accessible); break; case QAccessible::ObjectShow: qDebug() << "show" << interface->object(); break; case QAccessible::Focus: { static QSpiAccessible *lastFocused = 0; if (lastFocused) { QDBusVariant data; data.setVariant(QVariant::fromValue(lastFocused->getReference())); emit lastFocused->StateChanged("focused", 0, 0, data, getRootReference()); } lastFocused = qobject_cast<QSpiAccessible*>(accessible); } } // qDebug() << "QSpiAccessibleBridge::notifyAccessibilityUpdate" << QString::number(reason, 16) // << " obj: " << interface->object() // << (interface->isValid() ? interface->object()->objectName() : " invalid interface!") // << accessible->interface; accessible->accessibleEvent((QAccessible::Event)reason); } QSpiAdaptor* QSpiAccessibleBridge::objectToAccessible(QObject *object) { Q_ASSERT(object); QString path = QSpiAccessible::pathForObject(object); if (adaptors.contains(path)) return adaptors.value(path); QAccessibleInterface* interface = QAccessible::queryAccessibleInterface(object); if (!interface) { qWarning() << "Create accessible for object which cannot create an accessible interface." << object; return 0; } return interfaceToAccessible(interface, 0, true); } QSpiAdaptor* QSpiAccessibleBridge::interfaceToAccessible(QAccessibleInterface* interface, int index, bool takeOwnershipOfInterface) { Q_ASSERT(interface && interface->isValid()); QString path = QSpiAccessible::pathForInterface(interface, index); // optimize? if (adaptors.contains(path)) { if (adaptors.value(path)->associatedInterface()->object() != interface->object()) { QSpiAdaptor* originalAdaptor = adaptors.take(path); qDebug() << "not the same: " << originalAdaptor->associatedInterface()->object() << interface->object() << " at path: " << path; // ItemViews create qobjects for rows/cells later as needed. // Those may initially be 0. // remove object // add new interface cache->emitRemoveAccessible(originalAdaptor->getReference()); delete originalAdaptor; // Q_ASSERT(0); } else { return adaptors.value(path); } } // FIXME if this works, we can save code below... // QAccessibleInterface* copy(QAccessibleInterface(*interface)); // if we cannot keep the interface around (notifyAccessibility will delete interfaces) // we need to ask for one that we can keep if (!takeOwnershipOfInterface) { QAccessibleInterface* ownedInterface = QAccessible::queryAccessibleInterface(interface->object()); if (!ownedInterface) { QAccessibleInterface* parentInterface; interface->navigate(QAccessible::Ancestor, 1, &parentInterface); Q_ASSERT(parentInterface); int index = parentInterface->indexOfChild(interface); parentInterface->navigate(QAccessible::Child, index, &ownedInterface); delete parentInterface; } Q_ASSERT(ownedInterface); Q_ASSERT(interface->object() == ownedInterface->object()); interface = ownedInterface; } QSpiAdaptor *accessible = new QSpiAccessible(interface, index); // put ourself in the list of accessibles adaptors.insert(path, accessible); notifyAboutCreation(accessible); return accessible; } void QSpiAccessibleBridge::notifyAboutCreation(QSpiAdaptor* accessible) { // say hello to d-bus cache->emitAddAccessible(accessible->getCacheItem()); // notify about the new child of our parent int childCount = 0; QSpiAdaptor* parentAdaptor = 0; if (accessible->childIndex() == 0) { QAccessibleInterface *parent = 0; accessible->associatedInterface()->navigate(QAccessible::Ancestor, 1, &parent); if (parent) { parentAdaptor = interfaceToAccessible(parent, 0, true); childCount = parent->childCount(); } } else { parentAdaptor = interfaceToAccessible(accessible->associatedInterface(), 0, true); childCount = accessible->associatedInterface()->childCount(); } if (parentAdaptor) { QSpiObjectReference r = accessible->getReference(); QDBusVariant data; data.setVariant(QVariant::fromValue(r)); parentAdaptor->signalChildrenChanged("add", childCount, 0, data); } } void QSpiAccessibleBridge::objectDestroyed(QObject* o) { QString path = QSpiAccessible::pathForObject(o); adaptors.remove(path); } void QSpiAccessibleBridge::removeAdaptor(QSpiAdaptor *adaptor) { adaptors.remove(adaptor->getReference().path.path()); }
/* * D-Bus AT-SPI, Qt Adaptor * * Copyright 2008-2011 Nokia Corporation and/or its subsidiary(-ies). * Copyright 2008, 2009 Codethink Ltd. * * 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, see <http://www.gnu.org/licenses/>. */ #include "bridge.h" #include "adaptor.h" #include "accessible.h" #include "application.h" #include "cache.h" #include "constant_mappings.h" #include "dbusconnection.h" #include "struct_marshallers.h" #include "generated/dec_proxy.h" #include "generated/event_adaptor.h" #include <QEvent> #include <QKeyEvent> #define QSPI_DEC_NAME "/org/a11y/atspi/Registry" #define QSPI_DEC_OBJECT_PATH "/org/a11y/atspi/registry/deviceeventcontroller" QSpiAccessibleBridge* QSpiAccessibleBridge::self = 0; QSpiAccessibleBridge::QSpiAccessibleBridge() : cache(0), initialized(false) { Q_ASSERT(self == 0); self = this; dbusConnection = new DBusConnection(); if (!dBusConnection().isConnected()) { qWarning() << "Could not connect to dbus."; } qSpiInitializeStructTypes(); qSpiInitializeConstantMappings(); /* Create the cache of accessible objects */ cache = new QSpiDBusCache(dBusConnection(), this); dec = new DeviceEventControllerProxy(this); bool reg = dBusConnection().registerObject(QSPI_DEC_OBJECT_PATH, this, QDBusConnection::ExportAdaptors); qDebug() << "Registered DEC: " << reg; QAccessibleInterface* i = QAccessible::queryAccessibleInterface(qApp); QSpiAdaptor* applicationAccessible = new QSpiApplication(dbusConnection->connection(), i); adaptors.insert(QString(QSPI_OBJECT_PATH_ROOT), applicationAccessible); connect(applicationAccessible, SIGNAL(windowActivated(QObject*)), this, SLOT(windowActivated(QObject*))); } void QSpiAccessibleBridge::windowActivated(QObject* window) { QSpiAdaptor* a = spiBridge->objectToAccessible(window); QSpiAccessible* acc = static_cast<QSpiAccessible*>(a); acc->windowActivated(); } QSpiAccessibleBridge::~QSpiAccessibleBridge() { delete dbusConnection; } // Qt currently doesn't delete plugins. QDBusConnection QSpiAccessibleBridge::dBusConnection() const { return dbusConnection->connection(); } void QSpiAccessibleBridge::setRootObject(QAccessibleInterface *interface) { initialized = true; // the interface we get will be for the QApplication object. // we already cache it in the constructor. Q_ASSERT(interface->object() == qApp); } QSpiObjectReference QSpiAccessibleBridge::getRootReference() const { return QSpiObjectReference(dBusConnection(), QDBusObjectPath(QSPI_OBJECT_PATH_ROOT)); } void QSpiAccessibleBridge::notifyAccessibilityUpdate(int reason, QAccessibleInterface *interface, int index) { Q_ASSERT(interface && interface->isValid()); if (!initialized) return; // this gets deleted, so create one if we don't have it yet QSpiAdaptor* accessible = interfaceToAccessible(interface, index, false); //Q_ASSERT(accessible->associatedInterface()->object() == interface->object()); if (accessible->associatedInterface()->object() == interface->object()) { qWarning() << "Creating accessible with different object than the original interface!"; } switch (reason) { case QAccessible::ObjectCreated: qDebug() << "created" << interface->object(); // make sure we don't duplicate this. seems to work for qml loaders. notifyAboutCreation(accessible); break; case QAccessible::ObjectShow: qDebug() << "show" << interface->object(); break; case QAccessible::Focus: { static QSpiAccessible *lastFocused = 0; if (lastFocused) { QDBusVariant data; data.setVariant(QVariant::fromValue(lastFocused->getReference())); emit lastFocused->StateChanged("focused", 0, 0, data, getRootReference()); } lastFocused = qobject_cast<QSpiAccessible*>(accessible); } } // qDebug() << "QSpiAccessibleBridge::notifyAccessibilityUpdate" << QString::number(reason, 16) // << " obj: " << interface->object() // << (interface->isValid() ? interface->object()->objectName() : " invalid interface!") // << accessible->interface; accessible->accessibleEvent((QAccessible::Event)reason); } QSpiAdaptor* QSpiAccessibleBridge::objectToAccessible(QObject *object) { Q_ASSERT(object); QString path = QSpiAccessible::pathForObject(object); if (adaptors.contains(path)) return adaptors.value(path); QAccessibleInterface* interface = QAccessible::queryAccessibleInterface(object); if (!interface) { qWarning() << "Create accessible for object which cannot create an accessible interface." << object; return 0; } return interfaceToAccessible(interface, 0, true); } QSpiAdaptor* QSpiAccessibleBridge::interfaceToAccessible(QAccessibleInterface* interface, int index, bool takeOwnershipOfInterface) { Q_ASSERT(interface && interface->isValid()); if (interface->object() == qApp) { return adaptors.value(QSPI_OBJECT_PATH_ROOT); } QString path = QSpiAccessible::pathForInterface(interface, index); // optimize? if (adaptors.contains(path)) { if (adaptors.value(path)->associatedInterface()->object() != interface->object()) { QSpiAdaptor* originalAdaptor = adaptors.take(path); qDebug() << "not the same: " << originalAdaptor->associatedInterface()->object() << interface->object() << " at path: " << path; // ItemViews create qobjects for rows/cells later as needed. // Those may initially be 0. // remove object // add new interface cache->emitRemoveAccessible(originalAdaptor->getReference()); delete originalAdaptor; // Q_ASSERT(0); } else { return adaptors.value(path); } } // FIXME if this works, we can save code below... // QAccessibleInterface* copy(QAccessibleInterface(*interface)); // if we cannot keep the interface around (notifyAccessibility will delete interfaces) // we need to ask for one that we can keep if (!takeOwnershipOfInterface) { QAccessibleInterface* ownedInterface = QAccessible::queryAccessibleInterface(interface->object()); if (!ownedInterface) { QAccessibleInterface* parentInterface; interface->navigate(QAccessible::Ancestor, 1, &parentInterface); Q_ASSERT(parentInterface); int index = parentInterface->indexOfChild(interface); parentInterface->navigate(QAccessible::Child, index, &ownedInterface); delete parentInterface; } Q_ASSERT(ownedInterface); Q_ASSERT(interface->object() == ownedInterface->object()); interface = ownedInterface; } QSpiAdaptor *accessible = new QSpiAccessible(interface, index); // put ourself in the list of accessibles adaptors.insert(path, accessible); notifyAboutCreation(accessible); return accessible; } void QSpiAccessibleBridge::notifyAboutCreation(QSpiAdaptor* accessible) { // say hello to d-bus cache->emitAddAccessible(accessible->getCacheItem()); // notify about the new child of our parent int childCount = 0; QSpiAdaptor* parentAdaptor = 0; if (accessible->childIndex() == 0) { QAccessibleInterface *parent = 0; accessible->associatedInterface()->navigate(QAccessible::Ancestor, 1, &parent); if (parent) { parentAdaptor = interfaceToAccessible(parent, 0, true); childCount = parent->childCount(); } } else { parentAdaptor = interfaceToAccessible(accessible->associatedInterface(), 0, true); childCount = accessible->associatedInterface()->childCount(); } if (parentAdaptor) { QSpiObjectReference r = accessible->getReference(); QDBusVariant data; data.setVariant(QVariant::fromValue(r)); parentAdaptor->signalChildrenChanged("add", childCount, 0, data); } } void QSpiAccessibleBridge::objectDestroyed(QObject* o) { QString path = QSpiAccessible::pathForObject(o); adaptors.remove(path); } void QSpiAccessibleBridge::removeAdaptor(QSpiAdaptor *adaptor) { adaptors.remove(adaptor->getReference().path.path()); }
Return the correct root object.
Return the correct root object.
C++
lgpl-2.1
KDE/qtatspi,KDE/qtatspi,KDE/qtatspi
faf91b678d053cdbd20b41779b4e61193d6f033a
src/buffer.cpp
src/buffer.cpp
/** * @author See Contributors.txt for code contributors and overview of BadgerDB. * * @section LICENSE * Copyright (c) 2012 Database Group, Computer Sciences Department, University of Wisconsin-Madison. */ /** * @author Databases Project 3 (Buffer Manager): Charles Conley, Josh Cordell, Bryce Greiber */ #include <memory> #include <iostream> #include "buffer.h" #include "exceptions/buffer_exceeded_exception.h" #include "exceptions/page_not_pinned_exception.h" #include "exceptions/page_pinned_exception.h" #include "exceptions/bad_buffer_exception.h" #include "exceptions/hash_not_found_exception.h" namespace badgerdb { //---------------------------------------- // Constructor of the class BufMgr //---------------------------------------- BufMgr::BufMgr(std::uint32_t bufs) : numBufs(bufs) { bufDescTable = new BufDesc[bufs]; for (FrameId i = 0; i < bufs; i++) { bufDescTable[i].frameNo = i; bufDescTable[i].valid = false; } bufPool = new Page[bufs]; int htsize = ((((int) (bufs * 1.2))*2)/2)+1; hashTable = new BufHashTbl (htsize); // allocate the buffer hash table clockHand = bufs - 1; } /** * Destructor for BufMgr. For all dirty pages, flush the file associated. This will write the most up to date content to the disk. * Deallocate all data structures from the constructor */ BufMgr::~BufMgr() { ///flush files for(int j = 0; j > numBufs; j++){ if(bufDescTable[j].dirty){ flushFile(bufDescTable[j].file); } } ///Now delete hashTable; delete[] bufPool; delete[] bufDescTable; } /** * Move the "hand" pointer along the buffer clock. use the remainder to stay in bounds. * Input: Address to frame (for reference return) * Output: frame as a referenced value. */ void BufMgr::advanceClock() { clockHand = (clockHand + 1) % numBufs; } ///Implement the clock algorithm ///add a pinned count, if pinned count = numBufs, then throw exception ///run through each buf and check for validity following diagram. void BufMgr::allocBuf(FrameId & frame) { ///track if a frame has been found bool frameFound = false; std::uint32_t pinnedCount = 0; ///start loop, until frame is found. Only time it will leave loop is if frame is found ///or bufferexceededexception occurs while(!frameFound && (pinnedCount < numBufs)){ advanceClock(); ///found a buffer frame that can be used, exit loop if(!bufDescTable[clockHand].valid){ frameFound = true; break; } ///check the refbit, if it is false then frame is found and the entry in the hashtable needs to be removed else if(bufDescTable[clockHand].refbit){ bufDescTable[clockHand].refbit = false; continue; }else if(bufDescTable[clockHand].pinCnt > 0) { pinnedCount++; continue; }else{ if(bufDescTable[clockHand].dirty){ bufDescTable[clockHand].file->writePage(bufPool[clockHand]); } frameFound = true; ///remove the hashtable entry hashTable->remove(bufDescTable[clockHand].file, bufDescTable[clockHand].pageNo); } } ///All pages are pinned, otherwise found free frame if(pinnedCount == numBufs){ throw BufferExceededException(); } else { frame = clockHand; bufDescTable[clockHand].Clear(); } } /** * Check to see if the page is in the buffer, if so then return the pointer to the page * If the page is not located in the buffer then add it to the buffer and return the page pointer. * Input: file pointer, pageNo, address of page(for reference return) * Outpu: Returns the address of a page for reading */ void BufMgr::readPage(File* file, const PageId pageNo, Page*& page) { FrameId frameNo; /// check whether page is already in buffer pool with lookup(), throws HashNotFoundExc. try { hashTable->lookup(file, pageNo, frameNo); /// no exception thrown, in hash table /// set appropriate refbit bufDescTable[frameNo].refbit = 1; /// increment pin count bufDescTable[frameNo].pinCnt++; /// return pointer to frame containing the page via page parameter page = &bufPool[frameNo]; } catch (const HashNotFoundException& e) { /// not in buffer pool, need to add to buffer /// allocate buffer frame allocBuf(frameNo); /// add to bufPool bufPool[frameNo] = file->readPage(pageNo); /// set the description table bufDescTable[frameNo].Set(file, pageNo); /// insert page into hash table hashTable->insert(file, pageNo, frameNo); /// return the page pointer page = &bufPool[frameNo]; } } /** * updates the descTable to correlate with a page that is no longer pinned in the buffer * Throws exception if the page is not pinned. Does not throw anything if the page is not in the buffer * Input: file pointer, pageNo, boolean dirty * Outpu: N/A */ void BufMgr::unPinPage(File* file, const PageId pageNo, const bool dirty) { FrameId frameNo = 0; ///check hashtable for page try { hashTable->lookup(file, pageNo, frameNo); ///check if pin cnt is already set to 0. throw appropriate error if (bufDescTable[frameNo].pinCnt == 0){ throw PageNotPinnedException(file->filename(), pageNo, frameNo); } ///set dirty bit if input bit is true if(dirty){ bufDescTable[frameNo].dirty = dirty; } ///decrement pin count bufDescTable[frameNo].pinCnt--; } catch(const HashNotFoundException& e){ } } /** * create a page within a file when one does not already exist * Add to buffer since it is newly created and this is a form of access * Input: file pointer, pageNo, address of page(for reference return) * Output: returns a page address that is now allocated */ void BufMgr::allocPage(File* file, PageId &pageNo, Page*& page) { FrameId frameNo; ///allocate page and get buffer frame pool Page filePage = file->allocatePage(); allocBuf(frameNo); pageNo = filePage.page_number(); ///insert into hashtable then set frame hashTable->insert(file, pageNo, frameNo); bufDescTable[frameNo].Set(file, pageNo); bufPool[frameNo] = filePage; ///passs correct pointer page = &bufPool[frameNo]; } /** * Clears files from the buffer table. The important part of this function is to write to disk the changed pages. * If the page is not valid or if the page is pinned then this will cause exceptions to be thrown. * Input: file pointer * Outpu: N/A */ void BufMgr::flushFile(const File* file) { for(uint32_t i = 0; i < numBufs; i++){ //check to see if the entry is from this file if(file == bufDescTable[i].file){ //before proceeding, check valid bit and pinned if(!bufDescTable[i].valid){ throw BadBufferException(i, bufDescTable[i].dirty, bufDescTable[i].valid, bufDescTable[i].refbit); }else if(bufDescTable[i].pinCnt > 0) { throw PagePinnedException(file->filename(), bufDescTable[i].pageNo, i); } ///Check for dirty page which will need to be written to disk if (bufDescTable[i].dirty){ bufDescTable[i].file->writePage(bufPool[i]); bufDescTable[i].dirty = false; } ///remove the page and clear the buffer hashTable->remove(file, bufDescTable[i].pageNo); bufDescTable[i].Clear(); } } } /** * Dispose Page deletes the page from the hashtable if it is present but also deletes the page in the file. * If it is not in hashtable then ignores the table and only removes the page from the file. * Input: file pointer, pageNo * Outpu: N/A */ void BufMgr::disposePage(File* file, const PageId PageNo) { FrameId frameNo = 0; /// if allocated in buffer pool, free it try { hashTable->lookup(file, PageNo, frameNo); /// remove page from hash table bufDescTable[frameNo].Clear(); hashTable->remove(file, PageNo); } catch (const HashNotFoundException& e) { /// not in hash table, shouldn't need to do anything } file->deletePage(PageNo); } void BufMgr::printSelf(void) { BufDesc* tmpbuf; int validFrames = 0; for (std::uint32_t i = 0; i < numBufs; i++) { tmpbuf = &(bufDescTable[i]); std::cout << "FrameNo:" << i << " "; tmpbuf->Print(); if (tmpbuf->valid == true) validFrames++; } std::cout << "Total Number of Valid Frames:" << validFrames << "\n"; } }
/** * @author See Contributors.txt for code contributors and overview of BadgerDB. * * @section LICENSE * Copyright (c) 2012 Database Group, Computer Sciences Department, University of Wisconsin-Madison. */ /** * @author Databases Project 3 (Buffer Manager): Charles Conley, Josh Cordell, Bryce Greiber */ #include <memory> #include <iostream> #include "buffer.h" #include "exceptions/buffer_exceeded_exception.h" #include "exceptions/page_not_pinned_exception.h" #include "exceptions/page_pinned_exception.h" #include "exceptions/bad_buffer_exception.h" #include "exceptions/hash_not_found_exception.h" namespace badgerdb { //---------------------------------------- // Constructor of the class BufMgr //---------------------------------------- BufMgr::BufMgr(std::uint32_t bufs) : numBufs(bufs) { bufDescTable = new BufDesc[bufs]; for (FrameId i = 0; i < bufs; i++) { bufDescTable[i].frameNo = i; bufDescTable[i].valid = false; } bufPool = new Page[bufs]; int htsize = ((((int) (bufs * 1.2))*2)/2)+1; hashTable = new BufHashTbl (htsize); // allocate the buffer hash table clockHand = bufs - 1; } /** * Destructor for BufMgr. For all dirty pages, flush the file associated. This will write the most up to date content to the disk. * Deallocate all data structures from the constructor */ BufMgr::~BufMgr() { ///flush files for(uint32_t j = 0; j > numBufs; j++){ if(bufDescTable[j].dirty){ flushFile(bufDescTable[j].file); } } ///Now delete hashTable; delete[] bufPool; delete[] bufDescTable; } /** * Move the "hand" pointer along the buffer clock. use the remainder to stay in bounds. * Input: Address to frame (for reference return) * Output: frame as a referenced value. */ void BufMgr::advanceClock() { clockHand = (clockHand + 1) % numBufs; } ///Implement the clock algorithm ///add a pinned count, if pinned count = numBufs, then throw exception ///run through each buf and check for validity following diagram. void BufMgr::allocBuf(FrameId & frame) { ///track if a frame has been found bool frameFound = false; std::uint32_t pinnedCount = 0; ///start loop, until frame is found. Only time it will leave loop is if frame is found ///or bufferexceededexception occurs while(!frameFound && (pinnedCount < numBufs)){ advanceClock(); ///found a buffer frame that can be used, exit loop if(!bufDescTable[clockHand].valid){ frameFound = true; break; } ///check the refbit, if it is false then frame is found and the entry in the hashtable needs to be removed else if(bufDescTable[clockHand].refbit){ bufDescTable[clockHand].refbit = false; continue; }else if(bufDescTable[clockHand].pinCnt > 0) { pinnedCount++; continue; }else{ if(bufDescTable[clockHand].dirty){ bufDescTable[clockHand].file->writePage(bufPool[clockHand]); } frameFound = true; ///remove the hashtable entry hashTable->remove(bufDescTable[clockHand].file, bufDescTable[clockHand].pageNo); } } ///All pages are pinned, otherwise found free frame if(pinnedCount == numBufs){ throw BufferExceededException(); } else { frame = clockHand; bufDescTable[clockHand].Clear(); } } /** * Check to see if the page is in the buffer, if so then return the pointer to the page * If the page is not located in the buffer then add it to the buffer and return the page pointer. * Input: file pointer, pageNo, address of page(for reference return) * Outpu: Returns the address of a page for reading */ void BufMgr::readPage(File* file, const PageId pageNo, Page*& page) { FrameId frameNo; /// check whether page is already in buffer pool with lookup(), throws HashNotFoundExc. try { hashTable->lookup(file, pageNo, frameNo); /// no exception thrown, in hash table /// set appropriate refbit bufDescTable[frameNo].refbit = 1; /// increment pin count bufDescTable[frameNo].pinCnt++; /// return pointer to frame containing the page via page parameter page = &bufPool[frameNo]; } catch (const HashNotFoundException& e) { /// not in buffer pool, need to add to buffer /// allocate buffer frame allocBuf(frameNo); /// add to bufPool bufPool[frameNo] = file->readPage(pageNo); /// set the description table bufDescTable[frameNo].Set(file, pageNo); /// insert page into hash table hashTable->insert(file, pageNo, frameNo); /// return the page pointer page = &bufPool[frameNo]; } } /** * updates the descTable to correlate with a page that is no longer pinned in the buffer * Throws exception if the page is not pinned. Does not throw anything if the page is not in the buffer * Input: file pointer, pageNo, boolean dirty * Outpu: N/A */ void BufMgr::unPinPage(File* file, const PageId pageNo, const bool dirty) { FrameId frameNo = 0; ///check hashtable for page try { hashTable->lookup(file, pageNo, frameNo); ///check if pin cnt is already set to 0. throw appropriate error if (bufDescTable[frameNo].pinCnt == 0){ throw PageNotPinnedException(file->filename(), pageNo, frameNo); } ///set dirty bit if input bit is true if(dirty){ bufDescTable[frameNo].dirty = dirty; } ///decrement pin count bufDescTable[frameNo].pinCnt--; } catch(const HashNotFoundException& e){ } } /** * create a page within a file when one does not already exist * Add to buffer since it is newly created and this is a form of access * Input: file pointer, pageNo, address of page(for reference return) * Output: returns a page address that is now allocated */ void BufMgr::allocPage(File* file, PageId &pageNo, Page*& page) { FrameId frameNo; ///allocate page and get buffer frame pool Page filePage = file->allocatePage(); allocBuf(frameNo); pageNo = filePage.page_number(); ///insert into hashtable then set frame hashTable->insert(file, pageNo, frameNo); bufDescTable[frameNo].Set(file, pageNo); bufPool[frameNo] = filePage; ///passs correct pointer page = &bufPool[frameNo]; } /** * Clears files from the buffer table. The important part of this function is to write to disk the changed pages. * If the page is not valid or if the page is pinned then this will cause exceptions to be thrown. * Input: file pointer * Outpu: N/A */ void BufMgr::flushFile(const File* file) { for(uint32_t i = 0; i < numBufs; i++){ //check to see if the entry is from this file if(file == bufDescTable[i].file){ //before proceeding, check valid bit and pinned if(!bufDescTable[i].valid){ throw BadBufferException(i, bufDescTable[i].dirty, bufDescTable[i].valid, bufDescTable[i].refbit); }else if(bufDescTable[i].pinCnt > 0) { throw PagePinnedException(file->filename(), bufDescTable[i].pageNo, i); } ///Check for dirty page which will need to be written to disk if (bufDescTable[i].dirty){ bufDescTable[i].file->writePage(bufPool[i]); bufDescTable[i].dirty = false; } ///remove the page and clear the buffer hashTable->remove(file, bufDescTable[i].pageNo); bufDescTable[i].Clear(); } } } /** * Dispose Page deletes the page from the hashtable if it is present but also deletes the page in the file. * If it is not in hashtable then ignores the table and only removes the page from the file. * Input: file pointer, pageNo * Outpu: N/A */ void BufMgr::disposePage(File* file, const PageId PageNo) { FrameId frameNo = 0; /// if allocated in buffer pool, free it try { hashTable->lookup(file, PageNo, frameNo); /// remove page from hash table bufDescTable[frameNo].Clear(); hashTable->remove(file, PageNo); } catch (const HashNotFoundException& e) { /// not in hash table, shouldn't need to do anything } file->deletePage(PageNo); } void BufMgr::printSelf(void) { BufDesc* tmpbuf; int validFrames = 0; for (std::uint32_t i = 0; i < numBufs; i++) { tmpbuf = &(bufDescTable[i]); std::cout << "FrameNo:" << i << " "; tmpbuf->Print(); if (tmpbuf->valid == true) validFrames++; } std::cout << "Total Number of Valid Frames:" << validFrames << "\n"; } }
fix int to uint32_t warning
fix int to uint32_t warning
C++
apache-2.0
CharlesConley/DBProject3
7a53954417b8c3e3ecf0c757b480e1346bb77067
tutorials/math/exampleMultiRoot.C
tutorials/math/exampleMultiRoot.C
/// \file /// \ingroup tutorial_math /// \notebook -nodraw /// Example of using multiroot finder based on GSL algorithm. /// Find the root of Rosenbrock system of equations: /// \f[ /// f1(x,y) = a(1-x) /// \f] /// \f[ /// f2(x,y) = b(y-x^2) /// \f] /// with: /// \f[ /// a = 1, b=10 /// \f] /// /// The MultiRootFinder is based on GSL and it requires the MathMore library /// installed /// /// Usage: /// /// ~~~{.cpp} /// >.x exampleMultiRoot.C() /// ~~~ /// /// or /// /// ~~~{.cpp} /// >.x exampleMultiRoot(algoname,printlevel) /// ~~~ /// /// where algoname is for an algorithm not using the derivatives: /// hybridS (default) , hybrid, dnewton, broyden /// /// \macro_output /// \macro_code /// /// \author Lorenzo Moneta #include "RConfigure.h" #ifdef R__HAS_MATHMORE #include "Math/MultiRootFinder.h" #endif #include "Math/WrappedMultiTF1.h" #include "TF2.h" #include "TError.h" // example of using multi root finder based on GSL // need to use an algorithm not requiring the derivative //like hybrids (default), hybrid, dnewton, broyden using namespace ROOT::Math; void exampleMultiRoot(const char * algo = 0, int printlevel = 1) { #ifndef R__HAS_MATHMORE Error("exampleMultiRoot","libMathMore is not available - cannot run this tutorial"); #else ROOT::Math::MultiRootFinder r(algo); //defining the function // use Rosenbrock functions TF2 * f1 = new TF2("f1","[0]*(1-x)+[1]*y"); TF2 * f2 = new TF2("f2","[0]*(y-x*x)"); f1->SetParameters(1,0); f2->SetParameter(0,10); // wrap the functions ROOT::Math::WrappedMultiTF1 g1(*f1,2); ROOT::Math::WrappedMultiTF1 g2(*f2,2); r.AddFunction(g1); r.AddFunction(g2); r.SetPrintLevel(printlevel); // starting point double x0[2]={-1,-1}; r.Solve(x0); #endif }
/// \file /// \ingroup tutorial_math /// \notebook -nodraw /// Example of using multiroot finder based on GSL algorithm. /// Find the root of Rosenbrock system of equations: /// \f[ /// f1(x,y) = a(1-x) /// \f] /// \f[ /// f2(x,y) = b(y-x^2) /// \f] /// with: /// \f[ /// a = 1, b=10 /// \f] /// /// The MultiRootFinder is based on GSL and it requires the MathMore library /// installed /// /// Usage: /// /// ~~~{.cpp} /// >.x exampleMultiRoot.C() /// ~~~ /// /// or /// /// ~~~{.cpp} /// >.x exampleMultiRoot(algoname,printlevel) /// ~~~ /// /// where algoname is for an algorithm not using the derivatives: /// hybridS (default) , hybrid, dnewton, broyden /// /// \macro_output /// \macro_code /// /// \author Lorenzo Moneta #include "RConfigure.h" #ifdef R__HAS_MATHMORE #include "Math/MultiRootFinder.h" #else #error libMathMore is not available - cannot run this tutorial #endif #include "Math/WrappedMultiTF1.h" #include "TF2.h" #include "TError.h" // example of using multi root finder based on GSL // need to use an algorithm not requiring the derivative //like hybrids (default), hybrid, dnewton, broyden using namespace ROOT::Math; void exampleMultiRoot(const char * algo = 0, int printlevel = 1) { ROOT::Math::MultiRootFinder r(algo); //defining the function // use Rosenbrock functions TF2 * f1 = new TF2("f1","[0]*(1-x)+[1]*y"); TF2 * f2 = new TF2("f2","[0]*(y-x*x)"); f1->SetParameters(1,0); f2->SetParameter(0,10); // wrap the functions ROOT::Math::WrappedMultiTF1 g1(*f1,2); ROOT::Math::WrappedMultiTF1 g2(*f2,2); r.AddFunction(g1); r.AddFunction(g2); r.SetPrintLevel(printlevel); // starting point double x0[2]={-1,-1}; r.Solve(x0); }
Move the preprocessor directives out of the function body.
Move the preprocessor directives out of the function body.
C++
lgpl-2.1
thomaskeck/root,satyarth934/root,olifre/root,satyarth934/root,bbockelm/root,beniz/root,gbitzes/root,zzxuanyuan/root,beniz/root,pspe/root,simonpf/root,buuck/root,karies/root,agarciamontoro/root,gganis/root,bbockelm/root,BerserkerTroll/root,beniz/root,gbitzes/root,bbockelm/root,buuck/root,zzxuanyuan/root,Y--/root,Y--/root,thomaskeck/root,gganis/root,agarciamontoro/root,satyarth934/root,abhinavmoudgil95/root,olifre/root,karies/root,pspe/root,zzxuanyuan/root-compressor-dummy,BerserkerTroll/root,gbitzes/root,satyarth934/root,karies/root,gbitzes/root,root-mirror/root,BerserkerTroll/root,gbitzes/root,pspe/root,buuck/root,beniz/root,buuck/root,mhuwiler/rootauto,abhinavmoudgil95/root,zzxuanyuan/root,Y--/root,agarciamontoro/root,olifre/root,gbitzes/root,georgtroska/root,karies/root,simonpf/root,bbockelm/root,karies/root,olifre/root,gganis/root,pspe/root,zzxuanyuan/root-compressor-dummy,pspe/root,zzxuanyuan/root,mhuwiler/rootauto,buuck/root,Y--/root,georgtroska/root,zzxuanyuan/root,karies/root,olifre/root,abhinavmoudgil95/root,pspe/root,olifre/root,satyarth934/root,zzxuanyuan/root,pspe/root,gbitzes/root,mhuwiler/rootauto,davidlt/root,satyarth934/root,gbitzes/root,thomaskeck/root,satyarth934/root,mhuwiler/rootauto,bbockelm/root,georgtroska/root,Y--/root,georgtroska/root,beniz/root,buuck/root,simonpf/root,gganis/root,gbitzes/root,beniz/root,thomaskeck/root,gganis/root,simonpf/root,davidlt/root,davidlt/root,buuck/root,beniz/root,root-mirror/root,bbockelm/root,beniz/root,mhuwiler/rootauto,bbockelm/root,davidlt/root,BerserkerTroll/root,mhuwiler/rootauto,karies/root,root-mirror/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root-compressor-dummy,simonpf/root,karies/root,mhuwiler/rootauto,georgtroska/root,zzxuanyuan/root-compressor-dummy,abhinavmoudgil95/root,satyarth934/root,olifre/root,agarciamontoro/root,gganis/root,zzxuanyuan/root-compressor-dummy,abhinavmoudgil95/root,BerserkerTroll/root,simonpf/root,BerserkerTroll/root,georgtroska/root,zzxuanyuan/root,georgtroska/root,olifre/root,BerserkerTroll/root,mhuwiler/rootauto,root-mirror/root,mhuwiler/rootauto,buuck/root,beniz/root,root-mirror/root,zzxuanyuan/root,bbockelm/root,zzxuanyuan/root,gganis/root,Y--/root,mhuwiler/rootauto,davidlt/root,buuck/root,buuck/root,davidlt/root,BerserkerTroll/root,zzxuanyuan/root,abhinavmoudgil95/root,BerserkerTroll/root,bbockelm/root,simonpf/root,Y--/root,karies/root,olifre/root,pspe/root,gganis/root,georgtroska/root,agarciamontoro/root,pspe/root,root-mirror/root,abhinavmoudgil95/root,thomaskeck/root,abhinavmoudgil95/root,davidlt/root,buuck/root,root-mirror/root,simonpf/root,simonpf/root,agarciamontoro/root,gganis/root,abhinavmoudgil95/root,gganis/root,simonpf/root,beniz/root,davidlt/root,simonpf/root,satyarth934/root,thomaskeck/root,thomaskeck/root,gbitzes/root,abhinavmoudgil95/root,beniz/root,agarciamontoro/root,thomaskeck/root,BerserkerTroll/root,pspe/root,zzxuanyuan/root-compressor-dummy,davidlt/root,Y--/root,karies/root,gbitzes/root,agarciamontoro/root,root-mirror/root,georgtroska/root,olifre/root,georgtroska/root,davidlt/root,zzxuanyuan/root,georgtroska/root,thomaskeck/root,gganis/root,Y--/root,bbockelm/root,abhinavmoudgil95/root,root-mirror/root,agarciamontoro/root,Y--/root,root-mirror/root,olifre/root,root-mirror/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root,satyarth934/root,zzxuanyuan/root-compressor-dummy,Y--/root,satyarth934/root,agarciamontoro/root,mhuwiler/rootauto,zzxuanyuan/root-compressor-dummy,thomaskeck/root,davidlt/root,pspe/root,zzxuanyuan/root-compressor-dummy,agarciamontoro/root,karies/root,BerserkerTroll/root,bbockelm/root
86a45e1e2d5ef2d166c4ae8e28d07c61352d7729
src/main.cpp
src/main.cpp
#include <iostream> #include "shell.cpp" #include <boost/tokenizer.hpp> #include <vector> using namespace std; using namespace boost; void print_parse(vector<vector<string> > vec) { if(vec.size() == 0) { cout << "Empty vector\n"; cout << endl; return; } for(unsigned i = 0; i < vec.size(); ++i) { for(unsigned j = 0; j < (vec.at(i)).size(); ++j) { cout << (vec.at(i)).at(j) << " "; } cout << endl; } cout << endl; return; } vector<vector<string> > parse(string com) { vector<vector<string> > v; vector<string> v2; char_separator<char> delim(" ", "|&#);"); tokenizer<char_separator<char> >mytok(com, delim); for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); ++it) { v2.push_back(*it); } for(unsigned i = 0; i < v2.size(); ++i) { vector<string> v3; if(v2.at(i) == "|") //check for || command { ++i; if(v2.at(i) == "|") { v3.push_back("||"); } else //exit if || isn't fully implemented { cout << "Invalid Command Line." << endl; exit(1); } } else if(v2.at(i) == "&") //check for && command { ++i; if(v2.at(i) == "&") { v3.push_back("&&"); } else //exit if && isn't fully implemented { cout << "Invalid Command Line." << endl; exit(1); } } else if(v2.at(i) == ";") { v3.push_back(v2.at(i)); } else if(v2.at(i) == "#") { v3.push_back(v2.at(i)); v.push_back(v3); return v; } else //create a command vector without connectors or hashes { while((i < v2.size()) && (v2.at(i) != "&") && (v2.at(i) != "|") && (v2.at(i) != ";") && (v2.at(i) != "#")) { v3.push_back(v2.at(i)); ++i; } i = i - 1; } v.push_back(v3); } return v; } const int ARRAY_MAX = 20; vector<vector<string> > make_com() { string cmd; char hostname[ARRAY_MAX]; char login[ARRAY_MAX]; int result = getlogin_r(login, ARRAY_MAX); if (result) { perror("getlogin"); } else { cout << login; } result = gethostname(hostname, ARRAY_MAX); if (result) { perror("gethostname"); } else { cout << '@' << hostname; } cout << "$ "; getline(cin, cmd); //cout << endl; return parse(cmd); } bool create_tree(vector<vector<string> > v) { Shell_Base* left = 0; string exit = "exit"; if((v.at(0)).at(0) == "exit") { return false; } if((v.at(0)).at(0) == "#") { return true; } for(unsigned i = 0; i < v.size(); ++i) { if(((v.at(i)).at(0) == "&&") || ((v.at(i)).at(0) == "||") || ((v.at(i)).at(0) == ";")) { if(i == 0) { cout << "Error: invalid command.\n"; return false; } if( ((i + 1) < v.size()) && ((v.at(i)).at(0) == "&&")) { Shell_Base* temp = new Command(v.at(i + 1)); Shell_Base * a = new And(left, temp); if(v.at(i + 1).at(0) == exit) { return false; } else if( ((v.at(i + 1)).at(0) == "&&") || ((v.at(i + 1)).at(0) == "||") || ((v.at(i + 1)).at(0) == ";")) { cout << "Error: Consecutive connectors.\n"; return true; } else if((v.at(i + 1)).at(0) == "#") { return true; } a->execute(); } else if( ((i + 1) < v.size()) && ((v.at(i)).at(0) == "||")) { Shell_Base* temp = new Command(v.at(i + 1)); Shell_Base* a = new Or(left, temp); if(v.at(i + 1).at(0) == exit) { return false; } else if( ((v.at(i + 1)).at(0) == "&&") || ((v.at(i + 1)).at(0) == "||") || ((v.at(i + 1)).at(0) == ";")) { cout << "Error: Consecutive connectors.\n"; return true; } else if((v.at(i + 1)).at(0) == "#") { return true; } a->execute(); } else if( ((v.at(i)).at(0) == ";")) { Shell_Base* temp = new Command(v.at(i + 1)); Shell_Base* a = new Semi(left, temp); if(v.at(i + 1).at(0) == exit) { return false; } else if( ((v.at(i + 1)).at(0) == "&&") || ((v.at(i + 1)).at(0) == "||") || ((v.at(i + 1)).at(0) == ";")) { cout << "Error: Consecutive connectors.\n"; return true; } else if((v.at(i + 1)).at(0) == "#") { return true; } a->execute(); } } else if((v.at(i)).at(0) == "#") { return true; } else { Shell_Base* a = new Command(v.at(i)); if (i == 0 && v.at(i).at(0) != exit) {a->execute();} else if (i == 0 && v.at(i).at(0) == exit) { return false; } left = a; if (a->get_executed() == -1) { return false; } } } return true; } void rshell() { bool test = true; do { test = create_tree(make_com()); } while (test); } int main() { // Test case for parse /* vector<string> test_vector; string test_string = "ls assignments | | cd CS100 && iss ; hello"; test_vector = parse(test_string); for (unsigned int i = 0; i < test_vector.size(); i++) { cout << '(' << test_vector.at(i) << ')' << ' '; } cout << endl; */ // Test case for Command Leaf class // DELETE OUTPUT FOR EXECUTE IN Command::execute() // DELETE OUTPUT STATEMENTS OF ELSE BRANCH OF execute() IN EVERY CLASS /* string a = "s"; string b = "-a"; vector<string> v1; v1.push_back(a); v1.push_back(b); Shell_Base * A = new Command(v1); cout << "executing child A:" << endl; A->execute(); cout << endl; string c = "ls"; //string d = "-a"; vector<string> v2; v2.push_back(c); //v2.push_back(d); Shell_Base * B = new Command(v2); cout << "executing child B:" << endl; B->execute(); cout << endl; string e = "s"; string f = "I love Brian Crites."; vector<string> v3; v3.push_back(e); v3.push_back(f); Shell_Base * C = new Command(v3); cout << "executing child C:" << endl; C->execute(); cout << endl; */ // Test case for Or composite class (uses A, B, and C from Leaf class) /* Shell_Base * D = new Or(A,B); cout << "executing A || B:" << endl; D->execute(); cout << endl; Shell_Base * E = new Or(D, C); cout << "executing (A || B) || C:" << endl; E->execute(); cout << endl; */ // Test case for And composite class (uses A, B, and C from Leaf class) /* Shell_Base * F = new And(A,B); cout << "executing A && B:" << endl; F->execute(); cout << endl; Shell_Base * G = new And(F, C); cout << "executing (A && B) && C:" << endl; G->execute(); cout << endl; */ // Test case for Semi composite class (uses A, B, and C from Leaf class) /* Shell_Base * H = new Semi(A,B); cout << "executing A;B:" << endl; H->execute(); cout << endl; Shell_Base * I = new Semi(H, C); cout << "executing (A;B);C:" << endl; I->execute(); cout << endl; */ //print_parse(rshell()); rshell(); return 0; }
#include <iostream> #include "shell.cpp" #include <boost/tokenizer.hpp> #include <vector> using namespace std; using namespace boost; void print_parse(vector<vector<string> > vec) { if(vec.size() == 0) { cout << "Empty vector\n"; cout << endl; return; } for(unsigned i = 0; i < vec.size(); ++i) { for(unsigned j = 0; j < (vec.at(i)).size(); ++j) { cout << (vec.at(i)).at(j) << " "; } cout << endl; } cout << endl; return; } bool check_par(string cmd) { unsigned size = cmd.size(); int open_par = 0; int close_par = 0; for(unsigned i = 0; i < size; ++i) { if(cmd.at(i) == '(') { ++open_par; } else if(cmd.at(i) == ')') { ++close_par; } } if(open_par != close_par) { cout << "Error: Hanging parenthesis/n"; return false; } return true; } vector<vector<string> > parse(string com) { vector<vector<string> > v; vector<string> v2; char_separator<char> delim(" ", "|&#);"); tokenizer<char_separator<char> >mytok(com, delim); for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); ++it) { v2.push_back(*it); } for(unsigned i = 0; i < v2.size(); ++i) { vector<string> v3; if(v2.at(i) == "|") //check for || command { ++i; if(v2.at(i) == "|") { v3.push_back("||"); } else //exit if || isn't fully implemented { cout << "Invalid Command Line." << endl; exit(1); } } else if(v2.at(i) == "&") //check for && command { ++i; if(v2.at(i) == "&") { v3.push_back("&&"); } else //exit if && isn't fully implemented { cout << "Invalid Command Line." << endl; exit(1); } } else if(v2.at(i) == ";") { v3.push_back(v2.at(i)); } else if(v2.at(i) == "#") { v3.push_back(v2.at(i)); v.push_back(v3); return v; } else //create a command vector without connectors or hashes { while((i < v2.size()) && (v2.at(i) != "&") && (v2.at(i) != "|") && (v2.at(i) != ";") && (v2.at(i) != "#")) { v3.push_back(v2.at(i)); ++i; } i = i - 1; } v.push_back(v3); } return v; } const int ARRAY_MAX = 20; vector<vector<string> > make_com() { string cmd; char hostname[ARRAY_MAX]; char login[ARRAY_MAX]; int result = getlogin_r(login, ARRAY_MAX); if (result) { perror("getlogin"); } else { cout << login; } result = gethostname(hostname, ARRAY_MAX); if (result) { perror("gethostname"); } else { cout << '@' << hostname; } cout << "$ "; getline(cin, cmd); //cout << endl; if(check_par(cmd) == false) { exit(1); } return parse(cmd); } bool create_tree(vector<vector<string> > v) { Shell_Base* left = 0; string exit = "exit"; if((v.at(0)).at(0) == "exit") { return false; } if((v.at(0)).at(0) == "#") { return true; } for(unsigned i = 0; i < v.size(); ++i) { if(((v.at(i)).at(0) == "&&") || ((v.at(i)).at(0) == "||") || ((v.at(i)).at(0) == ";")) { if(i == 0) { cout << "Error: invalid command.\n"; return false; } if( ((i + 1) < v.size()) && ((v.at(i)).at(0) == "&&")) { Shell_Base* temp = new Command(v.at(i + 1)); Shell_Base * a = new And(left, temp); if(v.at(i + 1).at(0) == exit) { return false; } else if( ((v.at(i + 1)).at(0) == "&&") || ((v.at(i + 1)).at(0) == "||") || ((v.at(i + 1)).at(0) == ";")) { cout << "Error: Consecutive connectors.\n"; return true; } else if((v.at(i + 1)).at(0) == "#") { return true; } a->execute(); } else if( ((i + 1) < v.size()) && ((v.at(i)).at(0) == "||")) { Shell_Base* temp = new Command(v.at(i + 1)); Shell_Base* a = new Or(left, temp); if(v.at(i + 1).at(0) == exit) { return false; } else if( ((v.at(i + 1)).at(0) == "&&") || ((v.at(i + 1)).at(0) == "||") || ((v.at(i + 1)).at(0) == ";")) { cout << "Error: Consecutive connectors.\n"; return true; } else if((v.at(i + 1)).at(0) == "#") { return true; } a->execute(); } else if( ((v.at(i)).at(0) == ";")) { Shell_Base* temp = new Command(v.at(i + 1)); Shell_Base* a = new Semi(left, temp); if(v.at(i + 1).at(0) == exit) { return false; } else if( ((v.at(i + 1)).at(0) == "&&") || ((v.at(i + 1)).at(0) == "||") || ((v.at(i + 1)).at(0) == ";")) { cout << "Error: Consecutive connectors.\n"; return true; } else if((v.at(i + 1)).at(0) == "#") { return true; } a->execute(); } } else if((v.at(i)).at(0) == "#") { return true; } else { Shell_Base* a = new Command(v.at(i)); if (i == 0 && v.at(i).at(0) != exit) {a->execute();} else if (i == 0 && v.at(i).at(0) == exit) { return false; } left = a; if (a->get_executed() == -1) { return false; } } } return true; } void rshell() { bool test = true; do { test = create_tree(make_com()); } while (test); } int main() { // Test case for parse /* vector<string> test_vector; string test_string = "ls assignments | | cd CS100 && iss ; hello"; test_vector = parse(test_string); for (unsigned int i = 0; i < test_vector.size(); i++) { cout << '(' << test_vector.at(i) << ')' << ' '; } cout << endl; */ // Test case for Command Leaf class // DELETE OUTPUT FOR EXECUTE IN Command::execute() // DELETE OUTPUT STATEMENTS OF ELSE BRANCH OF execute() IN EVERY CLASS /* string a = "s"; string b = "-a"; vector<string> v1; v1.push_back(a); v1.push_back(b); Shell_Base * A = new Command(v1); cout << "executing child A:" << endl; A->execute(); cout << endl; string c = "ls"; //string d = "-a"; vector<string> v2; v2.push_back(c); //v2.push_back(d); Shell_Base * B = new Command(v2); cout << "executing child B:" << endl; B->execute(); cout << endl; string e = "s"; string f = "I love Brian Crites."; vector<string> v3; v3.push_back(e); v3.push_back(f); Shell_Base * C = new Command(v3); cout << "executing child C:" << endl; C->execute(); cout << endl; */ // Test case for Or composite class (uses A, B, and C from Leaf class) /* Shell_Base * D = new Or(A,B); cout << "executing A || B:" << endl; D->execute(); cout << endl; Shell_Base * E = new Or(D, C); cout << "executing (A || B) || C:" << endl; E->execute(); cout << endl; */ // Test case for And composite class (uses A, B, and C from Leaf class) /* Shell_Base * F = new And(A,B); cout << "executing A && B:" << endl; F->execute(); cout << endl; Shell_Base * G = new And(F, C); cout << "executing (A && B) && C:" << endl; G->execute(); cout << endl; */ // Test case for Semi composite class (uses A, B, and C from Leaf class) /* Shell_Base * H = new Semi(A,B); cout << "executing A;B:" << endl; H->execute(); cout << endl; Shell_Base * I = new Semi(H, C); cout << "executing (A;B);C:" << endl; I->execute(); cout << endl; */ vector<vector<string> > temp = make_com(); print_parse(temp); //print_parse(rshell()); rshell(); return 0; }
Update main.cpp
Update main.cpp check hanging parenthesis
C++
bsd-3-clause
kcole002/rshell,kcole002/rshell
f3cdc1ba2d8449aed9f4e219c1d0ef72d6e97f36
input/inputmanager.cpp
input/inputmanager.cpp
/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2010 Kim Jung Nissen <[email protected]> * Copyright (C) 2010 Laszlo Papp <[email protected]> * * 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 "inputmanager.h" #include "inputmanagerprivate.h" #include "gluondevices.h" #ifdef Q_WS_X11 #include "detectlinux.h" #endif #ifdef Q_WS_MAC #include "detectmac.h" #endif #ifdef Q_WS_WIN #include "detectwin.h" #endif #include <QtGui/QKeyEvent> #include <QtCore/QCoreApplication> #include <QtCore/QDebug> using namespace GluonInput; GLUON_DEFINE_SINGLETON(InputManager) InputManager::InputManager( QObject* parent ) : d( new InputManagerPrivate ) { init(); } InputManager::~InputManager() { delete d->m_detect; delete d; } void InputManager::init() { QObject* parent = QCoreApplication::instance(); if( !parent ) { qDebug() << "No QCoreApplication instance found, the InputManager instance may be leaked when leaving"; } #ifdef Q_WS_X11 d->m_detect = new DetectLinux( parent ); #endif #ifdef Q_WS_MAC d->m_detect = new DetectMac( parent ); #endif #ifdef Q_WS_WIN d->m_detect = new DetectWin( parent ); #endif if( d->m_detect ) { if( !d->m_detect->isReadable() ) { setInputManagementType(QT_INPUT_HIGHLEVEL); if (filteredObject()) installEventFiltered(filteredObject()); // else // qDebug() << "Null filtered object pointer - no install"; InputDevice* keyboard = new Keyboard( 0, this ); d->m_detect->addKeyboard( static_cast<Keyboard*>( keyboard ) ); InputDevice* mouse = new Mouse( 0, this ); d->m_detect->addMouse( static_cast<Mouse*>( mouse ) ); InputDevice* touch = new Touch( 0, this ); d->m_detect->addTouch( static_cast<Touch*>( touch ) ); } else { #ifdef Q_WS_X11 setInputManagementType(LINUX_INPUT_LOWLEVEL); #elif defined(Q_WS_MAC) setInputManagementType(MAC_INPUT_LOWLEVEL); #elif defined(Q_WS_WIN) setInputManagementType(WIN_INPUT_LOWLEVEL); #endif if (filteredObject()) removeEventFiltered(filteredObject()); // else // qDebug() << "Null filtered object pointer - no remove"; d->m_detect->detectDevices(); } } else { qDebug() << "Instance not created, fail!"; } } void InputManager::detectDevices() { d->m_detect->detectDevices(); } void InputManager::setAllEnabled( bool enable ) { d->m_detect->setAllEnabled( enable ); } unsigned int InputManager::deviceCount() { return inputList().size(); } unsigned int InputManager::keyboardCount() { return d->m_detect->keyboardList().size(); } unsigned int InputManager::mouseCount() { return d->m_detect->mouseList().size(); } unsigned int InputManager::joystickCount() { return d->m_detect->joystickList().size(); } unsigned int InputManager::touchCount() { return d->m_detect->touchList().size(); } unsigned int InputManager::unknownDeviceCount() { return d->m_detect->unknownDeviceList().size(); } QList<Keyboard*> InputManager::keyboardList() { return d->m_detect->keyboardList(); } QList<Mouse*> InputManager::mouseList() { return d->m_detect->mouseList(); } QList<Joystick*> InputManager::joystickList() { return d->m_detect->joystickList(); } QList<Touch*> InputManager::touchList() { return d->m_detect->touchList(); } QList<InputDevice*> InputManager::unknownDeviceList() { return d->m_detect->unknownDeviceList(); } InputList InputManager::inputList() { return d->m_detect->inputList(); } Keyboard* InputManager::keyboard( int id ) { if( !d->m_detect->keyboardList().isEmpty() ) { return d->m_detect->keyboardList().at( id ); } return 0; } Mouse* InputManager::mouse( int id ) { if( !d->m_detect->mouseList().isEmpty() ) { return d->m_detect->mouseList().at( id ); } return 0; } Joystick* InputManager::joystick( int id ) { if( !d->m_detect->joystickList().isEmpty() ) { return d->m_detect->joystickList().at( id ); } return 0; } Touch* InputManager::touch( int id ) { if( !d->m_detect->touchList().isEmpty() ) { return d->m_detect->touchList().at( id ); } return 0; } InputDevice* InputManager::input( int id ) { if( !d->m_detect->inputList().isEmpty() ) { return d->m_detect->inputList().at( id ); } return 0; } bool InputManager::eventFilter(QObject* object, QEvent* event) { if (object != m_filteredObj.data()) return false; switch (event->type()) { case QEvent::KeyPress: { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); keyboard(0)->setButtonState(keyEvent->key(), 1); emit keyPressed(keyEvent->key()); return true; } case QEvent::KeyRelease: { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); keyboard(0)->setButtonState(keyEvent->key(), 0); emit keyReleased(keyEvent->key()); return true; } case QEvent::MouseMove: { QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event); mouse(0)->setPosition( mouseEvent->pos( ) ); return true; } case QEvent::Wheel: { QWheelEvent *wheelEvent = static_cast<QWheelEvent *>(event); mouse(0)->setHWheelPosition( wheelEvent->x( ) ); mouse(0)->setHWheelPosition( wheelEvent->y( ) ); return true; } case QEvent::MouseButtonPress: { QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event); switch (mouseEvent->button()) { case Qt::LeftButton: return true; case Qt::RightButton: return true; case Qt::MiddleButton: return true; case Qt::XButton1: return true; case Qt::XButton2: return true; default: return false; } } case QEvent::Gesture: { QGestureEvent *gestureEvent = static_cast<QGestureEvent *>(event); if (QGesture *swipe = gestureEvent->gesture(Qt::SwipeGesture)) swipeTriggered(static_cast<QSwipeGesture *>(swipe)); else if (QGesture *pan = gestureEvent->gesture(Qt::PanGesture)) panTriggered(static_cast<QPanGesture *>(pan)); if (QGesture *pinch = gestureEvent->gesture(Qt::PinchGesture)) pinchTriggered(static_cast<QPinchGesture *>(pinch)); return true; } case QEvent::GestureOverride: { QGestureEvent *gestureEvent = static_cast<QGestureEvent *>(event); if (QGesture *swipe = gestureEvent->gesture(Qt::SwipeGesture)) swipeTriggered(static_cast<QSwipeGesture *>(swipe)); else if (QGesture *pan = gestureEvent->gesture(Qt::PanGesture)) panTriggered(static_cast<QPanGesture *>(pan)); if (QGesture *pinch = gestureEvent->gesture(Qt::PinchGesture)) pinchTriggered(static_cast<QPinchGesture *>(pinch)); return true; } default: return false; } return false; } void InputManager::swipeTriggered(QSwipeGesture *gesture) { if (gesture->state() == Qt::GestureFinished) { if (gesture->horizontalDirection() == QSwipeGesture::Left || gesture->verticalDirection() == QSwipeGesture::Up) ; } } void InputManager::panTriggered(QPanGesture *gesture) { } void InputManager::pinchTriggered(QPinchGesture *gesture) { } void InputManager::installEventFiltered(QObject *filteredObj) { filteredObj->installEventFilter(this); qobject_cast<QWidget*>(filteredObj)->grabGesture(Qt::PanGesture); qobject_cast<QWidget*>(filteredObj)->grabGesture(Qt::PinchGesture); qobject_cast<QWidget*>(filteredObj)->grabGesture(Qt::SwipeGesture); } void InputManager::removeEventFiltered(QObject *filteredObj) { filteredObj->removeEventFilter(this); } QObject* InputManager::filteredObject() { return m_filteredObj.data(); } void InputManager::setFilteredObject(QObject *filteredObj) { if( filteredObj && inputManagementType() == QT_INPUT_HIGHLEVEL ) { if( !m_filteredObj.isNull() ) removeEventFiltered( m_filteredObj.data() ); installEventFiltered(filteredObj); } m_filteredObj = filteredObj; } InputManager::InputManagementType InputManager::inputManagementType() const { return m_inputManagementType; } void InputManager::setInputManagementType( InputManager::InputManagementType inputManagementType ) { m_inputManagementType = inputManagementType; } #include "inputmanager.moc"
/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2010 Kim Jung Nissen <[email protected]> * Copyright (C) 2010 Laszlo Papp <[email protected]> * * 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 "inputmanager.h" #include "inputmanagerprivate.h" #include "gluondevices.h" #ifdef Q_WS_X11 #include "detectlinux.h" #endif #ifdef Q_WS_MAC #include "detectmac.h" #endif #ifdef Q_WS_WIN #include "detectwin.h" #endif #include <QtGui/QKeyEvent> #include <QtCore/QCoreApplication> #include <QtCore/QDebug> using namespace GluonInput; GLUON_DEFINE_SINGLETON(InputManager) InputManager::InputManager( QObject* parent ) : d( new InputManagerPrivate ) { init(); } InputManager::~InputManager() { delete d->m_detect; delete d; } void InputManager::init() { QObject* parent = QCoreApplication::instance(); if( !parent ) { qDebug() << "No QCoreApplication instance found, the InputManager instance may be leaked when leaving"; } #ifdef Q_WS_X11 d->m_detect = new DetectLinux( parent ); #endif #ifdef Q_WS_MAC d->m_detect = new DetectMac( parent ); #endif #ifdef Q_WS_WIN d->m_detect = new DetectWin( parent ); #endif if( d->m_detect ) { if( !d->m_detect->isReadable() ) { setInputManagementType(QT_INPUT_HIGHLEVEL); if (filteredObject()) installEventFiltered(filteredObject()); // else // qDebug() << "Null filtered object pointer - no install"; InputDevice* keyboard = new Keyboard( 0, this ); d->m_detect->addKeyboard( static_cast<Keyboard*>( keyboard ) ); InputDevice* mouse = new Mouse( 0, this ); d->m_detect->addMouse( static_cast<Mouse*>( mouse ) ); InputDevice* touch = new Touch( 0, this ); d->m_detect->addTouch( static_cast<Touch*>( touch ) ); } else { #ifdef Q_WS_X11 setInputManagementType(LINUX_INPUT_LOWLEVEL); #elif defined(Q_WS_MAC) setInputManagementType(MAC_INPUT_LOWLEVEL); #elif defined(Q_WS_WIN) setInputManagementType(WIN_INPUT_LOWLEVEL); #endif if (filteredObject()) removeEventFiltered(filteredObject()); // else // qDebug() << "Null filtered object pointer - no remove"; d->m_detect->detectDevices(); } } else { qDebug() << "Instance not created, fail!"; } } void InputManager::detectDevices() { d->m_detect->detectDevices(); } void InputManager::setAllEnabled( bool enable ) { d->m_detect->setAllEnabled( enable ); } unsigned int InputManager::deviceCount() { return inputList().size(); } unsigned int InputManager::keyboardCount() { return d->m_detect->keyboardList().size(); } unsigned int InputManager::mouseCount() { return d->m_detect->mouseList().size(); } unsigned int InputManager::joystickCount() { return d->m_detect->joystickList().size(); } unsigned int InputManager::touchCount() { return d->m_detect->touchList().size(); } unsigned int InputManager::unknownDeviceCount() { return d->m_detect->unknownDeviceList().size(); } QList<Keyboard*> InputManager::keyboardList() { return d->m_detect->keyboardList(); } QList<Mouse*> InputManager::mouseList() { return d->m_detect->mouseList(); } QList<Joystick*> InputManager::joystickList() { return d->m_detect->joystickList(); } QList<Touch*> InputManager::touchList() { return d->m_detect->touchList(); } QList<InputDevice*> InputManager::unknownDeviceList() { return d->m_detect->unknownDeviceList(); } InputList InputManager::inputList() { return d->m_detect->inputList(); } Keyboard* InputManager::keyboard( int id ) { if( !d->m_detect->keyboardList().isEmpty() ) { return d->m_detect->keyboardList().at( id ); } return 0; } Mouse* InputManager::mouse( int id ) { if( !d->m_detect->mouseList().isEmpty() ) { return d->m_detect->mouseList().at( id ); } return 0; } Joystick* InputManager::joystick( int id ) { if( !d->m_detect->joystickList().isEmpty() ) { return d->m_detect->joystickList().at( id ); } return 0; } Touch* InputManager::touch( int id ) { if( !d->m_detect->touchList().isEmpty() ) { return d->m_detect->touchList().at( id ); } return 0; } InputDevice* InputManager::input( int id ) { if( !d->m_detect->inputList().isEmpty() ) { return d->m_detect->inputList().at( id ); } return 0; } bool InputManager::eventFilter(QObject* object, QEvent* event) { if (object != m_filteredObj.data()) return false; switch (event->type()) { case QEvent::KeyPress: { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); keyboard(0)->setButtonState(keyEvent->key(), 1); emit keyPressed(keyEvent->key()); return true; } case QEvent::KeyRelease: { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); keyboard(0)->setButtonState(keyEvent->key(), 0); emit keyReleased(keyEvent->key()); return true; } case QEvent::MouseMove: { //qDebug() << "MouseMove"; QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event); mouse(0)->setPosition( mouseEvent->pos( ) ); return true; } case QEvent::Wheel: { QWheelEvent *wheelEvent = static_cast<QWheelEvent *>(event); mouse(0)->setHWheelPosition( wheelEvent->x( ) ); mouse(0)->setHWheelPosition( wheelEvent->y( ) ); return true; } case QEvent::MouseButtonPress: { QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event); switch (mouseEvent->button()) { case Qt::LeftButton: return true; case Qt::RightButton: return true; case Qt::MiddleButton: return true; case Qt::XButton1: return true; case Qt::XButton2: return true; default: return false; } } case QEvent::Gesture: { QGestureEvent *gestureEvent = static_cast<QGestureEvent *>(event); if (QGesture *swipe = gestureEvent->gesture(Qt::SwipeGesture)) swipeTriggered(static_cast<QSwipeGesture *>(swipe)); else if (QGesture *pan = gestureEvent->gesture(Qt::PanGesture)) panTriggered(static_cast<QPanGesture *>(pan)); if (QGesture *pinch = gestureEvent->gesture(Qt::PinchGesture)) pinchTriggered(static_cast<QPinchGesture *>(pinch)); return true; } case QEvent::GestureOverride: { QGestureEvent *gestureEvent = static_cast<QGestureEvent *>(event); if (QGesture *swipe = gestureEvent->gesture(Qt::SwipeGesture)) swipeTriggered(static_cast<QSwipeGesture *>(swipe)); else if (QGesture *pan = gestureEvent->gesture(Qt::PanGesture)) panTriggered(static_cast<QPanGesture *>(pan)); if (QGesture *pinch = gestureEvent->gesture(Qt::PinchGesture)) pinchTriggered(static_cast<QPinchGesture *>(pinch)); return true; } default: return false; } return false; } void InputManager::swipeTriggered(QSwipeGesture *gesture) { if (gesture->state() == Qt::GestureFinished) { if (gesture->horizontalDirection() == QSwipeGesture::Left || gesture->verticalDirection() == QSwipeGesture::Up) ; } } void InputManager::panTriggered(QPanGesture *gesture) { } void InputManager::pinchTriggered(QPinchGesture *gesture) { } void InputManager::installEventFiltered(QObject *filteredObj) { filteredObj->installEventFilter(this); qobject_cast<QWidget*>(filteredObj)->grabGesture(Qt::PanGesture); qobject_cast<QWidget*>(filteredObj)->grabGesture(Qt::PinchGesture); qobject_cast<QWidget*>(filteredObj)->grabGesture(Qt::SwipeGesture); qobject_cast<QWidget*>(filteredObj)->setMouseTracking(true); } void InputManager::removeEventFiltered(QObject *filteredObj) { filteredObj->removeEventFilter(this); } QObject* InputManager::filteredObject() { return m_filteredObj.data(); } void InputManager::setFilteredObject(QObject *filteredObj) { if( filteredObj && inputManagementType() == QT_INPUT_HIGHLEVEL ) { if( !m_filteredObj.isNull() ) removeEventFiltered( m_filteredObj.data() ); installEventFiltered(filteredObj); } m_filteredObj = filteredObj; } InputManager::InputManagementType InputManager::inputManagementType() const { return m_inputManagementType; } void InputManager::setInputManagementType( InputManager::InputManagementType inputManagementType ) { m_inputManagementType = inputManagementType; } #include "inputmanager.moc"
Enable mouse tracking so we always get mouse move events.
Input: Enable mouse tracking so we always get mouse move events.
C++
lgpl-2.1
KDE/gluon,KDE/gluon,KDE/gluon,pranavrc/example-gluon,pranavrc/example-gluon,pranavrc/example-gluon,KDE/gluon,pranavrc/example-gluon
b7a5a1a46d1d4d30fab704b08a74a3e581556395
content/browser/child_process_security_policy.cc
content/browser/child_process_security_policy.cc
// 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 "content/browser/child_process_security_policy.h" #include "base/file_path.h" #include "base/logging.h" #include "base/platform_file.h" #include "base/stl_util.h" #include "base/string_util.h" #include "content/public/common/bindings_policy.h" #include "content/public/common/url_constants.h" #include "googleurl/src/gurl.h" #include "net/url_request/url_request.h" static const int kReadFilePermissions = base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ | base::PLATFORM_FILE_EXCLUSIVE_READ | base::PLATFORM_FILE_ASYNC; static const int kEnumerateDirectoryPermissions = kReadFilePermissions | base::PLATFORM_FILE_ENUMERATE; // The SecurityState class is used to maintain per-child process security state // information. class ChildProcessSecurityPolicy::SecurityState { public: SecurityState() : enabled_bindings_(0), can_read_raw_cookies_(false) { } ~SecurityState() { scheme_policy_.clear(); } // Grant permission to request URLs with the specified scheme. void GrantScheme(const std::string& scheme) { scheme_policy_[scheme] = true; } // Revoke permission to request URLs with the specified scheme. void RevokeScheme(const std::string& scheme) { scheme_policy_[scheme] = false; } // Grant certain permissions to a file. void GrantPermissionsForFile(const FilePath& file, int permissions) { file_permissions_[file.StripTrailingSeparators()] |= permissions; } // Revokes all permissions granted to a file. void RevokeAllPermissionsForFile(const FilePath& file) { file_permissions_.erase(file.StripTrailingSeparators()); } void GrantBindings(int bindings) { enabled_bindings_ |= bindings; } void GrantReadRawCookies() { can_read_raw_cookies_ = true; } void RevokeReadRawCookies() { can_read_raw_cookies_ = false; } // Determine whether permission has been granted to request url. // Schemes that have not been granted default to being denied. bool CanRequestURL(const GURL& url) { SchemeMap::const_iterator judgment(scheme_policy_.find(url.scheme())); if (judgment == scheme_policy_.end()) return false; // Unmentioned schemes are disallowed. return judgment->second; } // Determine if the certain permissions have been granted to a file. bool HasPermissionsForFile(const FilePath& file, int permissions) { FilePath current_path = file.StripTrailingSeparators(); FilePath last_path; while (current_path != last_path) { if (file_permissions_.find(current_path) != file_permissions_.end()) return (file_permissions_[current_path] & permissions) == permissions; last_path = current_path; current_path = current_path.DirName(); } return false; } bool has_web_ui_bindings() const { return enabled_bindings_ & content::BINDINGS_POLICY_WEB_UI; } bool can_read_raw_cookies() const { return can_read_raw_cookies_; } private: typedef std::map<std::string, bool> SchemeMap; typedef std::map<FilePath, int> FileMap; // bit-set of PlatformFileFlags // Maps URL schemes to whether permission has been granted or revoked: // |true| means the scheme has been granted. // |false| means the scheme has been revoked. // If a scheme is not present in the map, then it has never been granted // or revoked. SchemeMap scheme_policy_; // The set of files the child process is permited to upload to the web. FileMap file_permissions_; int enabled_bindings_; bool can_read_raw_cookies_; DISALLOW_COPY_AND_ASSIGN(SecurityState); }; ChildProcessSecurityPolicy::ChildProcessSecurityPolicy() { // We know about these schemes and believe them to be safe. RegisterWebSafeScheme(chrome::kHttpScheme); RegisterWebSafeScheme(chrome::kHttpsScheme); RegisterWebSafeScheme(chrome::kFtpScheme); RegisterWebSafeScheme(chrome::kDataScheme); RegisterWebSafeScheme("feed"); RegisterWebSafeScheme(chrome::kBlobScheme); RegisterWebSafeScheme(chrome::kFileSystemScheme); // We know about the following pseudo schemes and treat them specially. RegisterPseudoScheme(chrome::kAboutScheme); RegisterPseudoScheme(chrome::kJavaScriptScheme); RegisterPseudoScheme(chrome::kViewSourceScheme); } ChildProcessSecurityPolicy::~ChildProcessSecurityPolicy() { web_safe_schemes_.clear(); pseudo_schemes_.clear(); STLDeleteContainerPairSecondPointers(security_state_.begin(), security_state_.end()); security_state_.clear(); } // static ChildProcessSecurityPolicy* ChildProcessSecurityPolicy::GetInstance() { return Singleton<ChildProcessSecurityPolicy>::get(); } void ChildProcessSecurityPolicy::Add(int child_id) { base::AutoLock lock(lock_); AddChild(child_id); } void ChildProcessSecurityPolicy::AddWorker(int child_id, int main_render_process_id) { base::AutoLock lock(lock_); AddChild(child_id); worker_map_[child_id] = main_render_process_id; } void ChildProcessSecurityPolicy::Remove(int child_id) { base::AutoLock lock(lock_); if (!security_state_.count(child_id)) return; // May be called multiple times. delete security_state_[child_id]; security_state_.erase(child_id); worker_map_.erase(child_id); } void ChildProcessSecurityPolicy::RegisterWebSafeScheme( const std::string& scheme) { base::AutoLock lock(lock_); DCHECK(web_safe_schemes_.count(scheme) == 0) << "Add schemes at most once."; DCHECK(pseudo_schemes_.count(scheme) == 0) << "Web-safe implies not pseudo."; web_safe_schemes_.insert(scheme); } bool ChildProcessSecurityPolicy::IsWebSafeScheme(const std::string& scheme) { base::AutoLock lock(lock_); return (web_safe_schemes_.find(scheme) != web_safe_schemes_.end()); } void ChildProcessSecurityPolicy::RegisterPseudoScheme( const std::string& scheme) { base::AutoLock lock(lock_); DCHECK(pseudo_schemes_.count(scheme) == 0) << "Add schemes at most once."; DCHECK(web_safe_schemes_.count(scheme) == 0) << "Pseudo implies not web-safe."; pseudo_schemes_.insert(scheme); } bool ChildProcessSecurityPolicy::IsPseudoScheme(const std::string& scheme) { base::AutoLock lock(lock_); return (pseudo_schemes_.find(scheme) != pseudo_schemes_.end()); } void ChildProcessSecurityPolicy::RegisterDisabledSchemes( const std::set<std::string>& schemes) { base::AutoLock lock(lock_); disabled_schemes_ = schemes; } bool ChildProcessSecurityPolicy::IsDisabledScheme(const std::string& scheme) { base::AutoLock lock(lock_); return disabled_schemes_.find(scheme) != disabled_schemes_.end(); } void ChildProcessSecurityPolicy::GrantRequestURL( int child_id, const GURL& url) { if (!url.is_valid()) return; // Can't grant the capability to request invalid URLs. if (IsWebSafeScheme(url.scheme())) return; // The scheme has already been whitelisted for every child process. if (IsPseudoScheme(url.scheme())) { // The view-source scheme is a special case of a pseudo-URL that eventually // results in requesting its embedded URL. if (url.SchemeIs(chrome::kViewSourceScheme)) { // URLs with the view-source scheme typically look like: // view-source:http://www.google.com/a // In order to request these URLs, the child_id needs to be able to // request the embedded URL. GrantRequestURL(child_id, GURL(url.path())); } return; // Can't grant the capability to request pseudo schemes. } { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return; // If the child process has been commanded to request a scheme, then we // grant it the capability to request URLs of that scheme. state->second->GrantScheme(url.scheme()); } } void ChildProcessSecurityPolicy::GrantReadFile(int child_id, const FilePath& file) { GrantPermissionsForFile(child_id, file, kReadFilePermissions); } void ChildProcessSecurityPolicy::GrantReadDirectory(int child_id, const FilePath& directory) { GrantPermissionsForFile(child_id, directory, kEnumerateDirectoryPermissions); } void ChildProcessSecurityPolicy::GrantPermissionsForFile( int child_id, const FilePath& file, int permissions) { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return; state->second->GrantPermissionsForFile(file, permissions); } void ChildProcessSecurityPolicy::RevokeAllPermissionsForFile( int child_id, const FilePath& file) { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return; state->second->RevokeAllPermissionsForFile(file); } void ChildProcessSecurityPolicy::GrantScheme(int child_id, const std::string& scheme) { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return; state->second->GrantScheme(scheme); } void ChildProcessSecurityPolicy::GrantWebUIBindings(int child_id) { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return; state->second->GrantBindings(content::BINDINGS_POLICY_WEB_UI); // Web UI bindings need the ability to request chrome: URLs. state->second->GrantScheme(chrome::kChromeUIScheme); // Web UI pages can contain links to file:// URLs. state->second->GrantScheme(chrome::kFileScheme); } void ChildProcessSecurityPolicy::GrantReadRawCookies(int child_id) { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return; state->second->GrantReadRawCookies(); } void ChildProcessSecurityPolicy::RevokeReadRawCookies(int child_id) { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return; state->second->RevokeReadRawCookies(); } bool ChildProcessSecurityPolicy::CanRequestURL( int child_id, const GURL& url) { if (!url.is_valid()) return false; // Can't request invalid URLs. if (IsDisabledScheme(url.scheme())) return false; // The scheme is disabled by policy. if (IsWebSafeScheme(url.scheme())) return true; // The scheme has been white-listed for every child process. if (IsPseudoScheme(url.scheme())) { // There are a number of special cases for pseudo schemes. if (url.SchemeIs(chrome::kViewSourceScheme)) { // A view-source URL is allowed if the child process is permitted to // request the embedded URL. Careful to avoid pointless recursion. GURL child_url(url.path()); if (child_url.SchemeIs(chrome::kViewSourceScheme) && url.SchemeIs(chrome::kViewSourceScheme)) return false; return CanRequestURL(child_id, child_url); } if (LowerCaseEqualsASCII(url.spec(), chrome::kAboutBlankURL)) return true; // Every child process can request <about:blank>. // URLs like <about:memory> and <about:crash> shouldn't be requestable by // any child process. Also, this case covers <javascript:...>, which should // be handled internally by the process and not kicked up to the browser. return false; } if (!net::URLRequest::IsHandledURL(url)) return true; // This URL request is destined for ShellExecute. { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return false; // Otherwise, we consult the child process's security state to see if it is // allowed to request the URL. return state->second->CanRequestURL(url); } } bool ChildProcessSecurityPolicy::CanReadFile(int child_id, const FilePath& file) { return HasPermissionsForFile(child_id, file, kReadFilePermissions); } bool ChildProcessSecurityPolicy::CanReadDirectory(int child_id, const FilePath& directory) { return HasPermissionsForFile(child_id, directory, kEnumerateDirectoryPermissions); } bool ChildProcessSecurityPolicy::HasPermissionsForFile( int child_id, const FilePath& file, int permissions) { base::AutoLock lock(lock_); bool result = ChildProcessHasPermissionsForFile(child_id, file, permissions); if (!result) { // If this is a worker thread that has no access to a given file, // let's check that its renderer process has access to that file instead. WorkerToMainProcessMap::iterator iter = worker_map_.find(child_id); if (iter != worker_map_.end() && iter->second != 0) { result = ChildProcessHasPermissionsForFile(iter->second, file, permissions); } } return result; } bool ChildProcessSecurityPolicy::HasWebUIBindings(int child_id) { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return false; return state->second->has_web_ui_bindings(); } bool ChildProcessSecurityPolicy::CanReadRawCookies(int child_id) { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return false; return state->second->can_read_raw_cookies(); } void ChildProcessSecurityPolicy::AddChild(int child_id) { if (security_state_.count(child_id) != 0) { NOTREACHED() << "Add child process at most once."; return; } security_state_[child_id] = new SecurityState(); } bool ChildProcessSecurityPolicy::ChildProcessHasPermissionsForFile( int child_id, const FilePath& file, int permissions) { SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return false; return state->second->HasPermissionsForFile(file, permissions); }
// 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 "content/browser/child_process_security_policy.h" #include "base/file_path.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/platform_file.h" #include "base/stl_util.h" #include "base/string_util.h" #include "content/public/common/bindings_policy.h" #include "content/public/common/url_constants.h" #include "googleurl/src/gurl.h" #include "net/url_request/url_request.h" static const int kReadFilePermissions = base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ | base::PLATFORM_FILE_EXCLUSIVE_READ | base::PLATFORM_FILE_ASYNC; static const int kEnumerateDirectoryPermissions = kReadFilePermissions | base::PLATFORM_FILE_ENUMERATE; // The SecurityState class is used to maintain per-child process security state // information. class ChildProcessSecurityPolicy::SecurityState { public: SecurityState() : enabled_bindings_(0), can_read_raw_cookies_(false) { } ~SecurityState() { scheme_policy_.clear(); UMA_HISTOGRAM_COUNTS("ChildProcessSecurityPolicy.PerChildFilePermissions", file_permissions_.size()); } // Grant permission to request URLs with the specified scheme. void GrantScheme(const std::string& scheme) { scheme_policy_[scheme] = true; } // Revoke permission to request URLs with the specified scheme. void RevokeScheme(const std::string& scheme) { scheme_policy_[scheme] = false; } // Grant certain permissions to a file. void GrantPermissionsForFile(const FilePath& file, int permissions) { FilePath stripped = file.StripTrailingSeparators(); file_permissions_[stripped] |= permissions; UMA_HISTOGRAM_COUNTS("ChildProcessSecurityPolicy.FilePermissionPathLength", stripped.value().size()); } // Revokes all permissions granted to a file. void RevokeAllPermissionsForFile(const FilePath& file) { file_permissions_.erase(file.StripTrailingSeparators()); } void GrantBindings(int bindings) { enabled_bindings_ |= bindings; } void GrantReadRawCookies() { can_read_raw_cookies_ = true; } void RevokeReadRawCookies() { can_read_raw_cookies_ = false; } // Determine whether permission has been granted to request url. // Schemes that have not been granted default to being denied. bool CanRequestURL(const GURL& url) { SchemeMap::const_iterator judgment(scheme_policy_.find(url.scheme())); if (judgment == scheme_policy_.end()) return false; // Unmentioned schemes are disallowed. return judgment->second; } // Determine if the certain permissions have been granted to a file. bool HasPermissionsForFile(const FilePath& file, int permissions) { FilePath current_path = file.StripTrailingSeparators(); FilePath last_path; while (current_path != last_path) { if (file_permissions_.find(current_path) != file_permissions_.end()) return (file_permissions_[current_path] & permissions) == permissions; last_path = current_path; current_path = current_path.DirName(); } return false; } bool has_web_ui_bindings() const { return enabled_bindings_ & content::BINDINGS_POLICY_WEB_UI; } bool can_read_raw_cookies() const { return can_read_raw_cookies_; } private: typedef std::map<std::string, bool> SchemeMap; typedef std::map<FilePath, int> FileMap; // bit-set of PlatformFileFlags // Maps URL schemes to whether permission has been granted or revoked: // |true| means the scheme has been granted. // |false| means the scheme has been revoked. // If a scheme is not present in the map, then it has never been granted // or revoked. SchemeMap scheme_policy_; // The set of files the child process is permited to upload to the web. FileMap file_permissions_; int enabled_bindings_; bool can_read_raw_cookies_; DISALLOW_COPY_AND_ASSIGN(SecurityState); }; ChildProcessSecurityPolicy::ChildProcessSecurityPolicy() { // We know about these schemes and believe them to be safe. RegisterWebSafeScheme(chrome::kHttpScheme); RegisterWebSafeScheme(chrome::kHttpsScheme); RegisterWebSafeScheme(chrome::kFtpScheme); RegisterWebSafeScheme(chrome::kDataScheme); RegisterWebSafeScheme("feed"); RegisterWebSafeScheme(chrome::kBlobScheme); RegisterWebSafeScheme(chrome::kFileSystemScheme); // We know about the following pseudo schemes and treat them specially. RegisterPseudoScheme(chrome::kAboutScheme); RegisterPseudoScheme(chrome::kJavaScriptScheme); RegisterPseudoScheme(chrome::kViewSourceScheme); } ChildProcessSecurityPolicy::~ChildProcessSecurityPolicy() { web_safe_schemes_.clear(); pseudo_schemes_.clear(); STLDeleteContainerPairSecondPointers(security_state_.begin(), security_state_.end()); security_state_.clear(); } // static ChildProcessSecurityPolicy* ChildProcessSecurityPolicy::GetInstance() { return Singleton<ChildProcessSecurityPolicy>::get(); } void ChildProcessSecurityPolicy::Add(int child_id) { base::AutoLock lock(lock_); AddChild(child_id); } void ChildProcessSecurityPolicy::AddWorker(int child_id, int main_render_process_id) { base::AutoLock lock(lock_); AddChild(child_id); worker_map_[child_id] = main_render_process_id; } void ChildProcessSecurityPolicy::Remove(int child_id) { base::AutoLock lock(lock_); if (!security_state_.count(child_id)) return; // May be called multiple times. delete security_state_[child_id]; security_state_.erase(child_id); worker_map_.erase(child_id); } void ChildProcessSecurityPolicy::RegisterWebSafeScheme( const std::string& scheme) { base::AutoLock lock(lock_); DCHECK(web_safe_schemes_.count(scheme) == 0) << "Add schemes at most once."; DCHECK(pseudo_schemes_.count(scheme) == 0) << "Web-safe implies not pseudo."; web_safe_schemes_.insert(scheme); } bool ChildProcessSecurityPolicy::IsWebSafeScheme(const std::string& scheme) { base::AutoLock lock(lock_); return (web_safe_schemes_.find(scheme) != web_safe_schemes_.end()); } void ChildProcessSecurityPolicy::RegisterPseudoScheme( const std::string& scheme) { base::AutoLock lock(lock_); DCHECK(pseudo_schemes_.count(scheme) == 0) << "Add schemes at most once."; DCHECK(web_safe_schemes_.count(scheme) == 0) << "Pseudo implies not web-safe."; pseudo_schemes_.insert(scheme); } bool ChildProcessSecurityPolicy::IsPseudoScheme(const std::string& scheme) { base::AutoLock lock(lock_); return (pseudo_schemes_.find(scheme) != pseudo_schemes_.end()); } void ChildProcessSecurityPolicy::RegisterDisabledSchemes( const std::set<std::string>& schemes) { base::AutoLock lock(lock_); disabled_schemes_ = schemes; } bool ChildProcessSecurityPolicy::IsDisabledScheme(const std::string& scheme) { base::AutoLock lock(lock_); return disabled_schemes_.find(scheme) != disabled_schemes_.end(); } void ChildProcessSecurityPolicy::GrantRequestURL( int child_id, const GURL& url) { if (!url.is_valid()) return; // Can't grant the capability to request invalid URLs. if (IsWebSafeScheme(url.scheme())) return; // The scheme has already been whitelisted for every child process. if (IsPseudoScheme(url.scheme())) { // The view-source scheme is a special case of a pseudo-URL that eventually // results in requesting its embedded URL. if (url.SchemeIs(chrome::kViewSourceScheme)) { // URLs with the view-source scheme typically look like: // view-source:http://www.google.com/a // In order to request these URLs, the child_id needs to be able to // request the embedded URL. GrantRequestURL(child_id, GURL(url.path())); } return; // Can't grant the capability to request pseudo schemes. } { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return; // If the child process has been commanded to request a scheme, then we // grant it the capability to request URLs of that scheme. state->second->GrantScheme(url.scheme()); } } void ChildProcessSecurityPolicy::GrantReadFile(int child_id, const FilePath& file) { GrantPermissionsForFile(child_id, file, kReadFilePermissions); } void ChildProcessSecurityPolicy::GrantReadDirectory(int child_id, const FilePath& directory) { GrantPermissionsForFile(child_id, directory, kEnumerateDirectoryPermissions); } void ChildProcessSecurityPolicy::GrantPermissionsForFile( int child_id, const FilePath& file, int permissions) { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return; state->second->GrantPermissionsForFile(file, permissions); } void ChildProcessSecurityPolicy::RevokeAllPermissionsForFile( int child_id, const FilePath& file) { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return; state->second->RevokeAllPermissionsForFile(file); } void ChildProcessSecurityPolicy::GrantScheme(int child_id, const std::string& scheme) { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return; state->second->GrantScheme(scheme); } void ChildProcessSecurityPolicy::GrantWebUIBindings(int child_id) { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return; state->second->GrantBindings(content::BINDINGS_POLICY_WEB_UI); // Web UI bindings need the ability to request chrome: URLs. state->second->GrantScheme(chrome::kChromeUIScheme); // Web UI pages can contain links to file:// URLs. state->second->GrantScheme(chrome::kFileScheme); } void ChildProcessSecurityPolicy::GrantReadRawCookies(int child_id) { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return; state->second->GrantReadRawCookies(); } void ChildProcessSecurityPolicy::RevokeReadRawCookies(int child_id) { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return; state->second->RevokeReadRawCookies(); } bool ChildProcessSecurityPolicy::CanRequestURL( int child_id, const GURL& url) { if (!url.is_valid()) return false; // Can't request invalid URLs. if (IsDisabledScheme(url.scheme())) return false; // The scheme is disabled by policy. if (IsWebSafeScheme(url.scheme())) return true; // The scheme has been white-listed for every child process. if (IsPseudoScheme(url.scheme())) { // There are a number of special cases for pseudo schemes. if (url.SchemeIs(chrome::kViewSourceScheme)) { // A view-source URL is allowed if the child process is permitted to // request the embedded URL. Careful to avoid pointless recursion. GURL child_url(url.path()); if (child_url.SchemeIs(chrome::kViewSourceScheme) && url.SchemeIs(chrome::kViewSourceScheme)) return false; return CanRequestURL(child_id, child_url); } if (LowerCaseEqualsASCII(url.spec(), chrome::kAboutBlankURL)) return true; // Every child process can request <about:blank>. // URLs like <about:memory> and <about:crash> shouldn't be requestable by // any child process. Also, this case covers <javascript:...>, which should // be handled internally by the process and not kicked up to the browser. return false; } if (!net::URLRequest::IsHandledURL(url)) return true; // This URL request is destined for ShellExecute. { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return false; // Otherwise, we consult the child process's security state to see if it is // allowed to request the URL. return state->second->CanRequestURL(url); } } bool ChildProcessSecurityPolicy::CanReadFile(int child_id, const FilePath& file) { return HasPermissionsForFile(child_id, file, kReadFilePermissions); } bool ChildProcessSecurityPolicy::CanReadDirectory(int child_id, const FilePath& directory) { return HasPermissionsForFile(child_id, directory, kEnumerateDirectoryPermissions); } bool ChildProcessSecurityPolicy::HasPermissionsForFile( int child_id, const FilePath& file, int permissions) { base::AutoLock lock(lock_); bool result = ChildProcessHasPermissionsForFile(child_id, file, permissions); if (!result) { // If this is a worker thread that has no access to a given file, // let's check that its renderer process has access to that file instead. WorkerToMainProcessMap::iterator iter = worker_map_.find(child_id); if (iter != worker_map_.end() && iter->second != 0) { result = ChildProcessHasPermissionsForFile(iter->second, file, permissions); } } return result; } bool ChildProcessSecurityPolicy::HasWebUIBindings(int child_id) { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return false; return state->second->has_web_ui_bindings(); } bool ChildProcessSecurityPolicy::CanReadRawCookies(int child_id) { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return false; return state->second->can_read_raw_cookies(); } void ChildProcessSecurityPolicy::AddChild(int child_id) { if (security_state_.count(child_id) != 0) { NOTREACHED() << "Add child process at most once."; return; } security_state_[child_id] = new SecurityState(); } bool ChildProcessSecurityPolicy::ChildProcessHasPermissionsForFile( int child_id, const FilePath& file, int permissions) { SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return false; return state->second->HasPermissionsForFile(file, permissions); }
Add UMA stats for per-child file permissions count
Add UMA stats for per-child file permissions count BUG=none TEST=none Review URL: http://codereview.chromium.org/8569006 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@111112 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
yitian134/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,yitian134/chromium
2554c1b81bb8c40e1989025c6f18e7935720b156
src/randomenv.cpp
src/randomenv.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <randomenv.h> #include <crypto/sha512.h> #include <support/cleanse.h> #include <util/time.h> // for GetTime() #ifdef WIN32 #include <compat.h> // for Windows API #endif #include <algorithm> #include <chrono> #include <thread> #include <vector> #include <stdint.h> #include <string.h> #ifndef WIN32 #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #endif #ifdef __MACH__ #include <mach/clock.h> #include <mach/mach.h> #include <mach/mach_time.h> #endif namespace { void RandAddSeedPerfmon(CSHA512& hasher) { #ifdef WIN32 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom // Seed with the entire set of perfmon data // This can take up to 2 seconds, so only do it every 10 minutes static int64_t nLastPerfmon; if (GetTime() < nLastPerfmon + 10 * 60) return; nLastPerfmon = GetTime(); std::vector<unsigned char> vData(250000, 0); long ret = 0; unsigned long nSize = 0; const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data while (true) { nSize = vData.size(); ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", nullptr, nullptr, vData.data(), &nSize); if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize) break; vData.resize(std::max((vData.size() * 3) / 2, nMaxSize)); // Grow size of buffer exponentially } RegCloseKey(HKEY_PERFORMANCE_DATA); if (ret == ERROR_SUCCESS) { hasher.Write(vData.data(), nSize); memory_cleanse(vData.data(), nSize); } else { // Performance data is only a best-effort attempt at improving the // situation when the OS randomness (and other sources) aren't // adequate. As a result, failure to read it is isn't considered critical, // so we don't call RandFailure(). // TODO: Add logging when the logger is made functional before global // constructors have been invoked. } #endif } /** Helper to easily feed data into a CSHA512. * * Note that this does not serialize the passed object (like stream.h's << operators do). * Its raw memory representation is used directly. */ template<typename T> CSHA512& operator<<(CSHA512& hasher, const T& data) { static_assert(!std::is_same<typename std::decay<T>::type, char*>::value, "Calling operator<<(CSHA512, char*) is probably not what you want"); static_assert(!std::is_same<typename std::decay<T>::type, unsigned char*>::value, "Calling operator<<(CSHA512, unsigned char*) is probably not what you want"); static_assert(!std::is_same<typename std::decay<T>::type, const char*>::value, "Calling operator<<(CSHA512, const char*) is probably not what you want"); static_assert(!std::is_same<typename std::decay<T>::type, const unsigned char*>::value, "Calling operator<<(CSHA512, const unsigned char*) is probably not what you want"); hasher.Write((const unsigned char*)&data, sizeof(data)); return hasher; } } // namespace void RandAddDynamicEnv(CSHA512& hasher) { RandAddSeedPerfmon(hasher); // Various clocks #ifdef WIN32 FILETIME ftime; GetSystemTimeAsFileTime(&ftime); hasher << ftime; #else # ifndef __MACH__ // On non-MacOS systems, use various clock_gettime() calls. struct timespec ts; # ifdef CLOCK_MONOTONIC clock_gettime(CLOCK_MONOTONIC, &ts); hasher << ts.tv_sec << ts.tv_nsec; # endif # ifdef CLOCK_REALTIME clock_gettime(CLOCK_REALTIME, &ts); hasher << ts.tv_sec << ts.tv_nsec; # endif # ifdef CLOCK_BOOTTIME clock_gettime(CLOCK_BOOTTIME, &ts); hasher << ts.tv_sec << ts.tv_nsec; # endif # else // On MacOS use mach_absolute_time (number of CPU ticks since boot) as a replacement for CLOCK_MONOTONIC, // and clock_get_time for CALENDAR_CLOCK as a replacement for CLOCK_REALTIME. hasher << mach_absolute_time(); // From https://gist.github.com/jbenet/1087739 clock_serv_t cclock; mach_timespec_t mts; if (host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock) == KERN_SUCCESS && clock_get_time(cclock, &mts) == KERN_SUCCESS) { hasher << mts.tv_sec << mts.tv_nsec; mach_port_deallocate(mach_task_self(), cclock); } # endif // gettimeofday is available on all UNIX systems, but only has microsecond precision. struct timeval tv; gettimeofday(&tv, nullptr); hasher << tv.tv_sec << tv.tv_usec; #endif // Probably redundant, but also use all the clocks C++11 provides: hasher << std::chrono::system_clock::now().time_since_epoch().count(); hasher << std::chrono::steady_clock::now().time_since_epoch().count(); hasher << std::chrono::high_resolution_clock::now().time_since_epoch().count(); } void RandAddStaticEnv(CSHA512& hasher) { #ifdef WIN32 hasher << GetCurrentProcessId() << GetCurrentThreadId(); #else hasher << getpid(); #endif hasher << std::this_thread::get_id(); }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <randomenv.h> #include <clientversion.h> #include <crypto/sha512.h> #include <support/cleanse.h> #include <util/time.h> // for GetTime() #ifdef WIN32 #include <compat.h> // for Windows API #endif #include <algorithm> #include <chrono> #include <climits> #include <thread> #include <vector> #include <stdint.h> #include <string.h> #ifndef WIN32 #include <sys/types.h> // must go before a number of other headers #include <fcntl.h> #include <netinet/in.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/utsname.h> #include <unistd.h> #endif #ifdef __MACH__ #include <mach/clock.h> #include <mach/mach.h> #include <mach/mach_time.h> #endif #if HAVE_DECL_GETIFADDRS #include <ifaddrs.h> #endif //! Necessary on some platforms extern char** environ; namespace { void RandAddSeedPerfmon(CSHA512& hasher) { #ifdef WIN32 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom // Seed with the entire set of perfmon data // This can take up to 2 seconds, so only do it every 10 minutes static int64_t nLastPerfmon; if (GetTime() < nLastPerfmon + 10 * 60) return; nLastPerfmon = GetTime(); std::vector<unsigned char> vData(250000, 0); long ret = 0; unsigned long nSize = 0; const size_t nMaxSize = 10000000; // Bail out at more than 10MB of performance data while (true) { nSize = vData.size(); ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", nullptr, nullptr, vData.data(), &nSize); if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize) break; vData.resize(std::max((vData.size() * 3) / 2, nMaxSize)); // Grow size of buffer exponentially } RegCloseKey(HKEY_PERFORMANCE_DATA); if (ret == ERROR_SUCCESS) { hasher.Write(vData.data(), nSize); memory_cleanse(vData.data(), nSize); } else { // Performance data is only a best-effort attempt at improving the // situation when the OS randomness (and other sources) aren't // adequate. As a result, failure to read it is isn't considered critical, // so we don't call RandFailure(). // TODO: Add logging when the logger is made functional before global // constructors have been invoked. } #endif } /** Helper to easily feed data into a CSHA512. * * Note that this does not serialize the passed object (like stream.h's << operators do). * Its raw memory representation is used directly. */ template<typename T> CSHA512& operator<<(CSHA512& hasher, const T& data) { static_assert(!std::is_same<typename std::decay<T>::type, char*>::value, "Calling operator<<(CSHA512, char*) is probably not what you want"); static_assert(!std::is_same<typename std::decay<T>::type, unsigned char*>::value, "Calling operator<<(CSHA512, unsigned char*) is probably not what you want"); static_assert(!std::is_same<typename std::decay<T>::type, const char*>::value, "Calling operator<<(CSHA512, const char*) is probably not what you want"); static_assert(!std::is_same<typename std::decay<T>::type, const unsigned char*>::value, "Calling operator<<(CSHA512, const unsigned char*) is probably not what you want"); hasher.Write((const unsigned char*)&data, sizeof(data)); return hasher; } #ifndef WIN32 void AddSockaddr(CSHA512& hasher, const struct sockaddr *addr) { if (addr == nullptr) return; switch (addr->sa_family) { case AF_INET: hasher.Write((const unsigned char*)addr, sizeof(sockaddr_in)); break; case AF_INET6: hasher.Write((const unsigned char*)addr, sizeof(sockaddr_in6)); break; default: hasher.Write((const unsigned char*)&addr->sa_family, sizeof(addr->sa_family)); } } void AddFile(CSHA512& hasher, const char *path) { struct stat sb = {}; int f = open(path, O_RDONLY); size_t total = 0; if (f != -1) { unsigned char fbuf[4096]; int n; hasher.Write((const unsigned char*)&f, sizeof(f)); if (fstat(f, &sb) == 0) hasher << sb; do { n = read(f, fbuf, sizeof(fbuf)); if (n > 0) hasher.Write(fbuf, n); total += n; /* not bothering with EINTR handling. */ } while (n == sizeof(fbuf) && total < 1048576); // Read only the first 1 Mbyte close(f); } } void AddPath(CSHA512& hasher, const char *path) { struct stat sb = {}; if (stat(path, &sb) == 0) { hasher.Write((const unsigned char*)path, strlen(path) + 1); hasher << sb; } } #endif } // namespace void RandAddDynamicEnv(CSHA512& hasher) { RandAddSeedPerfmon(hasher); // Various clocks #ifdef WIN32 FILETIME ftime; GetSystemTimeAsFileTime(&ftime); hasher << ftime; #else # ifndef __MACH__ // On non-MacOS systems, use various clock_gettime() calls. struct timespec ts = {}; # ifdef CLOCK_MONOTONIC clock_gettime(CLOCK_MONOTONIC, &ts); hasher << ts; # endif # ifdef CLOCK_REALTIME clock_gettime(CLOCK_REALTIME, &ts); hasher << ts; # endif # ifdef CLOCK_BOOTTIME clock_gettime(CLOCK_BOOTTIME, &ts); hasher << ts; # endif # else // On MacOS use mach_absolute_time (number of CPU ticks since boot) as a replacement for CLOCK_MONOTONIC, // and clock_get_time for CALENDAR_CLOCK as a replacement for CLOCK_REALTIME. hasher << mach_absolute_time(); // From https://gist.github.com/jbenet/1087739 clock_serv_t cclock; mach_timespec_t mts = {}; if (host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock) == KERN_SUCCESS && clock_get_time(cclock, &mts) == KERN_SUCCESS) { hasher << mts; mach_port_deallocate(mach_task_self(), cclock); } # endif // gettimeofday is available on all UNIX systems, but only has microsecond precision. struct timeval tv = {}; gettimeofday(&tv, nullptr); hasher << tv; #endif // Probably redundant, but also use all the clocks C++11 provides: hasher << std::chrono::system_clock::now().time_since_epoch().count(); hasher << std::chrono::steady_clock::now().time_since_epoch().count(); hasher << std::chrono::high_resolution_clock::now().time_since_epoch().count(); #ifndef WIN32 // Current resource usage. struct rusage usage = {}; if (getrusage(RUSAGE_SELF, &usage) == 0) hasher << usage; #endif #ifdef __linux__ AddFile(hasher, "/proc/diskstats"); AddFile(hasher, "/proc/vmstat"); AddFile(hasher, "/proc/schedstat"); AddFile(hasher, "/proc/zoneinfo"); AddFile(hasher, "/proc/meminfo"); AddFile(hasher, "/proc/softirqs"); AddFile(hasher, "/proc/stat"); AddFile(hasher, "/proc/self/schedstat"); AddFile(hasher, "/proc/self/status"); #endif // Stack and heap location void* addr = malloc(4097); hasher << &addr << addr; free(addr); } void RandAddStaticEnv(CSHA512& hasher) { // Some compile-time static properties hasher << (CHAR_MIN < 0) << sizeof(void*) << sizeof(long) << sizeof(int); #if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) hasher << __GNUC__ << __GNUC_MINOR__ << __GNUC_PATCHLEVEL__; #endif #ifdef _MSC_VER hasher << _MSC_VER; #endif hasher << __cplusplus; #ifdef _XOPEN_VERSION hasher << _XOPEN_VERSION; #endif #ifdef __VERSION__ const char* COMPILER_VERSION = __VERSION__; hasher.Write((const unsigned char*)COMPILER_VERSION, strlen(COMPILER_VERSION) + 1); #endif // Bitcoin client version hasher << CLIENT_VERSION; // Memory locations hasher << &hasher << &RandAddStaticEnv << &malloc << &errno << &environ; // Hostname char hname[256]; if (gethostname(hname, 256) == 0) { hasher.Write((const unsigned char*)hname, strnlen(hname, 256)); } #if HAVE_DECL_GETIFADDRS // Network interfaces struct ifaddrs *ifad = NULL; getifaddrs(&ifad); struct ifaddrs *ifit = ifad; while (ifit != NULL) { hasher.Write((const unsigned char*)&ifit, sizeof(ifit)); hasher.Write((const unsigned char*)ifit->ifa_name, strlen(ifit->ifa_name) + 1); hasher.Write((const unsigned char*)&ifit->ifa_flags, sizeof(ifit->ifa_flags)); AddSockaddr(hasher, ifit->ifa_addr); AddSockaddr(hasher, ifit->ifa_netmask); AddSockaddr(hasher, ifit->ifa_dstaddr); ifit = ifit->ifa_next; } freeifaddrs(ifad); #endif #ifndef WIN32 // UNIX kernel information struct utsname name; if (uname(&name) != -1) { hasher.Write((const unsigned char*)&name.sysname, strlen(name.sysname) + 1); hasher.Write((const unsigned char*)&name.nodename, strlen(name.nodename) + 1); hasher.Write((const unsigned char*)&name.release, strlen(name.release) + 1); hasher.Write((const unsigned char*)&name.version, strlen(name.version) + 1); hasher.Write((const unsigned char*)&name.machine, strlen(name.machine) + 1); } /* Path and filesystem provided data */ AddPath(hasher, "/"); AddPath(hasher, "."); AddPath(hasher, "/tmp"); AddPath(hasher, "/home"); AddPath(hasher, "/proc"); #ifdef __linux__ AddFile(hasher, "/proc/cmdline"); AddFile(hasher, "/proc/cpuinfo"); AddFile(hasher, "/proc/version"); #endif AddFile(hasher, "/etc/passwd"); AddFile(hasher, "/etc/group"); AddFile(hasher, "/etc/hosts"); AddFile(hasher, "/etc/resolv.conf"); AddFile(hasher, "/etc/timezone"); AddFile(hasher, "/etc/localtime"); /* TODO: sysctl's for OSX to fetch information not available from /proc */ #endif // Env variables if (environ) { for (size_t i = 0; environ[i]; ++i) { hasher.Write((const unsigned char*)environ[i], strlen(environ[i])); } } // Process, thread, user, session, group, ... ids. #ifdef WIN32 hasher << GetCurrentProcessId() << GetCurrentThreadId(); #else hasher << getpid() << getppid() << getsid(0) << getpgid(0) << getuid() << geteuid() << getgid() << getegid(); #endif hasher << std::this_thread::get_id(); }
Gather additional entropy from the environment
Gather additional entropy from the environment This based on code by Gregory Maxwell.
C++
mit
AkioNak/bitcoin,rnicoll/bitcoin,GroestlCoin/GroestlCoin,MeshCollider/bitcoin,jonasschnelli/bitcoin,jlopp/statoshi,MarcoFalke/bitcoin,monacoinproject/monacoin,sstone/bitcoin,Sjors/bitcoin,monacoinproject/monacoin,pstratem/bitcoin,mruddy/bitcoin,sipsorcery/bitcoin,apoelstra/bitcoin,ahmedbodi/vertcoin,fujicoin/fujicoin,domob1812/bitcoin,cdecker/bitcoin,yenliangl/bitcoin,litecoin-project/litecoin,domob1812/namecore,mm-s/bitcoin,n1bor/bitcoin,JeremyRubin/bitcoin,prusnak/bitcoin,bitcoin/bitcoin,namecoin/namecore,tjps/bitcoin,DigitalPandacoin/pandacoin,rnicoll/dogecoin,MeshCollider/bitcoin,peercoin/peercoin,dscotese/bitcoin,Xekyo/bitcoin,jnewbery/bitcoin,monacoinproject/monacoin,mitchellcash/bitcoin,rnicoll/bitcoin,anditto/bitcoin,fanquake/bitcoin,pataquets/namecoin-core,rnicoll/dogecoin,midnightmagic/bitcoin,GroestlCoin/GroestlCoin,andreaskern/bitcoin,andreaskern/bitcoin,GroestlCoin/bitcoin,anditto/bitcoin,kallewoof/bitcoin,EthanHeilman/bitcoin,peercoin/peercoin,jnewbery/bitcoin,domob1812/namecore,particl/particl-core,ElementsProject/elements,bitcoinknots/bitcoin,GroestlCoin/GroestlCoin,instagibbs/bitcoin,Xekyo/bitcoin,particl/particl-core,achow101/bitcoin,yenliangl/bitcoin,cdecker/bitcoin,achow101/bitcoin,ElementsProject/elements,AkioNak/bitcoin,qtumproject/qtum,jambolo/bitcoin,peercoin/peercoin,namecoin/namecore,DigitalPandacoin/pandacoin,apoelstra/bitcoin,domob1812/namecore,practicalswift/bitcoin,GroestlCoin/GroestlCoin,tecnovert/particl-core,peercoin/peercoin,midnightmagic/bitcoin,prusnak/bitcoin,domob1812/bitcoin,litecoin-project/litecoin,DigitalPandacoin/pandacoin,sipsorcery/bitcoin,ahmedbodi/vertcoin,GroestlCoin/bitcoin,kallewoof/bitcoin,tjps/bitcoin,bitcoinsSG/bitcoin,achow101/bitcoin,qtumproject/qtum,sipsorcery/bitcoin,cdecker/bitcoin,GroestlCoin/bitcoin,jambolo/bitcoin,cdecker/bitcoin,vertcoin/vertcoin,MarcoFalke/bitcoin,achow101/bitcoin,tjps/bitcoin,fujicoin/fujicoin,alecalve/bitcoin,JeremyRubin/bitcoin,apoelstra/bitcoin,monacoinproject/monacoin,DigitalPandacoin/pandacoin,peercoin/peercoin,practicalswift/bitcoin,MarcoFalke/bitcoin,EthanHeilman/bitcoin,sipsorcery/bitcoin,dscotese/bitcoin,anditto/bitcoin,mruddy/bitcoin,ajtowns/bitcoin,gjhiggins/vcoincore,GroestlCoin/bitcoin,instagibbs/bitcoin,vertcoin/vertcoin,Xekyo/bitcoin,ElementsProject/elements,namecoin/namecore,ElementsProject/elements,AkioNak/bitcoin,rnicoll/dogecoin,instagibbs/bitcoin,particl/particl-core,sstone/bitcoin,rnicoll/dogecoin,ajtowns/bitcoin,kallewoof/bitcoin,gjhiggins/vcoincore,jonasschnelli/bitcoin,mm-s/bitcoin,dscotese/bitcoin,mruddy/bitcoin,midnightmagic/bitcoin,particl/particl-core,domob1812/bitcoin,litecoin-project/litecoin,andreaskern/bitcoin,Sjors/bitcoin,litecoin-project/litecoin,vertcoin/vertcoin,fanquake/bitcoin,jamesob/bitcoin,tecnovert/particl-core,monacoinproject/monacoin,practicalswift/bitcoin,JeremyRubin/bitcoin,kallewoof/bitcoin,andreaskern/bitcoin,midnightmagic/bitcoin,GroestlCoin/GroestlCoin,n1bor/bitcoin,tjps/bitcoin,fanquake/bitcoin,jlopp/statoshi,vertcoin/vertcoin,rnicoll/bitcoin,Xekyo/bitcoin,mitchellcash/bitcoin,Sjors/bitcoin,lateminer/bitcoin,sstone/bitcoin,fujicoin/fujicoin,alecalve/bitcoin,apoelstra/bitcoin,pataquets/namecoin-core,particl/particl-core,qtumproject/qtum,jambolo/bitcoin,MarcoFalke/bitcoin,tjps/bitcoin,bitcoinsSG/bitcoin,qtumproject/qtum,pataquets/namecoin-core,sstone/bitcoin,prusnak/bitcoin,jamesob/bitcoin,jlopp/statoshi,AkioNak/bitcoin,GroestlCoin/bitcoin,anditto/bitcoin,n1bor/bitcoin,EthanHeilman/bitcoin,bitcoinknots/bitcoin,cdecker/bitcoin,namecoin/namecoin-core,namecoin/namecoin-core,gjhiggins/vcoincore,lateminer/bitcoin,mitchellcash/bitcoin,rnicoll/dogecoin,prusnak/bitcoin,jlopp/statoshi,kallewoof/bitcoin,mm-s/bitcoin,gjhiggins/vcoincore,MarcoFalke/bitcoin,practicalswift/bitcoin,gjhiggins/vcoincore,tjps/bitcoin,domob1812/bitcoin,anditto/bitcoin,jambolo/bitcoin,domob1812/namecore,sipsorcery/bitcoin,bitcoinknots/bitcoin,monacoinproject/monacoin,fujicoin/fujicoin,alecalve/bitcoin,qtumproject/qtum,jonasschnelli/bitcoin,ElementsProject/elements,yenliangl/bitcoin,mitchellcash/bitcoin,sipsorcery/bitcoin,Sjors/bitcoin,DigitalPandacoin/pandacoin,bitcoin/bitcoin,sstone/bitcoin,domob1812/bitcoin,namecoin/namecore,jlopp/statoshi,GroestlCoin/GroestlCoin,AkioNak/bitcoin,bitcoinsSG/bitcoin,midnightmagic/bitcoin,ajtowns/bitcoin,vertcoin/vertcoin,lateminer/bitcoin,litecoin-project/litecoin,mitchellcash/bitcoin,lateminer/bitcoin,andreaskern/bitcoin,Xekyo/bitcoin,EthanHeilman/bitcoin,instagibbs/bitcoin,namecoin/namecoin-core,dscotese/bitcoin,anditto/bitcoin,tecnovert/particl-core,jambolo/bitcoin,apoelstra/bitcoin,MeshCollider/bitcoin,practicalswift/bitcoin,cdecker/bitcoin,prusnak/bitcoin,MeshCollider/bitcoin,yenliangl/bitcoin,n1bor/bitcoin,pstratem/bitcoin,midnightmagic/bitcoin,ahmedbodi/vertcoin,sstone/bitcoin,bitcoin/bitcoin,ajtowns/bitcoin,jamesob/bitcoin,JeremyRubin/bitcoin,ajtowns/bitcoin,bitcoin/bitcoin,namecoin/namecore,pataquets/namecoin-core,pstratem/bitcoin,vertcoin/vertcoin,namecoin/namecoin-core,prusnak/bitcoin,yenliangl/bitcoin,mruddy/bitcoin,bitcoinknots/bitcoin,achow101/bitcoin,EthanHeilman/bitcoin,JeremyRubin/bitcoin,rnicoll/bitcoin,lateminer/bitcoin,yenliangl/bitcoin,mruddy/bitcoin,dscotese/bitcoin,ahmedbodi/vertcoin,fanquake/bitcoin,kallewoof/bitcoin,jonasschnelli/bitcoin,mm-s/bitcoin,bitcoin/bitcoin,qtumproject/qtum,bitcoinsSG/bitcoin,EthanHeilman/bitcoin,JeremyRubin/bitcoin,jnewbery/bitcoin,rnicoll/bitcoin,pstratem/bitcoin,instagibbs/bitcoin,domob1812/namecore,jambolo/bitcoin,instagibbs/bitcoin,andreaskern/bitcoin,MeshCollider/bitcoin,fujicoin/fujicoin,Xekyo/bitcoin,jamesob/bitcoin,DigitalPandacoin/pandacoin,jnewbery/bitcoin,n1bor/bitcoin,domob1812/bitcoin,gjhiggins/vcoincore,dscotese/bitcoin,n1bor/bitcoin,pstratem/bitcoin,namecoin/namecore,pataquets/namecoin-core,pstratem/bitcoin,AkioNak/bitcoin,jlopp/statoshi,jamesob/bitcoin,mm-s/bitcoin,practicalswift/bitcoin,tecnovert/particl-core,mitchellcash/bitcoin,MarcoFalke/bitcoin,alecalve/bitcoin,litecoin-project/litecoin,fanquake/bitcoin,rnicoll/bitcoin,alecalve/bitcoin,lateminer/bitcoin,fanquake/bitcoin,pataquets/namecoin-core,achow101/bitcoin,MeshCollider/bitcoin,jnewbery/bitcoin,apoelstra/bitcoin,ahmedbodi/vertcoin,Sjors/bitcoin,alecalve/bitcoin,bitcoinsSG/bitcoin,particl/particl-core,bitcoinsSG/bitcoin,ahmedbodi/vertcoin,peercoin/peercoin,tecnovert/particl-core,bitcoinknots/bitcoin,ajtowns/bitcoin,jonasschnelli/bitcoin,namecoin/namecoin-core,tecnovert/particl-core,mruddy/bitcoin,qtumproject/qtum,ElementsProject/elements,domob1812/namecore,fujicoin/fujicoin,jamesob/bitcoin,namecoin/namecoin-core,GroestlCoin/bitcoin,mm-s/bitcoin,bitcoin/bitcoin
50a544f354d770744bc18c0c30d5db86b7fcdaaf
include/dll/watcher.hpp
include/dll/watcher.hpp
//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include <fstream> #include <sys/stat.h> #include "cpp_utils/stop_watch.hpp" #include "trainer/rbm_training_context.hpp" #include "layer_traits.hpp" #include "dbn_traits.hpp" namespace dll { template <typename R> struct default_rbm_watcher { cpp::stop_watch<std::chrono::seconds> watch; template <typename RBM = R> void training_begin(const RBM& rbm) { using rbm_t = std::decay_t<RBM>; std::cout << "Train RBM with \"" << RBM::desc::template trainer_t<RBM, false>::name() << "\"" << std::endl; rbm.display(); std::cout << "With parameters:" << std::endl; if(std::is_same<typename rbm_t::weight, float>::value){ std::cout << " single-precision" << std::endl; } else if(std::is_same<typename rbm_t::weight, double>::value){ std::cout << " double-precision" << std::endl; } else { std::cout << " unknown-precision (something is wrong...)" << std::endl; } std::cout << " learning_rate=" << rbm.learning_rate << std::endl; std::cout << " batch_size=" << get_batch_size(rbm) << std::endl; if (layer_traits<RBM>::has_momentum()) { std::cout << " momentum=" << rbm.momentum << std::endl; } if (w_decay(layer_traits<RBM>::decay()) == decay_type::L1 || w_decay(layer_traits<RBM>::decay()) == decay_type::L1L2) { std::cout << " weight_cost(L1)=" << rbm.l1_weight_cost << std::endl; } if (w_decay(layer_traits<RBM>::decay()) == decay_type::L2 || w_decay(layer_traits<RBM>::decay()) == decay_type::L1L2) { std::cout << " weight_cost(L2)=" << rbm.l2_weight_cost << std::endl; } if (layer_traits<RBM>::sparsity_method() == sparsity_method::LEE) { std::cout << " Sparsity (Lee): pbias=" << rbm.pbias << std::endl; std::cout << " Sparsity (Lee): pbias_lambda=" << rbm.pbias_lambda << std::endl; } else if (layer_traits<RBM>::sparsity_method() == sparsity_method::GLOBAL_TARGET) { std::cout << " sparsity_target(Global)=" << rbm.sparsity_target << std::endl; } else if (layer_traits<RBM>::sparsity_method() == sparsity_method::LOCAL_TARGET) { std::cout << " sparsity_target(Local)=" << rbm.sparsity_target << std::endl; } } template <typename RBM = R> void epoch_end(std::size_t epoch, const rbm_training_context& context, const RBM& /*rbm*/) { char formatted[1024]; if (layer_traits<RBM>::free_energy()) { snprintf(formatted, 1024, "epoch %ld - Reconstruction error: %.5f - Free energy: %.3f - Sparsity: %.5f", epoch, context.reconstruction_error, context.free_energy, context.sparsity); } else { snprintf(formatted, 1024, "epoch %ld - Reconstruction error: %.5f - Sparsity: %.5f", epoch, context.reconstruction_error, context.sparsity); } std::cout << formatted << std::endl; } template <typename RBM = R> void batch_end(const RBM& /* rbm */, const rbm_training_context& context, std::size_t batch, std::size_t batches) { char formatted[1024]; sprintf(formatted, "Batch %ld/%ld - Reconstruction error: %.5f - Sparsity: %.5f", batch, batches, context.batch_error, context.batch_sparsity); std::cout << formatted << std::endl; } template <typename RBM = R> void training_end(const RBM&) { std::cout << "Training took " << watch.elapsed() << "s" << std::endl; } }; template <typename DBN> struct default_dbn_watcher { static constexpr const bool ignore_sub = false; static constexpr const bool replace_sub = false; cpp::stop_watch<std::chrono::seconds> watch; void pretraining_begin(const DBN& /*dbn*/, std::size_t max_epochs) { std::cout << "DBN: Pretraining begin for " << max_epochs << " epochs" << std::endl; } template <typename RBM> void pretrain_layer(const DBN& /*dbn*/, std::size_t I, const RBM& rbm, std::size_t input_size) { if (input_size) { std::cout << "DBN: Pretrain layer " << I << " (" << rbm.to_short_string() << ") with " << input_size << " entries" << std::endl; } else { std::cout << "DBN: Pretrain layer " << I << " (" << rbm.to_short_string() << ")" << std::endl; } } void pretraining_end(const DBN& /*dbn*/) { std::cout << "DBN: Pretraining finished after " << watch.elapsed() << "s" << std::endl; } void pretraining_batch(const DBN& /*dbn*/, std::size_t batch) { std::cout << "DBN: Pretraining batch " << batch << std::endl; } void fine_tuning_begin(const DBN& dbn) { std::cout << "Train DBN with \"" << DBN::desc::template trainer_t<DBN>::name() << "\"" << std::endl; std::cout << "With parameters:" << std::endl; std::cout << " learning_rate=" << dbn.learning_rate << std::endl; if (dbn_traits<DBN>::has_momentum()) { std::cout << " momentum=" << dbn.momentum << std::endl; } if (w_decay(dbn_traits<DBN>::decay()) == decay_type::L1 || w_decay(dbn_traits<DBN>::decay()) == decay_type::L1L2) { std::cout << " weight_cost(L1)=" << dbn.l1_weight_cost << std::endl; } if (w_decay(dbn_traits<DBN>::decay()) == decay_type::L2 || w_decay(dbn_traits<DBN>::decay()) == decay_type::L1L2) { std::cout << " weight_cost(L2)=" << dbn.l2_weight_cost << std::endl; } if (dbn_traits<DBN>::lr_driver() == lr_driver_type::BOLD) { std::cout << " lr_driver(BOLD)=" << dbn.lr_bold_inc << ":" << dbn.lr_bold_dec << std::endl; } if (dbn_traits<DBN>::lr_driver() == lr_driver_type::STEP) { std::cout << " lr_driver(STEP)=" << dbn.lr_step_size << ":" << dbn.lr_step_gamma << std::endl; } } void ft_epoch_end(std::size_t epoch, double error, double loss, const DBN&) { char formatted[1024]; snprintf(formatted, 1024, "epoch %ld - Classification error: %.5f Loss: %.5f", epoch, error, loss); std::cout << formatted << std::endl; } void ft_batch_end(size_t epoch, size_t batch, size_t batches, double batch_error, double batch_loss, double error, const DBN&) { char formatted[1024]; snprintf(formatted, 1024, "epoch %ld:%ld/%ld- B. Error: %.5f B. Loss: %.5f Set: %.5f", epoch, batch, batches, batch_error, batch_loss, error); std::cout << formatted << std::endl; } void ft_batch_end(size_t epoch, double batch_error, double batch_loss, double error, const DBN&) { char formatted[1024]; snprintf(formatted, 1024, "epoch %ld - B.Error: %.5f B.Loss: %.5f Set: %.5f", epoch, batch_error, batch_loss, error); std::cout << formatted << std::endl; } void lr_adapt(const DBN& dbn) { char formatted[1024]; snprintf(formatted, 1024, "driver: learning rate adapted to %.5f", dbn.learning_rate); std::cout << formatted << std::endl; } void fine_tuning_end(const DBN&) { std::cout << "Training took " << watch.elapsed() << "s" << std::endl; } }; template <typename DBN> struct silent_dbn_watcher : default_dbn_watcher<DBN> { static constexpr const bool ignore_sub = true; static constexpr const bool replace_sub = false; }; template <typename DBN> struct mute_dbn_watcher { static constexpr const bool ignore_sub = true; static constexpr const bool replace_sub = false; void pretraining_begin(const DBN& /*dbn*/, std::size_t /*max_epochs*/) {} template <typename RBM> void pretrain_layer(const DBN& /*dbn*/, std::size_t /*I*/, const RBM& /*rbm*/, std::size_t /*input_size*/) {} void pretraining_end(const DBN& /*dbn*/) {} void pretraining_batch(const DBN& /*dbn*/, std::size_t /*batch*/) {} void fine_tuning_begin(const DBN& /*dbn*/) {} void ft_epoch_end(std::size_t /*epoch*/, double /*error*/, const DBN& /*dbn*/) {} void ft_batch_end(size_t /*epoch*/, size_t /*batch*/, size_t /*batches*/, double /*batch_error*/, double /*error*/, const DBN& /*dbn*/) {} void ft_batch_end(size_t /*epoch*/, double /*batch_error*/, double /*error*/, const DBN& /*dbn*/) {} void lr_adapt(const DBN& /*dbn*/) {} void fine_tuning_end(const DBN& /*dbn*/) {} }; //TODO This is currently useless template <typename R> struct histogram_watcher { default_rbm_watcher<R> parent; template <typename RBM = R> void training_begin(const RBM& rbm) { parent.training_begin(rbm); } template <typename RBM = R> void epoch_end(std::size_t epoch, double error, double /*free_energy*/, const RBM& rbm) { parent.epoch_end(epoch, error, rbm); } template <typename RBM = R> void batch_end(const RBM& rbm, const rbm_training_context& context, std::size_t batch, std::size_t batches) { parent.batch_end(rbm, context, batch, batches); } template <typename RBM = R> void training_end(const RBM& rbm) { parent.training_end(rbm); } void generate_hidden_images(std::size_t epoch, const R& rbm) { mkdir("reports", 0777); auto folder = "reports/epoch_" + std::to_string(epoch); mkdir(folder.c_str(), 0777); for (std::size_t j = 0; j < R::num_hidden; ++j) { auto path = folder + "/h_" + std::to_string(j) + ".dat"; std::ofstream file(path, std::ios::out); if (!file) { std::cout << "Could not open file " << path << std::endl; } else { std::size_t i = R::num_visible; while (i > 0) { --i; auto value = rbm.w(i, j); file << static_cast<std::size_t>(value > 0 ? static_cast<std::size_t>(value * 255.0) << 8 : static_cast<std::size_t>(-value * 255.0) << 16) << " "; } file << std::endl; file.close(); } } } void generate_histograms(std::size_t epoch, const R& rbm) { mkdir("reports", 0777); auto folder = "reports/epoch_" + std::to_string(epoch); mkdir(folder.c_str(), 0777); generate_histogram(folder + "/weights.dat", rbm.w); generate_histogram(folder + "/visibles.dat", rbm.a); generate_histogram(folder + "/hiddens.dat", rbm.b); } template <typename Container> void generate_histogram(const std::string& path, const Container& weights) { std::ofstream file(path, std::ios::out); if (!file) { std::cout << "Could not open file " << path << std::endl; } else { for (auto& weight : weights) { file << weight << std::endl; } file << std::endl; file.close(); } } }; } //end of dll namespace
//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include <fstream> #include <sys/stat.h> #include "cpp_utils/stop_watch.hpp" #include "trainer/rbm_training_context.hpp" #include "layer_traits.hpp" #include "dbn_traits.hpp" namespace dll { template <typename R> struct default_rbm_watcher { cpp::stop_watch<std::chrono::seconds> watch; template <typename RBM = R> void training_begin(const RBM& rbm) { using rbm_t = std::decay_t<RBM>; std::cout << "Train RBM with \"" << RBM::desc::template trainer_t<RBM, false>::name() << "\"" << std::endl; rbm.display(); std::cout << "With parameters:" << std::endl; if(std::is_same<typename rbm_t::weight, float>::value){ std::cout << " single-precision" << std::endl; } else if(std::is_same<typename rbm_t::weight, double>::value){ std::cout << " double-precision" << std::endl; } else { std::cout << " unknown-precision (something is wrong...)" << std::endl; } std::cout << " learning_rate=" << rbm.learning_rate << std::endl; std::cout << " batch_size=" << get_batch_size(rbm) << std::endl; if (layer_traits<RBM>::has_momentum()) { std::cout << " momentum=" << rbm.momentum << std::endl; } if (layer_traits<RBM>::has_clip_gradients()) { std::cout << " gradient clip=" << rbm.gradient_clip << std::endl; } if (w_decay(layer_traits<RBM>::decay()) == decay_type::L1 || w_decay(layer_traits<RBM>::decay()) == decay_type::L1L2) { std::cout << " weight_cost(L1)=" << rbm.l1_weight_cost << std::endl; } if (w_decay(layer_traits<RBM>::decay()) == decay_type::L2 || w_decay(layer_traits<RBM>::decay()) == decay_type::L1L2) { std::cout << " weight_cost(L2)=" << rbm.l2_weight_cost << std::endl; } if (layer_traits<RBM>::sparsity_method() == sparsity_method::LEE) { std::cout << " Sparsity (Lee): pbias=" << rbm.pbias << std::endl; std::cout << " Sparsity (Lee): pbias_lambda=" << rbm.pbias_lambda << std::endl; } else if (layer_traits<RBM>::sparsity_method() == sparsity_method::GLOBAL_TARGET) { std::cout << " sparsity_target(Global)=" << rbm.sparsity_target << std::endl; } else if (layer_traits<RBM>::sparsity_method() == sparsity_method::LOCAL_TARGET) { std::cout << " sparsity_target(Local)=" << rbm.sparsity_target << std::endl; } } template <typename RBM = R> void epoch_end(std::size_t epoch, const rbm_training_context& context, const RBM& /*rbm*/) { char formatted[1024]; if (layer_traits<RBM>::free_energy()) { snprintf(formatted, 1024, "epoch %ld - Reconstruction error: %.5f - Free energy: %.3f - Sparsity: %.5f", epoch, context.reconstruction_error, context.free_energy, context.sparsity); } else { snprintf(formatted, 1024, "epoch %ld - Reconstruction error: %.5f - Sparsity: %.5f", epoch, context.reconstruction_error, context.sparsity); } std::cout << formatted << std::endl; } template <typename RBM = R> void batch_end(const RBM& /* rbm */, const rbm_training_context& context, std::size_t batch, std::size_t batches) { char formatted[1024]; sprintf(formatted, "Batch %ld/%ld - Reconstruction error: %.5f - Sparsity: %.5f", batch, batches, context.batch_error, context.batch_sparsity); std::cout << formatted << std::endl; } template <typename RBM = R> void training_end(const RBM&) { std::cout << "Training took " << watch.elapsed() << "s" << std::endl; } }; template <typename DBN> struct default_dbn_watcher { static constexpr const bool ignore_sub = false; static constexpr const bool replace_sub = false; cpp::stop_watch<std::chrono::seconds> watch; void pretraining_begin(const DBN& /*dbn*/, std::size_t max_epochs) { std::cout << "DBN: Pretraining begin for " << max_epochs << " epochs" << std::endl; } template <typename RBM> void pretrain_layer(const DBN& /*dbn*/, std::size_t I, const RBM& rbm, std::size_t input_size) { if (input_size) { std::cout << "DBN: Pretrain layer " << I << " (" << rbm.to_short_string() << ") with " << input_size << " entries" << std::endl; } else { std::cout << "DBN: Pretrain layer " << I << " (" << rbm.to_short_string() << ")" << std::endl; } } void pretraining_end(const DBN& /*dbn*/) { std::cout << "DBN: Pretraining finished after " << watch.elapsed() << "s" << std::endl; } void pretraining_batch(const DBN& /*dbn*/, std::size_t batch) { std::cout << "DBN: Pretraining batch " << batch << std::endl; } void fine_tuning_begin(const DBN& dbn) { std::cout << "Train DBN with \"" << DBN::desc::template trainer_t<DBN>::name() << "\"" << std::endl; std::cout << "With parameters:" << std::endl; std::cout << " learning_rate=" << dbn.learning_rate << std::endl; if (dbn_traits<DBN>::has_momentum()) { std::cout << " momentum=" << dbn.momentum << std::endl; } if (w_decay(dbn_traits<DBN>::decay()) == decay_type::L1 || w_decay(dbn_traits<DBN>::decay()) == decay_type::L1L2) { std::cout << " weight_cost(L1)=" << dbn.l1_weight_cost << std::endl; } if (w_decay(dbn_traits<DBN>::decay()) == decay_type::L2 || w_decay(dbn_traits<DBN>::decay()) == decay_type::L1L2) { std::cout << " weight_cost(L2)=" << dbn.l2_weight_cost << std::endl; } if (dbn_traits<DBN>::lr_driver() == lr_driver_type::BOLD) { std::cout << " lr_driver(BOLD)=" << dbn.lr_bold_inc << ":" << dbn.lr_bold_dec << std::endl; } if (dbn_traits<DBN>::lr_driver() == lr_driver_type::STEP) { std::cout << " lr_driver(STEP)=" << dbn.lr_step_size << ":" << dbn.lr_step_gamma << std::endl; } } void ft_epoch_end(std::size_t epoch, double error, double loss, const DBN&) { char formatted[1024]; snprintf(formatted, 1024, "epoch %ld - Classification error: %.5f Loss: %.5f", epoch, error, loss); std::cout << formatted << std::endl; } void ft_batch_end(size_t epoch, size_t batch, size_t batches, double batch_error, double batch_loss, double error, const DBN&) { char formatted[1024]; snprintf(formatted, 1024, "epoch %ld:%ld/%ld- B. Error: %.5f B. Loss: %.5f Set: %.5f", epoch, batch, batches, batch_error, batch_loss, error); std::cout << formatted << std::endl; } void ft_batch_end(size_t epoch, double batch_error, double batch_loss, double error, const DBN&) { char formatted[1024]; snprintf(formatted, 1024, "epoch %ld - B.Error: %.5f B.Loss: %.5f Set: %.5f", epoch, batch_error, batch_loss, error); std::cout << formatted << std::endl; } void lr_adapt(const DBN& dbn) { char formatted[1024]; snprintf(formatted, 1024, "driver: learning rate adapted to %.5f", dbn.learning_rate); std::cout << formatted << std::endl; } void fine_tuning_end(const DBN&) { std::cout << "Training took " << watch.elapsed() << "s" << std::endl; } }; template <typename DBN> struct silent_dbn_watcher : default_dbn_watcher<DBN> { static constexpr const bool ignore_sub = true; static constexpr const bool replace_sub = false; }; template <typename DBN> struct mute_dbn_watcher { static constexpr const bool ignore_sub = true; static constexpr const bool replace_sub = false; void pretraining_begin(const DBN& /*dbn*/, std::size_t /*max_epochs*/) {} template <typename RBM> void pretrain_layer(const DBN& /*dbn*/, std::size_t /*I*/, const RBM& /*rbm*/, std::size_t /*input_size*/) {} void pretraining_end(const DBN& /*dbn*/) {} void pretraining_batch(const DBN& /*dbn*/, std::size_t /*batch*/) {} void fine_tuning_begin(const DBN& /*dbn*/) {} void ft_epoch_end(std::size_t /*epoch*/, double /*error*/, const DBN& /*dbn*/) {} void ft_batch_end(size_t /*epoch*/, size_t /*batch*/, size_t /*batches*/, double /*batch_error*/, double /*error*/, const DBN& /*dbn*/) {} void ft_batch_end(size_t /*epoch*/, double /*batch_error*/, double /*error*/, const DBN& /*dbn*/) {} void lr_adapt(const DBN& /*dbn*/) {} void fine_tuning_end(const DBN& /*dbn*/) {} }; //TODO This is currently useless template <typename R> struct histogram_watcher { default_rbm_watcher<R> parent; template <typename RBM = R> void training_begin(const RBM& rbm) { parent.training_begin(rbm); } template <typename RBM = R> void epoch_end(std::size_t epoch, double error, double /*free_energy*/, const RBM& rbm) { parent.epoch_end(epoch, error, rbm); } template <typename RBM = R> void batch_end(const RBM& rbm, const rbm_training_context& context, std::size_t batch, std::size_t batches) { parent.batch_end(rbm, context, batch, batches); } template <typename RBM = R> void training_end(const RBM& rbm) { parent.training_end(rbm); } void generate_hidden_images(std::size_t epoch, const R& rbm) { mkdir("reports", 0777); auto folder = "reports/epoch_" + std::to_string(epoch); mkdir(folder.c_str(), 0777); for (std::size_t j = 0; j < R::num_hidden; ++j) { auto path = folder + "/h_" + std::to_string(j) + ".dat"; std::ofstream file(path, std::ios::out); if (!file) { std::cout << "Could not open file " << path << std::endl; } else { std::size_t i = R::num_visible; while (i > 0) { --i; auto value = rbm.w(i, j); file << static_cast<std::size_t>(value > 0 ? static_cast<std::size_t>(value * 255.0) << 8 : static_cast<std::size_t>(-value * 255.0) << 16) << " "; } file << std::endl; file.close(); } } } void generate_histograms(std::size_t epoch, const R& rbm) { mkdir("reports", 0777); auto folder = "reports/epoch_" + std::to_string(epoch); mkdir(folder.c_str(), 0777); generate_histogram(folder + "/weights.dat", rbm.w); generate_histogram(folder + "/visibles.dat", rbm.a); generate_histogram(folder + "/hiddens.dat", rbm.b); } template <typename Container> void generate_histogram(const std::string& path, const Container& weights) { std::ofstream file(path, std::ios::out); if (!file) { std::cout << "Could not open file " << path << std::endl; } else { for (auto& weight : weights) { file << weight << std::endl; } file << std::endl; file.close(); } } }; } //end of dll namespace
Update the display for gradient clipping
Update the display for gradient clipping
C++
mit
wichtounet/dll,wichtounet/dll,wichtounet/dll
49356220cf6ddb32536bf49043913489becb4fdd
src/rapidjson.cpp
src/rapidjson.cpp
#include <limits> #include <cstdio> #include <vector> #include <algorithm> #include <lua.hpp> // __SSE2__ and __SSE4_2__ are recognized by gcc, clang, and the Intel compiler. // We use -march=native with gmake to enable -msse2 and -msse4.2, if supported. #if defined(__SSE4_2__) # define RAPIDJSON_SSE42 #elif defined(__SSE2__) # define RAPIDJSON_SSE2 #endif #include "rapidjson/document.h" #include "rapidjson/encodedstream.h" #include "rapidjson/error/en.h" #include "rapidjson/error/error.h" #include "rapidjson/filereadstream.h" #include "rapidjson/filewritestream.h" #include "rapidjson/prettywriter.h" #include "rapidjson/rapidjson.h" #include "rapidjson/reader.h" #include "rapidjson/schema.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "Userdata.hpp" #include "values.hpp" #include "luax.hpp" #include "file.hpp" #include "StringStream.hpp" using namespace rapidjson; #ifndef LUA_RAPIDJSON_VERSION #define LUA_RAPIDJSON_VERSION "scm" #endif static void createSharedMeta(lua_State* L, const char* meta, const char* type) { luaL_newmetatable(L, meta); // [meta] lua_pushstring(L, type); // [meta, name] lua_setfield(L, -2, "__jsontype"); // [meta] lua_pop(L, 1); // [] } static int makeTableType(lua_State* L, int idx, const char* meta, const char* type) { bool isnoarg = lua_isnoneornil(L, idx); bool istable = lua_istable(L, idx); if (!isnoarg && !istable) return luaL_argerror(L, idx, "optional table excepted"); if (isnoarg) lua_createtable(L, 0, 0); // [table] else // is table. { lua_pushvalue(L, idx); // [table] if (lua_getmetatable(L, -1)) { // already have a metatable, just set the __jsontype field. // [table, meta] lua_pushstring(L, type); // [table, meta, name] lua_setfield(L, -2, "__jsontype"); // [table, meta] lua_pop(L, 1); // [table] return 1; } // else fall through } // Now we have a table without meta table luaL_getmetatable(L, meta); // [table, meta] lua_setmetatable(L, -2); // [table] return 1; } static int json_object(lua_State* L) { return makeTableType(L, 1, "json.object", "object"); } static int json_array(lua_State* L) { return makeTableType(L, 1, "json.array", "array"); } template<typename Stream> int decode(lua_State* L, Stream* s) { int top = lua_gettop(L); values::ToLuaHandler handler(L); Reader reader; ParseResult r = reader.Parse(*s, handler); if (!r) { lua_settop(L, top); lua_pushnil(L); lua_pushfstring(L, "%s (%d)", GetParseError_En(r.Code()), r.Offset()); return 2; } return 1; } static int json_decode(lua_State* L) { size_t len = 0; const char* contents = nullptr; if (lua_type(L, 1) == LUA_TSTRING) { contents = luaL_checklstring(L, 1, &len); } else { contents = reinterpret_cast<const char*>(lua_touserdata(L, 1)); len = luaL_checkinteger(L, 2); } rapidjson::extend::StringStream s(contents, len); return decode(L, &s); } static int json_load(lua_State* L) { const char* filename = luaL_checklstring(L, 1, NULL); FILE* fp = file::open(filename, "rb"); if (fp == NULL) luaL_error(L, "error while open file: %s", filename); char buffer[512]; FileReadStream fs(fp, buffer, sizeof(buffer)); AutoUTFInputStream<unsigned, FileReadStream> eis(fs); int n = decode(L, &eis); fclose(fp); return n; } struct Key { Key(const char* k, SizeType l) : key(k), size(l) {} bool operator<(const Key& rhs) const { return strcmp(key, rhs.key) < 0; } const char* key; SizeType size; }; class Encoder { bool pretty; bool sort_keys; bool empty_table_as_array; int max_depth; static const int MAX_DEPTH_DEFAULT = 128; public: Encoder(lua_State*L, int opt) : pretty(false), sort_keys(false), empty_table_as_array(false), max_depth(MAX_DEPTH_DEFAULT) { if (lua_isnoneornil(L, opt)) return; luaL_checktype(L, opt, LUA_TTABLE); pretty = luax::optboolfield(L, opt, "pretty", false); sort_keys = luax::optboolfield(L, opt, "sort_keys", false); empty_table_as_array = luax::optboolfield(L, opt, "empty_table_as_array", false); max_depth = luax::optintfield(L, opt, "max_depth", MAX_DEPTH_DEFAULT); } private: template<typename Writer> void encodeValue(lua_State* L, Writer* writer, int idx, int depth = 0) { size_t len; const char* s; int64_t integer; int t = lua_type(L, idx); switch (t) { case LUA_TBOOLEAN: writer->Bool(lua_toboolean(L, idx) != 0); return; case LUA_TNUMBER: if (luax::isinteger(L, idx, &integer)) writer->Int64(integer); else { if (!writer->Double(lua_tonumber(L, idx))) luaL_error(L, "error while encode double value."); } return; case LUA_TSTRING: s = lua_tolstring(L, idx, &len); writer->String(s, static_cast<SizeType>(len)); return; case LUA_TTABLE: return encodeTable(L, writer, idx, depth + 1); case LUA_TNIL: writer->Null(); return; case LUA_TFUNCTION: if (values::isnull(L, idx)) { writer->Null(); return; } // otherwise fall thought case LUA_TLIGHTUSERDATA: // fall thought case LUA_TUSERDATA: // fall thought case LUA_TTHREAD: // fall thought case LUA_TNONE: // fall thought default: luaL_error(L, "value type : %s", lua_typename(L, t)); } } template<typename Writer> void encodeTable(lua_State* L, Writer* writer, int idx, int depth) { if (depth > max_depth) luaL_error(L, "nested too depth"); if (!lua_checkstack(L, 4)) // requires at least 4 slots in stack: table, key, value, key luaL_error(L, "stack overflow"); lua_pushvalue(L, idx); // [table] if (values::isarray(L, -1, empty_table_as_array)) { encodeArray(L, writer, depth); lua_pop(L, 1); // [] return; } // is object. if (!sort_keys) { encodeObject(L, writer, depth); lua_pop(L, 1); // [] return; } lua_pushnil(L); // [table, nil] std::vector<Key> keys; while (lua_next(L, -2)) { // [table, key, value] if (lua_type(L, -2) == LUA_TSTRING) { size_t len = 0; const char* key = lua_tolstring(L, -2, &len); keys.push_back(Key(key, static_cast<SizeType>(len))); } // pop value, leaving original key lua_pop(L, 1); // [table, key] } // [table] encodeObject(L, writer, depth, keys); lua_pop(L, 1); } template<typename Writer> void encodeObject(lua_State* L, Writer* writer, int depth) { writer->StartObject(); // [table] lua_pushnil(L); // [table, nil] while (lua_next(L, -2)) { // [table, key, value] if (lua_type(L, -2) == LUA_TSTRING) { size_t len = 0; const char* key = lua_tolstring(L, -2, &len); writer->Key(key, static_cast<SizeType>(len)); encodeValue(L, writer, -1, depth); } // pop value, leaving original key lua_pop(L, 1); // [table, key] } // [table] writer->EndObject(); } template<typename Writer> void encodeObject(lua_State* L, Writer* writer, int depth, std::vector<Key> &keys) { // [table] writer->StartObject(); std::sort(keys.begin(), keys.end()); std::vector<Key>::const_iterator i = keys.begin(); std::vector<Key>::const_iterator e = keys.end(); for (; i != e; ++i) { writer->Key(i->key, static_cast<SizeType>(i->size)); lua_pushlstring(L, i->key, i->size); // [table, key] lua_gettable(L, -2); // [table, value] encodeValue(L, writer, -1, depth); lua_pop(L, 1); // [table] } // [table] writer->EndObject(); } template<typename Writer> void encodeArray(lua_State* L, Writer* writer, int depth) { // [table] writer->StartArray(); int MAX = static_cast<int>(luax::rawlen(L, -1)); // lua_rawlen always returns value >= 0 for (int n = 1; n <= MAX; ++n) { lua_rawgeti(L, -1, n); // [table, element] encodeValue(L, writer, -1, depth); lua_pop(L, 1); // [table] } writer->EndArray(); // [table] } public: template<typename Stream> void encode(lua_State* L, Stream* s, int idx) { if (pretty) { PrettyWriter<Stream> writer(*s); encodeValue(L, &writer, idx); } else { Writer<Stream> writer(*s); encodeValue(L, &writer, idx); } } }; static int json_encode(lua_State* L) { try{ Encoder encode(L, 2); StringBuffer s; encode.encode(L, &s, 1); lua_pushlstring(L, s.GetString(), s.GetSize()); return 1; } catch (...) { luaL_error(L, "error while encoding"); } return 0; } static int json_dump(lua_State* L) { Encoder encoder(L, 3); const char* filename = luaL_checkstring(L, 2); FILE* fp = file::open(filename, "wb"); if (fp == NULL) luaL_error(L, "error while open file: %s", filename); char buffer[512]; FileWriteStream fs(fp, buffer, sizeof(buffer)); encoder.encode(L, &fs, 1); fclose(fp); return 0; } namespace values { static int nullref = LUA_NOREF; /** * Returns rapidjson.null. */ int json_null(lua_State* L) { lua_rawgeti(L, LUA_REGISTRYINDEX, nullref); return 1; } } static const luaL_Reg methods[] = { // string <--> lua table { "decode", json_decode }, { "encode", json_encode }, // file <--> lua table { "load", json_load }, { "dump", json_dump }, // special tags and functions { "null", values::json_null }, { "object", json_object }, { "array", json_array }, // JSON types { "Document", Userdata<Document>::create }, { "SchemaDocument", Userdata<SchemaDocument>::create }, { "SchemaValidator", Userdata<SchemaValidator>::create }, {NULL, NULL } }; extern "C" { LUALIB_API int luaopen_rapidjson(lua_State* L) { lua_newtable(L); // [rapidjson] luax::setfuncs(L, methods); // [rapidjson] lua_pushliteral(L, "rapidjson"); // [rapidjson, name] lua_setfield(L, -2, "_NAME"); // [rapidjson] lua_pushliteral(L, LUA_RAPIDJSON_VERSION); // [rapidjson, version] lua_setfield(L, -2, "_VERSION"); // [rapidjson] lua_getfield(L, -1, "null"); // [rapidjson, json.null] values::nullref = luaL_ref(L, LUA_REGISTRYINDEX); // [rapidjson] createSharedMeta(L, "json.object", "object"); createSharedMeta(L, "json.array", "array"); Userdata<Document>::luaopen(L); Userdata<SchemaDocument>::luaopen(L); Userdata<SchemaValidator>::luaopen(L); return 1; } }
#include <limits> #include <cstdio> #include <vector> #include <algorithm> #include <lua.hpp> // __SSE2__ and __SSE4_2__ are recognized by gcc, clang, and the Intel compiler. // We use -march=native with gmake to enable -msse2 and -msse4.2, if supported. #if defined(__SSE4_2__) # define RAPIDJSON_SSE42 #elif defined(__SSE2__) # define RAPIDJSON_SSE2 #endif #include "rapidjson/document.h" #include "rapidjson/encodedstream.h" #include "rapidjson/error/en.h" #include "rapidjson/error/error.h" #include "rapidjson/filereadstream.h" #include "rapidjson/filewritestream.h" #include "rapidjson/prettywriter.h" #include "rapidjson/rapidjson.h" #include "rapidjson/reader.h" #include "rapidjson/schema.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "Userdata.hpp" #include "values.hpp" #include "luax.hpp" #include "file.hpp" #include "StringStream.hpp" using namespace rapidjson; #ifndef LUA_RAPIDJSON_VERSION #define LUA_RAPIDJSON_VERSION "scm" #endif static void createSharedMeta(lua_State* L, const char* meta, const char* type) { luaL_newmetatable(L, meta); // [meta] lua_pushstring(L, type); // [meta, name] lua_setfield(L, -2, "__jsontype"); // [meta] lua_pop(L, 1); // [] } static int makeTableType(lua_State* L, int idx, const char* meta, const char* type) { bool isnoarg = lua_isnoneornil(L, idx); bool istable = lua_istable(L, idx); if (!isnoarg && !istable) return luaL_argerror(L, idx, "optional table excepted"); if (isnoarg) lua_createtable(L, 0, 0); // [table] else // is table. { lua_pushvalue(L, idx); // [table] if (lua_getmetatable(L, -1)) { // already have a metatable, just set the __jsontype field. // [table, meta] lua_pushstring(L, type); // [table, meta, name] lua_setfield(L, -2, "__jsontype"); // [table, meta] lua_pop(L, 1); // [table] return 1; } // else fall through } // Now we have a table without meta table luaL_getmetatable(L, meta); // [table, meta] lua_setmetatable(L, -2); // [table] return 1; } static int json_object(lua_State* L) { return makeTableType(L, 1, "json.object", "object"); } static int json_array(lua_State* L) { return makeTableType(L, 1, "json.array", "array"); } template<typename Stream> int decode(lua_State* L, Stream* s) { int top = lua_gettop(L); values::ToLuaHandler handler(L); Reader reader; ParseResult r = reader.Parse(*s, handler); if (!r) { lua_settop(L, top); lua_pushnil(L); lua_pushfstring(L, "%s (%d)", GetParseError_En(r.Code()), r.Offset()); return 2; } return 1; } static int json_decode(lua_State* L) { size_t len = 0; const char* contents = nullptr; switch(lua_type(L, 1)) { case LUA_TSTRING: contents = luaL_checklstring(L, 1, &len); break; case LUA_TLIGHTUSERDATA: contents = reinterpret_cast<const char*>(lua_touserdata(L, 1)); len = luaL_checkinteger(L, 2); break; default: return luaL_typerror(L, 1, "required string or lightuserdata (points to a memory of a string)"); } rapidjson::extend::StringStream s(contents, len); return decode(L, &s); } static int json_load(lua_State* L) { const char* filename = luaL_checklstring(L, 1, NULL); FILE* fp = file::open(filename, "rb"); if (fp == NULL) luaL_error(L, "error while open file: %s", filename); char buffer[512]; FileReadStream fs(fp, buffer, sizeof(buffer)); AutoUTFInputStream<unsigned, FileReadStream> eis(fs); int n = decode(L, &eis); fclose(fp); return n; } struct Key { Key(const char* k, SizeType l) : key(k), size(l) {} bool operator<(const Key& rhs) const { return strcmp(key, rhs.key) < 0; } const char* key; SizeType size; }; class Encoder { bool pretty; bool sort_keys; bool empty_table_as_array; int max_depth; static const int MAX_DEPTH_DEFAULT = 128; public: Encoder(lua_State*L, int opt) : pretty(false), sort_keys(false), empty_table_as_array(false), max_depth(MAX_DEPTH_DEFAULT) { if (lua_isnoneornil(L, opt)) return; luaL_checktype(L, opt, LUA_TTABLE); pretty = luax::optboolfield(L, opt, "pretty", false); sort_keys = luax::optboolfield(L, opt, "sort_keys", false); empty_table_as_array = luax::optboolfield(L, opt, "empty_table_as_array", false); max_depth = luax::optintfield(L, opt, "max_depth", MAX_DEPTH_DEFAULT); } private: template<typename Writer> void encodeValue(lua_State* L, Writer* writer, int idx, int depth = 0) { size_t len; const char* s; int64_t integer; int t = lua_type(L, idx); switch (t) { case LUA_TBOOLEAN: writer->Bool(lua_toboolean(L, idx) != 0); return; case LUA_TNUMBER: if (luax::isinteger(L, idx, &integer)) writer->Int64(integer); else { if (!writer->Double(lua_tonumber(L, idx))) luaL_error(L, "error while encode double value."); } return; case LUA_TSTRING: s = lua_tolstring(L, idx, &len); writer->String(s, static_cast<SizeType>(len)); return; case LUA_TTABLE: return encodeTable(L, writer, idx, depth + 1); case LUA_TNIL: writer->Null(); return; case LUA_TFUNCTION: if (values::isnull(L, idx)) { writer->Null(); return; } // otherwise fall thought case LUA_TLIGHTUSERDATA: // fall thought case LUA_TUSERDATA: // fall thought case LUA_TTHREAD: // fall thought case LUA_TNONE: // fall thought default: luaL_error(L, "value type : %s", lua_typename(L, t)); } } template<typename Writer> void encodeTable(lua_State* L, Writer* writer, int idx, int depth) { if (depth > max_depth) luaL_error(L, "nested too depth"); if (!lua_checkstack(L, 4)) // requires at least 4 slots in stack: table, key, value, key luaL_error(L, "stack overflow"); lua_pushvalue(L, idx); // [table] if (values::isarray(L, -1, empty_table_as_array)) { encodeArray(L, writer, depth); lua_pop(L, 1); // [] return; } // is object. if (!sort_keys) { encodeObject(L, writer, depth); lua_pop(L, 1); // [] return; } lua_pushnil(L); // [table, nil] std::vector<Key> keys; while (lua_next(L, -2)) { // [table, key, value] if (lua_type(L, -2) == LUA_TSTRING) { size_t len = 0; const char* key = lua_tolstring(L, -2, &len); keys.push_back(Key(key, static_cast<SizeType>(len))); } // pop value, leaving original key lua_pop(L, 1); // [table, key] } // [table] encodeObject(L, writer, depth, keys); lua_pop(L, 1); } template<typename Writer> void encodeObject(lua_State* L, Writer* writer, int depth) { writer->StartObject(); // [table] lua_pushnil(L); // [table, nil] while (lua_next(L, -2)) { // [table, key, value] if (lua_type(L, -2) == LUA_TSTRING) { size_t len = 0; const char* key = lua_tolstring(L, -2, &len); writer->Key(key, static_cast<SizeType>(len)); encodeValue(L, writer, -1, depth); } // pop value, leaving original key lua_pop(L, 1); // [table, key] } // [table] writer->EndObject(); } template<typename Writer> void encodeObject(lua_State* L, Writer* writer, int depth, std::vector<Key> &keys) { // [table] writer->StartObject(); std::sort(keys.begin(), keys.end()); std::vector<Key>::const_iterator i = keys.begin(); std::vector<Key>::const_iterator e = keys.end(); for (; i != e; ++i) { writer->Key(i->key, static_cast<SizeType>(i->size)); lua_pushlstring(L, i->key, i->size); // [table, key] lua_gettable(L, -2); // [table, value] encodeValue(L, writer, -1, depth); lua_pop(L, 1); // [table] } // [table] writer->EndObject(); } template<typename Writer> void encodeArray(lua_State* L, Writer* writer, int depth) { // [table] writer->StartArray(); int MAX = static_cast<int>(luax::rawlen(L, -1)); // lua_rawlen always returns value >= 0 for (int n = 1; n <= MAX; ++n) { lua_rawgeti(L, -1, n); // [table, element] encodeValue(L, writer, -1, depth); lua_pop(L, 1); // [table] } writer->EndArray(); // [table] } public: template<typename Stream> void encode(lua_State* L, Stream* s, int idx) { if (pretty) { PrettyWriter<Stream> writer(*s); encodeValue(L, &writer, idx); } else { Writer<Stream> writer(*s); encodeValue(L, &writer, idx); } } }; static int json_encode(lua_State* L) { try{ Encoder encode(L, 2); StringBuffer s; encode.encode(L, &s, 1); lua_pushlstring(L, s.GetString(), s.GetSize()); return 1; } catch (...) { luaL_error(L, "error while encoding"); } return 0; } static int json_dump(lua_State* L) { Encoder encoder(L, 3); const char* filename = luaL_checkstring(L, 2); FILE* fp = file::open(filename, "wb"); if (fp == NULL) luaL_error(L, "error while open file: %s", filename); char buffer[512]; FileWriteStream fs(fp, buffer, sizeof(buffer)); encoder.encode(L, &fs, 1); fclose(fp); return 0; } namespace values { static int nullref = LUA_NOREF; /** * Returns rapidjson.null. */ int json_null(lua_State* L) { lua_rawgeti(L, LUA_REGISTRYINDEX, nullref); return 1; } } static const luaL_Reg methods[] = { // string <--> lua table { "decode", json_decode }, { "encode", json_encode }, // file <--> lua table { "load", json_load }, { "dump", json_dump }, // special tags and functions { "null", values::json_null }, { "object", json_object }, { "array", json_array }, // JSON types { "Document", Userdata<Document>::create }, { "SchemaDocument", Userdata<SchemaDocument>::create }, { "SchemaValidator", Userdata<SchemaValidator>::create }, {NULL, NULL } }; extern "C" { LUALIB_API int luaopen_rapidjson(lua_State* L) { lua_newtable(L); // [rapidjson] luax::setfuncs(L, methods); // [rapidjson] lua_pushliteral(L, "rapidjson"); // [rapidjson, name] lua_setfield(L, -2, "_NAME"); // [rapidjson] lua_pushliteral(L, LUA_RAPIDJSON_VERSION); // [rapidjson, version] lua_setfield(L, -2, "_VERSION"); // [rapidjson] lua_getfield(L, -1, "null"); // [rapidjson, json.null] values::nullref = luaL_ref(L, LUA_REGISTRYINDEX); // [rapidjson] createSharedMeta(L, "json.object", "object"); createSharedMeta(L, "json.array", "array"); Userdata<Document>::luaopen(L); Userdata<SchemaDocument>::luaopen(L); Userdata<SchemaValidator>::luaopen(L); return 1; } }
Refactor json_decode.
Refactor json_decode.
C++
mit
xpol/lua-rapidjson,xpol/lua-rapidjson
f0072bf8b89e0280e5b86b721e37a3960227a24a
wsgi_boost/request_handlers.cpp
wsgi_boost/request_handlers.cpp
/* Request handlers for WSGI apps and static files Copyright (c) 2016 Roman Miroshnychenko <[email protected]> License: MIT, see License.txt */ #include "request_handlers.h" #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/gzip.hpp> #include <boost/iostreams/copy.hpp> #include <fstream> #include <iostream> #include <sstream> using namespace std; namespace py = boost::python; namespace fs = boost::filesystem; namespace sys = boost::system; namespace alg = boost::algorithm; namespace wsgi_boost { #pragma region StaticRequestHandler void StaticRequestHandler::handle() { const auto content_dir_path = fs::path{ m_request.content_dir }; if (!fs::exists(content_dir_path)) { m_response.send_mesage("500 Internal Server Error", "Error 500: Internal server error! Invalid content directory."); return; } if (m_request.method != "GET" && m_request.method != "HEAD") { m_response.send_mesage("405 Method Not Allowed"); return; } open_file(content_dir_path); } void StaticRequestHandler::open_file(const fs::path& content_dir_path) { fs::path path = content_dir_path; path /= boost::regex_replace(m_request.path, m_request.path_regex, ""); if (fs::exists(path)) { path = fs::canonical(path); // Checking if path is inside content_dir if (distance(content_dir_path.begin(), content_dir_path.end()) <= distance(path.begin(), path.end()) && equal(content_dir_path.begin(), content_dir_path.end(), path.begin())) { if (fs::is_directory(path)) { path /= "index.html"; } if (fs::exists(path) && fs::is_regular_file(path)) { ifstream ifs; ifs.open(path.string(), ifstream::in | ios::binary); if (ifs) { headers_type out_headers; out_headers.emplace_back("Cache-Control", m_cache_control); time_t last_modified = fs::last_write_time(path); out_headers.emplace_back("Last-Modified", time_to_header(last_modified)); string ims = m_request.get_header("If-Modified-Since"); if (ims != "" && header_to_time(ims) >= last_modified) { out_headers.emplace_back("Content-Length", "0"); m_response.send_header("304 Not Modified", out_headers, true); return; } string ext = path.extension().string(); string mime = get_mime(ext); out_headers.emplace_back("Content-Type", mime); if (m_request.use_gzip && is_compressable(ext) && m_request.check_header("Accept-Encoding", "gzip")) { boost::iostreams::filtering_istream gzstream; gzstream.push(boost::iostreams::gzip_compressor()); gzstream.push(ifs); stringstream compressed; boost::iostreams::copy(gzstream, compressed); out_headers.emplace_back("Content-Encoding", "gzip"); send_file(compressed, out_headers); } else { out_headers.emplace_back("Accept-Ranges", "bytes"); send_file(ifs, out_headers); } ifs.close(); return; } } } } m_response.send_mesage("404 Not Found", "Error 404: Requested content not found!"); } void StaticRequestHandler::send_file(istream& content_stream, headers_type& headers) { content_stream.seekg(0, ios::end); size_t length = content_stream.tellg(); headers.emplace_back("Content-Length", to_string(length)); size_t start_pos = 0; size_t end_pos = length - 1; string requested_range = m_request.get_header("Range"); pair<string, string> range; if (requested_range != "" && ((range = parse_range(requested_range)) != pair<string, string>())) { if (range.first != string()) { start_pos = stoull(range.first); } else { range.first = to_string(start_pos); } if (range.second != string()) { end_pos = stoull(range.second); } else { range.second = to_string(end_pos); } if (start_pos > end_pos || start_pos >= length || end_pos >= length) { m_response.send_mesage("416 Range Not Satisfiable"); return; } else { headers.emplace_back("Content-Range", "bytes " + range.first + "-" + range.second + "/" + to_string(length)); m_response.send_header("206 Partial Content", headers, true); } } else { m_response.send_header("200 OK", headers, true); } if (m_request.method == "GET") { if (start_pos > 0) content_stream.seekg(start_pos); else content_stream.seekg(0, ios::beg); const size_t buffer_size = 131072; vector<char> buffer(buffer_size); size_t read_length; size_t bytes_left = end_pos - start_pos + 1; while (bytes_left > 0 && ((read_length = content_stream.read(&buffer[0], min(bytes_left, buffer_size)).gcount()) > 0)) { sys::error_code ec = m_response.send_data(string(&buffer[0], read_length), true); if (ec) return; bytes_left -= read_length; } } } #pragma endregion #pragma region WsgiRequestHandler WsgiRequestHandler::WsgiRequestHandler(Request& request, Response& response, py::object& app, bool async) : BaseRequestHandler(request, response), m_app{ app }, m_async{ async } { function<void(py::object)> wr{ [this](py::object data) { sys::error_code ec = m_response.send_header(m_status, m_out_headers); if (ec) return; m_headers_sent = true; string cpp_data = py::extract<string>(data); GilRelease release_gil; m_response.send_data(cpp_data); } }; m_write = py::make_function(wr, py::default_call_policies(), py::args("data"), boost::mpl::vector<void, py::object>()); function<py::object(py::str, py::list, py::object)> sr{ [this](py::str status, py::list headers, py::object exc_info = py::object()) { if (!exc_info.is_none()) { py::object format_exc = py::import("traceback").attr("format_exc")(); string exc_msg = py::extract<string>(format_exc); cerr << exc_msg << '\n'; exc_info = py::object(); } this->m_status = py::extract<string>(status); m_out_headers.clear(); bool has_cont_len = false; bool has_chunked = false; for (size_t i = 0; i < py::len(headers); ++i) { py::object header = headers[i]; string header_name = py::extract<string>(header[0]); string header_value = py::extract<string>(header[1]); // If a WSGI app does not provide Content-Length header (e.g. Django) // we use Transfer-Encoding: chunked if (alg::iequals(header_name, "Content-Length")) has_cont_len = true; if (alg::iequals(header_name, "Transfer-Encoding") && alg::icontains(header_value, "chunked")) has_chunked = true; m_out_headers.emplace_back(header_name, header_value); } if (!(has_cont_len || has_chunked)) { this->m_send_chunked = true; m_out_headers.emplace_back("Transfer-Encoding", "chunked"); } return m_write; } }; m_start_response = py::make_function(sr, py::default_call_policies(), (py::arg("status"), "headers", py::arg("exc_info") = py::object()), boost::mpl::vector<py::object, py::str, py::list, py::object>()); } void WsgiRequestHandler::handle() { if (m_app.is_none()) { m_response.send_mesage("500 Internal Server Error", "Error 500: Internal server error! WSGI application is not set."); return; } prepare_environ(); if (m_request.check_header("Expect", "100-continue")) { m_response.send_mesage("100 Continue"); } py::object args = get_python_object(Py_BuildValue("(O,O)", m_environ.ptr(), m_start_response.ptr())); Iterator iterable{ get_python_object(PyEval_CallObject(m_app.ptr(), args.ptr())) }; send_iterable(iterable); } void WsgiRequestHandler::prepare_environ() { m_environ["REQUEST_METHOD"] = m_request.method; m_environ["SCRIPT_NAME"] = ""; pair<string, string> path_and_query = split_path(m_request.path); m_environ["PATH_INFO"] = path_and_query.first; m_environ["QUERY_STRING"] = path_and_query.second; string ct = m_request.get_header("Content-Type"); if (ct != "") { m_environ["CONTENT_TYPE"] = ct; } string cl = m_request.get_header("Content-Length"); if (cl != "") { m_environ["CONTENT_LENGTH"] = cl; } m_environ["SERVER_NAME"] = m_request.host_name; m_environ["SERVER_PORT"] = to_string(m_request.local_endpoint_port); m_environ["SERVER_PROTOCOL"] = m_request.http_version; for (const auto& header : m_request.headers) { if (alg::iequals(header.first, "Content-Length") || alg::iequals(header.first, "Content-Type")) continue; string env_header = header.first; transform_header(env_header); if (!m_environ.has_key(env_header)) m_environ[env_header] = header.second; else m_environ[env_header] = m_environ[env_header] + "," + header.second; } m_environ["REMOTE_ADDR"] = m_environ["REMOTE_HOST"] = m_request.remote_address(); m_environ["REMOTE_PORT"] = to_string(m_request.remote_port()); m_environ["wsgi.version"] = py::make_tuple<int, int>(1, 0); m_environ["wsgi.url_scheme"] = m_request.url_scheme; InputWrapper input{ m_request.connection(), m_async }; m_environ["wsgi.input"] = input; m_environ["wsgi.errors"] = py::import("sys").attr("stderr"); m_environ["wsgi.multithread"] = true; m_environ["wsgi.multiprocess"] = false; m_environ["wsgi.run_once"] = false; m_environ["wsgi.file_wrapper"] = py::import("wsgiref.util").attr("FileWrapper"); } void WsgiRequestHandler::send_iterable(Iterator& iterable) { py::object iterator = iterable.attr("__iter__")(); while (true) { try { #if PY_MAJOR_VERSION < 3 std::string chunk = py::extract<string>(iterator.attr("next")()); #else std::string chunk = py::extract<string>(iterator.attr("__next__")()); #endif GilRelease release_gil; sys::error_code ec; if (!m_headers_sent) { ec = m_response.send_header(m_status, m_out_headers); if (ec) break; m_headers_sent = true; } if (m_send_chunked) { size_t length = chunk.length(); // Do not sent 0-length chunks if (length == 0) continue; chunk = hex(length) + "\r\n" + chunk + "\r\n"; } ec = m_response.send_data(chunk, m_async); if (ec) break; } catch (const py::error_already_set&) { if (PyErr_ExceptionMatches(PyExc_StopIteration)) { PyErr_Clear(); if (m_send_chunked) m_response.send_data("0\r\n\r\n"); break; } throw; } } } #pragma endregion }
/* Request handlers for WSGI apps and static files Copyright (c) 2016 Roman Miroshnychenko <[email protected]> License: MIT, see License.txt */ #include "request_handlers.h" #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/gzip.hpp> #include <boost/iostreams/copy.hpp> #include <fstream> #include <iostream> #include <sstream> using namespace std; namespace py = boost::python; namespace fs = boost::filesystem; namespace sys = boost::system; namespace alg = boost::algorithm; namespace wsgi_boost { #pragma region StaticRequestHandler void StaticRequestHandler::handle() { const auto content_dir_path = fs::path{ m_request.content_dir }; if (!fs::exists(content_dir_path)) { m_response.send_mesage("500 Internal Server Error", "Error 500: Internal server error! Invalid content directory."); return; } if (m_request.method != "GET" && m_request.method != "HEAD") { m_response.send_mesage("405 Method Not Allowed"); return; } open_file(content_dir_path); } void StaticRequestHandler::open_file(const fs::path& content_dir_path) { fs::path path = content_dir_path; path /= boost::regex_replace(m_request.path, m_request.path_regex, ""); if (fs::exists(path)) { path = fs::canonical(path); // Checking if path is inside content_dir if (distance(content_dir_path.begin(), content_dir_path.end()) <= distance(path.begin(), path.end()) && equal(content_dir_path.begin(), content_dir_path.end(), path.begin())) { if (fs::is_directory(path)) { path /= "index.html"; } if (fs::exists(path) && fs::is_regular_file(path)) { ifstream ifs; ifs.open(path.string(), ifstream::in | ios::binary); if (ifs) { headers_type out_headers; out_headers.emplace_back("Cache-Control", m_cache_control); time_t last_modified = fs::last_write_time(path); out_headers.emplace_back("Last-Modified", time_to_header(last_modified)); string ims = m_request.get_header("If-Modified-Since"); if (ims != "" && header_to_time(ims) >= last_modified) { out_headers.emplace_back("Content-Length", "0"); m_response.send_header("304 Not Modified", out_headers, true); return; } string ext = path.extension().string(); string mime = get_mime(ext); out_headers.emplace_back("Content-Type", mime); if (m_request.use_gzip && is_compressable(ext) && m_request.check_header("Accept-Encoding", "gzip")) { boost::iostreams::filtering_istream gzstream; gzstream.push(boost::iostreams::gzip_compressor()); gzstream.push(ifs); stringstream compressed; boost::iostreams::copy(gzstream, compressed); out_headers.emplace_back("Content-Encoding", "gzip"); send_file(compressed, out_headers); } else { out_headers.emplace_back("Accept-Ranges", "bytes"); send_file(ifs, out_headers); } ifs.close(); return; } } } } m_response.send_mesage("404 Not Found", "Error 404: Requested content not found!"); } void StaticRequestHandler::send_file(istream& content_stream, headers_type& headers) { content_stream.seekg(0, ios::end); size_t length = content_stream.tellg(); headers.emplace_back("Content-Length", to_string(length)); size_t start_pos = 0; size_t end_pos = length - 1; string requested_range = m_request.get_header("Range"); pair<string, string> range; if (requested_range != "" && ((range = parse_range(requested_range)) != pair<string, string>())) { if (range.first != string()) { start_pos = stoull(range.first); } else { range.first = to_string(start_pos); } if (range.second != string()) { end_pos = stoull(range.second); } else { range.second = to_string(end_pos); } if (start_pos > end_pos || start_pos >= length || end_pos >= length) { m_response.send_mesage("416 Range Not Satisfiable"); return; } else { headers.emplace_back("Content-Range", "bytes " + range.first + "-" + range.second + "/" + to_string(length)); m_response.send_header("206 Partial Content", headers, true); } } else { m_response.send_header("200 OK", headers, true); } if (m_request.method == "GET") { if (start_pos > 0) content_stream.seekg(start_pos); else content_stream.seekg(0, ios::beg); const size_t buffer_size = 131072; vector<char> buffer(buffer_size); size_t read_length; size_t bytes_left = end_pos - start_pos + 1; while (bytes_left > 0 && ((read_length = content_stream.read(&buffer[0], min(bytes_left, buffer_size)).gcount()) > 0)) { sys::error_code ec = m_response.send_data(string(&buffer[0], read_length), true); if (ec) return; bytes_left -= read_length; } } } #pragma endregion #pragma region WsgiRequestHandler WsgiRequestHandler::WsgiRequestHandler(Request& request, Response& response, py::object& app, bool async) : BaseRequestHandler(request, response), m_app{ app }, m_async{ async } { // Create write() callable: https://www.python.org/dev/peps/pep-3333/#the-write-callable function<void(py::object)> wr{ [this](py::object data) { sys::error_code ec = m_response.send_header(m_status, m_out_headers); if (ec) return; m_headers_sent = true; string cpp_data = py::extract<string>(data); GilRelease release_gil; m_response.send_data(cpp_data); } }; m_write = py::make_function(wr, py::default_call_policies(), py::args("data"), boost::mpl::vector<void, py::object>()); // Create start_response() callable: https://www.python.org/dev/peps/pep-3333/#the-start-response-callable function<py::object(py::str, py::list, py::object)> sr{ [this](py::str status, py::list headers, py::object exc_info = py::object()) { if (!exc_info.is_none()) { py::object format_exc = py::import("traceback").attr("format_exc")(); string exc_msg = py::extract<string>(format_exc); cerr << exc_msg << '\n'; exc_info = py::object(); } this->m_status = py::extract<string>(status); m_out_headers.clear(); bool has_cont_len = false; bool has_chunked = false; for (size_t i = 0; i < py::len(headers); ++i) { py::object header = headers[i]; string header_name = py::extract<string>(header[0]); string header_value = py::extract<string>(header[1]); // If a WSGI app does not provide Content-Length header (e.g. Django) // we use Transfer-Encoding: chunked if (alg::iequals(header_name, "Content-Length")) has_cont_len = true; if (alg::iequals(header_name, "Transfer-Encoding") && alg::icontains(header_value, "chunked")) has_chunked = true; m_out_headers.emplace_back(header_name, header_value); } if (!(has_cont_len || has_chunked)) { this->m_send_chunked = true; m_out_headers.emplace_back("Transfer-Encoding", "chunked"); } return m_write; } }; m_start_response = py::make_function(sr, py::default_call_policies(), (py::arg("status"), py::arg("headers"), py::arg("exc_info") = py::object()), boost::mpl::vector<py::object, py::str, py::list, py::object>()); } void WsgiRequestHandler::handle() { if (m_app.is_none()) { m_response.send_mesage("500 Internal Server Error", "Error 500: Internal server error! WSGI application is not set."); return; } prepare_environ(); if (m_request.check_header("Expect", "100-continue")) { m_response.send_mesage("100 Continue"); } py::object args = get_python_object(Py_BuildValue("(O,O)", m_environ.ptr(), m_start_response.ptr())); Iterator iterable{ get_python_object(PyEval_CallObject(m_app.ptr(), args.ptr())) }; send_iterable(iterable); } void WsgiRequestHandler::prepare_environ() { m_environ["REQUEST_METHOD"] = m_request.method; m_environ["SCRIPT_NAME"] = ""; pair<string, string> path_and_query = split_path(m_request.path); m_environ["PATH_INFO"] = path_and_query.first; m_environ["QUERY_STRING"] = path_and_query.second; string ct = m_request.get_header("Content-Type"); if (ct != "") { m_environ["CONTENT_TYPE"] = ct; } string cl = m_request.get_header("Content-Length"); if (cl != "") { m_environ["CONTENT_LENGTH"] = cl; } m_environ["SERVER_NAME"] = m_request.host_name; m_environ["SERVER_PORT"] = to_string(m_request.local_endpoint_port); m_environ["SERVER_PROTOCOL"] = m_request.http_version; for (const auto& header : m_request.headers) { if (alg::iequals(header.first, "Content-Length") || alg::iequals(header.first, "Content-Type")) continue; string env_header = header.first; transform_header(env_header); if (!m_environ.has_key(env_header)) m_environ[env_header] = header.second; else m_environ[env_header] = m_environ[env_header] + "," + header.second; } m_environ["REMOTE_ADDR"] = m_environ["REMOTE_HOST"] = m_request.remote_address(); m_environ["REMOTE_PORT"] = to_string(m_request.remote_port()); m_environ["wsgi.version"] = py::make_tuple<int, int>(1, 0); m_environ["wsgi.url_scheme"] = m_request.url_scheme; InputWrapper input{ m_request.connection(), m_async }; m_environ["wsgi.input"] = input; m_environ["wsgi.errors"] = py::import("sys").attr("stderr"); m_environ["wsgi.multithread"] = true; m_environ["wsgi.multiprocess"] = false; m_environ["wsgi.run_once"] = false; m_environ["wsgi.file_wrapper"] = py::import("wsgiref.util").attr("FileWrapper"); } void WsgiRequestHandler::send_iterable(Iterator& iterable) { py::object iterator = iterable.attr("__iter__")(); while (true) { try { #if PY_MAJOR_VERSION < 3 std::string chunk = py::extract<string>(iterator.attr("next")()); #else std::string chunk = py::extract<string>(iterator.attr("__next__")()); #endif GilRelease release_gil; sys::error_code ec; if (!m_headers_sent) { ec = m_response.send_header(m_status, m_out_headers); if (ec) break; m_headers_sent = true; } if (m_send_chunked) { size_t length = chunk.length(); // Skip 0-length chunks, if any if (length == 0) continue; chunk = hex(length) + "\r\n" + chunk + "\r\n"; } ec = m_response.send_data(chunk, m_async); if (ec) break; } catch (const py::error_already_set&) { if (PyErr_ExceptionMatches(PyExc_StopIteration)) { PyErr_Clear(); if (m_send_chunked) m_response.send_data("0\r\n\r\n"); break; } throw; } } } #pragma endregion }
Add some comments
Add some comments
C++
mit
romanvm/WsgiBoostServer,romanvm/WsgiBoostServer,romanvm/WsgiBoostServer,romanvm/WsgiBoostServer
28717a8a60e6877eda842944393efa4c0ad2e006
lib/Analysis/DomPrinter.cpp
lib/Analysis/DomPrinter.cpp
//===- DomPrinter.cpp - DOT printer for the dominance trees ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines '-dot-dom' and '-dot-postdom' analysis passes, which emit // a dom.<fnname>.dot or postdom.<fnname>.dot file for each function in the // program, with a graph of the dominance/postdominance tree of that // function. // // There are also passes available to directly call dotty ('-view-dom' or // '-view-postdom'). By appending '-only' like '-dot-dom-only' only the // names of the bbs are printed, but the content is hidden. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/DomPrinter.h" #include "llvm/Pass.h" #include "llvm/Function.h" #include "llvm/Analysis/CFGPrinter.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/PostDominators.h" using namespace llvm; namespace llvm { template<> struct DOTGraphTraits<DomTreeNode*> : public DefaultDOTGraphTraits { static std::string getNodeLabel(DomTreeNode *Node, DomTreeNode *Graph, bool ShortNames) { BasicBlock *BB = Node->getBlock(); if (!BB) return "Post dominance root node"; return DOTGraphTraits<const Function*>::getNodeLabel(BB, BB->getParent(), ShortNames); } }; template<> struct DOTGraphTraits<DominatorTree*> : public DOTGraphTraits<DomTreeNode*> { static std::string getGraphName(DominatorTree *DT) { return "Dominator tree"; } static std::string getNodeLabel(DomTreeNode *Node, DominatorTree *G, bool ShortNames) { return DOTGraphTraits<DomTreeNode*>::getNodeLabel(Node, G->getRootNode(), ShortNames); } }; template<> struct DOTGraphTraits<PostDominatorTree*> : public DOTGraphTraits<DomTreeNode*> { static std::string getGraphName(PostDominatorTree *DT) { return "Post dominator tree"; } static std::string getNodeLabel(DomTreeNode *Node, PostDominatorTree *G, bool ShortNames) { return DOTGraphTraits<DomTreeNode*>::getNodeLabel(Node, G->getRootNode(), ShortNames); } }; } namespace { template <class Analysis, bool OnlyBBS> struct GenericGraphViewer : public FunctionPass { static char ID; std::string Name; GenericGraphViewer(std::string GraphName) : FunctionPass(&ID) { Name = GraphName; } virtual bool runOnFunction(Function &F) { Analysis *Graph; Graph = &getAnalysis<Analysis>(); ViewGraph(Graph, Name, OnlyBBS); return false; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); AU.addRequired<Analysis>(); } }; struct DomViewer : public GenericGraphViewer<DominatorTree, false> { static char ID; DomViewer() : GenericGraphViewer<DominatorTree, false>("dom"){} }; struct DomOnlyViewer : public GenericGraphViewer<DominatorTree, true> { static char ID; DomOnlyViewer() : GenericGraphViewer<DominatorTree, true>("domonly"){} }; struct PostDomViewer : public GenericGraphViewer<PostDominatorTree, false> { static char ID; PostDomViewer() : GenericGraphViewer<PostDominatorTree, false>("postdom"){} }; struct PostDomOnlyViewer : public GenericGraphViewer<PostDominatorTree, true> { static char ID; PostDomOnlyViewer() : GenericGraphViewer<PostDominatorTree, true>("postdomonly"){} }; } // end anonymous namespace char DomViewer::ID = 0; RegisterPass<DomViewer> A("view-dom", "View dominance tree of function"); char DomOnlyViewer::ID = 0; RegisterPass<DomOnlyViewer> B("view-dom-only", "View dominance tree of function " "(with no function bodies)"); char PostDomViewer::ID = 0; RegisterPass<PostDomViewer> C("view-postdom", "View postdominance tree of function"); char PostDomOnlyViewer::ID = 0; RegisterPass<PostDomOnlyViewer> D("view-postdom-only", "View postdominance tree of function " "(with no function bodies)"); namespace { template <class Analysis, bool OnlyBBS> struct GenericGraphPrinter : public FunctionPass { static char ID; std::string Name; GenericGraphPrinter(std::string GraphName) : FunctionPass(&ID) { Name = GraphName; } virtual bool runOnFunction(Function &F) { Analysis *Graph; std::string Filename = Name + "." + F.getNameStr() + ".dot"; errs() << "Writing '" << Filename << "'..."; std::string ErrorInfo; raw_fd_ostream File(Filename.c_str(), ErrorInfo); Graph = &getAnalysis<Analysis>(); if (ErrorInfo.empty()) WriteGraph(File, Graph, OnlyBBS); else errs() << " error opening file for writing!"; errs() << "\n"; return false; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); AU.addRequired<Analysis>(); } }; struct DomPrinter : public GenericGraphPrinter<DominatorTree, false> { static char ID; DomPrinter() : GenericGraphPrinter<DominatorTree, false>("dom"){} }; struct DomOnlyPrinter : public GenericGraphPrinter<DominatorTree, true> { static char ID; DomOnlyPrinter() : GenericGraphPrinter<DominatorTree, true>("domonly"){} }; struct PostDomPrinter : public GenericGraphPrinter<PostDominatorTree, false> { static char ID; PostDomPrinter() : GenericGraphPrinter<PostDominatorTree, false>("postdom"){} }; struct PostDomOnlyPrinter : public GenericGraphPrinter<PostDominatorTree, true> { static char ID; PostDomOnlyPrinter() : GenericGraphPrinter<PostDominatorTree, true>("postdomonly"){} }; } // end anonymous namespace char DomPrinter::ID = 0; RegisterPass<DomPrinter> E("dot-dom", "Print dominance tree of function " "to 'dot' file"); char DomOnlyPrinter::ID = 0; RegisterPass<DomOnlyPrinter> F("dot-dom-only", "Print dominance tree of function " "to 'dot' file " "(with no function bodies)"); char PostDomPrinter::ID = 0; RegisterPass<PostDomPrinter> G("dot-postdom", "Print postdominance tree of function " "to 'dot' file"); char PostDomOnlyPrinter::ID = 0; RegisterPass<PostDomOnlyPrinter> H("dot-postdom-only", "Print postdominance tree of function " "to 'dot' file " "(with no function bodies)"); // Create methods available outside of this file, to use them // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by // the link time optimization. FunctionPass *llvm::createDomPrinterPass() { return new DomPrinter(); } FunctionPass *llvm::createDomOnlyPrinterPass() { return new DomOnlyPrinter(); } FunctionPass *llvm::createDomViewerPass() { return new DomViewer(); } FunctionPass *llvm::createDomOnlyViewerPass() { return new DomOnlyViewer(); } FunctionPass *llvm::createPostDomPrinterPass() { return new PostDomPrinter(); } FunctionPass *llvm::createPostDomOnlyPrinterPass() { return new PostDomOnlyPrinter(); } FunctionPass *llvm::createPostDomViewerPass() { return new PostDomViewer(); } FunctionPass *llvm::createPostDomOnlyViewerPass() { return new PostDomOnlyViewer(); }
//===- DomPrinter.cpp - DOT printer for the dominance trees ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines '-dot-dom' and '-dot-postdom' analysis passes, which emit // a dom.<fnname>.dot or postdom.<fnname>.dot file for each function in the // program, with a graph of the dominance/postdominance tree of that // function. // // There are also passes available to directly call dotty ('-view-dom' or // '-view-postdom'). By appending '-only' like '-dot-dom-only' only the // names of the bbs are printed, but the content is hidden. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/DomPrinter.h" #include "llvm/Pass.h" #include "llvm/Function.h" #include "llvm/Analysis/CFGPrinter.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/PostDominators.h" using namespace llvm; namespace llvm { template<> struct DOTGraphTraits<DomTreeNode*> : public DefaultDOTGraphTraits { static std::string getNodeLabel(DomTreeNode *Node, DomTreeNode *Graph, bool ShortNames) { BasicBlock *BB = Node->getBlock(); if (!BB) return "Post dominance root node"; return DOTGraphTraits<const Function*>::getNodeLabel(BB, BB->getParent(), ShortNames); } }; template<> struct DOTGraphTraits<DominatorTree*> : public DOTGraphTraits<DomTreeNode*> { static std::string getGraphName(DominatorTree *DT) { return "Dominator tree"; } static std::string getNodeLabel(DomTreeNode *Node, DominatorTree *G, bool ShortNames) { return DOTGraphTraits<DomTreeNode*>::getNodeLabel(Node, G->getRootNode(), ShortNames); } }; template<> struct DOTGraphTraits<PostDominatorTree*> : public DOTGraphTraits<DomTreeNode*> { static std::string getGraphName(PostDominatorTree *DT) { return "Post dominator tree"; } static std::string getNodeLabel(DomTreeNode *Node, PostDominatorTree *G, bool ShortNames) { return DOTGraphTraits<DomTreeNode*>::getNodeLabel(Node, G->getRootNode(), ShortNames); } }; } namespace { template <class Analysis, bool OnlyBBS> struct GenericGraphViewer : public FunctionPass { std::string Name; GenericGraphViewer(std::string GraphName, const void *ID) : FunctionPass(ID) { Name = GraphName; } virtual bool runOnFunction(Function &F) { Analysis *Graph; Graph = &getAnalysis<Analysis>(); ViewGraph(Graph, Name, OnlyBBS); return false; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); AU.addRequired<Analysis>(); } }; struct DomViewer : public GenericGraphViewer<DominatorTree, false> { static char ID; DomViewer() : GenericGraphViewer<DominatorTree, false>("dom", &ID){} }; struct DomOnlyViewer : public GenericGraphViewer<DominatorTree, true> { static char ID; DomOnlyViewer() : GenericGraphViewer<DominatorTree, true>("domonly", &ID){} }; struct PostDomViewer : public GenericGraphViewer<PostDominatorTree, false> { static char ID; PostDomViewer() : GenericGraphViewer<PostDominatorTree, false>("postdom", &ID){} }; struct PostDomOnlyViewer : public GenericGraphViewer<PostDominatorTree, true> { static char ID; PostDomOnlyViewer() : GenericGraphViewer<PostDominatorTree, true>("postdomonly", &ID){} }; } // end anonymous namespace char DomViewer::ID = 0; RegisterPass<DomViewer> A("view-dom", "View dominance tree of function"); char DomOnlyViewer::ID = 0; RegisterPass<DomOnlyViewer> B("view-dom-only", "View dominance tree of function " "(with no function bodies)"); char PostDomViewer::ID = 0; RegisterPass<PostDomViewer> C("view-postdom", "View postdominance tree of function"); char PostDomOnlyViewer::ID = 0; RegisterPass<PostDomOnlyViewer> D("view-postdom-only", "View postdominance tree of function " "(with no function bodies)"); namespace { template <class Analysis, bool OnlyBBS> struct GenericGraphPrinter : public FunctionPass { static char ID; std::string Name; GenericGraphPrinter(std::string GraphName) : FunctionPass(&ID) { Name = GraphName; } virtual bool runOnFunction(Function &F) { Analysis *Graph; std::string Filename = Name + "." + F.getNameStr() + ".dot"; errs() << "Writing '" << Filename << "'..."; std::string ErrorInfo; raw_fd_ostream File(Filename.c_str(), ErrorInfo); Graph = &getAnalysis<Analysis>(); if (ErrorInfo.empty()) WriteGraph(File, Graph, OnlyBBS); else errs() << " error opening file for writing!"; errs() << "\n"; return false; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); AU.addRequired<Analysis>(); } }; struct DomPrinter : public GenericGraphPrinter<DominatorTree, false> { static char ID; DomPrinter() : GenericGraphPrinter<DominatorTree, false>("dom"){} }; struct DomOnlyPrinter : public GenericGraphPrinter<DominatorTree, true> { static char ID; DomOnlyPrinter() : GenericGraphPrinter<DominatorTree, true>("domonly"){} }; struct PostDomPrinter : public GenericGraphPrinter<PostDominatorTree, false> { static char ID; PostDomPrinter() : GenericGraphPrinter<PostDominatorTree, false>("postdom"){} }; struct PostDomOnlyPrinter : public GenericGraphPrinter<PostDominatorTree, true> { static char ID; PostDomOnlyPrinter() : GenericGraphPrinter<PostDominatorTree, true>("postdomonly"){} }; } // end anonymous namespace char DomPrinter::ID = 0; RegisterPass<DomPrinter> E("dot-dom", "Print dominance tree of function " "to 'dot' file"); char DomOnlyPrinter::ID = 0; RegisterPass<DomOnlyPrinter> F("dot-dom-only", "Print dominance tree of function " "to 'dot' file " "(with no function bodies)"); char PostDomPrinter::ID = 0; RegisterPass<PostDomPrinter> G("dot-postdom", "Print postdominance tree of function " "to 'dot' file"); char PostDomOnlyPrinter::ID = 0; RegisterPass<PostDomOnlyPrinter> H("dot-postdom-only", "Print postdominance tree of function " "to 'dot' file " "(with no function bodies)"); // Create methods available outside of this file, to use them // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by // the link time optimization. FunctionPass *llvm::createDomPrinterPass() { return new DomPrinter(); } FunctionPass *llvm::createDomOnlyPrinterPass() { return new DomOnlyPrinter(); } FunctionPass *llvm::createDomViewerPass() { return new DomViewer(); } FunctionPass *llvm::createDomOnlyViewerPass() { return new DomOnlyViewer(); } FunctionPass *llvm::createPostDomPrinterPass() { return new PostDomPrinter(); } FunctionPass *llvm::createPostDomOnlyPrinterPass() { return new PostDomOnlyPrinter(); } FunctionPass *llvm::createPostDomViewerPass() { return new PostDomViewer(); } FunctionPass *llvm::createPostDomOnlyViewerPass() { return new PostDomOnlyViewer(); }
fix some problems with ID definitions, which will hopefully fix the build bots.
fix some problems with ID definitions, which will hopefully fix the build bots. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@84399 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-2-clause
chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,dslab-epfl/asap,chubbymaggie/asap
d07e29712544000b65cc036677d4752961e815b6
exec.cc
exec.cc
// Copyright 2015 Google Inc. All rights reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build ignore #include "exec.h" #include <stdio.h> #include <stdlib.h> #include <memory> #include <unordered_map> #include <utility> #include <vector> #include "command.h" #include "dep.h" #include "eval.h" #include "expr.h" #include "fileutil.h" #include "flags.h" #include "log.h" #include "string_piece.h" #include "strutil.h" #include "symtab.h" #include "var.h" namespace { const double kNotExist = -2.0; const double kProcessing = -1.0; class Executor { public: explicit Executor(Evaluator* ev) : ce_(ev) { shell_ = ev->GetShellAndFlag(); } double ExecNode(DepNode* n, DepNode* needed_by) { auto found = done_.find(n->output); if (found != done_.end()) { if (found->second == kProcessing) { WARN("Circular %s <- %s dependency dropped.", needed_by ? needed_by->output.c_str() : "(null)", n->output.c_str()); } return found->second; } done_[n->output] = kProcessing; double output_ts = GetTimestamp(n->output.c_str()); LOG("ExecNode: %s for %s", n->output.c_str(), needed_by ? needed_by->output.c_str() : "(null)"); if (!n->has_rule && output_ts == kNotExist && !n->is_phony) { if (needed_by) { ERROR("*** No rule to make target '%s', needed by '%s'.", n->output.c_str(), needed_by->output.c_str()); } else { ERROR("*** No rule to make target '%s'.", n->output.c_str()); } } double latest = kProcessing; for (DepNode* d : n->order_onlys) { if (Exists(d->output.str())) { continue; } double ts = ExecNode(d, n); if (latest < ts) latest = ts; } for (DepNode* d : n->deps) { double ts = ExecNode(d, n); if (latest < ts) latest = ts; } if (output_ts >= latest && !n->is_phony) { done_[n->output] = output_ts; return output_ts; } vector<Command*> commands; ce_.Eval(n, &commands); for (Command* command : commands) { num_commands_ += 1; if (command->echo) { printf("%s\n", command->cmd.c_str()); fflush(stdout); } if (!g_flags.is_dry_run) { string out; int result = RunCommand(shell_, command->cmd.c_str(), RedirectStderr::STDOUT, &out); printf("%s", out.c_str()); if (result != 0) { if (command->ignore_error) { fprintf(stderr, "[%s] Error %d (ignored)\n", command->output.c_str(), WEXITSTATUS(result)); } else { fprintf(stderr, "*** [%s] Error %d\n", command->output.c_str(), WEXITSTATUS(result)); exit(1); } } } delete command; } done_[n->output] = output_ts; return output_ts; } uint64_t Count() { return num_commands_; } private: CommandEvaluator ce_; unordered_map<Symbol, double> done_; string shell_; uint64_t num_commands_; }; } // namespace void Exec(const vector<DepNode*>& roots, Evaluator* ev) { unique_ptr<Executor> executor(new Executor(ev)); for (DepNode* root : roots) { executor->ExecNode(root, NULL); } if (executor->Count() == 0) { for (DepNode* root : roots) { printf("kati: Nothing to be done for `%s'.\n", root->output.c_str()); } } }
// Copyright 2015 Google Inc. All rights reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build ignore #include "exec.h" #include <stdio.h> #include <stdlib.h> #include <memory> #include <unordered_map> #include <utility> #include <vector> #include "command.h" #include "dep.h" #include "eval.h" #include "expr.h" #include "fileutil.h" #include "flags.h" #include "log.h" #include "string_piece.h" #include "strutil.h" #include "symtab.h" #include "var.h" namespace { const double kNotExist = -2.0; const double kProcessing = -1.0; class Executor { public: explicit Executor(Evaluator* ev) : ce_(ev), num_commands_(0) { shell_ = ev->GetShellAndFlag(); } double ExecNode(DepNode* n, DepNode* needed_by) { auto found = done_.find(n->output); if (found != done_.end()) { if (found->second == kProcessing) { WARN("Circular %s <- %s dependency dropped.", needed_by ? needed_by->output.c_str() : "(null)", n->output.c_str()); } return found->second; } done_[n->output] = kProcessing; double output_ts = GetTimestamp(n->output.c_str()); LOG("ExecNode: %s for %s", n->output.c_str(), needed_by ? needed_by->output.c_str() : "(null)"); if (!n->has_rule && output_ts == kNotExist && !n->is_phony) { if (needed_by) { ERROR("*** No rule to make target '%s', needed by '%s'.", n->output.c_str(), needed_by->output.c_str()); } else { ERROR("*** No rule to make target '%s'.", n->output.c_str()); } } double latest = kProcessing; for (DepNode* d : n->order_onlys) { if (Exists(d->output.str())) { continue; } double ts = ExecNode(d, n); if (latest < ts) latest = ts; } for (DepNode* d : n->deps) { double ts = ExecNode(d, n); if (latest < ts) latest = ts; } if (output_ts >= latest && !n->is_phony) { done_[n->output] = output_ts; return output_ts; } vector<Command*> commands; ce_.Eval(n, &commands); for (Command* command : commands) { num_commands_ += 1; if (command->echo) { printf("%s\n", command->cmd.c_str()); fflush(stdout); } if (!g_flags.is_dry_run) { string out; int result = RunCommand(shell_, command->cmd.c_str(), RedirectStderr::STDOUT, &out); printf("%s", out.c_str()); if (result != 0) { if (command->ignore_error) { fprintf(stderr, "[%s] Error %d (ignored)\n", command->output.c_str(), WEXITSTATUS(result)); } else { fprintf(stderr, "*** [%s] Error %d\n", command->output.c_str(), WEXITSTATUS(result)); exit(1); } } } delete command; } done_[n->output] = output_ts; return output_ts; } uint64_t Count() { return num_commands_; } private: CommandEvaluator ce_; unordered_map<Symbol, double> done_; string shell_; uint64_t num_commands_; }; } // namespace void Exec(const vector<DepNode*>& roots, Evaluator* ev) { unique_ptr<Executor> executor(new Executor(ev)); for (DepNode* root : roots) { executor->ExecNode(root, NULL); } if (executor->Count() == 0) { for (DepNode* root : roots) { printf("kati: Nothing to be done for `%s'.\n", root->output.c_str()); } } }
Stop using an uninitialized value
[C++] Stop using an uninitialized value
C++
apache-2.0
google/kati,google/kati,google/kati,danw/kati,danw/kati,danw/kati,google/kati,danw/kati,danw/kati,google/kati,danw/kati
cfbb3b64e2cb915a578125dc5dfaee628f05ffa4
include/etl/context.hpp
include/etl/context.hpp
//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once namespace etl { /*! * \brief Wrapper used in the context to force an implementation to be used */ template<typename T> struct forced_impl { T impl; ///< The impl to be used (if forced == true) bool forced = false; ///< Indicate if forced or default }; /*! * \brief The contextual configuration of ETL */ struct context { bool serial = false; ///< Force serial execution bool parallel = false; ///< Force parallel execution forced_impl<scalar_impl> scalar_selector; ///< Force selector for scalar operations forced_impl<sum_impl> sum_selector; ///< Forced selector for sum forced_impl<transpose_impl> transpose_selector; ///< Forced selector for transpose forced_impl<dot_impl> dot_selector; ///< Forced selector for dot forced_impl<conv_impl> conv_selector; ///< Forced selector for conv forced_impl<gemm_impl> gemm_selector; ///< Forced selector for gemm forced_impl<outer_impl> outer_selector; ///< Forced selector for outer product forced_impl<fft_impl> fft_selector; ///< Forced selector for fft }; /*! * \brief Return the configuration context of the current thread. * \return the configuration context of the current thread */ inline context& local_context(){ static thread_local context local_context; return local_context; } namespace detail { /*! * \brief RAII helper for setting the context to serial */ struct serial_context { bool old_serial; serial_context(){ old_serial = etl::local_context().serial; etl::local_context().serial = true; } ~serial_context(){ etl::local_context().serial = old_serial; } operator bool(){ return true; } }; /*! * \brief RAII helper for setting the context to parallel */ struct parallel_context { bool old_parallel; parallel_context(){ old_parallel = etl::local_context().parallel; etl::local_context().parallel = true; } ~parallel_context(){ etl::local_context().parallel = old_parallel; } operator bool(){ return true; } }; } //end of namespace detail /*! * \brief Define the start of an ETL serial section */ #define SERIAL_SECTION if(auto etl_serial_context__ = etl::detail::serial_context()) /*! * \brief Define the start of an ETL parallel section */ #define PARALLEL_SECTION if(auto etl_parallel_context__ = etl::detail::parallel_context()) } //end of namespace etl
//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once namespace etl { /*! * \brief Wrapper used in the context to force an implementation to be used */ template<typename T> struct forced_impl { T impl; ///< The impl to be used (if forced == true) bool forced = false; ///< Indicate if forced or default }; /*! * \brief The contextual configuration of ETL */ struct context { bool serial = false; ///< Force serial execution bool parallel = false; ///< Force parallel execution forced_impl<scalar_impl> scalar_selector; ///< Force selector for scalar operations forced_impl<sum_impl> sum_selector; ///< Forced selector for sum forced_impl<transpose_impl> transpose_selector; ///< Forced selector for transpose forced_impl<dot_impl> dot_selector; ///< Forced selector for dot forced_impl<conv_impl> conv_selector; ///< Forced selector for conv forced_impl<gemm_impl> gemm_selector; ///< Forced selector for gemm forced_impl<outer_impl> outer_selector; ///< Forced selector for outer product forced_impl<fft_impl> fft_selector; ///< Forced selector for fft }; /*! * \brief Return the configuration context of the current thread. * \return the configuration context of the current thread */ inline context& local_context(){ static thread_local context local_context; return local_context; } namespace detail { template<typename T> forced_impl<T>& get_forced_impl(); template<> inline forced_impl<scalar_impl>& get_forced_impl(){ return local_context().scalar_selector; } template<> inline forced_impl<sum_impl>& get_forced_impl(){ return local_context().sum_selector; } template<> inline forced_impl<transpose_impl>& get_forced_impl(){ return local_context().transpose_selector; } template<> inline forced_impl<dot_impl>& get_forced_impl(){ return local_context().dot_selector; } template<> inline forced_impl<conv_impl>& get_forced_impl(){ return local_context().conv_selector; } template<> inline forced_impl<gemm_impl>& get_forced_impl(){ return local_context().gemm_selector; } template<> inline forced_impl<outer_impl>& get_forced_impl(){ return local_context().outer_selector; } template<> inline forced_impl<fft_impl>& get_forced_impl(){ return local_context().fft_selector; } /*! * \brief RAII helper for setting the context to serial */ struct serial_context { bool old_serial; serial_context(){ old_serial = etl::local_context().serial; etl::local_context().serial = true; } ~serial_context(){ etl::local_context().serial = old_serial; } operator bool(){ return true; } }; /*! * \brief RAII helper for setting the context to parallel */ struct parallel_context { bool old_parallel; parallel_context(){ old_parallel = etl::local_context().parallel; etl::local_context().parallel = true; } ~parallel_context(){ etl::local_context().parallel = old_parallel; } operator bool(){ return true; } }; } //end of namespace detail /*! * \brief Define the start of an ETL serial section */ #define SERIAL_SECTION if(auto etl_serial_context__ = etl::detail::serial_context()) /*! * \brief Define the start of an ETL parallel section */ #define PARALLEL_SECTION if(auto etl_parallel_context__ = etl::detail::parallel_context()) } //end of namespace etl
Add access by type
Add access by type
C++
mit
wichtounet/etl,wichtounet/etl
8bcdd304eb520c23580f68430079c92d77de82ca
include/inpal_prime.hpp
include/inpal_prime.hpp
// // inpal_prime.hpp // Inverse Palindrome Library // // Created by Bryan Triana on 7/21/16. // Copyright © 2016 Inverse Palindrome. All rights reserved. // #ifndef inpal_prime_hpp #define inpal_prime_hpp #include <vector> #include <string> namespace inpal { namespace prime { //general purpose functions std::vector<std::size_t> prime_list(std::size_t range); std::vector<bool> prime_sieve(std::size_t range); std::vector<std::size_t> factor_list(std::size_t num); //special purpose functions std::size_t prime_locate(std::size_t pos); std::size_t max_prime(std::size_t range); std::size_t prime_count(std::size_t range); double prime_density(double range); bool prime_test(std::size_t num); bool twin_test(std::size_t num); bool cousin_test(std::size_t num); bool sexy_test(std::size_t num); std::size_t max_palprime(std::size_t range); std::size_t max_factor(std::size_t num); std::size_t factor_count(std::size_t num); } } #endif /* inpal_prime_hpp */
// // inpal_prime.hpp // Inverse Palindrome Library // // Created by Bryan Triana on 7/21/16. // Copyright © 2016 Inverse Palindrome. All rights reserved. // #ifndef inpal_prime_hpp #define inpal_prime_hpp #include <vector> #include <string> namespace inpal { namespace prime { //general purpose functions std::vector<std::size_t> prime_list(std::size_t range); std::vector<bool> prime_sieve(std::size_t range); std::vector<std::size_t> factor_list(std::size_t num); //special purpose functions std::size_t prime_locate(std::size_t pos); std::size_t max_prime(std::size_t range); std::size_t prime_count(std::size_t range); double prime_density(double range); bool prime_test(std::size_t num); bool twin_test(std::size_t num); bool cousin_test(std::size_t num); bool sexy_test(std::size_t num); std::size_t max_palprime(std::size_t range); std::size_t max_factor(std::size_t num); std::size_t factor_count(std::size_t num); } } #endif /* inpal_prime_hpp */
Update inpal_prime.hpp
Update inpal_prime.hpp
C++
mit
InversePalindrome/Prime-Numbers
3e044403e1acaaef7038d8891caa04a5e0c5a21c
gm/texteffects.cpp
gm/texteffects.cpp
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkFlattenableBuffers.h" #include "SkLayerRasterizer.h" #include "SkBlurMaskFilter.h" static void r0(SkLayerRasterizer* rast, SkPaint& p) { p.setMaskFilter(SkBlurMaskFilter::Create(SkIntToScalar(3), SkBlurMaskFilter::kNormal_BlurStyle))->unref(); rast->addLayer(p, SkIntToScalar(3), SkIntToScalar(3)); p.setMaskFilter(NULL); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SK_Scalar1); rast->addLayer(p); p.setAlpha(0x11); p.setStyle(SkPaint::kFill_Style); p.setXfermodeMode(SkXfermode::kSrc_Mode); rast->addLayer(p); } static void r1(SkLayerRasterizer* rast, SkPaint& p) { rast->addLayer(p); p.setAlpha(0x40); p.setXfermodeMode(SkXfermode::kSrc_Mode); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SK_Scalar1*2); rast->addLayer(p); } static void r2(SkLayerRasterizer* rast, SkPaint& p) { p.setStyle(SkPaint::kStrokeAndFill_Style); p.setStrokeWidth(SK_Scalar1*4); rast->addLayer(p); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SK_Scalar1*3/2); p.setXfermodeMode(SkXfermode::kClear_Mode); rast->addLayer(p); } static void r3(SkLayerRasterizer* rast, SkPaint& p) { p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SK_Scalar1*3); rast->addLayer(p); p.setAlpha(0x20); p.setStyle(SkPaint::kFill_Style); p.setXfermodeMode(SkXfermode::kSrc_Mode); rast->addLayer(p); } static void r4(SkLayerRasterizer* rast, SkPaint& p) { p.setAlpha(0x60); rast->addLayer(p, SkIntToScalar(3), SkIntToScalar(3)); p.setAlpha(0xFF); p.setXfermodeMode(SkXfermode::kClear_Mode); rast->addLayer(p, SK_Scalar1*3/2, SK_Scalar1*3/2); p.setXfermode(NULL); rast->addLayer(p); } #include "SkDiscretePathEffect.h" static void r5(SkLayerRasterizer* rast, SkPaint& p) { rast->addLayer(p); p.setPathEffect(new SkDiscretePathEffect(SK_Scalar1*4, SK_Scalar1*3))->unref(); p.setXfermodeMode(SkXfermode::kSrcOut_Mode); rast->addLayer(p); } static void r6(SkLayerRasterizer* rast, SkPaint& p) { rast->addLayer(p); p.setAntiAlias(false); SkLayerRasterizer* rast2 = new SkLayerRasterizer; r5(rast2, p); p.setRasterizer(rast2)->unref(); p.setXfermodeMode(SkXfermode::kClear_Mode); rast->addLayer(p); } #include "Sk2DPathEffect.h" static SkPathEffect* MakeDotEffect(SkScalar radius, const SkMatrix& matrix) { SkPath path; path.addCircle(0, 0, radius); return new SkPath2DPathEffect(matrix, path); } static void r7(SkLayerRasterizer* rast, SkPaint& p) { SkMatrix lattice; lattice.setScale(SK_Scalar1*6, SK_Scalar1*6, 0, 0); lattice.postSkew(SK_Scalar1/3, 0, 0, 0); p.setPathEffect(MakeDotEffect(SK_Scalar1*4, lattice))->unref(); rast->addLayer(p); } static void r8(SkLayerRasterizer* rast, SkPaint& p) { rast->addLayer(p); SkMatrix lattice; lattice.setScale(SK_Scalar1*6, SK_Scalar1*6, 0, 0); lattice.postSkew(SK_Scalar1/3, 0, 0, 0); p.setPathEffect(MakeDotEffect(SK_Scalar1*2, lattice))->unref(); p.setXfermodeMode(SkXfermode::kClear_Mode); rast->addLayer(p); p.setPathEffect(NULL); p.setXfermode(NULL); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SK_Scalar1); rast->addLayer(p); } class Line2DPathEffect : public Sk2DPathEffect { public: Line2DPathEffect(SkScalar width, const SkMatrix& matrix) : Sk2DPathEffect(matrix), fWidth(width) {} virtual bool filterPath(SkPath* dst, const SkPath& src, SkStrokeRec* rec) SK_OVERRIDE { if (this->INHERITED::filterPath(dst, src, rec)) { rec->setStrokeStyle(fWidth); return true; } return false; } SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(Line2DPathEffect) protected: virtual void nextSpan(int u, int v, int ucount, SkPath* dst) { if (ucount > 1) { SkPoint src[2], dstP[2]; src[0].set(SkIntToScalar(u) + SK_ScalarHalf, SkIntToScalar(v) + SK_ScalarHalf); src[1].set(SkIntToScalar(u+ucount) + SK_ScalarHalf, SkIntToScalar(v) + SK_ScalarHalf); this->getMatrix().mapPoints(dstP, src, 2); dst->moveTo(dstP[0]); dst->lineTo(dstP[1]); } } Line2DPathEffect(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) { fWidth = buffer.readScalar(); } virtual void flatten(SkFlattenableWriteBuffer& buffer) const SK_OVERRIDE { this->INHERITED::flatten(buffer); buffer.writeScalar(fWidth); } private: SkScalar fWidth; typedef Sk2DPathEffect INHERITED; }; static void r9(SkLayerRasterizer* rast, SkPaint& p) { rast->addLayer(p); SkMatrix lattice; lattice.setScale(SK_Scalar1, SK_Scalar1*6, 0, 0); lattice.postRotate(SkIntToScalar(30), 0, 0); p.setPathEffect(new Line2DPathEffect(SK_Scalar1*2, lattice))->unref(); p.setXfermodeMode(SkXfermode::kClear_Mode); rast->addLayer(p); p.setPathEffect(NULL); p.setXfermode(NULL); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SK_Scalar1); rast->addLayer(p); } typedef void (*raster_proc)(SkLayerRasterizer*, SkPaint&); static const raster_proc gRastProcs[] = { r0, r1, r2, r3, r4, r5, r6, r7, r8, r9 }; static const struct { SkColor fMul, fAdd; } gLightingColors[] = { { 0x808080, 0x800000 }, // general case { 0x707070, 0x707070 }, // no-pin case { 0xFFFFFF, 0x800000 }, // just-add case { 0x808080, 0x000000 }, // just-mul case { 0xFFFFFF, 0x000000 } // identity case }; #include "SkXfermode.h" static void apply_shader(SkPaint* paint, int index) { raster_proc proc = gRastProcs[index]; if (proc) { SkPaint p; SkLayerRasterizer* rast = new SkLayerRasterizer; p.setAntiAlias(true); proc(rast, p); paint->setRasterizer(rast)->unref(); } #if 0 SkScalar dir[] = { SK_Scalar1, SK_Scalar1, SK_Scalar1 }; paint->setMaskFilter(SkBlurMaskFilter::CreateEmboss(dir, SK_Scalar1/4, SkIntToScalar(4), SkIntToScalar(3)))->unref(); #endif paint->setColor(SK_ColorBLUE); } class TextEffectsGM : public skiagm::GM { public: TextEffectsGM() {} protected: virtual SkString onShortName() SK_OVERRIDE { return SkString("texteffects"); } virtual SkISize onISize() SK_OVERRIDE { return SkISize::Make(640, 480); } virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE { canvas->save(); SkPaint paint; paint.setAntiAlias(true); paint.setTextSize(SkIntToScalar(56)); SkScalar x = SkIntToScalar(20); SkScalar y = paint.getTextSize(); SkString str("Hamburgefons"); for (size_t i = 0; i < SK_ARRAY_COUNT(gRastProcs); i++) { apply_shader(&paint, i); // paint.setMaskFilter(NULL); // paint.setColor(SK_ColorBLACK); canvas->drawText(str.c_str(), str.size(), x, y, paint); y += paint.getFontSpacing(); } canvas->restore(); } private: typedef skiagm::GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static skiagm::GM* MyFactory(void*) { return new TextEffectsGM; } static skiagm::GMRegistry reg(MyFactory);
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkFlattenableBuffers.h" #include "SkLayerRasterizer.h" #include "SkBlurMaskFilter.h" static void r0(SkLayerRasterizer* rast, SkPaint& p) { p.setMaskFilter(SkBlurMaskFilter::Create(SkIntToScalar(3), SkBlurMaskFilter::kNormal_BlurStyle))->unref(); rast->addLayer(p, SkIntToScalar(3), SkIntToScalar(3)); p.setMaskFilter(NULL); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SK_Scalar1); rast->addLayer(p); p.setAlpha(0x11); p.setStyle(SkPaint::kFill_Style); p.setXfermodeMode(SkXfermode::kSrc_Mode); rast->addLayer(p); } static void r1(SkLayerRasterizer* rast, SkPaint& p) { rast->addLayer(p); p.setAlpha(0x40); p.setXfermodeMode(SkXfermode::kSrc_Mode); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SK_Scalar1*2); rast->addLayer(p); } static void r2(SkLayerRasterizer* rast, SkPaint& p) { p.setStyle(SkPaint::kStrokeAndFill_Style); p.setStrokeWidth(SK_Scalar1*4); rast->addLayer(p); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SK_Scalar1*3/2); p.setXfermodeMode(SkXfermode::kClear_Mode); rast->addLayer(p); } static void r3(SkLayerRasterizer* rast, SkPaint& p) { p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SK_Scalar1*3); rast->addLayer(p); p.setAlpha(0x20); p.setStyle(SkPaint::kFill_Style); p.setXfermodeMode(SkXfermode::kSrc_Mode); rast->addLayer(p); } static void r4(SkLayerRasterizer* rast, SkPaint& p) { p.setAlpha(0x60); rast->addLayer(p, SkIntToScalar(3), SkIntToScalar(3)); p.setAlpha(0xFF); p.setXfermodeMode(SkXfermode::kClear_Mode); rast->addLayer(p, SK_Scalar1*3/2, SK_Scalar1*3/2); p.setXfermode(NULL); rast->addLayer(p); } #include "SkDiscretePathEffect.h" static void r5(SkLayerRasterizer* rast, SkPaint& p) { rast->addLayer(p); p.setPathEffect(new SkDiscretePathEffect(SK_Scalar1*4, SK_Scalar1*3))->unref(); p.setXfermodeMode(SkXfermode::kSrcOut_Mode); rast->addLayer(p); } static void r6(SkLayerRasterizer* rast, SkPaint& p) { rast->addLayer(p); p.setAntiAlias(false); SkLayerRasterizer* rast2 = new SkLayerRasterizer; r5(rast2, p); p.setRasterizer(rast2)->unref(); p.setXfermodeMode(SkXfermode::kClear_Mode); rast->addLayer(p); } #include "Sk2DPathEffect.h" static SkPathEffect* MakeDotEffect(SkScalar radius, const SkMatrix& matrix) { SkPath path; path.addCircle(0, 0, radius); return new SkPath2DPathEffect(matrix, path); } static void r7(SkLayerRasterizer* rast, SkPaint& p) { SkMatrix lattice; lattice.setScale(SK_Scalar1*6, SK_Scalar1*6, 0, 0); lattice.postSkew(SK_Scalar1/3, 0, 0, 0); p.setPathEffect(MakeDotEffect(SK_Scalar1*4, lattice))->unref(); rast->addLayer(p); } static void r8(SkLayerRasterizer* rast, SkPaint& p) { rast->addLayer(p); SkMatrix lattice; lattice.setScale(SK_Scalar1*6, SK_Scalar1*6, 0, 0); lattice.postSkew(SK_Scalar1/3, 0, 0, 0); p.setPathEffect(MakeDotEffect(SK_Scalar1*2, lattice))->unref(); p.setXfermodeMode(SkXfermode::kClear_Mode); rast->addLayer(p); p.setPathEffect(NULL); p.setXfermode(NULL); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SK_Scalar1); rast->addLayer(p); } class Line2DPathEffect : public Sk2DPathEffect { public: Line2DPathEffect(SkScalar width, const SkMatrix& matrix) : Sk2DPathEffect(matrix), fWidth(width) {} virtual bool filterPath(SkPath* dst, const SkPath& src, SkStrokeRec* rec) SK_OVERRIDE { if (this->INHERITED::filterPath(dst, src, rec)) { rec->setStrokeStyle(fWidth); return true; } return false; } SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(Line2DPathEffect) protected: virtual void nextSpan(int u, int v, int ucount, SkPath* dst) { if (ucount > 1) { SkPoint src[2], dstP[2]; src[0].set(SkIntToScalar(u) + SK_ScalarHalf, SkIntToScalar(v) + SK_ScalarHalf); src[1].set(SkIntToScalar(u+ucount) + SK_ScalarHalf, SkIntToScalar(v) + SK_ScalarHalf); this->getMatrix().mapPoints(dstP, src, 2); dst->moveTo(dstP[0]); dst->lineTo(dstP[1]); } } Line2DPathEffect(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) { fWidth = buffer.readScalar(); } virtual void flatten(SkFlattenableWriteBuffer& buffer) const SK_OVERRIDE { this->INHERITED::flatten(buffer); buffer.writeScalar(fWidth); } private: SkScalar fWidth; typedef Sk2DPathEffect INHERITED; }; static void r9(SkLayerRasterizer* rast, SkPaint& p) { rast->addLayer(p); SkMatrix lattice; lattice.setScale(SK_Scalar1, SK_Scalar1*6, 0, 0); lattice.postRotate(SkIntToScalar(30), 0, 0); p.setPathEffect(new Line2DPathEffect(SK_Scalar1*2, lattice))->unref(); p.setXfermodeMode(SkXfermode::kClear_Mode); rast->addLayer(p); p.setPathEffect(NULL); p.setXfermode(NULL); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SK_Scalar1); rast->addLayer(p); } typedef void (*raster_proc)(SkLayerRasterizer*, SkPaint&); static const raster_proc gRastProcs[] = { r0, r1, r2, r3, r4, r5, r6, r7, r8, r9 }; static const struct { SkColor fMul, fAdd; } gLightingColors[] = { { 0x808080, 0x800000 }, // general case { 0x707070, 0x707070 }, // no-pin case { 0xFFFFFF, 0x800000 }, // just-add case { 0x808080, 0x000000 }, // just-mul case { 0xFFFFFF, 0x000000 } // identity case }; #include "SkXfermode.h" static void apply_shader(SkPaint* paint, int index) { raster_proc proc = gRastProcs[index]; if (proc) { SkPaint p; SkLayerRasterizer* rast = new SkLayerRasterizer; p.setAntiAlias(true); proc(rast, p); paint->setRasterizer(rast)->unref(); } #if 0 SkScalar dir[] = { SK_Scalar1, SK_Scalar1, SK_Scalar1 }; paint->setMaskFilter(SkBlurMaskFilter::CreateEmboss(dir, SK_Scalar1/4, SkIntToScalar(4), SkIntToScalar(3)))->unref(); #endif paint->setColor(SK_ColorBLUE); } class TextEffectsGM : public skiagm::GM { public: TextEffectsGM() {} protected: virtual SkString onShortName() SK_OVERRIDE { return SkString("texteffects"); } virtual SkISize onISize() SK_OVERRIDE { return SkISize::Make(460, 680); } virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE { canvas->save(); SkPaint paint; paint.setAntiAlias(true); paint.setTextSize(SkIntToScalar(56)); SkScalar x = SkIntToScalar(20); SkScalar y = paint.getTextSize(); SkString str("Hamburgefons"); for (size_t i = 0; i < SK_ARRAY_COUNT(gRastProcs); i++) { apply_shader(&paint, i); // paint.setMaskFilter(NULL); // paint.setColor(SK_ColorBLACK); canvas->drawText(str.c_str(), str.size(), x, y, paint); y += paint.getFontSpacing(); } canvas->restore(); } private: typedef skiagm::GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static skiagm::GM* MyFactory(void*) { return new TextEffectsGM; } static skiagm::GMRegistry reg(MyFactory);
adjust size to match the content
adjust size to match the content git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@5052 2bbb7eff-a529-9590-31e7-b0007b416f81
C++
bsd-3-clause
invisiblek/android_external_skia,FusionSP/external_chromium_org_third_party_skia,Tesla-Redux/android_external_skia,HalCanary/skia-hc,xzzz9097/android_external_skia,Samsung/skia,F-AOSP/platform_external_skia,ominux/skia,PAC-ROM/android_external_skia,wildermason/external_skia,AOSP-YU/platform_external_skia,MinimalOS-AOSP/platform_external_skia,SlimSaber/android_external_skia,vvuk/skia,NamelessRom/android_external_skia,Infusion-OS/android_external_skia,Tesla-Redux/android_external_skia,ench0/external_chromium_org_third_party_skia,AOSP-YU/platform_external_skia,qrealka/skia-hc,ominux/skia,MonkeyZZZZ/platform_external_skia,ctiao/platform-external-skia,suyouxin/android_external_skia,Igalia/skia,byterom/android_external_skia,Tesla-Redux/android_external_skia,HealthyHoney/temasek_SKIA,Euphoria-OS-Legacy/android_external_skia,aospo/platform_external_skia,ench0/external_skia,OptiPop/external_skia,byterom/android_external_skia,MarshedOut/android_external_skia,Igalia/skia,DARKPOP/external_chromium_org_third_party_skia,android-ia/platform_external_chromium_org_third_party_skia,boulzordev/android_external_skia,houst0nn/external_skia,DARKPOP/external_chromium_org_third_party_skia,xzzz9097/android_external_skia,ench0/external_chromium_org_third_party_skia,AndroidOpenDevelopment/android_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,MarshedOut/android_external_skia,aosp-mirror/platform_external_skia,samuelig/skia,timduru/platform-external-skia,Infusion-OS/android_external_skia,AsteroidOS/android_external_skia,tmpvar/skia.cc,Purity-Lollipop/platform_external_skia,nox/skia,codeaurora-unoffical/platform-external-skia,PAC-ROM/android_external_skia,AOSPB/external_skia,ench0/external_skia,jtg-gg/skia,android-ia/platform_external_skia,Hybrid-Rom/external_skia,GladeRom/android_external_skia,Omegaphora/external_skia,AsteroidOS/android_external_skia,TeamEOS/external_chromium_org_third_party_skia,wildermason/external_skia,fire855/android_external_skia,shahrzadmn/skia,qrealka/skia-hc,AsteroidOS/android_external_skia,PAC-ROM/android_external_skia,todotodoo/skia,mydongistiny/android_external_skia,YUPlayGodDev/platform_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,Purity-Lollipop/platform_external_skia,MonkeyZZZZ/platform_external_skia,MIPS/external-chromium_org-third_party-skia,DesolationStaging/android_external_skia,todotodoo/skia,Hybrid-Rom/external_skia,xzzz9097/android_external_skia,MinimalOS/android_external_skia,larsbergstrom/skia,TeamBliss-LP/android_external_skia,geekboxzone/mmallow_external_skia,AOSPA-L/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,w3nd1go/android_external_skia,TeamEOS/external_skia,FusionSP/external_chromium_org_third_party_skia,ominux/skia,AOSPU/external_chromium_org_third_party_skia,aosp-mirror/platform_external_skia,AsteroidOS/android_external_skia,ominux/skia,mmatyas/skia,MinimalOS/external_skia,invisiblek/android_external_skia,noselhq/skia,HealthyHoney/temasek_SKIA,nvoron23/skia,TeslaProject/external_skia,spezi77/android_external_skia,pcwalton/skia,FusionSP/android_external_skia,VRToxin-AOSP/android_external_skia,F-AOSP/platform_external_skia,TeamBliss-LP/android_external_skia,TeamEOS/external_skia,rubenvb/skia,ctiao/platform-external-skia,VRToxin-AOSP/android_external_skia,boulzordev/android_external_skia,mydongistiny/external_chromium_org_third_party_skia,Euphoria-OS-Legacy/android_external_skia,boulzordev/android_external_skia,todotodoo/skia,pcwalton/skia,Infusion-OS/android_external_skia,Omegaphora/external_chromium_org_third_party_skia,ench0/external_chromium_org_third_party_skia,MinimalOS/android_external_chromium_org_third_party_skia,geekboxzone/mmallow_external_skia,xzzz9097/android_external_skia,ominux/skia,Asteroid-Project/android_external_skia,Samsung/skia,MIPS/external-chromium_org-third_party-skia,google/skia,mydongistiny/android_external_skia,tmpvar/skia.cc,VentureROM-L/android_external_skia,TeamExodus/external_skia,MonkeyZZZZ/platform_external_skia,MonkeyZZZZ/platform_external_skia,aospo/platform_external_skia,sudosurootdev/external_skia,Infinitive-OS/platform_external_skia,qrealka/skia-hc,zhaochengw/platform_external_skia,pacerom/external_skia,aosp-mirror/platform_external_skia,AOSPB/external_skia,AOSPA-L/android_external_skia,MonkeyZZZZ/platform_external_skia,mmatyas/skia,Infinitive-OS/platform_external_skia,F-AOSP/platform_external_skia,MinimalOS/external_chromium_org_third_party_skia,ench0/external_chromium_org_third_party_skia,GladeRom/android_external_skia,larsbergstrom/skia,Hybrid-Rom/external_skia,xin3liang/platform_external_chromium_org_third_party_skia,geekboxzone/mmallow_external_skia,GladeRom/android_external_skia,nfxosp/platform_external_skia,xzzz9097/android_external_skia,AOSPU/external_chromium_org_third_party_skia,TeamTwisted/external_skia,Igalia/skia,AndroidOpenDevelopment/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,Fusion-Rom/android_external_skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,TeamEOS/external_chromium_org_third_party_skia,mmatyas/skia,amyvmiwei/skia,FusionSP/external_chromium_org_third_party_skia,temasek/android_external_skia,FusionSP/external_chromium_org_third_party_skia,Fusion-Rom/external_chromium_org_third_party_skia,TeamTwisted/external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,UBERMALLOW/external_skia,Euphoria-OS-Legacy/android_external_skia,wildermason/external_skia,VRToxin-AOSP/android_external_skia,nox/skia,UBERMALLOW/external_skia,TeamBliss-LP/android_external_skia,Euphoria-OS-Legacy/android_external_skia,GladeRom/android_external_skia,AsteroidOS/android_external_skia,NamelessRom/android_external_skia,BrokenROM/external_skia,Android-AOSP/external_skia,MarshedOut/android_external_skia,mydongistiny/external_chromium_org_third_party_skia,Purity-Lollipop/platform_external_skia,codeaurora-unoffical/platform-external-skia,DesolationStaging/android_external_skia,scroggo/skia,OptiPop/external_chromium_org_third_party_skia,TeamEOS/external_chromium_org_third_party_skia,fire855/android_external_skia,aospo/platform_external_skia,fire855/android_external_skia,PAC-ROM/android_external_skia,AOSP-YU/platform_external_skia,byterom/android_external_skia,vvuk/skia,PAC-ROM/android_external_skia,suyouxin/android_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,chenlian2015/skia_from_google,aosp-mirror/platform_external_skia,Plain-Andy/android_platform_external_skia,Pure-Aosp/android_external_skia,nvoron23/skia,TeamTwisted/external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,Hikari-no-Tenshi/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,UBERMALLOW/external_skia,TeslaOS/android_external_skia,Plain-Andy/android_platform_external_skia,pacerom/external_skia,Fusion-Rom/external_chromium_org_third_party_skia,larsbergstrom/skia,AOSPU/external_chromium_org_third_party_skia,boulzordev/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,HalCanary/skia-hc,samuelig/skia,RadonX-ROM/external_skia,pacerom/external_skia,geekboxzone/mmallow_external_skia,tmpvar/skia.cc,mydongistiny/android_external_skia,chenlian2015/skia_from_google,MyAOSP/external_chromium_org_third_party_skia,geekboxzone/lollipop_external_skia,PAC-ROM/android_external_skia,rubenvb/skia,amyvmiwei/skia,pacerom/external_skia,TeamBliss-LP/android_external_skia,akiss77/skia,xin3liang/platform_external_chromium_org_third_party_skia,Android-AOSP/external_skia,todotodoo/skia,ench0/external_chromium_org_third_party_skia,ominux/skia,Pure-Aosp/android_external_skia,AOSPB/external_skia,TeamExodus/external_skia,geekboxzone/lollipop_external_skia,geekboxzone/lollipop_external_skia,AOSPU/external_chromium_org_third_party_skia,w3nd1go/android_external_skia,geekboxzone/lollipop_external_skia,UBERMALLOW/external_skia,Fusion-Rom/android_external_skia,android-ia/platform_external_chromium_org_third_party_skia,SlimSaber/android_external_skia,Infinitive-OS/platform_external_skia,chenlian2015/skia_from_google,AsteroidOS/android_external_skia,F-AOSP/platform_external_skia,akiss77/skia,DARKPOP/external_chromium_org_third_party_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,OneRom/external_skia,sigysmund/platform_external_skia,sigysmund/platform_external_skia,amyvmiwei/skia,DesolationStaging/android_external_skia,sudosurootdev/external_skia,scroggo/skia,OptiPop/external_chromium_org_third_party_skia,zhaochengw/platform_external_skia,Infinitive-OS/platform_external_skia,NamelessRom/android_external_skia,AOSPU/external_chromium_org_third_party_skia,NamelessRom/android_external_skia,AOSPB/external_skia,Hikari-no-Tenshi/android_external_skia,wildermason/external_skia,TeamTwisted/external_skia,MinimalOS/external_chromium_org_third_party_skia,google/skia,MIPS/external-chromium_org-third_party-skia,AOSPU/external_chromium_org_third_party_skia,zhaochengw/platform_external_skia,sombree/android_external_skia,akiss77/skia,GladeRom/android_external_skia,akiss77/skia,MinimalOS-AOSP/platform_external_skia,Infinitive-OS/platform_external_skia,invisiblek/android_external_skia,amyvmiwei/skia,F-AOSP/platform_external_skia,mmatyas/skia,MyAOSP/external_chromium_org_third_party_skia,vanish87/skia,tmpvar/skia.cc,larsbergstrom/skia,DARKPOP/external_chromium_org_third_party_skia,amyvmiwei/skia,samuelig/skia,MinimalOS-AOSP/platform_external_skia,mmatyas/skia,CyanogenMod/android_external_chromium_org_third_party_skia,MinimalOS/external_chromium_org_third_party_skia,TeslaOS/android_external_skia,TeslaProject/external_skia,ctiao/platform-external-skia,BrokenROM/external_skia,FusionSP/android_external_skia,sombree/android_external_skia,ench0/external_skia,geekboxzone/lollipop_external_skia,tmpvar/skia.cc,TeamEOS/external_chromium_org_third_party_skia,houst0nn/external_skia,nfxosp/platform_external_skia,TeamEOS/external_skia,OneRom/external_skia,Samsung/skia,UBERMALLOW/external_skia,MinimalOS/external_chromium_org_third_party_skia,YUPlayGodDev/platform_external_skia,Omegaphora/external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,MinimalOS-AOSP/platform_external_skia,Khaon/android_external_skia,Hikari-no-Tenshi/android_external_skia,sombree/android_external_skia,MinimalOS-AOSP/platform_external_skia,Fusion-Rom/android_external_skia,Fusion-Rom/android_external_skia,Tesla-Redux/android_external_skia,Tesla-Redux/android_external_skia,mydongistiny/android_external_skia,boulzordev/android_external_skia,noselhq/skia,Omegaphora/external_chromium_org_third_party_skia,nvoron23/skia,w3nd1go/android_external_skia,OptiPop/external_skia,TeamEOS/external_chromium_org_third_party_skia,sigysmund/platform_external_skia,MyAOSP/external_chromium_org_third_party_skia,nfxosp/platform_external_skia,mmatyas/skia,FusionSP/android_external_skia,google/skia,FusionSP/external_chromium_org_third_party_skia,timduru/platform-external-skia,DesolationStaging/android_external_skia,TeamExodus/external_skia,fire855/android_external_skia,ench0/external_skia,F-AOSP/platform_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,nvoron23/skia,google/skia,MIPS/external-chromium_org-third_party-skia,amyvmiwei/skia,OneRom/external_skia,shahrzadmn/skia,MinimalOS/external_chromium_org_third_party_skia,Asteroid-Project/android_external_skia,HalCanary/skia-hc,vvuk/skia,MarshedOut/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,android-ia/platform_external_chromium_org_third_party_skia,Jichao/skia,MinimalOS/android_external_skia,Khaon/android_external_skia,BrokenROM/external_skia,MinimalOS/external_skia,OneRom/external_skia,AOSP-YU/platform_external_skia,sudosurootdev/external_skia,ctiao/platform-external-skia,byterom/android_external_skia,vvuk/skia,ctiao/platform-external-skia,TeamEOS/external_chromium_org_third_party_skia,noselhq/skia,AndroidOpenDevelopment/android_external_skia,SlimSaber/android_external_skia,aospo/platform_external_skia,Plain-Andy/android_platform_external_skia,Infusion-OS/android_external_skia,HealthyHoney/temasek_SKIA,rubenvb/skia,Omegaphora/external_skia,geekboxzone/mmallow_external_skia,vanish87/skia,HalCanary/skia-hc,TeamTwisted/external_skia,rubenvb/skia,spezi77/android_external_skia,YUPlayGodDev/platform_external_skia,mydongistiny/external_chromium_org_third_party_skia,sigysmund/platform_external_skia,android-ia/platform_external_chromium_org_third_party_skia,Infusion-OS/android_external_skia,rubenvb/skia,Hybrid-Rom/external_skia,MarshedOut/android_external_skia,Omegaphora/external_skia,aospo/platform_external_skia,boulzordev/android_external_skia,vvuk/skia,jtg-gg/skia,HealthyHoney/temasek_SKIA,Purity-Lollipop/platform_external_skia,DesolationStaging/android_external_skia,PAC-ROM/android_external_skia,MonkeyZZZZ/platform_external_skia,shahrzadmn/skia,VentureROM-L/android_external_skia,Omegaphora/external_chromium_org_third_party_skia,nfxosp/platform_external_skia,akiss77/skia,android-ia/platform_external_chromium_org_third_party_skia,suyouxin/android_external_skia,nfxosp/platform_external_skia,w3nd1go/android_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,boulzordev/android_external_skia,RadonX-ROM/external_skia,AsteroidOS/android_external_skia,Fusion-Rom/android_external_skia,AOSP-YU/platform_external_skia,geekboxzone/mmallow_external_skia,Infusion-OS/android_external_skia,temasek/android_external_skia,InfinitiveOS/external_skia,GladeRom/android_external_skia,MinimalOS-AOSP/platform_external_skia,mmatyas/skia,pcwalton/skia,YUPlayGodDev/platform_external_skia,geekboxzone/mmallow_external_skia,AOSPB/external_skia,pcwalton/skia,PAC-ROM/android_external_skia,VRToxin-AOSP/android_external_skia,OneRom/external_skia,MinimalOS/external_skia,sudosurootdev/external_skia,AOSP-YU/platform_external_skia,Tesla-Redux/android_external_skia,TeamEOS/external_skia,wildermason/external_skia,vvuk/skia,AOSPA-L/android_external_skia,wildermason/external_skia,MyAOSP/external_chromium_org_third_party_skia,Plain-Andy/android_platform_external_skia,samuelig/skia,Omegaphora/external_skia,nox/skia,Euphoria-OS-Legacy/android_external_skia,MyAOSP/external_chromium_org_third_party_skia,shahrzadmn/skia,TeamExodus/external_skia,Samsung/skia,larsbergstrom/skia,Android-AOSP/external_skia,w3nd1go/android_external_skia,ominux/skia,MinimalOS/android_external_skia,Fusion-Rom/android_external_skia,Fusion-Rom/android_external_skia,Pure-Aosp/android_external_skia,android-ia/platform_external_skia,akiss77/skia,SlimSaber/android_external_skia,Samsung/skia,VentureROM-L/android_external_skia,MinimalOS/android_external_skia,aospo/platform_external_skia,nvoron23/skia,AOSPB/external_skia,Khaon/android_external_skia,todotodoo/skia,DesolationStaging/android_external_skia,temasek/android_external_skia,ench0/external_skia,nox/skia,Hikari-no-Tenshi/android_external_skia,TeamTwisted/external_skia,HealthyHoney/temasek_SKIA,InfinitiveOS/external_skia,AOSPU/external_chromium_org_third_party_skia,DiamondLovesYou/skia-sys,GladeRom/android_external_skia,MinimalOS/external_skia,rubenvb/skia,aosp-mirror/platform_external_skia,Omegaphora/external_chromium_org_third_party_skia,ominux/skia,shahrzadmn/skia,HalCanary/skia-hc,mydongistiny/external_chromium_org_third_party_skia,Purity-Lollipop/platform_external_skia,TeslaProject/external_skia,zhaochengw/platform_external_skia,google/skia,pcwalton/skia,temasek/android_external_skia,InfinitiveOS/external_skia,nfxosp/platform_external_skia,Hikari-no-Tenshi/android_external_skia,AOSPB/external_skia,Fusion-Rom/external_chromium_org_third_party_skia,TeamBliss-LP/android_external_skia,temasek/android_external_skia,Plain-Andy/android_platform_external_skia,scroggo/skia,aospo/platform_external_skia,sigysmund/platform_external_skia,xzzz9097/android_external_skia,rubenvb/skia,TeamEOS/external_skia,tmpvar/skia.cc,rubenvb/skia,temasek/android_external_skia,android-ia/platform_external_chromium_org_third_party_skia,Igalia/skia,MonkeyZZZZ/platform_external_skia,Samsung/skia,DARKPOP/external_chromium_org_third_party_skia,mozilla-b2g/external_skia,HalCanary/skia-hc,YUPlayGodDev/platform_external_skia,Plain-Andy/android_platform_external_skia,Pure-Aosp/android_external_skia,vvuk/skia,MinimalOS/external_chromium_org_third_party_skia,aosp-mirror/platform_external_skia,OptiPop/external_chromium_org_third_party_skia,scroggo/skia,TeslaProject/external_skia,byterom/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,CyanogenMod/android_external_chromium_org_third_party_skia,geekboxzone/mmallow_external_skia,temasek/android_external_skia,Infinitive-OS/platform_external_skia,timduru/platform-external-skia,ominux/skia,zhaochengw/platform_external_skia,Samsung/skia,invisiblek/android_external_skia,samuelig/skia,TeamBliss-LP/android_external_skia,ench0/external_skia,OptiPop/external_chromium_org_third_party_skia,AOSP-YU/platform_external_skia,Purity-Lollipop/platform_external_skia,nfxosp/platform_external_skia,MinimalOS/external_skia,invisiblek/android_external_skia,Khaon/android_external_skia,geekboxzone/lollipop_external_skia,DiamondLovesYou/skia-sys,mydongistiny/android_external_skia,MinimalOS/external_skia,Purity-Lollipop/platform_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,BrokenROM/external_skia,AndroidOpenDevelopment/android_external_skia,GladeRom/android_external_skia,Omegaphora/external_chromium_org_third_party_skia,sudosurootdev/external_skia,FusionSP/android_external_skia,larsbergstrom/skia,chenlian2015/skia_from_google,houst0nn/external_skia,mozilla-b2g/external_skia,xzzz9097/android_external_skia,byterom/android_external_skia,invisiblek/android_external_skia,VentureROM-L/android_external_skia,geekboxzone/mmallow_external_skia,fire855/android_external_skia,rubenvb/skia,Pure-Aosp/android_external_skia,AndroidOpenDevelopment/android_external_skia,MarshedOut/android_external_skia,codeaurora-unoffical/platform-external-skia,MinimalOS/android_external_skia,InfinitiveOS/external_skia,android-ia/platform_external_chromium_org_third_party_skia,sombree/android_external_skia,AOSP-YU/platform_external_skia,geekboxzone/lollipop_external_skia,AOSPA-L/android_external_skia,aosp-mirror/platform_external_skia,BrokenROM/external_skia,OneRom/external_skia,OptiPop/external_chromium_org_third_party_skia,shahrzadmn/skia,zhaochengw/platform_external_skia,ench0/external_chromium_org_third_party_skia,Pure-Aosp/android_external_skia,AndroidOpenDevelopment/android_external_skia,jtg-gg/skia,RadonX-ROM/external_skia,android-ia/platform_external_skia,sudosurootdev/external_skia,Tesla-Redux/android_external_skia,Omegaphora/external_chromium_org_third_party_skia,sombree/android_external_skia,timduru/platform-external-skia,TeslaProject/external_skia,invisiblek/android_external_skia,VentureROM-L/android_external_skia,qrealka/skia-hc,OptiPop/external_skia,boulzordev/android_external_skia,MonkeyZZZZ/platform_external_skia,MyAOSP/external_chromium_org_third_party_skia,DiamondLovesYou/skia-sys,todotodoo/skia,vvuk/skia,mydongistiny/android_external_skia,MarshedOut/android_external_skia,Android-AOSP/external_skia,android-ia/platform_external_skia,suyouxin/android_external_skia,TeamExodus/external_skia,android-ia/platform_external_skia,Tesla-Redux/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,OptiPop/external_chromium_org_third_party_skia,MinimalOS-AOSP/platform_external_skia,timduru/platform-external-skia,PAC-ROM/android_external_skia,codeaurora-unoffical/platform-external-skia,pacerom/external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,scroggo/skia,ctiao/platform-external-skia,AndroidOpenDevelopment/android_external_skia,spezi77/android_external_skia,AOSP-YU/platform_external_skia,google/skia,tmpvar/skia.cc,qrealka/skia-hc,Khaon/android_external_skia,FusionSP/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,ench0/external_skia,MonkeyZZZZ/platform_external_skia,w3nd1go/android_external_skia,vanish87/skia,BrokenROM/external_skia,Omegaphora/external_skia,Khaon/android_external_skia,TeamEOS/external_chromium_org_third_party_skia,todotodoo/skia,Omegaphora/external_skia,Asteroid-Project/android_external_skia,InfinitiveOS/external_skia,w3nd1go/android_external_skia,pcwalton/skia,DiamondLovesYou/skia-sys,Infusion-OS/android_external_skia,qrealka/skia-hc,nvoron23/skia,aosp-mirror/platform_external_skia,MinimalOS/android_external_skia,nfxosp/platform_external_skia,samuelig/skia,MIPS/external-chromium_org-third_party-skia,Infinitive-OS/platform_external_skia,Infinitive-OS/platform_external_skia,mydongistiny/android_external_skia,InfinitiveOS/external_skia,Jichao/skia,spezi77/android_external_skia,FusionSP/external_chromium_org_third_party_skia,larsbergstrom/skia,akiss77/skia,qrealka/skia-hc,HalCanary/skia-hc,MIPS/external-chromium_org-third_party-skia,suyouxin/android_external_skia,vanish87/skia,DARKPOP/external_chromium_org_third_party_skia,noselhq/skia,Khaon/android_external_skia,samuelig/skia,FusionSP/external_chromium_org_third_party_skia,byterom/android_external_skia,OptiPop/external_skia,VentureROM-L/android_external_skia,scroggo/skia,RadonX-ROM/external_skia,google/skia,Android-AOSP/external_skia,TeslaProject/external_skia,Euphoria-OS-Legacy/android_external_skia,noselhq/skia,jtg-gg/skia,google/skia,TeamTwisted/external_skia,spezi77/android_external_skia,akiss77/skia,byterom/android_external_skia,vanish87/skia,jtg-gg/skia,larsbergstrom/skia,sombree/android_external_skia,sigysmund/platform_external_skia,android-ia/platform_external_skia,fire855/android_external_skia,noselhq/skia,MinimalOS/external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,MinimalOS-AOSP/platform_external_skia,shahrzadmn/skia,amyvmiwei/skia,TeamExodus/external_skia,shahrzadmn/skia,Asteroid-Project/android_external_skia,zhaochengw/platform_external_skia,Khaon/android_external_skia,noselhq/skia,invisiblek/android_external_skia,NamelessRom/android_external_skia,nox/skia,VRToxin-AOSP/android_external_skia,SlimSaber/android_external_skia,Hybrid-Rom/external_skia,todotodoo/skia,mmatyas/skia,noselhq/skia,vvuk/skia,Igalia/skia,Jichao/skia,RadonX-ROM/external_skia,AOSPA-L/android_external_skia,sigysmund/platform_external_skia,fire855/android_external_skia,NamelessRom/android_external_skia,mydongistiny/external_chromium_org_third_party_skia,MinimalOS/android_external_skia,vanish87/skia,TeslaOS/android_external_skia,timduru/platform-external-skia,MyAOSP/external_chromium_org_third_party_skia,sombree/android_external_skia,temasek/android_external_skia,Infusion-OS/android_external_skia,SlimSaber/android_external_skia,todotodoo/skia,Jichao/skia,Fusion-Rom/external_chromium_org_third_party_skia,AOSPB/external_skia,HalCanary/skia-hc,Omegaphora/external_skia,google/skia,sudosurootdev/external_skia,spezi77/android_external_skia,mozilla-b2g/external_skia,w3nd1go/android_external_skia,RadonX-ROM/external_skia,TeamTwisted/external_skia,AOSPA-L/android_external_skia,pcwalton/skia,HalCanary/skia-hc,zhaochengw/platform_external_skia,TeamEOS/external_skia,sudosurootdev/external_skia,Hybrid-Rom/external_skia,Samsung/skia,Fusion-Rom/external_chromium_org_third_party_skia,SlimSaber/android_external_skia,houst0nn/external_skia,shahrzadmn/skia,DiamondLovesYou/skia-sys,geekboxzone/lollipop_external_chromium_org_third_party_skia,amyvmiwei/skia,UBERMALLOW/external_skia,RadonX-ROM/external_skia,NamelessRom/android_external_skia,UBERMALLOW/external_skia,Android-AOSP/external_skia,vanish87/skia,nvoron23/skia,AOSPB/external_skia,OptiPop/external_skia,android-ia/platform_external_skia,tmpvar/skia.cc,pcwalton/skia,TeamTwisted/external_skia,Fusion-Rom/android_external_skia,TeamExodus/external_skia,TeamEOS/external_skia,mydongistiny/android_external_skia,Jichao/skia,OneRom/external_skia,mozilla-b2g/external_skia,UBERMALLOW/external_skia,OptiPop/external_chromium_org_third_party_skia,Hikari-no-Tenshi/android_external_skia,ench0/external_chromium_org_third_party_skia,mmatyas/skia,ench0/external_skia,MarshedOut/android_external_skia,geekboxzone/lollipop_external_skia,HalCanary/skia-hc,mozilla-b2g/external_skia,TeslaOS/android_external_skia,pacerom/external_skia,vanish87/skia,OptiPop/external_chromium_org_third_party_skia,Euphoria-OS-Legacy/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,FusionSP/external_chromium_org_third_party_skia,sigysmund/platform_external_skia,pcwalton/skia,nvoron23/skia,suyouxin/android_external_skia,tmpvar/skia.cc,mydongistiny/external_chromium_org_third_party_skia,jtg-gg/skia,Plain-Andy/android_platform_external_skia,nox/skia,MIPS/external-chromium_org-third_party-skia,nvoron23/skia,VRToxin-AOSP/android_external_skia,chenlian2015/skia_from_google,Hybrid-Rom/external_skia,mozilla-b2g/external_skia,MinimalOS/android_external_chromium_org_third_party_skia,InfinitiveOS/external_skia,OneRom/external_skia,HealthyHoney/temasek_SKIA,codeaurora-unoffical/platform-external-skia,Asteroid-Project/android_external_skia,houst0nn/external_skia,Pure-Aosp/android_external_skia,chenlian2015/skia_from_google,Asteroid-Project/android_external_skia,nfxosp/platform_external_skia,MinimalOS-AOSP/platform_external_skia,YUPlayGodDev/platform_external_skia,OneRom/external_skia,TeamExodus/external_skia,TeslaOS/android_external_skia,AOSPA-L/android_external_skia,AsteroidOS/android_external_skia,VRToxin-AOSP/android_external_skia,Asteroid-Project/android_external_skia,wildermason/external_skia,sombree/android_external_skia,Jichao/skia,SlimSaber/android_external_skia,Hybrid-Rom/external_skia,mydongistiny/external_chromium_org_third_party_skia,DesolationStaging/android_external_skia,codeaurora-unoffical/platform-external-skia,samuelig/skia,FusionSP/android_external_skia,TeamBliss-LP/android_external_skia,ctiao/platform-external-skia,YUPlayGodDev/platform_external_skia,OptiPop/external_skia,MinimalOS/android_external_chromium_org_third_party_skia,OptiPop/external_skia,xin3liang/platform_external_chromium_org_third_party_skia,MinimalOS/android_external_chromium_org_third_party_skia,DesolationStaging/android_external_skia,F-AOSP/platform_external_skia,android-ia/platform_external_skia,pacerom/external_skia,RadonX-ROM/external_skia,noselhq/skia,BrokenROM/external_skia,Android-AOSP/external_skia,Igalia/skia,xzzz9097/android_external_skia,TeslaOS/android_external_skia,Jichao/skia,FusionSP/android_external_skia,Igalia/skia,vanish87/skia,Pure-Aosp/android_external_skia,TeslaOS/android_external_skia,wildermason/external_skia,YUPlayGodDev/platform_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,android-ia/platform_external_chromium_org_third_party_skia,Jichao/skia,InfinitiveOS/external_skia,HealthyHoney/temasek_SKIA,scroggo/skia,VRToxin-AOSP/android_external_skia,mydongistiny/external_chromium_org_third_party_skia,timduru/platform-external-skia,w3nd1go/android_external_skia,Omegaphora/external_chromium_org_third_party_skia,suyouxin/android_external_skia,jtg-gg/skia,mozilla-b2g/external_skia,OptiPop/external_skia,aosp-mirror/platform_external_skia,VentureROM-L/android_external_skia,HealthyHoney/temasek_SKIA,TeamEOS/external_chromium_org_third_party_skia,MinimalOS/external_chromium_org_third_party_skia,BrokenROM/external_skia,boulzordev/android_external_skia,houst0nn/external_skia,MIPS/external-chromium_org-third_party-skia,larsbergstrom/skia,Asteroid-Project/android_external_skia,fire855/android_external_skia,qrealka/skia-hc,MyAOSP/external_chromium_org_third_party_skia,mozilla-b2g/external_skia,MinimalOS/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,Infinitive-OS/platform_external_skia,MarshedOut/android_external_skia,scroggo/skia,VRToxin-AOSP/android_external_skia,DiamondLovesYou/skia-sys,nox/skia,TeslaProject/external_skia,ench0/external_chromium_org_third_party_skia,Jichao/skia,codeaurora-unoffical/platform-external-skia,TeslaProject/external_skia,Hikari-no-Tenshi/android_external_skia,MinimalOS/external_skia,rubenvb/skia,akiss77/skia,houst0nn/external_skia,NamelessRom/android_external_skia,aospo/platform_external_skia,TeamExodus/external_skia,DiamondLovesYou/skia-sys,google/skia,xin3liang/platform_external_chromium_org_third_party_skia,Omegaphora/external_chromium_org_third_party_skia,MinimalOS/external_chromium_org_third_party_skia,YUPlayGodDev/platform_external_skia,TeslaOS/android_external_skia,Igalia/skia,F-AOSP/platform_external_skia,VentureROM-L/android_external_skia,Purity-Lollipop/platform_external_skia,nox/skia,Euphoria-OS-Legacy/android_external_skia,chenlian2015/skia_from_google,UBERMALLOW/external_skia,AOSPA-L/android_external_skia,codeaurora-unoffical/platform-external-skia,nox/skia
8954dfc468836a3080ae0a0f55c937ad4f35da89
include/rank_filter.hxx
include/rank_filter.hxx
#ifndef __RANK_FILTER__ #define __RANK_FILTER__ #include <deque> #include <cassert> #include <functional> #include <iostream> #include <boost/container/set.hpp> #include <boost/container/node_allocator.hpp> #include <vigra/multi_array.hxx> namespace rank_filter { template<class I1, class I2> inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end, I2& dest_begin, I2& dest_end, size_t half_length, double rank) { // Types in use. using T1 = typename std::iterator_traits<I1>::value_type; using T2 = typename std::iterator_traits<I2>::value_type; // Will ignore boundaries initially. // Then will try adding reflection. // Rank must be in the range 0 to 1 assert((0 <= rank) && (rank <= 1)); const size_t rank_pos = round(rank * (2 * half_length)); // The position of the size_t window_begin = 0; // Lengths. const typename std::iterator_traits<I1>::difference_type src_size = src_end - src_begin; const typename std::iterator_traits<I2>::difference_type dest_size = dest_end - dest_begin; typedef boost::container::multiset< T1, std::less<T1>, boost::container::node_allocator<T1>, boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset; typedef std::deque< typename multiset::iterator > deque; multiset sorted_window; deque window_iters; // Get the initial sorted window. // Include the reflection. for (size_t j = half_length; j > 0; j--) { window_iters.push_back(sorted_window.insert(src_begin[window_begin + j])); } for (size_t j = 0; j <= half_length; j++) { window_iters.push_back(sorted_window.insert(src_begin[window_begin + j])); } typename multiset::iterator rank_point = sorted_window.begin(); for (size_t i = 0; i < rank_pos; i++) { rank_point++; } typename multiset::iterator prev_iter; T1 prev_value; T1 next_value; while ( window_begin < src_size ) { dest_begin[window_begin] = *rank_point; prev_iter = window_iters.front(); prev_value = *prev_iter; window_iters.pop_front(); window_begin++; if ( window_begin < (src_size - half_length) ) { next_value = src_begin[window_begin + half_length]; } else { next_value = *(window_iters[window_iters.size() + 2*src_size - 2*(window_begin + half_length) - 2]); } if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) ) { if ( rank_point == prev_iter ) { window_iters.push_back(sorted_window.insert(next_value)); rank_point--; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } } else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point--; } else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) ) { if (rank_point == prev_iter) { window_iters.push_back(sorted_window.insert(next_value)); rank_point++; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point++; } } } } template<unsigned int N, class T1, class S1, class T2, class S2, typename std::enable_if<(N == 1), int>::type = 0> inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src, vigra::MultiArrayView <N, T2, S2> dest, unsigned long half_length, double rank, unsigned int axis = 0) { typename vigra::MultiArrayView <N, T1, S1>::const_iterator src_begin = src.begin(); typename vigra::MultiArrayView <N, T1, S1>::const_iterator src_end = src.end(); typename vigra::MultiArrayView <N, T2, S2>::iterator dest_begin = dest.begin(); typename vigra::MultiArrayView <N, T2, S2>::iterator dest_end = dest.end(); lineRankOrderFilter1D(src_begin, src_end, dest_begin, dest_end, half_length, rank); } template<unsigned int N, class T1, class S1, class T2, class S2, typename std::enable_if<(N > 1), int>::type = 0> inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src, vigra::MultiArrayView <N, T2, S2> dest, unsigned long half_length, double rank, unsigned int axis = 0) { typename vigra::MultiArrayView<N, T1, S1>::difference_type transposed_axes; for (unsigned int i = 0; i < N; i++) { transposed_axes[i] = i; } std::swap(transposed_axes[0], transposed_axes[axis]); vigra::MultiArray<N, T1> src_transposed(src.transpose(transposed_axes)); vigra::MultiArrayView<N, T2, S2> dest_transposed(dest.transpose(transposed_axes)); typename vigra::MultiArrayView<N - 1, T1, S1>::difference_type pos; pos = 0; bool done = false; bool carry = true; while (!done) { lineRankOrderFilterND(src_transposed.bindOuter(pos), dest_transposed.bindOuter(pos), half_length, rank, 0); carry = true; for (unsigned int i = 0; ( carry && (i < (N - 1)) ); i++) { if ( (++pos[i]) < src_transposed.shape(i + 1) ) { carry = false; } else { pos[i] = 0; carry = true; } } done = carry; } } template<unsigned int N, class T1, class S1, class T2, class S2> inline void lineRankOrderFilter(const vigra::MultiArrayView <N, T1, S1> &src, vigra::MultiArrayView <N, T2, S2> dest, unsigned long half_length, double rank, unsigned int axis = 0) { lineRankOrderFilterND(src, dest, half_length, rank, axis); } } namespace vigra { template <unsigned int N, class T, class S, typename std::enable_if<(N == 1), int>::type = 0> std::ostream& println(std::ostream& out, const vigra::MultiArrayView<N, T, S>& array, unsigned int indent=0) { for (unsigned int i = 0; i < indent; i++) { out << " "; } out << "{ "; for (unsigned int i = 0; i < (array.shape(0) - 1); i++) { out << array[i] << ", "; } out << array[array.shape(0) - 1] << " }"; return(out); } template <unsigned int N, class T, class S, typename std::enable_if<(N > 1), int>::type = 0> std::ostream& println(std::ostream& out, const vigra::MultiArrayView<N, T, S>& array, unsigned int indent=0) { for (unsigned int i = 0; i < indent; i++) { out << " "; } out << "{" << std::endl; for (unsigned int i = 0; i < (array.shape(0) - 1); i++) { println(out, array.bindOuter(i), indent+1); out << ", " << std::endl; } println(out, array.bindOuter(array.shape(0) - 1), indent+1); out << std::endl; for (unsigned int i = 0; i < indent; i++) { out << " "; } out << "}"; return(out); } template <unsigned int N, class T, class S> std::ostream& operator<<(std::ostream& out, const vigra::MultiArrayView<N, T, S>& array) { return(println(out, array)); } } #endif //__RANK_FILTER__
#ifndef __RANK_FILTER__ #define __RANK_FILTER__ #include <iostream> #include <vigra/multi_array.hxx> #include "rank_filter_base.hxx" namespace rank_filter { template<unsigned int N, class T1, class S1, class T2, class S2, typename std::enable_if<(N == 1), int>::type = 0> inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src, vigra::MultiArrayView <N, T2, S2> dest, unsigned long half_length, double rank, unsigned int axis = 0) { typename vigra::MultiArrayView <N, T1, S1>::const_iterator src_begin = src.begin(); typename vigra::MultiArrayView <N, T1, S1>::const_iterator src_end = src.end(); typename vigra::MultiArrayView <N, T2, S2>::iterator dest_begin = dest.begin(); typename vigra::MultiArrayView <N, T2, S2>::iterator dest_end = dest.end(); lineRankOrderFilter1D(src_begin, src_end, dest_begin, dest_end, half_length, rank); } template<unsigned int N, class T1, class S1, class T2, class S2, typename std::enable_if<(N > 1), int>::type = 0> inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src, vigra::MultiArrayView <N, T2, S2> dest, unsigned long half_length, double rank, unsigned int axis = 0) { typename vigra::MultiArrayView<N, T1, S1>::difference_type transposed_axes; for (unsigned int i = 0; i < N; i++) { transposed_axes[i] = i; } std::swap(transposed_axes[0], transposed_axes[axis]); vigra::MultiArray<N, T1> src_transposed(src.transpose(transposed_axes)); vigra::MultiArrayView<N, T2, S2> dest_transposed(dest.transpose(transposed_axes)); typename vigra::MultiArrayView<N - 1, T1, S1>::difference_type pos; pos = 0; bool done = false; bool carry = true; while (!done) { lineRankOrderFilterND(src_transposed.bindOuter(pos), dest_transposed.bindOuter(pos), half_length, rank, 0); carry = true; for (unsigned int i = 0; ( carry && (i < (N - 1)) ); i++) { if ( (++pos[i]) < src_transposed.shape(i + 1) ) { carry = false; } else { pos[i] = 0; carry = true; } } done = carry; } } template<unsigned int N, class T1, class S1, class T2, class S2> inline void lineRankOrderFilter(const vigra::MultiArrayView <N, T1, S1> &src, vigra::MultiArrayView <N, T2, S2> dest, unsigned long half_length, double rank, unsigned int axis = 0) { lineRankOrderFilterND(src, dest, half_length, rank, axis); } } namespace vigra { template <unsigned int N, class T, class S, typename std::enable_if<(N == 1), int>::type = 0> std::ostream& println(std::ostream& out, const vigra::MultiArrayView<N, T, S>& array, unsigned int indent=0) { for (unsigned int i = 0; i < indent; i++) { out << " "; } out << "{ "; for (unsigned int i = 0; i < (array.shape(0) - 1); i++) { out << array[i] << ", "; } out << array[array.shape(0) - 1] << " }"; return(out); } template <unsigned int N, class T, class S, typename std::enable_if<(N > 1), int>::type = 0> std::ostream& println(std::ostream& out, const vigra::MultiArrayView<N, T, S>& array, unsigned int indent=0) { for (unsigned int i = 0; i < indent; i++) { out << " "; } out << "{" << std::endl; for (unsigned int i = 0; i < (array.shape(0) - 1); i++) { println(out, array.bindOuter(i), indent+1); out << ", " << std::endl; } println(out, array.bindOuter(array.shape(0) - 1), indent+1); out << std::endl; for (unsigned int i = 0; i < indent; i++) { out << " "; } out << "}"; return(out); } template <unsigned int N, class T, class S> std::ostream& operator<<(std::ostream& out, const vigra::MultiArrayView<N, T, S>& array) { return(println(out, array)); } } #endif //__RANK_FILTER__
Include the base header file here so as to reuse the API it provides.
include/rank_filter.hxx: Include the base header file here so as to reuse the API it provides.
C++
bsd-3-clause
jakirkham/rank_filter,DudLab/rank_filter,nanshe-org/rank_filter,jakirkham/rank_filter,nanshe-org/rank_filter,jakirkham/rank_filter,nanshe-org/rank_filter,DudLab/rank_filter,DudLab/rank_filter
1633311d3f9e4e2c32d16734219a3b58eb85dbe2
gnelib/src/GNE.cpp
gnelib/src/GNE.cpp
/* GNE - Game Networking Engine, a portable multithreaded networking library. * Copyright (C) 2001 Jason Winnebeck ([email protected]) * Project website: http://www.rit.edu/~jpw9607/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "../include/gnelib/gneintern.h" #include "../include/gnelib/ConnectionEventGenerator.h" #include "../include/gnelib/ConnectionStats.h" #include "../include/gnelib/PacketParser.h" #include "../include/gnelib/GNE.h" #include "../include/gnelib/Address.h" #include "../include/gnelib/Error.h" #include "../include/gnelib/Errors.h" #include "../include/gnelib/PingPacket.h" #ifndef WIN32 #include <signal.h> #endif namespace GNE { namespace PacketParser { //this is declared here only so the user cannot access it, and the "real" //function can do checking on the ID given to it. void registerGNEPackets(); } char gameNameBuf[32] = {0}; guint32 userVersion = 0; ConnectionEventGenerator* eGen = NULL; static bool initialized = false; bool initGNE(NLenum networkType, int (*atexit_ptr)(void (*func)(void))) { if (!initialized) { gnedbg(1, "GNE initalized"); PacketParser::registerGNEPackets(); if (networkType != NO_NET) { if (nlInit() == NL_FALSE) return true; if (nlSelectNetwork(networkType) == NL_FALSE) return true; nlEnable(NL_BLOCKING_IO); nlEnable(NL_TCP_NO_DELAY); //GNE sends its data in little endian format. nlEnable(NL_LITTLE_ENDIAN_DATA); nlDisable(NL_SOCKET_STATS); eGen = new ConnectionEventGenerator(); eGen->start(); initialized = true; //We need only to set this to true if we are using HawkNL } #ifndef WIN32 signal(SIGPIPE, SIG_IGN); #endif atexit_ptr(shutdownGNE); return false; } return false; } void shutdownGNE() { if (initialized) { eGen->shutDown(); eGen->join(); delete eGen; nlShutdown(); initialized = false; gnedbg(1, "Closed GNE"); #ifdef _DEBUG killDebug(); //closes debugging if it was opened #endif } } Address getLocalAddress() { assert(initialized); NLaddress nlAddr; NLsocket temp = nlOpen(0, NL_RELIABLE); nlGetLocalAddr(temp, &nlAddr); nlClose(temp); Address ret(nlAddr); ret.setPort(0); return ret; } ConnectionStats getGlobalStats() { assert(initialized); ConnectionStats ret; ret.packetsSent = nlGetInteger(NL_PACKETS_SENT); ret.bytesSent = nlGetInteger(NL_BYTES_SENT); ret.avgBytesSent = nlGetInteger(NL_AVE_BYTES_SENT); ret.maxAvgBytesSent = nlGetInteger(NL_HIGH_BYTES_SENT); ret.packetsRecv = nlGetInteger(NL_PACKETS_RECEIVED); ret.bytesRecv = nlGetInteger(NL_BYTES_RECEIVED); ret.avgBytesRecv = nlGetInteger(NL_AVE_BYTES_RECEIVED); ret.maxAvgBytesRecv = nlGetInteger(NL_HIGH_BYTES_RECEIVED); ret.openSockets = nlGetInteger(NL_OPEN_SOCKETS); return ret; } void enableStats() { assert(initialized); nlEnable(NL_SOCKET_STATS); } void disableStats() { assert(initialized); nlDisable(NL_SOCKET_STATS); } void clearStats() { assert(initialized); nlClear(NL_ALL_STATS); } int getOpenConnections() { assert(initialized); return nlGetInteger(NL_OPEN_SOCKETS); } GNEProtocolVersionNumber getGNEProtocolVersion() { assert(initialized); GNEProtocolVersionNumber ret; ret.version = 0; ret.subVersion = 0; ret.build = 5; return ret; } const char* getGameName() { return gameNameBuf; } guint32 getUserVersion() { assert(initialized); return userVersion; } void setGameInformation(std::string gameName, guint32 version) { assert(initialized); assert(gameName.length() <= (std::string::size_type)GNE::MAX_GAME_NAME_LEN); //We do this assert since this function should only be called once. assert(gameNameBuf[0] == 0); userVersion = version; strncpy(gameNameBuf, gameName.c_str(), MAX_GAME_NAME_LEN); } void checkVersions(const GNEProtocolVersionNumber& otherGNE, std::string otherName, guint32 otherUser) { GNEProtocolVersionNumber us = getGNEProtocolVersion(); //Check the GNE version numbers if (otherGNE.version != us.version || otherGNE.subVersion != us.subVersion || otherGNE.build != us.build) { if ((otherGNE.version > us.version) || (otherGNE.version == us.version && otherGNE.subVersion > us.subVersion) || (otherGNE.subVersion == us.subVersion && otherGNE.build > us.build)) throw Error(Error::GNETheirVersionHigh); else throw Error(Error::GNETheirVersionLow); } //Check the game name if (otherName != gameNameBuf) throw WrongGame(otherName); //Check the user version numbers if (userVersion != otherUser) throw UserVersionMismatch(otherUser); } }
/* GNE - Game Networking Engine, a portable multithreaded networking library. * Copyright (C) 2001 Jason Winnebeck ([email protected]) * Project website: http://www.rit.edu/~jpw9607/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "../include/gnelib/gneintern.h" #include "../include/gnelib/ConnectionEventGenerator.h" #include "../include/gnelib/ConnectionStats.h" #include "../include/gnelib/PacketParser.h" #include "../include/gnelib/GNE.h" #include "../include/gnelib/Address.h" #include "../include/gnelib/Error.h" #include "../include/gnelib/Errors.h" #include "../include/gnelib/PingPacket.h" #ifndef WIN32 #include <signal.h> #endif namespace GNE { namespace PacketParser { //this is declared here only so the user cannot access it, and the "real" //function can do checking on the ID given to it. void registerGNEPackets(); } char gameNameBuf[32] = {0}; guint32 userVersion = 0; ConnectionEventGenerator* eGen = NULL; static bool initialized = false; bool initGNE(NLenum networkType, int (*atexit_ptr)(void (*func)(void))) { if (!initialized) { gnedbg(1, "GNE initalized"); PacketParser::registerGNEPackets(); if (networkType != NO_NET) { if (nlInit() == NL_FALSE) return true; if (nlSelectNetwork(networkType) == NL_FALSE) return true; nlEnable(NL_BLOCKING_IO); nlEnable(NL_TCP_NO_DELAY); //GNE sends its data in little endian format. nlEnable(NL_LITTLE_ENDIAN_DATA); nlDisable(NL_SOCKET_STATS); eGen = new ConnectionEventGenerator(); eGen->start(); initialized = true; //We need only to set this to true if we are using HawkNL } #ifndef WIN32 signal(SIGPIPE, SIG_IGN); #endif atexit_ptr(shutdownGNE); return false; } return false; } void shutdownGNE() { if (initialized) { eGen->shutDown(); eGen->join(); delete eGen; nlShutdown(); initialized = false; gnedbg(1, "Closed GNE"); #ifdef _DEBUG killDebug(); //closes debugging if it was opened #endif } } Address getLocalAddress() { assert(initialized); NLaddress nlAddr; NLsocket temp = nlOpen(0, NL_RELIABLE); nlGetLocalAddr(temp, &nlAddr); nlClose(temp); Address ret(nlAddr); ret.setPort(0); return ret; } ConnectionStats getGlobalStats() { assert(initialized); ConnectionStats ret; ret.packetsSent = nlGetInteger(NL_PACKETS_SENT); ret.bytesSent = nlGetInteger(NL_BYTES_SENT); ret.avgBytesSent = nlGetInteger(NL_AVE_BYTES_SENT); ret.maxAvgBytesSent = nlGetInteger(NL_HIGH_BYTES_SENT); ret.packetsRecv = nlGetInteger(NL_PACKETS_RECEIVED); ret.bytesRecv = nlGetInteger(NL_BYTES_RECEIVED); ret.avgBytesRecv = nlGetInteger(NL_AVE_BYTES_RECEIVED); ret.maxAvgBytesRecv = nlGetInteger(NL_HIGH_BYTES_RECEIVED); ret.openSockets = nlGetInteger(NL_OPEN_SOCKETS); return ret; } void enableStats() { assert(initialized); nlEnable(NL_SOCKET_STATS); } void disableStats() { assert(initialized); nlDisable(NL_SOCKET_STATS); } void clearStats() { assert(initialized); nlClear(NL_ALL_STATS); } int getOpenConnections() { assert(initialized); return nlGetInteger(NL_OPEN_SOCKETS); } GNEProtocolVersionNumber getGNEProtocolVersion() { assert(initialized); GNEProtocolVersionNumber ret; ret.version = 0; ret.subVersion = 0; ret.build = 6; return ret; } const char* getGameName() { return gameNameBuf; } guint32 getUserVersion() { assert(initialized); return userVersion; } void setGameInformation(std::string gameName, guint32 version) { assert(initialized); assert(gameName.length() <= (std::string::size_type)GNE::MAX_GAME_NAME_LEN); //We do this assert since this function should only be called once. assert(gameNameBuf[0] == 0); userVersion = version; strncpy(gameNameBuf, gameName.c_str(), MAX_GAME_NAME_LEN); } void checkVersions(const GNEProtocolVersionNumber& otherGNE, std::string otherName, guint32 otherUser) { GNEProtocolVersionNumber us = getGNEProtocolVersion(); //Check the GNE version numbers if (otherGNE.version != us.version || otherGNE.subVersion != us.subVersion || otherGNE.build != us.build) { if ((otherGNE.version > us.version) || (otherGNE.version == us.version && otherGNE.subVersion > us.subVersion) || (otherGNE.subVersion == us.subVersion && otherGNE.build > us.build)) throw Error(Error::GNETheirVersionHigh); else throw Error(Error::GNETheirVersionLow); } //Check the game name if (otherName != gameNameBuf) throw WrongGame(otherName); //Check the user version numbers if (userVersion != otherUser) throw UserVersionMismatch(otherUser); } }
Increment build no
Increment build no
C++
lgpl-2.1
gillius/gnelib,gillius/gnelib
3be523ed3ab62dbc1be6971355ebc95830f4183c
net/krb5auth/src/TKSocket.cxx
net/krb5auth/src/TKSocket.cxx
// @(#)root/krb5auth:$Id$ // Author: Maarten Ballintijn 27/10/2003 #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <netinet/in.h> #ifndef WIN32 # include <unistd.h> #endif #include "TKSocket.h" #include "TSocket.h" #include "TError.h" extern "C" { // missing from "krb5.h" extern int krb5_net_read(/*IN*/ krb5_context context, int fd, /*OUT*/ char *buf,/*IN*/ int len); extern int krb5_net_write(/*IN*/ krb5_context context, int fd, const char *buf, int len); } #ifdef __APPLE__ #define SOCKET int #define SOCKET_ERRNO errno #define SOCKET_EINTR EINTR #define SOCKET_READ(a,b,c) read(a,b,c) #define SOCKET_WRITE(a,b,c) write(a,b,c) /* * lib/krb5/os/net_read.c * * Copyright 1987, 1988, 1990 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. * */ /* * krb5_net_read() reads from the file descriptor "fd" to the buffer * "buf", until either 1) "len" bytes have been read or 2) cannot * read anymore from "fd". It returns the number of bytes read * or a read() error. (The calling interface is identical to * read(2).) * * XXX must not use non-blocking I/O */ int krb5_net_read(krb5_context /*context*/, int fd, register char *buf, register int len) { int cc, len2 = 0; do { cc = SOCKET_READ((SOCKET)fd, buf, len); if (cc < 0) { if (SOCKET_ERRNO == SOCKET_EINTR) continue; /* XXX this interface sucks! */ errno = SOCKET_ERRNO; return(cc); /* errno is already set */ } else if (cc == 0) { return(len2); } else { buf += cc; len2 += cc; len -= cc; } } while (len > 0); return(len2); } /* * lib/krb5/os/net_write.c * * Copyright 1987, 1988, 1990 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. * */ /* * krb5_net_write() writes "len" bytes from "buf" to the file * descriptor "fd". It returns the number of bytes written or * a write() error. (The calling interface is identical to * write(2).) * * XXX must not use non-blocking I/O */ int krb5_net_write(krb5_context /*context*/, int fd, register const char *buf, int len) { int cc; register int wrlen = len; do { cc = SOCKET_WRITE((SOCKET)fd, buf, wrlen); if (cc < 0) { if (SOCKET_ERRNO == SOCKET_EINTR) continue; /* XXX this interface sucks! */ errno = SOCKET_ERRNO; return(cc); } else { buf += cc; wrlen -= cc; } } while (wrlen > 0); return(len); } #endif ClassImp(TKSocket) krb5_context TKSocket::fgContext = 0; krb5_ccache TKSocket::fgCCDef = 0; krb5_principal TKSocket::fgClient = 0; //______________________________________________________________________________ TKSocket::TKSocket(TSocket *s) : fSocket(s), fServer(0), fAuthContext(0) { // Constructor } //______________________________________________________________________________ TKSocket::~TKSocket() { // Destructor krb5_free_principal(fgContext, fServer); krb5_auth_con_free(fgContext, fAuthContext); delete fSocket; } //______________________________________________________________________________ TKSocket *TKSocket::Connect(const char *server, Int_t port) { // Connect to 'server' on 'port' Int_t rc; if (fgContext == 0) { rc = krb5_init_context(&fgContext); if (rc != 0) { ::Error("TKSocket::Connect","while initializing krb5 (%d), %s", rc, error_message(rc)); return 0; } rc = krb5_cc_default(fgContext, &fgCCDef); if (rc != 0) { ::Error("TKSocket::Connect","while getting default credential cache (%d), %s", rc, error_message(rc)); krb5_free_context(fgContext); fgContext = 0; return 0; } rc = krb5_cc_get_principal(fgContext, fgCCDef, &fgClient); if (rc != 0) { ::Error("TKSocket::Connect","while getting client principal from %s (%d), %s", krb5_cc_get_name(fgContext,fgCCDef), rc, error_message(rc)); krb5_cc_close(fgContext,fgCCDef); fgCCDef = 0; krb5_free_context(fgContext); fgContext = 0; return 0; } } TSocket *s = new TSocket(server, port); if (!s->IsValid()) { ::SysError("TKSocket::Connect","Cannot connect to %s:%d", server, port); delete s; return 0; } TKSocket *ks = new TKSocket(s); rc = krb5_sname_to_principal(fgContext, server, "host", KRB5_NT_SRV_HST, &ks->fServer); if (rc != 0) { ::Error("TKSocket::Connect","while getting server principal (%d), %s", rc, error_message(rc)); delete ks; return 0; } krb5_data cksum_data; cksum_data.data = StrDup(server); cksum_data.length = strlen(server); krb5_error *err_ret; krb5_ap_rep_enc_part *rep_ret; int sock = ks->fSocket->GetDescriptor(); rc = krb5_sendauth(fgContext, &ks->fAuthContext, (krb5_pointer) &sock, (char *)"KRB5_TCP_Python_v1.0", fgClient, ks->fServer, AP_OPTS_MUTUAL_REQUIRED, &cksum_data, 0, /* no creds, use ccache instead */ fgCCDef, &err_ret, &rep_ret, 0); delete [] cksum_data.data; if (rc != 0) { ::Error("TKSocket::Connect","while sendauth (%d), %s", rc, error_message(rc)); delete ks; return 0; } return ks; } //______________________________________________________________________________ Int_t TKSocket::BlockRead(char *&buf, EEncoding &type) { // Read block on information from server. The result is stored in buf. // The number of read bytes is returned; -1 is returned in case of error. Int_t rc; Desc_t desc; Int_t fd = fSocket->GetDescriptor(); rc = krb5_net_read(fgContext, fd, (char *)&desc, sizeof(desc)); if (rc == 0) errno = ECONNABORTED; if (rc <= 0) { SysError("BlockRead","reading descriptor (%d), %s", rc, error_message(rc)); return -1; } type = static_cast<EEncoding>(ntohs(desc.fType)); krb5_data enc; enc.length = ntohs(desc.fLength); enc.data = new char[enc.length+1]; rc = krb5_net_read(fgContext, fd, enc.data, enc.length); enc.data[enc.length] = 0; if (rc == 0) errno = ECONNABORTED; if (rc <= 0) { SysError("BlockRead","reading data (%d), %s", rc, error_message(rc)); delete [] enc.data; return -1; } krb5_data out; switch (type) { case kNone: buf = enc.data; rc = enc.length; break; case kSafe: rc = krb5_rd_safe(fgContext, fAuthContext, &enc, &out, 0); break; case kPriv: rc = krb5_rd_priv(fgContext, fAuthContext, &enc, &out, 0); break; default: Error("BlockWrite","unknown encoding type (%d)", type); return -1; } if (type != kNone) { // copy data to buffer that is new'ed buf = new char[out.length+1]; memcpy(buf, out.data, out.length); buf[out.length] = 0; free(out.data); delete [] enc.data; rc = out.length; } return rc; } //______________________________________________________________________________ Int_t TKSocket::BlockWrite(const char *buf, Int_t length, EEncoding type) { // Block-send 'length' bytes to server from 'buf'. Desc_t desc; krb5_data in; krb5_data enc; Int_t rc; in.data = const_cast<char*>(buf); in.length = length; switch (type) { case kNone: enc.data = in.data; enc.length = in.length; break; case kSafe: rc = krb5_mk_safe(fgContext, fAuthContext, &in, &enc, 0); break; case kPriv: rc = krb5_mk_priv(fgContext, fAuthContext, &in, &enc, 0); break; default: Error("BlockWrite","unknown encoding type (%d)", type); return -1; } desc.fLength = htons(enc.length); desc.fType = htons(type); Int_t fd = fSocket->GetDescriptor(); rc = krb5_net_write(fgContext, fd, (char *)&desc, sizeof(desc)); if (rc <= 0) { Error("BlockWrite","writing descriptor (%d), %s", rc, error_message(rc)); return -1; } rc = krb5_net_write(fgContext, fd, (char *)enc.data, enc.length); if (rc <= 0) { Error("BlockWrite","writing data (%d), %s", rc, error_message(rc)); return -1; } if (type != kNone) free(enc.data); return rc; }
// @(#)root/krb5auth:$Id$ // Author: Maarten Ballintijn 27/10/2003 #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <netinet/in.h> #ifndef WIN32 # include <unistd.h> #endif #include "TKSocket.h" #include "TSocket.h" #include "TError.h" extern "C" { // missing from "krb5.h" extern int krb5_net_read(/*IN*/ krb5_context context, int fd, /*OUT*/ char *buf,/*IN*/ int len); extern int krb5_net_write(/*IN*/ krb5_context context, int fd, const char *buf, int len); } #ifdef __APPLE__ #define SOCKET int #define SOCKET_ERRNO errno #define SOCKET_EINTR EINTR #define SOCKET_READ(a,b,c) read(a,b,c) #define SOCKET_WRITE(a,b,c) write(a,b,c) /* * lib/krb5/os/net_read.c * * Copyright 1987, 1988, 1990 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. * */ /* * krb5_net_read() reads from the file descriptor "fd" to the buffer * "buf", until either 1) "len" bytes have been read or 2) cannot * read anymore from "fd". It returns the number of bytes read * or a read() error. (The calling interface is identical to * read(2).) * * XXX must not use non-blocking I/O */ int krb5_net_read(krb5_context /*context*/, int fd, register char *buf, register int len) { int cc, len2 = 0; do { cc = SOCKET_READ((SOCKET)fd, buf, len); if (cc < 0) { if (SOCKET_ERRNO == SOCKET_EINTR) continue; /* XXX this interface sucks! */ errno = SOCKET_ERRNO; return(cc); /* errno is already set */ } else if (cc == 0) { return(len2); } else { buf += cc; len2 += cc; len -= cc; } } while (len > 0); return(len2); } /* * lib/krb5/os/net_write.c * * Copyright 1987, 1988, 1990 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. * */ /* * krb5_net_write() writes "len" bytes from "buf" to the file * descriptor "fd". It returns the number of bytes written or * a write() error. (The calling interface is identical to * write(2).) * * XXX must not use non-blocking I/O */ int krb5_net_write(krb5_context /*context*/, int fd, register const char *buf, int len) { int cc; int wrlen = len; do { cc = SOCKET_WRITE((SOCKET)fd, buf, wrlen); if (cc < 0) { if (SOCKET_ERRNO == SOCKET_EINTR) continue; /* XXX this interface sucks! */ errno = SOCKET_ERRNO; return(cc); } else { buf += cc; wrlen -= cc; } } while (wrlen > 0); return(len); } #endif ClassImp(TKSocket) krb5_context TKSocket::fgContext = 0; krb5_ccache TKSocket::fgCCDef = 0; krb5_principal TKSocket::fgClient = 0; //______________________________________________________________________________ TKSocket::TKSocket(TSocket *s) : fSocket(s), fServer(0), fAuthContext(0) { // Constructor } //______________________________________________________________________________ TKSocket::~TKSocket() { // Destructor krb5_free_principal(fgContext, fServer); krb5_auth_con_free(fgContext, fAuthContext); delete fSocket; } //______________________________________________________________________________ TKSocket *TKSocket::Connect(const char *server, Int_t port) { // Connect to 'server' on 'port' Int_t rc; if (fgContext == 0) { rc = krb5_init_context(&fgContext); if (rc != 0) { ::Error("TKSocket::Connect","while initializing krb5 (%d), %s", rc, error_message(rc)); return 0; } rc = krb5_cc_default(fgContext, &fgCCDef); if (rc != 0) { ::Error("TKSocket::Connect","while getting default credential cache (%d), %s", rc, error_message(rc)); krb5_free_context(fgContext); fgContext = 0; return 0; } rc = krb5_cc_get_principal(fgContext, fgCCDef, &fgClient); if (rc != 0) { ::Error("TKSocket::Connect","while getting client principal from %s (%d), %s", krb5_cc_get_name(fgContext,fgCCDef), rc, error_message(rc)); krb5_cc_close(fgContext,fgCCDef); fgCCDef = 0; krb5_free_context(fgContext); fgContext = 0; return 0; } } TSocket *s = new TSocket(server, port); if (!s->IsValid()) { ::SysError("TKSocket::Connect","Cannot connect to %s:%d", server, port); delete s; return 0; } TKSocket *ks = new TKSocket(s); rc = krb5_sname_to_principal(fgContext, server, "host", KRB5_NT_SRV_HST, &ks->fServer); if (rc != 0) { ::Error("TKSocket::Connect","while getting server principal (%d), %s", rc, error_message(rc)); delete ks; return 0; } krb5_data cksum_data; cksum_data.data = StrDup(server); cksum_data.length = strlen(server); krb5_error *err_ret; krb5_ap_rep_enc_part *rep_ret; int sock = ks->fSocket->GetDescriptor(); rc = krb5_sendauth(fgContext, &ks->fAuthContext, (krb5_pointer) &sock, (char *)"KRB5_TCP_Python_v1.0", fgClient, ks->fServer, AP_OPTS_MUTUAL_REQUIRED, &cksum_data, 0, /* no creds, use ccache instead */ fgCCDef, &err_ret, &rep_ret, 0); delete [] cksum_data.data; if (rc != 0) { ::Error("TKSocket::Connect","while sendauth (%d), %s", rc, error_message(rc)); delete ks; return 0; } return ks; } //______________________________________________________________________________ Int_t TKSocket::BlockRead(char *&buf, EEncoding &type) { // Read block on information from server. The result is stored in buf. // The number of read bytes is returned; -1 is returned in case of error. Int_t rc; Desc_t desc; Int_t fd = fSocket->GetDescriptor(); rc = krb5_net_read(fgContext, fd, (char *)&desc, sizeof(desc)); if (rc == 0) errno = ECONNABORTED; if (rc <= 0) { SysError("BlockRead","reading descriptor (%d), %s", rc, error_message(rc)); return -1; } type = static_cast<EEncoding>(ntohs(desc.fType)); krb5_data enc; enc.length = ntohs(desc.fLength); enc.data = new char[enc.length+1]; rc = krb5_net_read(fgContext, fd, enc.data, enc.length); enc.data[enc.length] = 0; if (rc == 0) errno = ECONNABORTED; if (rc <= 0) { SysError("BlockRead","reading data (%d), %s", rc, error_message(rc)); delete [] enc.data; return -1; } krb5_data out; switch (type) { case kNone: buf = enc.data; rc = enc.length; break; case kSafe: rc = krb5_rd_safe(fgContext, fAuthContext, &enc, &out, 0); break; case kPriv: rc = krb5_rd_priv(fgContext, fAuthContext, &enc, &out, 0); break; default: Error("BlockWrite","unknown encoding type (%d)", type); return -1; } if (type != kNone) { // copy data to buffer that is new'ed buf = new char[out.length+1]; memcpy(buf, out.data, out.length); buf[out.length] = 0; free(out.data); delete [] enc.data; rc = out.length; } return rc; } //______________________________________________________________________________ Int_t TKSocket::BlockWrite(const char *buf, Int_t length, EEncoding type) { // Block-send 'length' bytes to server from 'buf'. Desc_t desc; krb5_data in; krb5_data enc; Int_t rc; in.data = const_cast<char*>(buf); in.length = length; switch (type) { case kNone: enc.data = in.data; enc.length = in.length; break; case kSafe: rc = krb5_mk_safe(fgContext, fAuthContext, &in, &enc, 0); break; case kPriv: rc = krb5_mk_priv(fgContext, fAuthContext, &in, &enc, 0); break; default: Error("BlockWrite","unknown encoding type (%d)", type); return -1; } desc.fLength = htons(enc.length); desc.fType = htons(type); Int_t fd = fSocket->GetDescriptor(); rc = krb5_net_write(fgContext, fd, (char *)&desc, sizeof(desc)); if (rc <= 0) { Error("BlockWrite","writing descriptor (%d), %s", rc, error_message(rc)); return -1; } rc = krb5_net_write(fgContext, fd, (char *)enc.data, enc.length); if (rc <= 0) { Error("BlockWrite","writing data (%d), %s", rc, error_message(rc)); return -1; } if (type != kNone) free(enc.data); return rc; }
Fix register warning.
Fix register warning.
C++
lgpl-2.1
tc3t/qoot,tc3t/qoot,tc3t/qoot,tc3t/qoot,tc3t/qoot,tc3t/qoot,tc3t/qoot,tc3t/qoot,tc3t/qoot,tc3t/qoot
605c7bac6cd2581093362a74c753fa56f2b24206
src/main.cpp
src/main.cpp
#include "mswin.h" #include "model.h" #include "random.h" #include "cmdline.h" #include "graphics.h" #include "config.h" #include "maths.h" #include "memory.h" #define IDT_TIMER 1 struct window_struct_t { model_t model; HDC hdc; HGLRC hglrc; LARGE_INTEGER last_performance_count; POINT initial_cursor_position; view_t view; float rate; int width, height; run_mode_t mode; }; LRESULT CALLBACK WndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { bool close_window = false; bool call_def_window_proc = false; if (msg == WM_CREATE) { const CREATESTRUCT * cs = reinterpret_cast <CREATESTRUCT *> (lParam); window_struct_t * ws = reinterpret_cast <window_struct_t *> (cs->lpCreateParams); ::SetWindowLongPtr (hwnd, GWLP_USERDATA, reinterpret_cast <LONG_PTR> (ws)); ws->width = cs->cx; ws->height = cs->cy; float td = usr::tank_distance, tz = usr::tank_depth, th = usr::tank_height; ws->view = { td, tz, (th * ws->width) / ws->height, th, }; ::GetCursorPos (& ws->initial_cursor_position); void * data (0); if (HRSRC data_found = ::FindResource (0, MAKEINTRESOURCE (256), MAKEINTRESOURCE (256))) if (HGLOBAL data_loaded = ::LoadResource (0, data_found)) if (LPVOID data_locked = ::LockResource (data_loaded)) data = data_locked; if (! data) return -1; LARGE_INTEGER performance_frequency; ::QueryPerformanceFrequency (& performance_frequency); ws->rate = usr::simulation_rate / performance_frequency.QuadPart; ::QueryPerformanceCounter (& ws->last_performance_count); ws->hdc = ::GetDC (hwnd); if (! ws->hdc) return -1; PIXELFORMATDESCRIPTOR pfd; ::ZeroMemory (& pfd, sizeof pfd); pfd.nSize = sizeof pfd; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; int npf = ::ChoosePixelFormat (ws->hdc, & pfd); ::SetPixelFormat (ws->hdc, npf, & pfd); ws->hglrc = ::wglCreateContext (ws->hdc); if (! ws->hglrc) return -1; if (! ::wglMakeCurrent (ws->hdc, ws->hglrc)) { ::wglDeleteContext (ws->hglrc); return -1; } typedef BOOL (WINAPI * fp_t) (int); if (fp_t wglSwapIntervalEXT = reinterpret_cast <fp_t> (::wglGetProcAddress ("wglSwapIntervalEXT"))) { wglSwapIntervalEXT (1); } screen (ws->width, ws->height); box (ws->view); lights (ws->view.distance, ws->view.depth, 3.0, 0.5, 1.0); clear (); // ws->model.initialize (data, ::GetTickCount (), ws->view); ws->model.initialize (data, 0, ws->view); ws->model.draw (); ::SetTimer (hwnd, IDT_TIMER, 1, nullptr); return 0; } else if (window_struct_t * ws = reinterpret_cast <window_struct_t *> (::GetWindowLongPtr (hwnd, GWLP_USERDATA))) { switch (msg) { case WM_PAINT: ::ValidateRect (hwnd, nullptr); break; case WM_TIMER: { ::SwapBuffers (ws->hdc); LARGE_INTEGER performance_count; ::QueryPerformanceCounter (& performance_count); real dt = ws->rate * (performance_count.QuadPart - ws->last_performance_count.QuadPart); ws->last_performance_count = performance_count; ws->model.proceed (dt < usr::max_frame_time ? dt : usr::max_frame_time); clear (); ws->model.draw (); } break; case WM_SETCURSOR: ::SetCursor (ws->mode == fullscreen ? nullptr : (::LoadCursor (nullptr, IDC_ARROW))); break; case WM_MOUSEMOVE: if (ws->mode == fullscreen) { // Compare the current mouse position with the one stored in the window long. POINT current { LOWORD (lParam), HIWORD (lParam) }; ::ClientToScreen (hwnd, & current); SHORT dx = current.x - ws->initial_cursor_position.x; SHORT dy = current.y - ws->initial_cursor_position.y; close_window = dx > 10 || dy > 10 || dx * dx + dy * dy > 100; } break; case WM_KEYDOWN: case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN: close_window = ws->mode == fullscreen || ws->mode == special; break; case WM_ACTIVATE: case WM_ACTIVATEAPP: case WM_NCACTIVATE: close_window = ws->mode == fullscreen && LOWORD (wParam) == WA_INACTIVE; call_def_window_proc = true; break; case WM_SYSCOMMAND: call_def_window_proc = (ws->mode != fullscreen || wParam != SC_SCREENSAVE) && wParam != SC_CLOSE; break; case WM_CLOSE: ::DestroyWindow (hwnd); break; case WM_DESTROY: ::wglMakeCurrent (nullptr, nullptr); ::wglDeleteContext (ws->hglrc); ::PostQuitMessage (0); break; default: call_def_window_proc = true; break; } } else call_def_window_proc = true; if (close_window) { ::KillTimer (hwnd, IDT_TIMER); ::PostMessage (hwnd, WM_CLOSE, 0, 0); } return call_def_window_proc ? ::DefWindowProc (hwnd, msg, wParam, lParam) : 0; } int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE, LPSTR lpszCmdLine, int) { // Parse the command line. HWND parent = 0; run_mode_t mode = parse_command_line (lpszCmdLine, & parent); if (mode == configure) { ::MessageBox (parent, usr::message, usr::message_window_name, MB_OK | MB_ICONASTERISK); return 0; } // Register the window class and create the screen saver window. DWORD style; DWORD ex_style; int left, top, width, height; if (mode == embedded) { RECT rect; ::GetClientRect (parent, & rect); left = 0; top = 0; width = rect.right; height = rect.bottom; style = WS_CHILD | WS_VISIBLE; ex_style = 0; } else { left = ::GetSystemMetrics (SM_XVIRTUALSCREEN); top = ::GetSystemMetrics (SM_YVIRTUALSCREEN); width = ::GetSystemMetrics (SM_CXVIRTUALSCREEN); height = ::GetSystemMetrics (SM_CYVIRTUALSCREEN); style = WS_POPUP | WS_VISIBLE; ex_style = ((mode == fullscreen) ? WS_EX_TOPMOST : 0); } WNDCLASS wc; // typedef struct { wc.style = 0 ; // UINT style; wc.lpfnWndProc = WndProc; // WNDPROC lpfnWndProc; wc.cbClsExtra = 0; // int cbClsExtra; wc.cbWndExtra = 8; // int cbWndExtra; wc.hInstance = hInstance; // HINSTANCE hInstance; wc.hIcon = 0; // HICON hIcon; wc.hCursor = ::LoadCursor (0, IDC_ARROW); // HCURSOR hCursor; wc.hbrBackground = 0; // HBRUSH hbrBackground; wc.lpszMenuName = 0; // LPCTSTR lpszMenuName; wc.lpszClassName = usr::window_class_name; // LPCTSTR lpszClassName; // } WNDCLASS; if (! ::RegisterClass (& wc)) return 10; window_struct_t ws; ws.mode = mode; // HWND CreateWindowEx HWND hwnd = ::CreateWindowEx (ex_style, // (DWORD dwExStyle, usr::window_class_name, // LPCTSTR lpClassName, usr::window_name, // LPCTSTR lpWindowName, style, // DWORD dwStyle, left, // int x, top, // int y, width, // int nWidth, height, // int nHeight, parent, // HWND hWndParent, 0, // HMENU hMenu, hInstance, // HINSTANCE hInstance, & ws); // LPVOID lpParam); if (! hwnd) return 14; // Enter the main loop. MSG msg; BOOL bRet; while ((bRet = ::GetMessage (& msg, nullptr, 0, 0)) != 0) { if (bRet == -1) { // TODO: check error code return ::GetLastError (); } else { ::TranslateMessage (& msg); ::DispatchMessage (& msg); } } return (msg.message == WM_QUIT ? msg.wParam : 1); }
#include "mswin.h" #include "model.h" #include "random.h" #include "cmdline.h" #include "graphics.h" #include "config.h" #include "maths.h" #include "memory.h" #define IDT_TIMER 1 struct window_struct_t { model_t model; HDC hdc; HGLRC hglrc; LARGE_INTEGER last_performance_count; POINT initial_cursor_position; view_t view; float rate; int width, height; run_mode_t mode; }; LRESULT CALLBACK WndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { bool close_window = false; bool call_def_window_proc = false; if (msg == WM_CREATE) { const CREATESTRUCT * cs = reinterpret_cast <CREATESTRUCT *> (lParam); window_struct_t * ws = reinterpret_cast <window_struct_t *> (cs->lpCreateParams); ::SetWindowLongPtr (hwnd, GWLP_USERDATA, reinterpret_cast <LONG_PTR> (ws)); ws->width = cs->cx; ws->height = cs->cy; float td = usr::tank_distance, tz = usr::tank_depth, th = usr::tank_height; ws->view = { td, tz, (th * ws->width) / ws->height, th, }; ::GetCursorPos (& ws->initial_cursor_position); void * data (0); if (HRSRC data_found = ::FindResource (0, MAKEINTRESOURCE (256), MAKEINTRESOURCE (256))) if (HGLOBAL data_loaded = ::LoadResource (0, data_found)) if (LPVOID data_locked = ::LockResource (data_loaded)) data = data_locked; if (! data) return -1; LARGE_INTEGER performance_frequency; ::QueryPerformanceFrequency (& performance_frequency); ws->rate = usr::simulation_rate / performance_frequency.QuadPart; ::QueryPerformanceCounter (& ws->last_performance_count); ws->hdc = ::GetDC (hwnd); if (! ws->hdc) return -1; PIXELFORMATDESCRIPTOR pfd; ::ZeroMemory (& pfd, sizeof pfd); pfd.nSize = sizeof pfd; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; int npf = ::ChoosePixelFormat (ws->hdc, & pfd); ::SetPixelFormat (ws->hdc, npf, & pfd); ws->hglrc = ::wglCreateContext (ws->hdc); if (! ws->hglrc) return -1; if (! ::wglMakeCurrent (ws->hdc, ws->hglrc)) { ::wglDeleteContext (ws->hglrc); return -1; } typedef BOOL (WINAPI * fp_t) (int); if (fp_t wglSwapIntervalEXT = reinterpret_cast <fp_t> (::wglGetProcAddress ("wglSwapIntervalEXT"))) { wglSwapIntervalEXT (1); } screen (ws->width, ws->height); box (ws->view); lights (ws->view.distance, ws->view.depth, 3.0, 0.5, 1.0); clear (); ws->model.initialize (data, ::GetTickCount (), ws->view); ws->model.draw (); ::SetTimer (hwnd, IDT_TIMER, 1, nullptr); return 0; } else if (window_struct_t * ws = reinterpret_cast <window_struct_t *> (::GetWindowLongPtr (hwnd, GWLP_USERDATA))) { switch (msg) { case WM_PAINT: ::ValidateRect (hwnd, nullptr); break; case WM_TIMER: { ::SwapBuffers (ws->hdc); LARGE_INTEGER performance_count; ::QueryPerformanceCounter (& performance_count); real dt = ws->rate * (performance_count.QuadPart - ws->last_performance_count.QuadPart); ws->last_performance_count = performance_count; ws->model.proceed (dt < usr::max_frame_time ? dt : usr::max_frame_time); clear (); ws->model.draw (); } break; case WM_SETCURSOR: ::SetCursor (ws->mode == fullscreen ? nullptr : (::LoadCursor (nullptr, IDC_ARROW))); break; case WM_MOUSEMOVE: if (ws->mode == fullscreen) { // Compare the current mouse position with the one stored in the window long. POINT current { LOWORD (lParam), HIWORD (lParam) }; ::ClientToScreen (hwnd, & current); SHORT dx = current.x - ws->initial_cursor_position.x; SHORT dy = current.y - ws->initial_cursor_position.y; close_window = dx > 10 || dy > 10 || dx * dx + dy * dy > 100; } break; case WM_KEYDOWN: case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN: close_window = ws->mode == fullscreen || ws->mode == special; break; case WM_ACTIVATE: case WM_ACTIVATEAPP: case WM_NCACTIVATE: close_window = ws->mode == fullscreen && LOWORD (wParam) == WA_INACTIVE; call_def_window_proc = true; break; case WM_SYSCOMMAND: call_def_window_proc = (ws->mode != fullscreen || wParam != SC_SCREENSAVE) && wParam != SC_CLOSE; break; case WM_CLOSE: ::DestroyWindow (hwnd); break; case WM_DESTROY: ::wglMakeCurrent (nullptr, nullptr); ::wglDeleteContext (ws->hglrc); ::PostQuitMessage (0); break; default: call_def_window_proc = true; break; } } else call_def_window_proc = true; if (close_window) { ::KillTimer (hwnd, IDT_TIMER); ::PostMessage (hwnd, WM_CLOSE, 0, 0); } return call_def_window_proc ? ::DefWindowProc (hwnd, msg, wParam, lParam) : 0; } int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE, LPSTR lpszCmdLine, int) { // Parse the command line. HWND parent = 0; run_mode_t mode = parse_command_line (lpszCmdLine, & parent); if (mode == configure) { ::MessageBox (parent, usr::message, usr::message_window_name, MB_OK | MB_ICONASTERISK); return 0; } // Register the window class and create the screen saver window. DWORD style; DWORD ex_style; int left, top, width, height; if (mode == embedded) { RECT rect; ::GetClientRect (parent, & rect); left = 0; top = 0; width = rect.right; height = rect.bottom; style = WS_CHILD | WS_VISIBLE; ex_style = 0; } else { left = ::GetSystemMetrics (SM_XVIRTUALSCREEN); top = ::GetSystemMetrics (SM_YVIRTUALSCREEN); width = ::GetSystemMetrics (SM_CXVIRTUALSCREEN); height = ::GetSystemMetrics (SM_CYVIRTUALSCREEN); style = WS_POPUP | WS_VISIBLE; ex_style = ((mode == fullscreen) ? WS_EX_TOPMOST : 0); } WNDCLASS wc; // typedef struct { wc.style = 0 ; // UINT style; wc.lpfnWndProc = WndProc; // WNDPROC lpfnWndProc; wc.cbClsExtra = 0; // int cbClsExtra; wc.cbWndExtra = 8; // int cbWndExtra; wc.hInstance = hInstance; // HINSTANCE hInstance; wc.hIcon = 0; // HICON hIcon; wc.hCursor = ::LoadCursor (0, IDC_ARROW); // HCURSOR hCursor; wc.hbrBackground = 0; // HBRUSH hbrBackground; wc.lpszMenuName = 0; // LPCTSTR lpszMenuName; wc.lpszClassName = usr::window_class_name; // LPCTSTR lpszClassName; // } WNDCLASS; if (! ::RegisterClass (& wc)) return 10; window_struct_t ws; ws.mode = mode; // HWND CreateWindowEx HWND hwnd = ::CreateWindowEx (ex_style, // (DWORD dwExStyle, usr::window_class_name, // LPCTSTR lpClassName, usr::window_name, // LPCTSTR lpWindowName, style, // DWORD dwStyle, left, // int x, top, // int y, width, // int nWidth, height, // int nHeight, parent, // HWND hWndParent, 0, // HMENU hMenu, hInstance, // HINSTANCE hInstance, & ws); // LPVOID lpParam); if (! hwnd) return 14; // Enter the main loop. MSG msg; BOOL bRet; while ((bRet = ::GetMessage (& msg, nullptr, 0, 0)) != 0) { if (bRet == -1) { // TODO: check error code return ::GetLastError (); } else { ::TranslateMessage (& msg); ::DispatchMessage (& msg); } } return (msg.message == WM_QUIT ? msg.wParam : 1); }
Use tick count as random seed.
Use tick count as random seed.
C++
apache-2.0
bustercopley/polymorph,bustercopley/polymorph
1ce54e2b31d1a15d741d8da9e94cb7bfbccbfedd
src/main.cpp
src/main.cpp
# include "module.hpp" #include "parse_state.hpp" #include <iostream> #include <iterator> using namespace std; int main() { istream_iterator<char> begin{std::cin}; istream_iterator<char> end{}; parse_state<istream_iterator<char>> state{begin, end, "command line"}; try { parse_file(state); } catch(const parse_exception& exc) { cerr << "command line:" << exc.pos.line << ":" << exc.pos.line_position << ": error: " << parse_error_strings[(unsigned int)exc.error] << endl; } }
# include "module.hpp" #include "parse_state.hpp" #include <iostream> #include <iterator> using namespace std; int main() { istream_iterator<char> begin{std::cin}; istream_iterator<char> end{}; parse_state<istream_iterator<char>> state{begin, end, 1}; try { parse_file(state); } catch(const parse_exception& exc) { cerr << "parse error" << endl; } }
fix main
fix main
C++
mit
mbid/asm-lisp
3f9eca796e77f4105a32fdde69110895947a6da5
xchainer/routines/connection.cc
xchainer/routines/connection.cc
#include "xchainer/routines/connection.h" #include <cstdint> #include <vector> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/constant.h" #include "xchainer/device.h" #include "xchainer/error.h" #include "xchainer/routines/math.h" #include "xchainer/stack_vector.h" namespace xchainer { namespace internal { int64_t GetConvOutDim(int64_t in_dim, int64_t kernel_size, int64_t stride, int64_t pad, bool cover_all) { if (cover_all) { return (in_dim + pad * 2 - kernel_size + stride - 1) / stride + 1; } return (in_dim + pad * 2 - kernel_size) / stride + 1; } int64_t GetConvTransposeOutDim(int64_t in_dim, int64_t kernel_size, int64_t stride, int64_t pad, bool cover_all) { if (cover_all) { return stride * (in_dim - 1) + kernel_size - stride + 1 - 2 * pad; } return stride * (in_dim - 1) + kernel_size - 2 * pad; } } // namespace internal namespace { Array ConvGradW( Dtype w_dtype, const Shape& w_shape, const Array& x, const Array& gy, const StackVector<int64_t, kMaxNdim>& stride, const StackVector<int64_t, kMaxNdim>& pad, bool cover_all) { int8_t ndim = w_shape.ndim() - 2; // Number of spacial dimensions assert(ndim > 0); assert(x.ndim() == ndim + 2); assert(gy.ndim() == ndim + 2); assert(stride.size() == static_cast<size_t>(ndim)); assert(pad.size() == static_cast<size_t>(ndim)); Array out = x.device().ConvGradWeight(w_dtype, w_shape, x, gy, stride, pad, cover_all); auto x_backward_function = [ x_shape = x.shape(), gy, stride, pad ](const Array& gout, const std::vector<GraphId>& graph_ids_to_stop_gradient)->Array { StackVector<int64_t, kMaxNdim> out_size{x_shape.begin() + 2, x_shape.end()}; assert(out_size.size() == stride.size()); return ConvTranspose(gy.AsConstant(graph_ids_to_stop_gradient), gout, nonstd::nullopt, stride, pad, out_size); }; auto gy_backward_function = [x, stride, pad, cover_all]( const Array& gout, const std::vector<GraphId>& graph_ids_to_stop_gradient) -> Array { return Conv(x.AsConstant(graph_ids_to_stop_gradient), gout, nonstd::nullopt, stride, pad, cover_all); }; internal::SetUpOpNodes("conv-grad-weight", {x, gy}, out, {x_backward_function, gy_backward_function}); return out; } } // namespace Array Conv( const Array& x, const Array& w, const nonstd::optional<Array>& b, const StackVector<int64_t, kMaxNdim>& stride, const StackVector<int64_t, kMaxNdim>& pad, bool cover_all) { int8_t ndim = x.ndim() - 2; // Number of spacial dimensions if (w.ndim() != ndim + 2) { throw DimensionError{"Mismatched number of dimensions between input ", x.ndim(), " and weights ", w.ndim(), "."}; } if (static_cast<int8_t>(stride.size()) != ndim) { throw DimensionError{"Wrong numbers of strides ", stride.size(), " for input with ", x.ndim(), " dimensions."}; } if (static_cast<int8_t>(pad.size()) != ndim) { throw DimensionError{"Wrong numbers of paddings ", pad.size(), " for input with ", x.ndim(), " dimensions."}; } if (w.shape()[1] != x.shape()[1]) { throw DimensionError{"Mismatched number of input channels in input ", x.shape(), " and weights ", w.shape(), "."}; } if (b.has_value() && (b->ndim() != 1 || b->shape()[0] != w.shape()[0])) { throw DimensionError{"Mismatched bias shape ", b->shape(), " for weights ", w.shape(), "."}; } Array out = x.device().Conv(x, w, b, stride, pad, cover_all); auto x_backward_function = [ x_shape = x.shape(), w, stride, pad ](const Array& gout, const std::vector<GraphId>& graph_ids_to_stop_gradient)->Array { StackVector<int64_t, kMaxNdim> out_size{x_shape.begin() + 2, x_shape.end()}; return ConvTranspose(gout, w.AsConstant(graph_ids_to_stop_gradient), nonstd::nullopt, stride, pad, out_size); }; auto w_backward_function = [ w_dtype = w.dtype(), w_shape = w.shape(), x, stride, pad, cover_all ]( const Array& gout, const std::vector<GraphId>& graph_ids_to_stop_gradient) ->Array { return ConvGradW(w_dtype, w_shape, x.AsConstant(graph_ids_to_stop_gradient), gout, stride, pad, cover_all); }; if (b.has_value()) { auto b_backward_function = [](const Array& gout, const std::vector<GraphId>&) -> Array { Axes axis{0}; for (int8_t i = 2; i < gout.ndim(); ++i) { axis.emplace_back(int64_t{i}); } return Sum(gout, axis, false); }; internal::SetUpOpNodes("conv", {x, w, *b}, out, {x_backward_function, w_backward_function, b_backward_function}); } else { internal::SetUpOpNodes("conv", {x, w}, out, {x_backward_function, w_backward_function}); } return out; } Array ConvTranspose( const Array& x, const Array& w, const nonstd::optional<Array>& b, const StackVector<int64_t, kMaxNdim>& stride, const StackVector<int64_t, kMaxNdim>& pad, const nonstd::optional<StackVector<int64_t, kMaxNdim>>& out_size) { int8_t ndim = x.ndim() - 2; // Number of spacial dimensions Shape in_dims{x.shape().begin() + 2, x.shape().end()}; Shape kernel_size{w.shape().begin() + 2, w.shape().end()}; bool cover_all = false; bool cover_all_determined = false; // Compute out_size if not specified StackVector<int64_t, kMaxNdim> real_out_size; if (out_size.has_value()) { real_out_size = *out_size; } else { cover_all_determined = true; for (int8_t i = 0; i < ndim; ++i) { real_out_size.emplace_back(internal::GetConvTransposeOutDim(in_dims[i], kernel_size[i], stride[i], pad[i], cover_all)); } } // Compute transposed convolution Array out = x.device().ConvTranspose(x, w, b, stride, pad, real_out_size); // Detect cover_all // TODO(niboshi): This logic is only required if x belongs to some graph. if (!cover_all_determined) { for (int8_t i = 0; i < ndim; ++i) { if (in_dims[i] != internal::GetConvOutDim(real_out_size[i], kernel_size[i], stride[i], pad[i], false)) { cover_all = true; break; } } cover_all_determined = true; // Check detected cover_all is consistent for (int8_t i = 0; i < ndim; ++i) { if (in_dims[i] != internal::GetConvOutDim(real_out_size[i], kernel_size[i], stride[i], pad[i], cover_all)) { throw XchainerError{"Output dims ", Shape{real_out_size.begin(), real_out_size.end()}, " is incosistent."}; } } } auto x_backward_function = [ x_shape = x.shape(), w, stride, pad, cover_all ](const Array& gout, const std::vector<GraphId>& graph_ids_to_stop_gradient) ->Array { return Conv(gout, w.AsConstant(graph_ids_to_stop_gradient), nonstd::nullopt, stride, pad, cover_all); }; auto w_backward_function = [ w_dtype = w.dtype(), w_shape = w.shape(), x, stride, pad, cover_all ]( const Array& gout, const std::vector<GraphId>& graph_ids_to_stop_gradient) ->Array { return ConvGradW(w_dtype, w_shape, gout, x.AsConstant(graph_ids_to_stop_gradient), stride, pad, cover_all); }; if (b.has_value()) { auto b_backward_function = [](const Array& gout, const std::vector<GraphId>&) -> Array { Axes axis{0}; for (int8_t i = 2; i < gout.ndim(); ++i) { axis.emplace_back(int64_t{i}); } return Sum(gout, axis, false); }; internal::SetUpOpNodes("conv_transpose", {x, w, *b}, out, {x_backward_function, w_backward_function, b_backward_function}); } else { internal::SetUpOpNodes("conv_transpose", {x, w}, out, {x_backward_function, w_backward_function}); } return out; } } // namespace xchainer
#include "xchainer/routines/connection.h" #include <cstdint> #include <vector> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/constant.h" #include "xchainer/device.h" #include "xchainer/error.h" #include "xchainer/routines/math.h" #include "xchainer/stack_vector.h" namespace xchainer { namespace internal { int64_t GetConvOutDim(int64_t in_dim, int64_t kernel_size, int64_t stride, int64_t pad, bool cover_all) { if (cover_all) { return (in_dim + pad * 2 - kernel_size + stride - 1) / stride + 1; } return (in_dim + pad * 2 - kernel_size) / stride + 1; } int64_t GetConvTransposeOutDim(int64_t in_dim, int64_t kernel_size, int64_t stride, int64_t pad, bool cover_all) { if (cover_all) { return stride * (in_dim - 1) + kernel_size - stride + 1 - 2 * pad; } return stride * (in_dim - 1) + kernel_size - 2 * pad; } } // namespace internal namespace { Array ConvGradW( Dtype w_dtype, const Shape& w_shape, const Array& x, const Array& gy, const StackVector<int64_t, kMaxNdim>& stride, const StackVector<int64_t, kMaxNdim>& pad, bool cover_all) { assert(w_shape.ndim() > 2); assert(x.ndim() == w_shape.ndim()); assert(gy.ndim() == w_shape.ndim()); assert(stride.size() == static_cast<size_t>(w_shape.ndim() - 2)); assert(pad.size() == static_cast<size_t>(w_shape.ndim() - 2)); Array out = x.device().ConvGradWeight(w_dtype, w_shape, x, gy, stride, pad, cover_all); auto x_backward_function = [ x_shape = x.shape(), gy, stride, pad ](const Array& gout, const std::vector<GraphId>& graph_ids_to_stop_gradient)->Array { StackVector<int64_t, kMaxNdim> out_size{x_shape.begin() + 2, x_shape.end()}; assert(out_size.size() == stride.size()); return ConvTranspose(gy.AsConstant(graph_ids_to_stop_gradient), gout, nonstd::nullopt, stride, pad, out_size); }; auto gy_backward_function = [x, stride, pad, cover_all]( const Array& gout, const std::vector<GraphId>& graph_ids_to_stop_gradient) -> Array { return Conv(x.AsConstant(graph_ids_to_stop_gradient), gout, nonstd::nullopt, stride, pad, cover_all); }; internal::SetUpOpNodes("conv-grad-weight", {x, gy}, out, {x_backward_function, gy_backward_function}); return out; } } // namespace Array Conv( const Array& x, const Array& w, const nonstd::optional<Array>& b, const StackVector<int64_t, kMaxNdim>& stride, const StackVector<int64_t, kMaxNdim>& pad, bool cover_all) { int8_t ndim = x.ndim() - 2; // Number of spacial dimensions if (w.ndim() != ndim + 2) { throw DimensionError{"Mismatched number of dimensions between input ", x.ndim(), " and weights ", w.ndim(), "."}; } if (static_cast<int8_t>(stride.size()) != ndim) { throw DimensionError{"Wrong numbers of strides ", stride.size(), " for input with ", x.ndim(), " dimensions."}; } if (static_cast<int8_t>(pad.size()) != ndim) { throw DimensionError{"Wrong numbers of paddings ", pad.size(), " for input with ", x.ndim(), " dimensions."}; } if (w.shape()[1] != x.shape()[1]) { throw DimensionError{"Mismatched number of input channels in input ", x.shape(), " and weights ", w.shape(), "."}; } if (b.has_value() && (b->ndim() != 1 || b->shape()[0] != w.shape()[0])) { throw DimensionError{"Mismatched bias shape ", b->shape(), " for weights ", w.shape(), "."}; } Array out = x.device().Conv(x, w, b, stride, pad, cover_all); auto x_backward_function = [ x_shape = x.shape(), w, stride, pad ](const Array& gout, const std::vector<GraphId>& graph_ids_to_stop_gradient)->Array { StackVector<int64_t, kMaxNdim> out_size{x_shape.begin() + 2, x_shape.end()}; return ConvTranspose(gout, w.AsConstant(graph_ids_to_stop_gradient), nonstd::nullopt, stride, pad, out_size); }; auto w_backward_function = [ w_dtype = w.dtype(), w_shape = w.shape(), x, stride, pad, cover_all ]( const Array& gout, const std::vector<GraphId>& graph_ids_to_stop_gradient) ->Array { return ConvGradW(w_dtype, w_shape, x.AsConstant(graph_ids_to_stop_gradient), gout, stride, pad, cover_all); }; if (b.has_value()) { auto b_backward_function = [](const Array& gout, const std::vector<GraphId>&) -> Array { Axes axis{0}; for (int8_t i = 2; i < gout.ndim(); ++i) { axis.emplace_back(int64_t{i}); } return Sum(gout, axis, false); }; internal::SetUpOpNodes("conv", {x, w, *b}, out, {x_backward_function, w_backward_function, b_backward_function}); } else { internal::SetUpOpNodes("conv", {x, w}, out, {x_backward_function, w_backward_function}); } return out; } Array ConvTranspose( const Array& x, const Array& w, const nonstd::optional<Array>& b, const StackVector<int64_t, kMaxNdim>& stride, const StackVector<int64_t, kMaxNdim>& pad, const nonstd::optional<StackVector<int64_t, kMaxNdim>>& out_size) { int8_t ndim = x.ndim() - 2; // Number of spacial dimensions Shape in_dims{x.shape().begin() + 2, x.shape().end()}; Shape kernel_size{w.shape().begin() + 2, w.shape().end()}; bool cover_all = false; bool cover_all_determined = false; // Compute out_size if not specified StackVector<int64_t, kMaxNdim> real_out_size; if (out_size.has_value()) { real_out_size = *out_size; } else { cover_all_determined = true; for (int8_t i = 0; i < ndim; ++i) { real_out_size.emplace_back(internal::GetConvTransposeOutDim(in_dims[i], kernel_size[i], stride[i], pad[i], cover_all)); } } // Compute transposed convolution Array out = x.device().ConvTranspose(x, w, b, stride, pad, real_out_size); // Detect cover_all // TODO(niboshi): This logic is only required if x belongs to some graph. if (!cover_all_determined) { for (int8_t i = 0; i < ndim; ++i) { if (in_dims[i] != internal::GetConvOutDim(real_out_size[i], kernel_size[i], stride[i], pad[i], false)) { cover_all = true; break; } } cover_all_determined = true; // Check detected cover_all is consistent for (int8_t i = 0; i < ndim; ++i) { if (in_dims[i] != internal::GetConvOutDim(real_out_size[i], kernel_size[i], stride[i], pad[i], cover_all)) { throw XchainerError{"Output dims ", Shape{real_out_size.begin(), real_out_size.end()}, " is incosistent."}; } } } auto x_backward_function = [ x_shape = x.shape(), w, stride, pad, cover_all ](const Array& gout, const std::vector<GraphId>& graph_ids_to_stop_gradient) ->Array { return Conv(gout, w.AsConstant(graph_ids_to_stop_gradient), nonstd::nullopt, stride, pad, cover_all); }; auto w_backward_function = [ w_dtype = w.dtype(), w_shape = w.shape(), x, stride, pad, cover_all ]( const Array& gout, const std::vector<GraphId>& graph_ids_to_stop_gradient) ->Array { return ConvGradW(w_dtype, w_shape, gout, x.AsConstant(graph_ids_to_stop_gradient), stride, pad, cover_all); }; if (b.has_value()) { auto b_backward_function = [](const Array& gout, const std::vector<GraphId>&) -> Array { Axes axis{0}; for (int8_t i = 2; i < gout.ndim(); ++i) { axis.emplace_back(int64_t{i}); } return Sum(gout, axis, false); }; internal::SetUpOpNodes("conv_transpose", {x, w, *b}, out, {x_backward_function, w_backward_function, b_backward_function}); } else { internal::SetUpOpNodes("conv_transpose", {x, w}, out, {x_backward_function, w_backward_function}); } return out; } } // namespace xchainer
remove unused warning
remove unused warning
C++
mit
okuta/chainer,hvy/chainer,okuta/chainer,niboshi/chainer,keisuke-umezawa/chainer,wkentaro/chainer,hvy/chainer,okuta/chainer,chainer/chainer,chainer/chainer,ktnyt/chainer,okuta/chainer,niboshi/chainer,chainer/chainer,niboshi/chainer,pfnet/chainer,wkentaro/chainer,hvy/chainer,ktnyt/chainer,jnishi/chainer,ktnyt/chainer,jnishi/chainer,ktnyt/chainer,wkentaro/chainer,jnishi/chainer,chainer/chainer,niboshi/chainer,jnishi/chainer,keisuke-umezawa/chainer,tkerola/chainer,hvy/chainer,wkentaro/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer
e298d7cc58e8d16234c7ba16ac7ab15c2057d736
lib/Support/GraphWriter.cpp
lib/Support/GraphWriter.cpp
//===-- GraphWriter.cpp - Implements GraphWriter support routines ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements misc. GraphWriter support routines. // //===----------------------------------------------------------------------===// #include "llvm/Support/GraphWriter.h" #include "llvm/System/Path.h" #include "llvm/System/Program.h" #include "llvm/Config/config.h" using namespace llvm; std::string llvm::DOT::EscapeString(const std::string &Label) { std::string Str(Label); for (unsigned i = 0; i != Str.length(); ++i) switch (Str[i]) { case '\n': Str.insert(Str.begin()+i, '\\'); // Escape character... ++i; Str[i] = 'n'; break; case '\t': Str.insert(Str.begin()+i, ' '); // Convert to two spaces ++i; Str[i] = ' '; break; case '\\': if (i+1 != Str.length()) switch (Str[i+1]) { case 'l': continue; // don't disturb \l case '|': case '{': case '}': Str.erase(Str.begin()+i); continue; default: break; } case '{': case '}': case '<': case '>': case '|': case '"': Str.insert(Str.begin()+i, '\\'); // Escape character... ++i; // don't infinite loop break; } return Str; } void llvm::DisplayGraph(const sys::Path &Filename, bool wait, GraphProgram::Name program) { std::string ErrMsg; #if HAVE_GRAPHVIZ sys::Path Graphviz(LLVM_PATH_GRAPHVIZ); std::vector<const char*> args; args.push_back(Graphviz.c_str()); args.push_back(Filename.c_str()); args.push_back(0); errs() << "Running 'Graphviz' program... "; if (sys::Program::ExecuteAndWait(Graphviz, &args[0],0,0,0,0,&ErrMsg)) errs() << "Error viewing graph " << Filename.str() << ": " << ErrMsg << "\n"; else Filename.eraseFromDisk(); #elif (HAVE_GV && (HAVE_DOT || HAVE_FDP || HAVE_NEATO || \ HAVE_TWOPI || HAVE_CIRCO)) sys::Path PSFilename = Filename; PSFilename.appendSuffix("ps"); sys::Path prog; // Set default grapher #if HAVE_CIRCO prog = sys::Path(LLVM_PATH_CIRCO); #endif #if HAVE_TWOPI prog = sys::Path(LLVM_PATH_TWOPI); #endif #if HAVE_NEATO prog = sys::Path(LLVM_PATH_NEATO); #endif #if HAVE_FDP prog = sys::Path(LLVM_PATH_FDP); #endif #if HAVE_DOT prog = sys::Path(LLVM_PATH_DOT); #endif // Find which program the user wants #if HAVE_DOT if (program == GraphProgram::DOT) prog = sys::Path(LLVM_PATH_DOT); #endif #if (HAVE_FDP) if (program == GraphProgram::FDP) prog = sys::Path(LLVM_PATH_FDP); #endif #if (HAVE_NEATO) if (program == GraphProgram::NEATO) prog = sys::Path(LLVM_PATH_NEATO); #endif #if (HAVE_TWOPI) if (program == GraphProgram::TWOPI) prog = sys::Path(LLVM_PATH_TWOPI); #endif #if (HAVE_CIRCO) if (program == GraphProgram::CIRCO) prog = sys::Path(LLVM_PATH_CIRCO); #endif std::vector<const char*> args; args.push_back(prog.c_str()); args.push_back("-Tps"); args.push_back("-Nfontname=Courier"); args.push_back("-Gsize=7.5,10"); args.push_back(Filename.c_str()); args.push_back("-o"); args.push_back(PSFilename.c_str()); args.push_back(0); errs() << "Running '" << prog.str() << "' program... "; if (sys::Program::ExecuteAndWait(prog, &args[0], 0, 0, 0, 0, &ErrMsg)) { errs() << "Error viewing graph " << Filename.str() << ": '" << ErrMsg << "\n"; } else { errs() << " done. \n"; sys::Path gv(LLVM_PATH_GV); args.clear(); args.push_back(gv.c_str()); args.push_back(PSFilename.c_str()); args.push_back("-spartan"); args.push_back(0); ErrMsg.clear(); if (wait) { if (sys::Program::ExecuteAndWait(gv, &args[0],0,0,0,0,&ErrMsg)) errs() << "Error viewing graph: " << ErrMsg << "\n"; Filename.eraseFromDisk(); PSFilename.eraseFromDisk(); } else { sys::Program::ExecuteNoWait(gv, &args[0],0,0,0,&ErrMsg); errs() << "Remember to erase graph files: " << Filename.str() << " " << PSFilename.str() << "\n"; } } #elif HAVE_DOTTY sys::Path dotty(LLVM_PATH_DOTTY); std::vector<const char*> args; args.push_back(dotty.c_str()); args.push_back(Filename.c_str()); args.push_back(0); errs() << "Running 'dotty' program... "; if (sys::Program::ExecuteAndWait(dotty, &args[0],0,0,0,0,&ErrMsg)) { errs() << "Error viewing graph " << Filename.str() << ": " << ErrMsg << "\n"; } else { #ifdef __MINGW32__ // Dotty spawns another app and doesn't wait until it returns return; #endif Filename.eraseFromDisk(); } #endif }
//===-- GraphWriter.cpp - Implements GraphWriter support routines ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements misc. GraphWriter support routines. // //===----------------------------------------------------------------------===// #include "llvm/Support/GraphWriter.h" #include "llvm/System/Path.h" #include "llvm/System/Program.h" #include "llvm/Config/config.h" using namespace llvm; std::string llvm::DOT::EscapeString(const std::string &Label) { std::string Str(Label); for (unsigned i = 0; i != Str.length(); ++i) switch (Str[i]) { case '\n': Str.insert(Str.begin()+i, '\\'); // Escape character... ++i; Str[i] = 'n'; break; case '\t': Str.insert(Str.begin()+i, ' '); // Convert to two spaces ++i; Str[i] = ' '; break; case '\\': if (i+1 != Str.length()) switch (Str[i+1]) { case 'l': continue; // don't disturb \l case '|': case '{': case '}': Str.erase(Str.begin()+i); continue; default: break; } case '{': case '}': case '<': case '>': case '|': case '"': Str.insert(Str.begin()+i, '\\'); // Escape character... ++i; // don't infinite loop break; } return Str; } void llvm::DisplayGraph(const sys::Path &Filename, bool wait, GraphProgram::Name program) { std::string ErrMsg; #if HAVE_GRAPHVIZ sys::Path Graphviz(LLVM_PATH_GRAPHVIZ); std::vector<const char*> args; args.push_back(Graphviz.c_str()); args.push_back(Filename.c_str()); args.push_back(0); errs() << "Running 'Graphviz' program... "; if (sys::Program::ExecuteAndWait(Graphviz, &args[0],0,0,0,0,&ErrMsg)) errs() << "Error viewing graph " << Filename.str() << ": " << ErrMsg << "\n"; else Filename.eraseFromDisk(); #elif (HAVE_GV && (HAVE_DOT || HAVE_FDP || HAVE_NEATO || \ HAVE_TWOPI || HAVE_CIRCO)) sys::Path PSFilename = Filename; PSFilename.appendSuffix("ps"); sys::Path prog; // Set default grapher #if HAVE_CIRCO prog = sys::Path(LLVM_PATH_CIRCO); #endif #if HAVE_TWOPI prog = sys::Path(LLVM_PATH_TWOPI); #endif #if HAVE_NEATO prog = sys::Path(LLVM_PATH_NEATO); #endif #if HAVE_FDP prog = sys::Path(LLVM_PATH_FDP); #endif #if HAVE_DOT prog = sys::Path(LLVM_PATH_DOT); #endif // Find which program the user wants #if HAVE_DOT if (program == GraphProgram::DOT) prog = sys::Path(LLVM_PATH_DOT); #endif #if (HAVE_FDP) if (program == GraphProgram::FDP) prog = sys::Path(LLVM_PATH_FDP); #endif #if (HAVE_NEATO) if (program == GraphProgram::NEATO) prog = sys::Path(LLVM_PATH_NEATO); #endif #if (HAVE_TWOPI) if (program == GraphProgram::TWOPI) prog = sys::Path(LLVM_PATH_TWOPI); #endif #if (HAVE_CIRCO) if (program == GraphProgram::CIRCO) prog = sys::Path(LLVM_PATH_CIRCO); #endif std::vector<const char*> args; args.push_back(prog.c_str()); args.push_back("-Tps"); args.push_back("-Nfontname=Courier"); args.push_back("-Gsize=7.5,10"); args.push_back(Filename.c_str()); args.push_back("-o"); args.push_back(PSFilename.c_str()); args.push_back(0); errs() << "Running '" << prog.str() << "' program... "; if (sys::Program::ExecuteAndWait(prog, &args[0], 0, 0, 0, 0, &ErrMsg)) { errs() << "Error viewing graph " << Filename.str() << ": '" << ErrMsg << "\n"; } else { errs() << " done. \n"; sys::Path gv(LLVM_PATH_GV); args.clear(); args.push_back(gv.c_str()); args.push_back(PSFilename.c_str()); args.push_back("--spartan"); args.push_back(0); ErrMsg.clear(); if (wait) { if (sys::Program::ExecuteAndWait(gv, &args[0],0,0,0,0,&ErrMsg)) errs() << "Error viewing graph: " << ErrMsg << "\n"; Filename.eraseFromDisk(); PSFilename.eraseFromDisk(); } else { sys::Program::ExecuteNoWait(gv, &args[0],0,0,0,&ErrMsg); errs() << "Remember to erase graph files: " << Filename.str() << " " << PSFilename.str() << "\n"; } } #elif HAVE_DOTTY sys::Path dotty(LLVM_PATH_DOTTY); std::vector<const char*> args; args.push_back(dotty.c_str()); args.push_back(Filename.c_str()); args.push_back(0); errs() << "Running 'dotty' program... "; if (sys::Program::ExecuteAndWait(dotty, &args[0],0,0,0,0,&ErrMsg)) { errs() << "Error viewing graph " << Filename.str() << ": " << ErrMsg << "\n"; } else { #ifdef __MINGW32__ // Dotty spawns another app and doesn't wait until it returns return; #endif Filename.eraseFromDisk(); } #endif }
Fix viewCFG on Linux.
Fix viewCFG on Linux. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@96834 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-2-clause
chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,chubbymaggie/asap,dslab-epfl/asap,chubbymaggie/asap,dslab-epfl/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm
0d5274da7d6c26d74b6ec78a68693cee80eb44a1
learn_cxx/learnTrait_access-different-name.cpp
learn_cxx/learnTrait_access-different-name.cpp
#include <math.h> #include <stdio.h> //#include <utility> ///////////////////////////////////////////////////////////////////////////// // 0) primary type typedef double mtype; ///////////////////////////////////////////////////////////////////////////// // 1) basic structure (Various) struct plane_point { double coord1; double coord2; }; struct plane_xy { double x; double y; }; ///////////////////////////////////////////////////////////////////////////// // Glues for 1 and 2 (basic structure VS basic algorithm) // // It's dirty! // //////////////////////////////////// // To wipe-off variance of 1 // // // Style-1 (function template, type parameter) // Pros: Client is easy to use // Cons: T may different //struct plane_point_access{ // template<typename T> // static double coord1(const T& p) { return p.coord1;} // template<typename T> // static double coord2(const T& p) {return p.coord2;} //}; //// usage: // plane_point_access::coord1(p); // type inferance // Style-2 (class template, type parameter) // Pros: T is treated as a whole, all assumption must be confirmed. // Cons: Client has to supply type (C++11 template alias eases) //template<typename T> //struct plane_point_access{ template<typename T> struct access_12{ static double coord1(const T& p) { return p.coord1;} static double coord2(const T& p) {return p.coord2;} }; //// usage: // plane_point_access<plane_point>::coord1(p); // //// C++11 // using ppa = plane_point_access<plane_point>; // ppa::coord1(p); // Style-3 (class template, non-type parameter) ////template<plane_point p> // not a valid type for a template non-type parameter //template<plane_point* p> //struct plane_point_access{ // static double coord1() { return p.coord1;} // static double coord2() { return p.coord2;} // } // //// usage: // plane_point_access<p>::coord1(); // Style-4 (function template, non-type parameter) //struct plane_point_access{ // template<plane_point* p> // static double coord1() { return p.coord1;} // template<plane_point* p> // static double coord2() { return p.coord2;} // } //// usage: // plane_point_access::coord1<p>(); template<typename T> struct access_xy{ static double coord1(const T& p) { return p.x;} static double coord2(const T& p) {return p.y;} }; ////////////////////////////////////// // To help type inferance for 2 // It makes access trait selection automatic. // template<typename T> struct default_access; // Style-1 (just redirection) // inferance implement (for 'plane_point') template<> struct default_access<plane_point> { using type = access_12<plane_point>; }; template<> struct default_access<plane_xy> { using type = access_xy<plane_xy>; }; // Style-2 (inplace declare) // Pros: // Cons: Can't reuse access method. // // inferance implement (for 'plane_xy') //template<> //struct default_access<plane_xy> //{ // typedef plane_xy T; // struct type{ // static double coord1(const T& p) { return p.x;} // static double coord2(const T& p) {return p.y;} // }; //}; // ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // 2) basic algorithm (Stable) // Note: Depends on constant assumptions. Here, we use access Trait. // http://en.wikipedia.org/wiki/Trait_(computer_programming) // //template<typename T, typename access> // No way to infer 'access', client code will be tough, no no no... template<typename T, typename access = typename default_access<T>::type> // Style-1 (type deduce) double point_distance(const T& point_a, const T& point_b) { double diff_coord1 = access::coord1(point_a) - access::coord1(point_b); double diff_coord2 = access::coord2(point_a) - access::coord2(point_b); double distance = hypot(diff_coord1, diff_coord2); return distance; } // Style-2 (make alise) // Pros: // Cons: It's a totally wrong idea. // // http://stackoverflow.com/questions/9864125/c11-how-to-alias-a-function // You cannot alias functions. // // Classes are types, so they can be aliased with typedef and using (in C++11). // Functions are much more like objects, so there's no mechanism to alias them. // In the same vein, there's no mechanism for aliasing variables. // //using plane_point_distance = double point_distance<plane_point, plane_point_access>(const plane_point& point_a, const plane_point& point_b); // Not valid // //double plane_point_distance(const plane_point& point_a, const plane_point& point_b) //{ //// return point_distance<plane_point, plane_point_access>(point_a, point_b); //// return point_distance<plane_point, plane_point_access>(std::forward(point_a), std::forward(point_b)); //} ///////////////////////////////////////////////////////////////////////////// // 100) sample client code void foo_use_ponit_dist() { double dis; plane_point a = {0, 0}; plane_point b = {1, 1}; dis = point_distance(a,b); printf("Plane any Distance is %f\n", dis); //////////////////////////// plane_xy p1 = {0, 0}; plane_xy p2 = {2, 2}; dis = point_distance(p1, p2); // Beautiful Life ... the harvest from previous code, printf("Plane XY Distance is %f\n", dis); } int main() { foo_use_ponit_dist(); }
#include <math.h> #include <stdio.h> //#include <utility> ///////////////////////////////////////////////////////////////////////////// // 0) primary type typedef double mtype; ///////////////////////////////////////////////////////////////////////////// // 1) basic structure (Various) struct plane_point { double coord1; double coord2; }; struct plane_xy { double x; double y; }; ///////////////////////////////////////////////////////////////////////////// // Glues for 1 and 2 (basic structure VS basic algorithm) // // It's dirty! // //////////////////////////////////// // To wipe-off variance of 1 // // // Style-1 (function template, type parameter) // Pros: Client is easy to use // Cons: T may different //struct plane_point_access{ // template<typename T> // static double coord1(const T& p) { return p.coord1;} // template<typename T> // static double coord2(const T& p) {return p.coord2;} //}; //// usage: // plane_point_access::coord1(p); // type inferance // Style-2 (class template, type parameter) // Pros: T is treated as a whole, all assumption must be confirmed. // Cons: Client has to supply type (C++11 template alias eases) //template<typename T> //struct plane_point_access{ template<typename T> struct access_12{ static double coord1(const T& p) { return p.coord1;} static double coord2(const T& p) {return p.coord2;} }; //// usage: // plane_point_access<plane_point>::coord1(p); // //// C++11 // using ppa = plane_point_access<plane_point>; // ppa::coord1(p); // Style-3 (class template, non-type parameter) // //// http://stackoverflow.com/questions/5687540/non-type-template-parameters //// template<plane_point p> // not a valid type for a template non-type parameter // //template<plane_point* p> //struct plane_point_access{ // static double coord1() { return p.coord1;} // static double coord2() { return p.coord2;} // } // //// usage: // plane_point_access<p>::coord1(); // Style-4 (function template, non-type parameter) //struct plane_point_access{ // template<plane_point* p> // static double coord1() { return p.coord1;} // template<plane_point* p> // static double coord2() { return p.coord2;} // } //// usage: // plane_point_access::coord1<p>(); template<typename T> struct access_xy{ static double coord1(const T& p) { return p.x;} static double coord2(const T& p) {return p.y;} }; ////////////////////////////////////// // To help type inferance for 2 // It makes access trait selection automatic. // template<typename T> struct default_access; // Style-1 (just redirection) // inferance implement (for 'plane_point') template<> struct default_access<plane_point> { using type = access_12<plane_point>; }; template<> struct default_access<plane_xy> { using type = access_xy<plane_xy>; }; // Style-2 (inplace declare) // Pros: // Cons: Can't reuse access method. // // inferance implement (for 'plane_xy') //template<> //struct default_access<plane_xy> //{ // typedef plane_xy T; // struct type{ // static double coord1(const T& p) { return p.x;} // static double coord2(const T& p) {return p.y;} // }; //}; // ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // 2) basic algorithm (Stable) // Note: Depends on constant assumptions. Here, we use access Trait. // http://en.wikipedia.org/wiki/Trait_(computer_programming) // //template<typename T, typename access> // No way to infer 'access', client code will be tough, no no no... // // http://stackoverflow.com/questions/2447458/default-template-arguments-for-function-templates // It said 'access = ' syntax is since C++11 (really ??) template<typename T, typename access = typename default_access<T>::type> // Style-1 (type deduce) double point_distance(const T& point_a, const T& point_b) { double diff_coord1 = access::coord1(point_a) - access::coord1(point_b); double diff_coord2 = access::coord2(point_a) - access::coord2(point_b); double distance = hypot(diff_coord1, diff_coord2); return distance; } // Style-2 (make alise) // Pros: // Cons: It's a totally wrong idea. // // http://stackoverflow.com/questions/9864125/c11-how-to-alias-a-function // You cannot alias functions. // // Classes are types, so they can be aliased with typedef and using (in C++11). // Functions are much more like objects, so there's no mechanism to alias them. // In the same vein, there's no mechanism for aliasing variables. // //using plane_point_distance = double point_distance<plane_point, plane_point_access>(const plane_point& point_a, const plane_point& point_b); // Not valid // //double plane_point_distance(const plane_point& point_a, const plane_point& point_b) //{ //// return point_distance<plane_point, plane_point_access>(point_a, point_b); //// return point_distance<plane_point, plane_point_access>(std::forward(point_a), std::forward(point_b)); //} ///////////////////////////////////////////////////////////////////////////// // 100) sample client code void foo_use_ponit_dist() { double dis; plane_point a = {0, 0}; plane_point b = {1, 1}; dis = point_distance(a,b); printf("Plane any Distance is %f\n", dis); //////////////////////////// plane_xy p1 = {0, 0}; plane_xy p2 = {2, 2}; dis = point_distance(p1, p2); // Beautiful Life ... the harvest from previous code, printf("Plane XY Distance is %f\n", dis); } // Additional Read (maybe help) // // http://en.wikipedia.org/wiki/Trait_(computer_programming) // a trait represents a collection of methods, that can be used to extend the functionality of a class ... // Traits are somewhat between an interface and a mixin: // an interface is made only of method signatures, // while a trait includes also the full method definitions, // on the other side mixins include method definitions, but the can also carry state through attributes while traits usually don't. // // http://accu.org/index.php/journals/442 // An introduction to C++ Traits // // http://www.cppblog.com/youxia/archive/2008/08/30/60443.html // 理解模板编程中的Trait和Mataprogram // int main() { foo_use_ponit_dist(); }
add references doc
add references doc
C++
unlicense
yangrongwei/ray-simple,yangrongwei/ray-simple,yangrongwei/ray-simple,yangrongwei/ray-simple,yangrongwei/ray-simple
4eb14382f61f789b4dc899233f14fa805c29c683
server/types/MediaSink.cpp
server/types/MediaSink.cpp
/* * MediaSink.cpp - Kurento Media Server * * Copyright (C) 2013 Kurento * Contact: Miguel París Díaz <[email protected]> * Contact: José Antonio Santos Cadenas <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "MediaSink.hpp" #include "MediaElement.hpp" #define GST_CAT_DEFAULT kurento_media_sink GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoMediaSink" namespace kurento { MediaSink::MediaSink (std::shared_ptr<MediaElement> parent, MediaType::type mediaType) : MediaPad (parent, mediaType, MediaPadType::type::MEDIA_SINK) { } MediaSink::~MediaSink() throw () { std::shared_ptr<MediaSrc> connectedSrcLocked; try { connectedSrcLocked = connectedSrc.lock(); } catch (std::bad_weak_ptr e) { } if (connectedSrcLocked != NULL) { connectedSrcLocked->disconnect (this); } } std::string MediaSink::getPadName () { if (getMediaType() == MediaType::type::AUDIO) return "audio_sink"; else return "video_sink"; } bool MediaSink::linkPad (std::shared_ptr<MediaSrc> mediaSrc, GstPad *src) { std::shared_ptr<MediaSrc> connectedSrcLocked; GstPad *sink; bool ret; mutex.lock(); try { connectedSrcLocked = connectedSrc.lock(); } catch (std::bad_weak_ptr e) { } if ( (sink = gst_element_get_static_pad (getElement(), getPadName().c_str() ) ) == NULL) sink = gst_element_get_request_pad (getElement(), getPadName().c_str() ); if (gst_pad_is_linked (sink) ) { unlink (connectedSrcLocked, sink); } if (gst_pad_link (src, sink) == GST_PAD_LINK_OK) { ret = true; connectedSrc = std::weak_ptr<MediaSrc> (mediaSrc); } else { gst_element_release_request_pad (getElement(), sink); ret = false; } g_object_unref (sink); mutex.unlock(); return ret; } void MediaSink::unlink (std::shared_ptr<MediaSrc> mediaSrc, GstPad *sink) { std::shared_ptr<MediaSrc> connectedSrcLocked; mutex.lock(); try { connectedSrcLocked = connectedSrc.lock(); } catch (std::bad_weak_ptr e) { } if (connectedSrcLocked != NULL && mediaSrc == connectedSrcLocked) { GstPad *peer; GstPad *sinkPad; if (sink == NULL) sinkPad = gst_element_get_static_pad (getElement(), getPadName().c_str() ); else sinkPad = sink; if (sinkPad == NULL) goto end; peer = gst_pad_get_peer (sinkPad); if (peer != NULL) { gst_pad_unlink (peer, sinkPad); g_object_unref (peer); } if (sink == NULL) { GstElement *elem; elem = gst_pad_get_parent_element (sinkPad); gst_element_release_request_pad (elem, sinkPad); g_object_unref (elem); g_object_unref (sinkPad); } end: connectedSrcLocked->removeSink (this); } mutex.unlock(); } std::shared_ptr<MediaSrc> MediaSink::getConnectedSrc () { std::shared_ptr<MediaSrc> connectedSrcLocked; try { connectedSrcLocked = connectedSrc.lock(); } catch (std::bad_weak_ptr e) { } return connectedSrcLocked; } MediaSink::StaticConstructor MediaSink::staticConstructor; MediaSink::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } // kurento
/* * MediaSink.cpp - Kurento Media Server * * Copyright (C) 2013 Kurento * Contact: Miguel París Díaz <[email protected]> * Contact: José Antonio Santos Cadenas <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "MediaSink.hpp" #include "MediaElement.hpp" #define GST_CAT_DEFAULT kurento_media_sink GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoMediaSink" namespace kurento { MediaSink::MediaSink (std::shared_ptr<MediaElement> parent, MediaType::type mediaType) : MediaPad (parent, mediaType, MediaPadType::type::MEDIA_SINK) { } MediaSink::~MediaSink() throw () { std::shared_ptr<MediaSrc> connectedSrcLocked; try { connectedSrcLocked = connectedSrc.lock(); } catch (std::bad_weak_ptr e) { } if (connectedSrcLocked != NULL) { connectedSrcLocked->disconnect (this); } } std::string MediaSink::getPadName () { if (getMediaType() == MediaType::type::AUDIO) return "audio_sink"; else return "video_sink"; } static void remove_from_parent (GstElement *element) { GstBin *parent = GST_BIN (GST_OBJECT_PARENT (element) ); if (parent == NULL) return; gst_object_ref (element); gst_bin_remove (parent, element); gst_element_set_state (element, GST_STATE_NULL); gst_object_unref (element); } static void sink_unlinked (GstPad *pad, GstPad *peer, GstElement *filter) { GstPad *src; GstPad *src_peer; src = gst_element_get_static_pad (filter, "src"); src_peer = gst_pad_get_peer (src); if (src_peer != NULL) { gst_pad_unlink (src, src_peer); gst_object_unref (src_peer); } else { remove_from_parent (filter); } gst_object_unref (src); } static void src_unlinked (GstPad *pad, GstPad *peer, GstElement *filter) { GstPad *sink; GstPad *sink_peer; sink = gst_element_get_static_pad (filter, "sink"); sink_peer = gst_pad_get_peer (sink); if (sink_peer != NULL) { gst_pad_unlink (sink_peer, sink); gst_object_unref (sink_peer); } else { remove_from_parent (filter); } gst_object_unref (sink); } bool MediaSink::linkPad (std::shared_ptr<MediaSrc> mediaSrc, GstPad *src) { std::shared_ptr<MediaSrc> connectedSrcLocked; GstPad *sink; bool ret = false; mutex.lock(); try { connectedSrcLocked = connectedSrc.lock(); } catch (std::bad_weak_ptr e) { } if ( (sink = gst_element_get_static_pad (getElement(), getPadName().c_str() ) ) == NULL) sink = gst_element_get_request_pad (getElement(), getPadName().c_str() ); if (gst_pad_is_linked (sink) ) { unlink (connectedSrcLocked, sink); } if (mediaSrc->parent == parent) { GstBin *container; GstElement *filter, *parent; GstPad *aux_sink, *aux_src; GST_DEBUG ("Connecting loopback, adding a capsfilter to allow connection"); parent = GST_ELEMENT (GST_OBJECT_PARENT (sink) ); if (parent == NULL) goto end; container = GST_BIN (GST_OBJECT_PARENT (parent) ); if (container == NULL) goto end; filter = gst_element_factory_make ("capsfilter", NULL); aux_sink = gst_element_get_static_pad (filter, "sink"); aux_src = gst_element_get_static_pad (filter, "src"); g_signal_connect (G_OBJECT (aux_sink), "unlinked", G_CALLBACK (sink_unlinked), filter ); g_signal_connect (G_OBJECT (aux_src), "unlinked", G_CALLBACK (src_unlinked), filter ); gst_bin_add (container, filter); gst_element_sync_state_with_parent (filter); if (gst_pad_link (aux_src, sink) == GST_PAD_LINK_OK) { if (gst_pad_link (src, aux_sink) == GST_PAD_LINK_OK) ret = true; else gst_pad_unlink (aux_src, sink); } g_object_unref (aux_sink); g_object_unref (aux_src); gst_debug_bin_to_dot_file_with_ts (GST_BIN (container), GST_DEBUG_GRAPH_SHOW_ALL, "loopback"); } else { if (gst_pad_link (src, sink) == GST_PAD_LINK_OK) ret = true; } if (ret == true) { connectedSrc = std::weak_ptr<MediaSrc> (mediaSrc); } else { gst_element_release_request_pad (getElement(), sink); } end: g_object_unref (sink); mutex.unlock(); return ret; } void MediaSink::unlink (std::shared_ptr<MediaSrc> mediaSrc, GstPad *sink) { std::shared_ptr<MediaSrc> connectedSrcLocked; mutex.lock(); try { connectedSrcLocked = connectedSrc.lock(); } catch (std::bad_weak_ptr e) { } if (connectedSrcLocked != NULL && mediaSrc == connectedSrcLocked) { GstPad *peer; GstPad *sinkPad; if (sink == NULL) sinkPad = gst_element_get_static_pad (getElement(), getPadName().c_str() ); else sinkPad = sink; if (sinkPad == NULL) goto end; peer = gst_pad_get_peer (sinkPad); if (peer != NULL) { gst_pad_unlink (peer, sinkPad); g_object_unref (peer); } if (sink == NULL) { GstElement *elem; elem = gst_pad_get_parent_element (sinkPad); gst_element_release_request_pad (elem, sinkPad); g_object_unref (elem); g_object_unref (sinkPad); } end: connectedSrcLocked->removeSink (this); } mutex.unlock(); } std::shared_ptr<MediaSrc> MediaSink::getConnectedSrc () { std::shared_ptr<MediaSrc> connectedSrcLocked; try { connectedSrcLocked = connectedSrc.lock(); } catch (std::bad_weak_ptr e) { } return connectedSrcLocked; } MediaSink::StaticConstructor MediaSink::staticConstructor; MediaSink::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } // kurento
Add an intermediate element to allow loopback connections
Add an intermediate element to allow loopback connections Change-Id: I217c574cb1f536f7a448444072cabbed231639a9
C++
lgpl-2.1
TribeMedia/kurento-media-server,todotobe1/kurento-media-server,Kurento/kurento-media-server,shelsonjava/kurento-media-server,mparis/kurento-media-server,mparis/kurento-media-server,lulufei/kurento-media-server,todotobe1/kurento-media-server,Kurento/kurento-media-server,shelsonjava/kurento-media-server,lulufei/kurento-media-server,TribeMedia/kurento-media-server
f2e8249c0106c4643ab5d9a715b15fd8dcf6362d
test/serializer.cpp
test/serializer.cpp
#include <catch/catch.hpp> #include <cmath> #include <limits> #include <RaPsCallion/serializer.h> namespace rapscallion { namespace test { void test(const std::string& inStr, const double in, const std::ptrdiff_t expected_size = -1) { GIVEN("the real number " + inStr) { WHEN("we serialize it") { Serializer s; serializer<decltype(+in)>::write(s, in); Deserializer d(s); THEN("the output meets size expectations") { const auto size = d.end - d.ptr; if (expected_size >= 0) CHECK(size == expected_size); // largest encoding of IEEE754 binary64 float: // (11 exponent bits + exponent sign + NaN/inf flag) = 13 bits / 7 bit/byte = 2 byte // (52 bit fraction + sign) = 53 bits / 7 bit/byte = 8 byte // + = 10 byte CHECK(size <= 10); AND_WHEN("we deserialize it again") { const auto out = serializer<decltype(+in)>::read(d); THEN("the deserialized output is equal to the original input") { if (std::isnan(in)) { CHECK(std::isnan(out)); } else { CHECK(out == in); CHECK(std::signbit(out) == std::signbit(in)); } } } } } } } } } SCENARIO("Serializing floating point numbers", "[serialization]") { using namespace rapscallion::test; #define STRIFY1ST(num, ...) #num #define TEST(...) \ test(STRIFY1ST(__VA_ARGS__, void), __VA_ARGS__) // Smallest encodings, only requiring flags TEST(std::numeric_limits<double>::infinity(), 1); TEST(-std::numeric_limits<double>::infinity(), 1); TEST(std::numeric_limits<double>::quiet_NaN(), 1); TEST(0.0, 1); TEST(-0.0, 1); TEST(0.03125, 2); TEST(-0.03125, 2); TEST(0.0625, 2); TEST(-0.0625, 2); TEST(0.125, 2); TEST(-0.125, 2); TEST(0.25, 2); TEST(-0.25, 2); TEST(0.5, 2); TEST(-0.5, 2); TEST(1.0, 2); TEST(-1.0, 2); TEST(2.0, 2); TEST(-2.0, 2); TEST(M_PI, 9); TEST(-M_PI, 9); TEST((float)M_PI, 5); TEST(-(float)M_PI, 5); TEST(std::numeric_limits<double>::epsilon()); TEST(std::numeric_limits<double>::min()); TEST(std::numeric_limits<double>::max(), 10); TEST(std::numeric_limits<double>::denorm_min()); #undef STRIFY #undef TEST }
#include <catch/catch.hpp> #include <cmath> #include <limits> #include <RaPsCallion/serializer.h> namespace rapscallion { namespace test { struct byte_view { constexpr byte_view() = default; byte_view(const Deserializer& d) : first(reinterpret_cast<const char*>(d.ptr)) , last (reinterpret_cast<const char*>(d.end)) {} template <size_t N> constexpr byte_view(const char (&arr)[N]) : first(arr) , last(&arr[N - 1]) {} constexpr const char* begin() const { return first; } constexpr const char* end() const { return last; } constexpr size_t size() const { return last - first; } constexpr bool empty() const { return first == last; } private: const char* first = nullptr; const char* last = nullptr; }; bool operator==(const byte_view& lhs, const byte_view& rhs) { return lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin()); } std::ostream& operator<<(std::ostream& os, const byte_view& v) { const auto oldFlags = os.setf(std::ios_base::hex, std::ios_base::basefield); const auto oldFill = os.fill('0'); os << '"'; for (const auto& c : v) { os << "\\x" << std::setw(2) << static_cast<unsigned>(static_cast<unsigned char>(c)); } os << '"'; os.setf(oldFlags); os.fill(oldFlags); return os; } void test(const std::string& inStr, const double in, const std::ptrdiff_t expected_size = -1, const byte_view& expected_serialization = byte_view()) { GIVEN("the real number " + inStr) { WHEN("we serialize it") { Serializer s; serializer<decltype(+in)>::write(s, in); Deserializer d(s); THEN("the serialized output meets expectations") { const byte_view serialized(d); if (expected_size >= 0) CHECK(serialized.size() == expected_size); // largest encoding of IEEE754 binary64 float: // (11 exponent bits + exponent sign + NaN/inf flag) = 13 bits / 7 bit/byte = 2 byte // (52 bit fraction + sign) = 53 bits / 7 bit/byte = 8 byte // + = 10 byte CHECK(serialized.size() <= 10); if (!expected_serialization.empty()) CHECK(serialized == expected_serialization); AND_WHEN("we deserialize it again") { const auto out = serializer<decltype(+in)>::read(d); THEN("the deserialized output is equal to the original input") { if (std::isnan(in)) { CHECK(std::isnan(out)); } else { CHECK(out == in); CHECK(std::signbit(out) == std::signbit(in)); } } } } } } } void test(const std::string& inStr, const double in, const byte_view& expected_serialization) { return test(inStr, in, expected_serialization.size(), expected_serialization); } } } SCENARIO("Serializing floating point numbers", "[serialization]") { using namespace rapscallion::test; #define STRIFY1ST(num, ...) #num #define TEST(...) \ test(STRIFY1ST(__VA_ARGS__, void), __VA_ARGS__) // Smallest encodings, only requiring flags TEST( std::numeric_limits<double>::infinity(), "\x02"); TEST(-std::numeric_limits<double>::infinity(), "\x03"); TEST(std::numeric_limits<double>::quiet_NaN(), "\x00"); TEST( 0.0, "\x04"); TEST(-0.0, "\x05"); TEST( 0.03125, "\x15" "\x01"); TEST(-0.03125, "\x17" "\x01"); TEST( 0.0625 , "\x11" "\x01"); TEST(-0.0625 , "\x13" "\x01"); TEST( 0.125 , "\x0d" "\x01"); TEST(-0.125 , "\x0f" "\x01"); TEST( 0.25 , "\x09" "\x01"); TEST(-0.25 , "\x0b" "\x01"); TEST( 0.5 , "\x06" "\x01"); TEST(-0.5 , "\x08" "\x01"); TEST( 1.0 , "\x0a" "\x01"); TEST(-1.0 , "\x0c" "\x01"); TEST( 2.0 , "\x0e" "\x01"); TEST(-2.0 , "\x10" "\x01"); TEST(M_PI, 9); TEST(-M_PI, 9); TEST((float)M_PI, 5); TEST(-(float)M_PI, 5); TEST(std::numeric_limits<double>::epsilon()); TEST(std::numeric_limits<double>::min()); TEST(std::numeric_limits<double>::max(), 10); TEST(std::numeric_limits<double>::denorm_min()); #undef STRIFY #undef TEST }
Add serialization format expectations to test
Add serialization format expectations to test To pin the format and to document the requirement that we want floats containing just the (implicit) one in the fraction to encode with a 0x01 byte for its fraction.
C++
mit
dascandy/rapscallion
9e756a6b6cb78a50b71899a40ef95252621fd353
test/test_astar.cpp
test/test_astar.cpp
#include <gtest/gtest.h> #include "simple_graph/list_graph.hpp" #include "simple_graph/astar.hpp" namespace { class ListGraphUndirectedTest : public ::testing::Test { protected: simple_graph::ListGraph<false, std::pair<float, float>, float> g; }; static float dist(const simple_graph::ListGraph<false, std::pair<float, float>, float> &g, int c, int r) { const auto &cdata = g.vertex(c).data(); const auto &rdata = g.vertex(r).data(); float xdiff = rdata.first - cdata.first; float ydiff = rdata.second - cdata.second; return std::sqrt(std::pow(xdiff, 2) + std::pow(ydiff, 2)); } TEST_F(ListGraphUndirectedTest, test_astar) { g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(0, std::make_pair(0.0f, 0.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(1, std::make_pair(1.0f, 1.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(2, std::make_pair(2.0f, 2.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(3, std::make_pair(5.0f, 5.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(4, std::make_pair(7.5f, 7.5f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(5, std::make_pair(3.0f, 1.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(6, std::make_pair(10.0f, 1.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(7, std::make_pair(10.0f, 10.0f))); EXPECT_EQ(8, g.vertex_num()); g.add_edge(simple_graph::Edge<float>(0, 1, dist(g, 0, 1))); g.add_edge(simple_graph::Edge<float>(1, 2, dist(g, 1, 2))); g.add_edge(simple_graph::Edge<float>(2, 3, dist(g, 2, 3))); g.add_edge(simple_graph::Edge<float>(3, 4, dist(g, 3, 4))); g.add_edge(simple_graph::Edge<float>(4, 7, dist(g, 4, 7))); g.add_edge(simple_graph::Edge<float>(0, 5, dist(g, 0, 5))); g.add_edge(simple_graph::Edge<float>(5, 6, dist(g, 5, 6))); g.add_edge(simple_graph::Edge<float>(6, 7, dist(g, 6, 7))); std::vector<int> path; std::function<float(int, int)> heuristic = [&](int c, int r) { return dist(g, c, r); }; EXPECT_EQ(true, astar(g, 0, 7, heuristic, &path)); EXPECT_EQ(6, path.size()); EXPECT_EQ(1, path[1]); EXPECT_EQ(4, path[4]); } TEST_F(ListGraphUndirectedTest, test_astar_neg) { g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(0, std::make_pair(0.0f, 0.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(1, std::make_pair(1.0f, 1.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(2, std::make_pair(2.0f, 2.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(3, std::make_pair(5.0f, 5.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(4, std::make_pair(15.0f, 15.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(5, std::make_pair(3.0f, 1.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(6, std::make_pair(10.0f, 1.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(7, std::make_pair(10.0f, 10.0f))); EXPECT_EQ(8, g.vertex_num()); g.add_edge(simple_graph::Edge<float>(0, 1, dist(g, 0, 1))); g.add_edge(simple_graph::Edge<float>(1, 2, dist(g, 1, 2))); g.add_edge(simple_graph::Edge<float>(2, 3, dist(g, 2, 3))); g.add_edge(simple_graph::Edge<float>(3, 4, dist(g, 3, 4))); g.add_edge(simple_graph::Edge<float>(4, 7, dist(g, 4, 7))); g.add_edge(simple_graph::Edge<float>(0, 5, dist(g, 0, 5))); g.add_edge(simple_graph::Edge<float>(5, 6, dist(g, 5, 6))); g.add_edge(simple_graph::Edge<float>(6, 7, dist(g, 6, 7))); std::vector<int> path; std::function<float(int, int)> heuristic = [&](int c, int r) { return dist(g, c, r); }; EXPECT_EQ(true, astar(g, 0, 7, heuristic, &path)); EXPECT_EQ(4, path.size()); EXPECT_EQ(5, path[1]); EXPECT_EQ(6, path[2]); } } // namespace int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#include <gtest/gtest.h> #include "simple_graph/list_graph.hpp" #include "simple_graph/astar.hpp" namespace { class ListGraphUndirectedTest : public ::testing::Test { protected: simple_graph::ListGraph<false, std::pair<float, float>, float> g; }; static float dist(const simple_graph::ListGraph<false, std::pair<float, float>, float> &g, int c, int r) { const auto &cdata = g.vertex(c).data(); const auto &rdata = g.vertex(r).data(); float xdiff = rdata.first - cdata.first; float ydiff = rdata.second - cdata.second; return std::sqrt(std::pow(xdiff, 2) + std::pow(ydiff, 2)); } TEST_F(ListGraphUndirectedTest, test_astar) { g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(0, std::make_pair(0.0f, 0.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(1, std::make_pair(1.0f, 1.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(2, std::make_pair(2.0f, 2.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(3, std::make_pair(5.0f, 5.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(4, std::make_pair(7.5f, 7.5f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(5, std::make_pair(3.0f, 1.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(6, std::make_pair(10.0f, 1.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(7, std::make_pair(10.0f, 10.0f))); EXPECT_EQ(8, g.vertex_num()); g.add_edge(simple_graph::Edge<float>(0, 1, dist(g, 0, 1))); g.add_edge(simple_graph::Edge<float>(1, 2, dist(g, 1, 2))); g.add_edge(simple_graph::Edge<float>(2, 3, dist(g, 2, 3))); g.add_edge(simple_graph::Edge<float>(3, 4, dist(g, 3, 4))); g.add_edge(simple_graph::Edge<float>(4, 7, dist(g, 4, 7))); g.add_edge(simple_graph::Edge<float>(0, 5, dist(g, 0, 5))); g.add_edge(simple_graph::Edge<float>(5, 6, dist(g, 5, 6))); g.add_edge(simple_graph::Edge<float>(6, 7, dist(g, 6, 7))); std::vector<int> path; std::function<float(int, int)> heuristic = [=](int c, int r) { return dist(g, c, r); }; EXPECT_EQ(true, astar(g, 0, 7, heuristic, &path)); EXPECT_EQ(6, path.size()); EXPECT_EQ(1, path[1]); EXPECT_EQ(4, path[4]); } TEST_F(ListGraphUndirectedTest, test_astar_neg) { g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(0, std::make_pair(0.0f, 0.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(1, std::make_pair(1.0f, 1.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(2, std::make_pair(2.0f, 2.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(3, std::make_pair(5.0f, 5.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(4, std::make_pair(15.0f, 15.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(5, std::make_pair(3.0f, 1.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(6, std::make_pair(10.0f, 1.0f))); g.set_vertex(simple_graph::Vertex<std::pair<float, float>>(7, std::make_pair(10.0f, 10.0f))); EXPECT_EQ(8, g.vertex_num()); g.add_edge(simple_graph::Edge<float>(0, 1, dist(g, 0, 1))); g.add_edge(simple_graph::Edge<float>(1, 2, dist(g, 1, 2))); g.add_edge(simple_graph::Edge<float>(2, 3, dist(g, 2, 3))); g.add_edge(simple_graph::Edge<float>(3, 4, dist(g, 3, 4))); g.add_edge(simple_graph::Edge<float>(4, 7, dist(g, 4, 7))); g.add_edge(simple_graph::Edge<float>(0, 5, dist(g, 0, 5))); g.add_edge(simple_graph::Edge<float>(5, 6, dist(g, 5, 6))); g.add_edge(simple_graph::Edge<float>(6, 7, dist(g, 6, 7))); std::vector<int> path; std::function<float(int, int)> heuristic = [=](int c, int r) { return dist(g, c, r); }; EXPECT_EQ(true, astar(g, 0, 7, heuristic, &path)); EXPECT_EQ(4, path.size()); EXPECT_EQ(5, path[1]); EXPECT_EQ(6, path[2]); } } // namespace int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
Change lambda capture in A* tests
Change lambda capture in A* tests
C++
mit
sfod/simple-graph
415138a1d3aec51bd56f261e8eba1cd4399dd30e
test/test_swarm.cpp
test/test_swarm.cpp
/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/alert_types.hpp" #include "libtorrent/thread.hpp" #include "libtorrent/time.hpp" #include <boost/tuple/tuple.hpp> #include "test.hpp" #include "setup_transfer.hpp" #include <iostream> void test_swarm(bool super_seeding = false, bool strict = false, bool seed_mode = false, bool time_critical = false) { using namespace libtorrent; // in case the previous run was terminated error_code ec; remove_all("./tmp1_swarm", ec); remove_all("./tmp2_swarm", ec); remove_all("./tmp3_swarm", ec); session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48000, 49000), "0.0.0.0", 0); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49000, 50000), "0.0.0.0", 0); session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50000, 51000), "0.0.0.0", 0); // this is to avoid everything finish from a single peer // immediately. To make the swarm actually connect all // three peers before finishing. float rate_limit = 100000; session_settings settings; settings.allow_multiple_connections_per_ip = true; settings.ignore_limits_on_local_network = false; settings.strict_super_seeding = strict; settings.upload_rate_limit = rate_limit; ses1.set_settings(settings); settings.download_rate_limit = rate_limit / 2; settings.upload_rate_limit = rate_limit; ses2.set_settings(settings); ses3.set_settings(settings); #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.out_enc_policy = pe_settings::forced; pes.in_enc_policy = pe_settings::forced; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); ses3.set_pe_settings(pes); #endif torrent_handle tor1; torrent_handle tor2; torrent_handle tor3; add_torrent_params p; p.seed_mode = seed_mode; // test using piece sizes smaller than 16kB boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true , false, true, "_swarm", 32 * 1024, 0, super_seeding, &p); int mask = alert::all_categories & ~(alert::progress_notification | alert::performance_warning); ses1.set_alert_mask(mask); ses2.set_alert_mask(mask); ses3.set_alert_mask(mask); if (time_critical) { tor2.set_piece_deadline(2, 0); tor2.set_piece_deadline(5, 1000); tor2.set_piece_deadline(8, 2000); } float sum_dl_rate2 = 0.f; float sum_dl_rate3 = 0.f; int count_dl_rates2 = 0; int count_dl_rates3 = 0; for (int i = 0; i < 80; ++i) { print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); print_alerts(ses3, "ses3"); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); torrent_status st3 = tor3.status(); if (st2.progress < 1.f && st2.progress > 0.5f) { sum_dl_rate2 += st2.download_payload_rate; ++count_dl_rates2; } if (st3.progress < 1.f && st3.progress > 0.5f) { sum_dl_rate3 += st3.download_rate; ++count_dl_rates3; } std::cerr << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << " - " << "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st3.progress * 100) << "% " << st3.num_peers << std::endl; if (st2.is_seeding && st3.is_seeding) break; test_sleep(1000); } TEST_CHECK(tor2.status().is_seeding); TEST_CHECK(tor3.status().is_seeding); float average2 = sum_dl_rate2 / float(count_dl_rates2); float average3 = sum_dl_rate3 / float(count_dl_rates3); std::cerr << average2 << std::endl; std::cerr << "average rate: " << (average2 / 1000.f) << "kB/s - " << (average3 / 1000.f) << "kB/s" << std::endl; if (tor2.status().is_seeding && tor3.status().is_seeding) std::cerr << "done\n"; // make sure the files are deleted ses1.remove_torrent(tor1, session::delete_files); ses2.remove_torrent(tor2, session::delete_files); ses3.remove_torrent(tor3, session::delete_files); std::auto_ptr<alert> a = ses1.pop_alert(); ptime end = time_now() + seconds(20); while (a.get() == 0 || dynamic_cast<torrent_deleted_alert*>(a.get()) == 0) { if (ses1.wait_for_alert(end - time_now()) == 0) { std::cerr << "wait_for_alert() expired" << std::endl; break; } a = ses1.pop_alert(); assert(a.get()); std::cerr << a->message() << std::endl; } TEST_CHECK(dynamic_cast<torrent_deleted_alert*>(a.get()) != 0); // there shouldn't be any alerts generated from now on // make sure that the timer in wait_for_alert() works // this should time out (ret == 0) and it should take // about 2 seconds ptime start = time_now_hires(); alert const* ret; while ((ret = ses1.wait_for_alert(seconds(2)))) { a = ses1.pop_alert(); std::cerr << ret->message() << std::endl; start = time_now(); } TEST_CHECK(time_now_hires() - start < seconds(3)); TEST_CHECK(time_now_hires() - start >= seconds(2)); TEST_CHECK(!exists("./tmp1_swarm/temporary")); TEST_CHECK(!exists("./tmp2_swarm/temporary")); TEST_CHECK(!exists("./tmp3_swarm/temporary")); remove_all("./tmp1_swarm", ec); remove_all("./tmp2_swarm", ec); remove_all("./tmp3_swarm", ec); } int test_main() { using namespace libtorrent; // with time critical pieces test_swarm(false, false, false, true); // with seed mode test_swarm(false, false, true); test_swarm(); // with super seeding test_swarm(true); // with strict super seeding test_swarm(true, true); return 0; }
/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/alert_types.hpp" #include "libtorrent/thread.hpp" #include "libtorrent/time.hpp" #include <boost/tuple/tuple.hpp> #include "test.hpp" #include "setup_transfer.hpp" #include <iostream> void test_swarm(bool super_seeding = false, bool strict = false, bool seed_mode = false, bool time_critical = false) { using namespace libtorrent; // in case the previous run was terminated error_code ec; remove_all("./tmp1_swarm", ec); remove_all("./tmp2_swarm", ec); remove_all("./tmp3_swarm", ec); session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48000, 49000), "0.0.0.0", 0); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49000, 50000), "0.0.0.0", 0); session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50000, 51000), "0.0.0.0", 0); // this is to avoid everything finish from a single peer // immediately. To make the swarm actually connect all // three peers before finishing. float rate_limit = 100000; session_settings settings; settings.allow_multiple_connections_per_ip = true; settings.ignore_limits_on_local_network = false; settings.strict_super_seeding = strict; settings.upload_rate_limit = rate_limit; ses1.set_settings(settings); settings.download_rate_limit = rate_limit / 2; settings.upload_rate_limit = rate_limit; ses2.set_settings(settings); ses3.set_settings(settings); #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.out_enc_policy = pe_settings::forced; pes.in_enc_policy = pe_settings::forced; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); ses3.set_pe_settings(pes); #endif torrent_handle tor1; torrent_handle tor2; torrent_handle tor3; add_torrent_params p; p.seed_mode = seed_mode; // test using piece sizes smaller than 16kB boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true , false, true, "_swarm", 32 * 1024, 0, super_seeding, &p); int mask = alert::all_categories & ~(alert::progress_notification | alert::performance_warning | alert::stats_notification); ses1.set_alert_mask(mask); ses2.set_alert_mask(mask); ses3.set_alert_mask(mask); if (time_critical) { tor2.set_piece_deadline(2, 0); tor2.set_piece_deadline(5, 1000); tor2.set_piece_deadline(8, 2000); } float sum_dl_rate2 = 0.f; float sum_dl_rate3 = 0.f; int count_dl_rates2 = 0; int count_dl_rates3 = 0; for (int i = 0; i < 80; ++i) { print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); print_alerts(ses3, "ses3"); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); torrent_status st3 = tor3.status(); if (st2.progress < 1.f && st2.progress > 0.5f) { sum_dl_rate2 += st2.download_payload_rate; ++count_dl_rates2; } if (st3.progress < 1.f && st3.progress > 0.5f) { sum_dl_rate3 += st3.download_rate; ++count_dl_rates3; } std::cerr << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << " - " << "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st3.progress * 100) << "% " << st3.num_peers << std::endl; if (st2.is_seeding && st3.is_seeding) break; test_sleep(1000); } TEST_CHECK(tor2.status().is_seeding); TEST_CHECK(tor3.status().is_seeding); float average2 = sum_dl_rate2 / float(count_dl_rates2); float average3 = sum_dl_rate3 / float(count_dl_rates3); std::cerr << average2 << std::endl; std::cerr << "average rate: " << (average2 / 1000.f) << "kB/s - " << (average3 / 1000.f) << "kB/s" << std::endl; if (tor2.status().is_seeding && tor3.status().is_seeding) std::cerr << "done\n"; // make sure the files are deleted ses1.remove_torrent(tor1, session::delete_files); ses2.remove_torrent(tor2, session::delete_files); ses3.remove_torrent(tor3, session::delete_files); std::auto_ptr<alert> a = ses1.pop_alert(); ptime end = time_now() + seconds(20); while (a.get() == 0 || dynamic_cast<torrent_deleted_alert*>(a.get()) == 0) { if (ses1.wait_for_alert(end - time_now()) == 0) { std::cerr << "wait_for_alert() expired" << std::endl; break; } a = ses1.pop_alert(); assert(a.get()); std::cerr << a->message() << std::endl; } TEST_CHECK(dynamic_cast<torrent_deleted_alert*>(a.get()) != 0); // there shouldn't be any alerts generated from now on // make sure that the timer in wait_for_alert() works // this should time out (ret == 0) and it should take // about 2 seconds ptime start = time_now_hires(); alert const* ret; while ((ret = ses1.wait_for_alert(seconds(2)))) { a = ses1.pop_alert(); std::cerr << ret->message() << std::endl; start = time_now(); } TEST_CHECK(time_now_hires() - start < seconds(3)); TEST_CHECK(time_now_hires() - start >= seconds(2)); TEST_CHECK(!exists("./tmp1_swarm/temporary")); TEST_CHECK(!exists("./tmp2_swarm/temporary")); TEST_CHECK(!exists("./tmp3_swarm/temporary")); remove_all("./tmp1_swarm", ec); remove_all("./tmp2_swarm", ec); remove_all("./tmp3_swarm", ec); } int test_main() { using namespace libtorrent; // with time critical pieces test_swarm(false, false, false, true); // with seed mode test_swarm(false, false, true); test_swarm(); // with super seeding test_swarm(true); // with strict super seeding test_swarm(true, true); return 0; }
print less in test_swarm.cpp
print less in test_swarm.cpp git-svn-id: 4f0141143c3c635d33f1b9f02fcb2b6c73e45c89@5482 a83610d8-ad2a-0410-a6ab-fc0612d85776
C++
bsd-3-clause
halorgium/libtorrent,halorgium/libtorrent,halorgium/libtorrent,archos-sa/libtorrent-avp,archos-sa/libtorrent-avp,halorgium/libtorrent,halorgium/libtorrent,archos-sa/libtorrent-avp,archos-sa/libtorrent-avp,archos-sa/libtorrent-avp,halorgium/libtorrent,archos-sa/libtorrent-avp
7c7700f216d36c8db5bef557757dc81ff99b578f
test/testconfig.cpp
test/testconfig.cpp
#include <Python.h> #include <cstdio> #include "plictests.h" TEST_GROUP(Config) { void teardown() { /* Remove all log files generated in ./misc/output: */ PyRun_SimpleString("import os;import glob;\ [os.remove(logFile) for logFile in glob.glob('misc/output/*.log')]"); PyRun_SimpleString("import logging;logging.getLogger('test').handlers = []"); } } bool doesFileExist(const char *filename) { FILE *fp(fopen(filename, "r")); if (fp == NULL) return false; fclose(fp); return true; } }; TEST(Config, config01SimpleString) { const std::string expected("DEBUG:root:" + debugMsg + "\n" + "INFO:root:" + infoMsg + "\n"); plic::configStr("import logging;\ logging.getLogger().handlers = [];\ logging.basicConfig(filename = 'misc/output/test01.log', level = logging.DEBUG)"); /* logging.basicConfig() configures the root logger, so don't log to the 'test' logger: */ plic::debug() << debugMsg; plic::info() << infoMsg; CHECK_EQUAL(expected, getContent("misc/output/test01.log")); } TEST(Config, config02SimpleFile) { const std::string expected("test - WARNING - " + warningMsg + "\n"); const char *outputFilename = "misc/output/test02.log"; CHECK_FALSE(doesFileExist(outputFilename)); plic::configFile("test/config02.py"); plic::debug("test") << debugMsg; plic::info("test") << infoMsg; plic::warning("test") << warningMsg; CHECK(doesFileExist(outputFilename)); CHECK_EQUAL(expected, getContent(outputFilename)); } TEST(Config, config03Utf8ConfigFile) { const std::string logger("test.test-äüöß"); const std::string nonAsciiMsg("Critical msg. with ä, ö, ü, ß"); const std::string expected(logger + " : " + nonAsciiMsg + "\n"); plic::configFile("test/config03.py"); plic::critical(logger) << nonAsciiMsg; CHECK_EQUAL(expected, getContent("misc/output/test03.log")); } TEST(Config, config04Latin1ConfigFile) { const std::string logger("test.test-äüöß"); const std::string nonAsciiMsg("Error msg. with ä, ö, ü, ß"); const std::string expected(logger + " : " + nonAsciiMsg + "\n"); plic::configFile("test/config04.py"); plic::error(logger) << nonAsciiMsg; CHECK_EQUAL(expected, getContent("misc/output/test04.log")); } TEST(Config, config05FileWithSyntaxError) { setupLogStream(); plic::configFile("test/config05.py"); plic::critical() << criticalMsg; CHECK(getLogString().empty()); cleanUpLogStream(); } TEST(Config, config06StringWithSyntaxError) { setupLogStream(); plic::configStr("&&& intended invalid syntax"); plic::critical() << criticalMsg; CHECK(getLogString().empty()); cleanUpLogStream(); } TEST(Config, nonExistingFile) { setupLogStream(); plic::configFile("test/nonexisting.py"); plic::critical() << criticalMsg; CHECK(getLogString().empty()); cleanUpLogStream(); }
#include <Python.h> #include <cstdio> #include "plictests.h" TEST_GROUP(Config) { void teardown() { /* Remove all log files generated in ./misc/output: */ PyRun_SimpleString("import os;import glob;\ [os.remove(logFile) for logFile in glob.glob('misc/output/*.log')]"); PyRun_SimpleString("import logging;logging.getLogger('test').handlers = []"); } bool doesFileExist(const char *filename) { FILE *fp(fopen(filename, "r")); if (fp == NULL) return false; fclose(fp); return true; } }; TEST(Config, config01SimpleString) { const std::string expected("DEBUG:root:" + debugMsg + "\n" + "INFO:root:" + infoMsg + "\n"); plic::configStr("import logging;\ logging.getLogger().handlers = [];\ logging.basicConfig(filename = 'misc/output/test01.log', level = logging.DEBUG)"); /* logging.basicConfig() configures the root logger, so don't log to the 'test' logger: */ plic::debug() << debugMsg; plic::info() << infoMsg; CHECK_EQUAL(expected, getContent("misc/output/test01.log")); } TEST(Config, config02SimpleFile) { const std::string expected("test - WARNING - " + warningMsg + "\n"); const char *outputFilename = "misc/output/test02.log"; CHECK_FALSE(doesFileExist(outputFilename)); plic::configFile("test/config02.py"); plic::debug("test") << debugMsg; plic::info("test") << infoMsg; plic::warning("test") << warningMsg; CHECK(doesFileExist(outputFilename)); CHECK_EQUAL(expected, getContent(outputFilename)); } TEST(Config, config03Utf8ConfigFile) { const std::string logger("test.test-äüöß"); const std::string nonAsciiMsg("Critical msg. with ä, ö, ü, ß"); const std::string expected(logger + " : " + nonAsciiMsg + "\n"); plic::configFile("test/config03.py"); plic::critical(logger) << nonAsciiMsg; CHECK_EQUAL(expected, getContent("misc/output/test03.log")); } TEST(Config, config04Latin1ConfigFile) { const std::string logger("test.test-äüöß"); const std::string nonAsciiMsg("Error msg. with ä, ö, ü, ß"); const std::string expected(logger + " : " + nonAsciiMsg + "\n"); plic::configFile("test/config04.py"); plic::error(logger) << nonAsciiMsg; CHECK_EQUAL(expected, getContent("misc/output/test04.log")); } TEST(Config, config05FileWithSyntaxError) { setupLogStream(); plic::configFile("test/config05.py"); plic::critical() << criticalMsg; CHECK(getLogString().empty()); cleanUpLogStream(); } TEST(Config, config06StringWithSyntaxError) { setupLogStream(); plic::configStr("&&& intended invalid syntax"); plic::critical() << criticalMsg; CHECK(getLogString().empty()); cleanUpLogStream(); } TEST(Config, nonExistingFile) { setupLogStream(); plic::configFile("test/nonexisting.py"); plic::critical() << criticalMsg; CHECK(getLogString().empty()); cleanUpLogStream(); }
remove forgotten curly brace
remove forgotten curly brace
C++
mit
lubgr/plic,lubgr/plic,lubgr/plic,lubgr/plic
3ecb8d259b22e186cf7f31910c3e76a657ae0dd3
src/rpcclient.cpp
src/rpcclient.cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcclient.h" #include "rpcprotocol.h" #include "util.h" #include "ui_interface.h" #include "chainparams.h" // for Params().RPCPort() #include <set> #include <stdint.h> using namespace std; using namespace json_spirit; class CRPCConvertParam { public: std::string methodName; // method whose params want conversion int paramIdx; // 0-based idx of param to convert }; static const CRPCConvertParam vRPCConvertParams[] = { { "stop", 0 }, { "getaddednodeinfo", 0 }, { "setgenerate", 0 }, { "setgenerate", 1 }, { "getnetworkhashps", 0 }, { "getnetworkhashps", 1 }, { "sendtoaddress", 1 }, { "settxfee", 0 }, { "getreceivedbyaddress", 1 }, { "getreceivedbyaccount", 1 }, { "listreceivedbyaddress", 0 }, { "listreceivedbyaddress", 1 }, { "listreceivedbyaddress", 2 }, { "listreceivedbyaccount", 0 }, { "listreceivedbyaccount", 1 }, { "listreceivedbyaccount", 2 }, { "getbalance", 1 }, { "getbalance", 2 }, { "getblockhash", 0 }, { "move", 2 }, { "move", 3 }, { "sendfrom", 2 }, { "sendfrom", 3 }, { "listtransactions", 1 }, { "listtransactions", 2 }, { "listtransactions", 3 }, { "listaccounts", 0 }, { "listaccounts", 1 }, { "walletpassphrase", 1 }, { "getblocktemplate", 0 }, { "listsinceblock", 1 }, { "listsinceblock", 2 }, { "sendmany", 1 }, { "sendmany", 2 }, { "addmultisigaddress", 0 }, { "addmultisigaddress", 1 }, { "createmultisig", 0 }, { "createmultisig", 1 }, { "listunspent", 0 }, { "listunspent", 1 }, { "listunspent", 2 }, { "getblock", 1 }, { "getrawtransaction", 1 }, { "createrawtransaction", 0 }, { "createrawtransaction", 1 }, { "signrawtransaction", 1 }, { "signrawtransaction", 2 }, { "sendrawtransaction", 1 }, { "gettxout", 1 }, { "gettxout", 2 }, { "lockunspent", 0 }, { "lockunspent", 1 }, { "importprivkey", 2 }, { "importaddress", 2 }, { "verifychain", 0 }, { "verifychain", 1 }, { "keypoolrefill", 0 }, { "getrawmempool", 0 }, { "estimatefee", 0 }, { "estimatepriority", 0 }, { "prioritisetransaction", 1 }, { "prioritisetransaction", 2 }, }; class CRPCConvertTable { private: std::set<std::pair<std::string, int> > members; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); } } static CRPCConvertTable rpcCvtTable; // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; // insert string value directly if (!rpcCvtTable.convert(strMethod, idx)) { params.push_back(strVal); } // parse string as JSON, insert bool/number/object/etc. value else { Value jVal; if (!read_string(strVal, jVal)) throw runtime_error(string("Error parsing JSON:")+strVal); params.push_back(jVal); } } return params; }
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcclient.h" #include "rpcprotocol.h" #include "util.h" #include "ui_interface.h" #include <set> #include <stdint.h> using namespace std; using namespace json_spirit; class CRPCConvertParam { public: std::string methodName; // method whose params want conversion int paramIdx; // 0-based idx of param to convert }; static const CRPCConvertParam vRPCConvertParams[] = { { "stop", 0 }, { "getaddednodeinfo", 0 }, { "setgenerate", 0 }, { "setgenerate", 1 }, { "getnetworkhashps", 0 }, { "getnetworkhashps", 1 }, { "sendtoaddress", 1 }, { "settxfee", 0 }, { "getreceivedbyaddress", 1 }, { "getreceivedbyaccount", 1 }, { "listreceivedbyaddress", 0 }, { "listreceivedbyaddress", 1 }, { "listreceivedbyaddress", 2 }, { "listreceivedbyaccount", 0 }, { "listreceivedbyaccount", 1 }, { "listreceivedbyaccount", 2 }, { "getbalance", 1 }, { "getbalance", 2 }, { "getblockhash", 0 }, { "move", 2 }, { "move", 3 }, { "sendfrom", 2 }, { "sendfrom", 3 }, { "listtransactions", 1 }, { "listtransactions", 2 }, { "listtransactions", 3 }, { "listaccounts", 0 }, { "listaccounts", 1 }, { "walletpassphrase", 1 }, { "getblocktemplate", 0 }, { "listsinceblock", 1 }, { "listsinceblock", 2 }, { "sendmany", 1 }, { "sendmany", 2 }, { "addmultisigaddress", 0 }, { "addmultisigaddress", 1 }, { "createmultisig", 0 }, { "createmultisig", 1 }, { "listunspent", 0 }, { "listunspent", 1 }, { "listunspent", 2 }, { "getblock", 1 }, { "getrawtransaction", 1 }, { "createrawtransaction", 0 }, { "createrawtransaction", 1 }, { "signrawtransaction", 1 }, { "signrawtransaction", 2 }, { "sendrawtransaction", 1 }, { "gettxout", 1 }, { "gettxout", 2 }, { "lockunspent", 0 }, { "lockunspent", 1 }, { "importprivkey", 2 }, { "importaddress", 2 }, { "verifychain", 0 }, { "verifychain", 1 }, { "keypoolrefill", 0 }, { "getrawmempool", 0 }, { "estimatefee", 0 }, { "estimatepriority", 0 }, { "prioritisetransaction", 1 }, { "prioritisetransaction", 2 }, }; class CRPCConvertTable { private: std::set<std::pair<std::string, int> > members; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); } } static CRPCConvertTable rpcCvtTable; // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; // insert string value directly if (!rpcCvtTable.convert(strMethod, idx)) { params.push_back(strVal); } // parse string as JSON, insert bool/number/object/etc. value else { Value jVal; if (!read_string(strVal, jVal)) throw runtime_error(string("Error parsing JSON:")+strVal); params.push_back(jVal); } } return params; }
remove include of chainparams.h
remove include of chainparams.h chainparams.h has not been used in this cpp file already, consider to remove it for clean.
C++
mit
Crowndev/crowncoin,domob1812/crowncoin,Crowndev/crowncoin,Infernoman/crowncoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,Infernoman/crowncoin,syscoin/syscoin,syscoin/syscoin,domob1812/crowncoin,Crowndev/crowncoin,domob1812/crowncoin,Infernoman/crowncoin,Crowndev/crowncoin,syscoin/syscoin,Crowndev/crowncoin,syscoin/syscoin,syscoin/syscoin,Crowndev/crowncoin,Infernoman/crowncoin,Infernoman/crowncoin,Infernoman/crowncoin,domob1812/crowncoin,domob1812/crowncoin,domob1812/crowncoin
a1201b1e39b59f9cbfc5f569eaa5f593c9122346
lib/http/HttpWorker.cpp
lib/http/HttpWorker.cpp
/* <src/HttpWorker.cpp> * * This file is part of the x0 web server project and is released under GPL-3. * http://www.xzero.io/ * * (c) 2009-2013 Christian Parpart <[email protected]> */ #include <x0/http/HttpWorker.h> #include <x0/http/HttpRequest.h> #include <x0/http/HttpServer.h> #include <x0/http/HttpConnection.h> #include <x0/ServerSocket.h> #include <x0/DebugLogger.h> #include <algorithm> #include <cstdarg> #include <ev++.h> #include <signal.h> #include <pthread.h> // XXX one a connection has been passed to a worker, it is *bound* to it. #if 0//!defined(XZERO_NDEBUG) //# define TRACE(n, msg...) X0_DEBUG("worker", (n), msg) # define TRACE(n, msg...) log(Severity::debug ## n, msg) #else # define TRACE(n, msg...) do {} while (0) #endif namespace x0 { /*! * Creates an HTTP worker instance. * * \param server the worker parents server instance * \param loop the event loop to be used within this worker * \param id unique ID within the server instance * \param threaded whether or not to spawn a thread to actually run this worker */ HttpWorker::HttpWorker(HttpServer& server, struct ev_loop *loop, unsigned int id, bool threaded) : id_(id), state_(Inactive), server_(server), loop_(loop), startupTime_(ev_now(loop_)), now_(), connectionLoad_(0), requestCount_(0), connectionCount_(0), thread_(pthread_self()), queue_(), resumeLock_(), resumeCondition_(), performanceCounter_(), stopHandler_(), killHandler_(), connections_(nullptr), freeConnections_(nullptr), evLoopCheck_(loop_), evNewConnection_(loop_), evWakeup_(loop_), fileinfo(loop_, &server_.fileinfoConfig_) { evLoopCheck_.set<HttpWorker, &HttpWorker::onLoopCheck>(this); evLoopCheck_.start(); evNewConnection_.set<HttpWorker, &HttpWorker::onNewConnection>(this); evNewConnection_.start(); evWakeup_.set<&HttpWorker::onWakeup>(); evWakeup_.start(); pthread_mutex_init(&resumeLock_, nullptr); pthread_cond_init(&resumeCondition_, nullptr); if (threaded) { pthread_create(&thread_, nullptr, &HttpWorker::_run, this); } setName("xzero-io/%d", id_); TRACE(1, "spawned"); } HttpWorker::~HttpWorker() { TRACE(1, "destroying"); clearCustomData(); pthread_cond_destroy(&resumeCondition_); pthread_mutex_destroy(&resumeLock_); evLoopCheck_.stop(); evNewConnection_.stop(); evWakeup_.stop(); freeCache(); ev_loop_destroy(loop_); } void* HttpWorker::_run(void* p) { reinterpret_cast<HttpWorker*>(p)->run(); return nullptr; } void HttpWorker::run() { state_ = Running; // XXX invoke onWorkerSpawned-hook here because we want to ensure this hook is // XXX being invoked from *within* the worker-thread. server_.onWorkerSpawn(this); TRACE(1, "enter loop"); ev_loop(loop_, 0); while (connections_) _kill(); server_.onWorkerUnspawn(this); state_ = Inactive; } /*! * Sets the thread/process name that's running this worker. */ void HttpWorker::setName(const char* fmt, ...) { char buf[17]; // the name may be at most 16 bytes long. va_list va; va_start(va, fmt); vsnprintf(buf, sizeof(buf), fmt, va); va_end(va); pthread_setname_np(thread_, buf); } void HttpWorker::log(LogMessage&& msg) { msg.addTag("worker/%u", id()); server().log(std::forward<LogMessage>(msg)); } /** enqueues/assigns/registers given client connection information to this worker. */ void HttpWorker::enqueue(std::pair<Socket*, ServerSocket*>&& client) { queue_.enqueue(client); evNewConnection_.send(); } /** callback to be invoked when new connection(s) have been assigned to this worker. */ void HttpWorker::onNewConnection(ev::async& /*w*/, int /*revents*/) { std::pair<Socket*, ServerSocket*> client; while (queue_.dequeue(&client)) { spawnConnection(client.first, client.second); } } void HttpWorker::onWakeup(ev::async& w, int revents) { // no-op - this callback is simply used to wake up the worker's event loop } void HttpWorker::spawnConnection(Socket* client, ServerSocket* listener) { TRACE(1, "client connected; fd:%d", client->handle()); ++connectionLoad_; ++connectionCount_; // XXX since socket has not been used so far, I might be able to defer its creation out of its socket descriptor // XXX so that I do not have to double-initialize libev's loop handles for this socket. client->setLoop(loop_); HttpConnection* c; if (likely(freeConnections_ != nullptr)) { c = freeConnections_; freeConnections_ = freeConnections_->next_; c->id_ = connectionCount_; } else { c = new HttpConnection(this, connectionCount_/*id*/); } if (connections_) connections_->prev_ = c; c->next_ = connections_; connections_ = c; c->start(listener, client); } /** releases/unregisters given (and to-be-destroyed) connection from this worker. * * This decrements the connection-load counter by one. */ void HttpWorker::release(HttpConnection* c) { // /--<--\ /--<--\ /--<--\ // NULL item1 item2 item3 NULL // \-->--/ \-->--/ \-->--/ --connectionLoad_; // unlink from active-list HttpConnection* prev = c->prev_; HttpConnection* next = c->next_; if (prev) prev->next_ = next; if (next) next->prev_ = prev; if (c == connections_) connections_ = next; // link into free-list c->next_ = freeConnections_; freeConnections_ = c; } /** * Clear some cached objects to free up memory. */ void HttpWorker::freeCache() { size_t i = 0; while (freeConnections_) { auto next = freeConnections_->next_; delete freeConnections_; freeConnections_ = next; ++i; } TRACE(1, "cleared %zu free-connections items", i); } void HttpWorker::handleRequest(HttpRequest *r) { ++requestCount_; performanceCounter_.touch(now_.value()); BufferRef expectHeader = r->requestHeader("Expect"); bool contentRequired = r->method == "POST" || r->method == "PUT"; if (contentRequired) { if (r->connection.contentLength() == -1 && !r->connection.isChunked()) { r->status = HttpStatus::LengthRequired; r->finish(); return; } } else { if (r->contentAvailable()) { r->status = HttpStatus::BadRequest; // FIXME do we have a better status code? r->finish(); return; } } if (expectHeader) { r->expectingContinue = equals(expectHeader, "100-continue"); if (!r->expectingContinue || !r->supportsProtocol(1, 1)) { r->status = HttpStatus::ExpectationFailed; r->finish(); return; } } server_.onPreProcess(r); if (!server_.requestHandler(r)) r->finish(); } void HttpWorker::_stop() { TRACE(1, "_stop"); evLoopCheck_.stop(); evNewConnection_.stop(); evWakeup_.stop(); for (auto handler: stopHandler_) handler(); } void HttpWorker::onLoopCheck(ev::check& /*w*/, int /*revents*/) { // update server time now_.update(ev_now(loop_)); } void HttpWorker::setAffinity(int cpu) { cpu_set_t set; CPU_ZERO(&set); CPU_SET(cpu, &set); TRACE(1, "setAffinity: %d", cpu); int rv = pthread_setaffinity_np(thread_, sizeof(set), &set); if (rv < 0) { log(Severity::error, "setting scheduler affinity on CPU %d failed for worker %u. %s", cpu, id_, strerror(errno)); } } void HttpWorker::bind(ServerSocket* s) { s->set<HttpWorker, &HttpWorker::spawnConnection>(this); } /** suspend the execution of the worker thread until resume() is invoked. * * \note has no effect on main worker * \see resume() */ void HttpWorker::suspend() { TRACE(1, "suspend"); if (id_ != 0) post<HttpWorker, &HttpWorker::_suspend>(this); } void HttpWorker::_suspend() { TRACE(1, "_suspend"); pthread_mutex_lock(&resumeLock_); state_ = Suspended; pthread_cond_wait(&resumeCondition_, &resumeLock_); state_ = Running; pthread_mutex_unlock(&resumeLock_); } /** resumes the previousely suspended worker thread. * * \note has no effect on main worker * \see suspend() */ void HttpWorker::resume() { TRACE(1, "resume"); if (id_ != 0) pthread_cond_signal(&resumeCondition_); } void HttpWorker::stop() { TRACE(1, "stop: post -> _stop() (while in state: %d)", state_); if (state_ != Running) return; post<HttpWorker, &HttpWorker::_stop>(this); } void HttpWorker::join() { if (thread_ != pthread_self()) { pthread_join(thread_, nullptr); } } /*! Actually aborts all active connections. * * \see HttpConnection::abort() */ void HttpWorker::kill() { TRACE(1, "kill: post -> _kill()"); post<HttpWorker, &HttpWorker::_kill>(this); } /*! Actually aborts all active connections. * * \note Must be invoked from within the worker's thread. * * \see HttpConnection::abort() */ void HttpWorker::_kill() { TRACE(1, "_kill()"); while (connections_) { std::list<HttpConnection*> copy; for (HttpConnection* c = connections_; c != nullptr; c = c->next_) copy.push_back(c); for (auto c: copy) c->abort(); #ifndef XZERO_NDEBUG for (HttpConnection* c = connections_; c != nullptr; c = c->next_) c->log(Severity::debug, "connection still open"); #endif } for (auto handler: killHandler_) { TRACE(1, "_kill: invoke kill handler"); handler(); } } std::list<std::function<void()>>::iterator HttpWorker::registerStopHandler(std::function<void()> callback) { stopHandler_.push_front(callback); return stopHandler_.begin(); } void HttpWorker::unregisterStopHandler(std::list<std::function<void()>>::iterator handle) { stopHandler_.erase(handle); } std::list<std::function<void()>>::iterator HttpWorker::registerKillHandler(std::function<void()> callback) { killHandler_.push_front(callback); return killHandler_.begin(); } void HttpWorker::unregisterKillHandler(std::list<std::function<void()>>::iterator handle) { killHandler_.erase(handle); } void HttpWorker::post_thunk3(int revents, void* arg) { std::function<void()>* callback = static_cast<std::function<void()>*>(arg); (*callback)(); delete callback; } } // namespace x0
/* <src/HttpWorker.cpp> * * This file is part of the x0 web server project and is released under GPL-3. * http://www.xzero.io/ * * (c) 2009-2013 Christian Parpart <[email protected]> */ #include <x0/http/HttpWorker.h> #include <x0/http/HttpRequest.h> #include <x0/http/HttpServer.h> #include <x0/http/HttpConnection.h> #include <x0/ServerSocket.h> #include <x0/DebugLogger.h> #include <algorithm> #include <cstdarg> #include <ev++.h> #include <signal.h> #include <pthread.h> // XXX one a connection has been passed to a worker, it is *bound* to it. #if 0//!defined(XZERO_NDEBUG) //# define TRACE(n, msg...) X0_DEBUG("worker", (n), msg) # define TRACE(n, msg...) log(Severity::debug ## n, msg) #else # define TRACE(n, msg...) do {} while (0) #endif namespace x0 { /*! * Creates an HTTP worker instance. * * \param server the worker parents server instance * \param loop the event loop to be used within this worker * \param id unique ID within the server instance * \param threaded whether or not to spawn a thread to actually run this worker */ HttpWorker::HttpWorker(HttpServer& server, struct ev_loop *loop, unsigned int id, bool threaded) : id_(id), state_(Inactive), server_(server), loop_(loop), startupTime_(ev_now(loop_)), now_(), connectionLoad_(0), requestCount_(0), connectionCount_(0), thread_(pthread_self()), queue_(), resumeLock_(), resumeCondition_(), performanceCounter_(), stopHandler_(), killHandler_(), connections_(nullptr), freeConnections_(nullptr), evLoopCheck_(loop_), evNewConnection_(loop_), evWakeup_(loop_), fileinfo(loop_, &server_.fileinfoConfig_) { evLoopCheck_.set<HttpWorker, &HttpWorker::onLoopCheck>(this); evLoopCheck_.start(); evNewConnection_.set<HttpWorker, &HttpWorker::onNewConnection>(this); evNewConnection_.start(); evWakeup_.set<&HttpWorker::onWakeup>(); evWakeup_.start(); pthread_mutex_init(&resumeLock_, nullptr); pthread_cond_init(&resumeCondition_, nullptr); if (threaded) { pthread_create(&thread_, nullptr, &HttpWorker::_run, this); } setName("xzero-io/%d", id_); TRACE(1, "spawned"); } HttpWorker::~HttpWorker() { TRACE(1, "destroying"); clearCustomData(); pthread_cond_destroy(&resumeCondition_); pthread_mutex_destroy(&resumeLock_); evLoopCheck_.stop(); evNewConnection_.stop(); evWakeup_.stop(); freeCache(); ev_loop_destroy(loop_); } void* HttpWorker::_run(void* p) { reinterpret_cast<HttpWorker*>(p)->run(); return nullptr; } void HttpWorker::run() { state_ = Running; // XXX invoke onWorkerSpawned-hook here because we want to ensure this hook is // XXX being invoked from *within* the worker-thread. server_.onWorkerSpawn(this); TRACE(1, "enter loop"); ev_loop(loop_, 0); while (connections_) _kill(); server_.onWorkerUnspawn(this); state_ = Inactive; } /*! * Sets the thread/process name that's running this worker. */ void HttpWorker::setName(const char* fmt, ...) { char buf[17]; // the name may be at most 16 bytes long. va_list va; va_start(va, fmt); vsnprintf(buf, sizeof(buf), fmt, va); va_end(va); pthread_setname_np(thread_, buf); } void HttpWorker::log(LogMessage&& msg) { msg.addTag("worker/%u", id()); server().log(std::forward<LogMessage>(msg)); } /** enqueues/assigns/registers given client connection information to this worker. */ void HttpWorker::enqueue(std::pair<Socket*, ServerSocket*>&& client) { queue_.enqueue(client); evNewConnection_.send(); } /** callback to be invoked when new connection(s) have been assigned to this worker. */ void HttpWorker::onNewConnection(ev::async& /*w*/, int /*revents*/) { std::pair<Socket*, ServerSocket*> client; while (queue_.dequeue(&client)) { spawnConnection(client.first, client.second); } } void HttpWorker::onWakeup(ev::async& w, int revents) { // no-op - this callback is simply used to wake up the worker's event loop } void HttpWorker::spawnConnection(Socket* client, ServerSocket* listener) { TRACE(1, "client connected; fd:%d", client->handle()); ++connectionLoad_; ++connectionCount_; // XXX since socket has not been used so far, I might be able to defer its creation out of its socket descriptor // XXX so that I do not have to double-initialize libev's loop handles for this socket. client->setLoop(loop_); HttpConnection* c; if (likely(freeConnections_ != nullptr)) { c = freeConnections_; c->id_ = connectionCount_; freeConnections_ = c->next_; } else { c = new HttpConnection(this, connectionCount_/*id*/); } if (connections_) connections_->prev_ = c; c->next_ = connections_; connections_ = c; c->start(listener, client); } /** releases/unregisters given (and to-be-destroyed) connection from this worker. * * This decrements the connection-load counter by one. */ void HttpWorker::release(HttpConnection* c) { // /--<--\ /--<--\ /--<--\ // NULL item1 item2 item3 NULL // \-->--/ \-->--/ \-->--/ --connectionLoad_; // unlink from active-list HttpConnection* prev = c->prev_; HttpConnection* next = c->next_; if (prev) prev->next_ = next; if (next) next->prev_ = prev; if (c == connections_) connections_ = next; // link into free-list c->next_ = freeConnections_; c->prev_ = nullptr; // not needed if (freeConnections_ && freeConnections_->prev_) freeConnections_->prev_ = c; // not needed freeConnections_ = c; } /** * Clear some cached objects to free up memory. */ void HttpWorker::freeCache() { size_t i = 0; while (freeConnections_) { auto next = freeConnections_->next_; delete freeConnections_; freeConnections_ = next; ++i; } TRACE(1, "cleared %zu free-connections items", i); } void HttpWorker::handleRequest(HttpRequest *r) { ++requestCount_; performanceCounter_.touch(now_.value()); BufferRef expectHeader = r->requestHeader("Expect"); bool contentRequired = r->method == "POST" || r->method == "PUT"; if (contentRequired) { if (r->connection.contentLength() == -1 && !r->connection.isChunked()) { r->status = HttpStatus::LengthRequired; r->finish(); return; } } else { if (r->contentAvailable()) { r->status = HttpStatus::BadRequest; // FIXME do we have a better status code? r->finish(); return; } } if (expectHeader) { r->expectingContinue = equals(expectHeader, "100-continue"); if (!r->expectingContinue || !r->supportsProtocol(1, 1)) { r->status = HttpStatus::ExpectationFailed; r->finish(); return; } } server_.onPreProcess(r); if (!server_.requestHandler(r)) r->finish(); } void HttpWorker::_stop() { TRACE(1, "_stop"); evLoopCheck_.stop(); evNewConnection_.stop(); evWakeup_.stop(); for (auto handler: stopHandler_) handler(); } void HttpWorker::onLoopCheck(ev::check& /*w*/, int /*revents*/) { // update server time now_.update(ev_now(loop_)); } void HttpWorker::setAffinity(int cpu) { cpu_set_t set; CPU_ZERO(&set); CPU_SET(cpu, &set); TRACE(1, "setAffinity: %d", cpu); int rv = pthread_setaffinity_np(thread_, sizeof(set), &set); if (rv < 0) { log(Severity::error, "setting scheduler affinity on CPU %d failed for worker %u. %s", cpu, id_, strerror(errno)); } } void HttpWorker::bind(ServerSocket* s) { s->set<HttpWorker, &HttpWorker::spawnConnection>(this); } /** suspend the execution of the worker thread until resume() is invoked. * * \note has no effect on main worker * \see resume() */ void HttpWorker::suspend() { TRACE(1, "suspend"); if (id_ != 0) post<HttpWorker, &HttpWorker::_suspend>(this); } void HttpWorker::_suspend() { TRACE(1, "_suspend"); pthread_mutex_lock(&resumeLock_); state_ = Suspended; pthread_cond_wait(&resumeCondition_, &resumeLock_); state_ = Running; pthread_mutex_unlock(&resumeLock_); } /** resumes the previousely suspended worker thread. * * \note has no effect on main worker * \see suspend() */ void HttpWorker::resume() { TRACE(1, "resume"); if (id_ != 0) pthread_cond_signal(&resumeCondition_); } void HttpWorker::stop() { TRACE(1, "stop: post -> _stop() (while in state: %d)", state_); if (state_ != Running) return; post<HttpWorker, &HttpWorker::_stop>(this); } void HttpWorker::join() { if (thread_ != pthread_self()) { pthread_join(thread_, nullptr); } } /*! Actually aborts all active connections. * * \see HttpConnection::abort() */ void HttpWorker::kill() { TRACE(1, "kill: post -> _kill()"); post<HttpWorker, &HttpWorker::_kill>(this); } /*! Actually aborts all active connections. * * \note Must be invoked from within the worker's thread. * * \see HttpConnection::abort() */ void HttpWorker::_kill() { TRACE(1, "_kill()"); while (connections_) { std::list<HttpConnection*> copy; for (HttpConnection* c = connections_; c != nullptr; c = c->next_) copy.push_back(c); for (auto c: copy) c->abort(); #ifndef XZERO_NDEBUG for (HttpConnection* c = connections_; c != nullptr; c = c->next_) c->log(Severity::debug, "connection still open"); #endif } for (auto handler: killHandler_) { TRACE(1, "_kill: invoke kill handler"); handler(); } } std::list<std::function<void()>>::iterator HttpWorker::registerStopHandler(std::function<void()> callback) { stopHandler_.push_front(callback); return stopHandler_.begin(); } void HttpWorker::unregisterStopHandler(std::list<std::function<void()>>::iterator handle) { stopHandler_.erase(handle); } std::list<std::function<void()>>::iterator HttpWorker::registerKillHandler(std::function<void()> callback) { killHandler_.push_front(callback); return killHandler_.begin(); } void HttpWorker::unregisterKillHandler(std::list<std::function<void()>>::iterator handle) { killHandler_.erase(handle); } void HttpWorker::post_thunk3(int revents, void* arg) { std::function<void()>* callback = static_cast<std::function<void()>*>(arg); (*callback)(); delete callback; } } // namespace x0
Revert "[http] HttpWorker: code cleanup"
Revert "[http] HttpWorker: code cleanup" This reverts commit d43c204724817b731872fd5715201464f4c0adb1.
C++
mit
xzero/x0,christianparpart/x0,xzero/x0,christianparpart/x0,christianparpart/x0,christianparpart/x0,xzero/x0,christianparpart/x0,christianparpart/x0,xzero/x0,xzero/x0,christianparpart/x0,xzero/x0
28e10e5d872d193e5ba55546bf0bffd5ce3b8a04
src/simulator.cpp
src/simulator.cpp
/** ** Copyright 2014 Rico Antonio Felix ** ** 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 "tv.hpp" int main(int argc, char **argv) { namespace CSP = compuSUAVE_Professional; CSP::TV bedroom; CSP::Remote::change_channel(bedroom, 40); CSP::Remote::display_settings(bedroom); return 0; }
/** ** Copyright 2014 Rico Antonio Felix ** ** 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 "tv.hpp" int main(int argc, char **argv) { namespace CSP = compuSUAVE_Professional; CSP::TV bedroom; CSP::Remote::toggle_mode(bedroom); CSP::Remote::change_channel(bedroom, 40); CSP::Remote::display_settings(bedroom); return 0; }
Update simulator.cpp
Update simulator.cpp
C++
apache-2.0
RicoAntonioFelix/TELEVISION-SIMULATOR
00a9cdfc908651c7cc6483b1549c6b9617e2a75d
src/context.hh
src/context.hh
#ifndef context_hh_INCLUDED #define context_hh_INCLUDED #include "window.hh" #include "user_interface.hh" namespace Kakoune { class InputHandler; // A Context is used to access non singleton objects for various services // in commands. // // The Context object links an InputHandler, an Editor (which may be a Window), // and a UserInterface. It may represent an interactive user window, or // a hook execution or a macro replay. struct Context { Context() {} explicit Context(Editor& editor) : m_editor(&editor) {} Context(InputHandler& input_handler, UserInterface& ui) : m_input_handler(&input_handler), m_ui(&ui) {} Context(InputHandler& input_handler, Editor& editor, UserInterface& ui) : m_input_handler(&input_handler), m_editor(&editor), m_ui(&ui) {} // to allow func(Context(Editor(...))) // make sure the context will not survive the next ';' explicit Context(Editor&& editor) : m_editor(&editor) {} Context(const Context&) = delete; Context(Context&&) = default; Context& operator=(const Context&) = delete; Buffer& buffer() const { if (not has_buffer()) throw runtime_error("no buffer in context"); return m_editor->buffer(); } bool has_buffer() const { return (bool)m_editor; } Editor& editor() const { if (not has_editor()) throw runtime_error("no editor in context"); return *m_editor.get(); } bool has_editor() const { return (bool)m_editor; } Window& window() const { if (not has_window()) throw runtime_error("no window in context"); return *dynamic_cast<Window*>(m_editor.get()); } bool has_window() const { return (bool)m_editor and dynamic_cast<Window*>(m_editor.get()); } InputHandler& input_handler() const { if (not has_input_handler()) throw runtime_error("no input handler in context"); return *m_input_handler; } bool has_input_handler() const { return (bool)m_input_handler; } UserInterface& ui() const { if (not has_ui()) throw runtime_error("no user interface in context"); return *m_ui; } bool has_ui() const { return (bool)m_ui; } void change_editor(Editor& editor) { m_editor.reset(&editor); if (has_window() && has_ui()) window().set_dimensions(ui().dimensions()); } OptionManager& options() const { if (has_window()) return window().options(); if (has_buffer()) return buffer().options(); return GlobalOptions::instance(); } HookManager& hooks() const { if (has_window()) return window().hooks(); if (has_buffer()) return buffer().hooks(); return GlobalHooks::instance(); } void print_status(const String& status) const { if (has_ui()) ui().print_status(status); } using Insertion = std::pair<InsertMode, std::vector<Key>>; Insertion& last_insert() { return m_last_insert; } void push_jump() { const SelectionList& jump = editor().selections(); if (m_current_jump != m_jump_list.end()) { auto begin = m_current_jump; if (&editor().buffer() != &begin->buffer() or (const SelectionList&)(*begin) != jump) ++begin; m_jump_list.erase(begin, m_jump_list.end()); } m_jump_list.push_back({editor().buffer(), jump}); m_current_jump = m_jump_list.end(); } const SelectionList& jump_forward() { if (m_current_jump != m_jump_list.end() and m_current_jump + 1 != m_jump_list.end()) return *++m_current_jump; throw runtime_error("no next jump"); } const SelectionList& jump_backward() { if (m_current_jump != m_jump_list.begin()) { if (m_current_jump == m_jump_list.end()) { push_jump(); --m_current_jump; } return *--m_current_jump; } throw runtime_error("no previous jump"); } void forget_jumps_to_buffer(Buffer& buffer) { for (auto it = m_jump_list.begin(); it != m_jump_list.end();) { if (&it->buffer() == &buffer) { if (it < m_current_jump) --m_current_jump; else if (it == m_current_jump) m_current_jump = m_jump_list.end()-1; it = m_jump_list.erase(it); } else ++it; } } int& numeric_param() { return m_numeric_param; } private: safe_ptr<Editor> m_editor; InputHandler* m_input_handler = nullptr; safe_ptr<UserInterface> m_ui; Insertion m_last_insert = {InsertMode::Insert, {}}; int m_numeric_param = 0; using JumpList = std::vector<DynamicSelectionList>; JumpList m_jump_list; JumpList::iterator m_current_jump = m_jump_list.begin(); }; } #endif // context_hh_INCLUDED
#ifndef context_hh_INCLUDED #define context_hh_INCLUDED #include "window.hh" #include "user_interface.hh" namespace Kakoune { class InputHandler; // A Context is used to access non singleton objects for various services // in commands. // // The Context object links an InputHandler, an Editor (which may be a Window), // and a UserInterface. It may represent an interactive user window, or // a hook execution or a macro replay. struct Context { Context() {} explicit Context(Editor& editor) : m_editor(&editor) {} Context(InputHandler& input_handler, UserInterface& ui) : m_input_handler(&input_handler), m_ui(&ui) {} Context(const Context&) = delete; Context& operator=(const Context&) = delete; Buffer& buffer() const { if (not has_buffer()) throw runtime_error("no buffer in context"); return m_editor->buffer(); } bool has_buffer() const { return (bool)m_editor; } Editor& editor() const { if (not has_editor()) throw runtime_error("no editor in context"); return *m_editor.get(); } bool has_editor() const { return (bool)m_editor; } Window& window() const { if (not has_window()) throw runtime_error("no window in context"); return *dynamic_cast<Window*>(m_editor.get()); } bool has_window() const { return (bool)m_editor and dynamic_cast<Window*>(m_editor.get()); } InputHandler& input_handler() const { if (not has_input_handler()) throw runtime_error("no input handler in context"); return *m_input_handler; } bool has_input_handler() const { return (bool)m_input_handler; } UserInterface& ui() const { if (not has_ui()) throw runtime_error("no user interface in context"); return *m_ui; } bool has_ui() const { return (bool)m_ui; } void change_editor(Editor& editor) { m_editor.reset(&editor); if (has_window() && has_ui()) window().set_dimensions(ui().dimensions()); } OptionManager& options() const { if (has_window()) return window().options(); if (has_buffer()) return buffer().options(); return GlobalOptions::instance(); } HookManager& hooks() const { if (has_window()) return window().hooks(); if (has_buffer()) return buffer().hooks(); return GlobalHooks::instance(); } void print_status(const String& status) const { if (has_ui()) ui().print_status(status); } using Insertion = std::pair<InsertMode, std::vector<Key>>; Insertion& last_insert() { return m_last_insert; } void push_jump() { const SelectionList& jump = editor().selections(); if (m_current_jump != m_jump_list.end()) { auto begin = m_current_jump; if (&editor().buffer() != &begin->buffer() or (const SelectionList&)(*begin) != jump) ++begin; m_jump_list.erase(begin, m_jump_list.end()); } m_jump_list.push_back({editor().buffer(), jump}); m_current_jump = m_jump_list.end(); } const SelectionList& jump_forward() { if (m_current_jump != m_jump_list.end() and m_current_jump + 1 != m_jump_list.end()) return *++m_current_jump; throw runtime_error("no next jump"); } const SelectionList& jump_backward() { if (m_current_jump != m_jump_list.begin()) { if (m_current_jump == m_jump_list.end()) { push_jump(); --m_current_jump; } return *--m_current_jump; } throw runtime_error("no previous jump"); } void forget_jumps_to_buffer(Buffer& buffer) { for (auto it = m_jump_list.begin(); it != m_jump_list.end();) { if (&it->buffer() == &buffer) { if (it < m_current_jump) --m_current_jump; else if (it == m_current_jump) m_current_jump = m_jump_list.end()-1; it = m_jump_list.erase(it); } else ++it; } } int& numeric_param() { return m_numeric_param; } private: safe_ptr<Editor> m_editor; InputHandler* m_input_handler = nullptr; safe_ptr<UserInterface> m_ui; Insertion m_last_insert = {InsertMode::Insert, {}}; int m_numeric_param = 0; using JumpList = std::vector<DynamicSelectionList>; JumpList m_jump_list; JumpList::iterator m_current_jump = m_jump_list.begin(); }; } #endif // context_hh_INCLUDED
remove some unused code
Context: remove some unused code
C++
unlicense
ekie/kakoune,mawww/kakoune,flavius/kakoune,zakgreant/kakoune,occivink/kakoune,jkonecny12/kakoune,danr/kakoune,rstacruz/kakoune,elegios/kakoune,casimir/kakoune,elegios/kakoune,occivink/kakoune,Asenar/kakoune,alexherbo2/kakoune,casimir/kakoune,alpha123/kakoune,occivink/kakoune,jkonecny12/kakoune,jjthrash/kakoune,occivink/kakoune,alpha123/kakoune,danielma/kakoune,ekie/kakoune,xificurC/kakoune,danielma/kakoune,mawww/kakoune,casimir/kakoune,ekie/kakoune,lenormf/kakoune,Asenar/kakoune,flavius/kakoune,rstacruz/kakoune,danr/kakoune,Asenar/kakoune,xificurC/kakoune,Somasis/kakoune,danielma/kakoune,zakgreant/kakoune,lenormf/kakoune,danr/kakoune,xificurC/kakoune,jjthrash/kakoune,Somasis/kakoune,rstacruz/kakoune,Somasis/kakoune,ekie/kakoune,alexherbo2/kakoune,Somasis/kakoune,alpha123/kakoune,casimir/kakoune,mawww/kakoune,jkonecny12/kakoune,jkonecny12/kakoune,alexherbo2/kakoune,alpha123/kakoune,alexherbo2/kakoune,jjthrash/kakoune,elegios/kakoune,danielma/kakoune,danr/kakoune,rstacruz/kakoune,lenormf/kakoune,elegios/kakoune,flavius/kakoune,mawww/kakoune,Asenar/kakoune,xificurC/kakoune,zakgreant/kakoune,flavius/kakoune,lenormf/kakoune,jjthrash/kakoune,zakgreant/kakoune
c752864b8101aa582883fdc5404fc7e5196a8bfc
src/subprocess.cc
src/subprocess.cc
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "subprocess.h" #include <algorithm> #include <map> #include <assert.h> #include <errno.h> #include <fcntl.h> #include <poll.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <sys/wait.h> #include "util.h" Subprocess::Subprocess() : fd_(-1), pid_(-1) { } Subprocess::~Subprocess() { if (fd_ >= 0) close(fd_); // Reap child if forgotten. if (pid_ != -1) Finish(); } bool Subprocess::Start(SubprocessSet* set, const string& command) { int output_pipe[2]; if (pipe(output_pipe) < 0) Fatal("pipe: %s", strerror(errno)); fd_ = output_pipe[0]; #if !defined(linux) // On linux we use ppoll in DoWork(); elsewhere we use pselect and so must // avoid overly-large FDs. if (fd_ >= static_cast<int>(FD_SETSIZE)) Fatal("pipe: %s", strerror(EMFILE)); #endif // !linux SetCloseOnExec(fd_); pid_ = fork(); if (pid_ < 0) Fatal("fork: %s", strerror(errno)); if (pid_ == 0) { close(output_pipe[0]); // Track which fd we use to report errors on. int error_pipe = output_pipe[1]; do { if (setpgid(0, 0) < 0) break; if (sigaction(SIGINT, &set->old_act_, 0) < 0) break; if (sigprocmask(SIG_SETMASK, &set->old_mask_, 0) < 0) break; // Open /dev/null over stdin. int devnull = open("/dev/null", O_WRONLY); if (devnull < 0) break; if (dup2(devnull, 0) < 0) break; close(devnull); if (dup2(output_pipe[1], 1) < 0 || dup2(output_pipe[1], 2) < 0) break; // Now can use stderr for errors. error_pipe = 2; close(output_pipe[1]); execl("/bin/sh", "/bin/sh", "-c", command.c_str(), (char *) NULL); } while (false); // If we get here, something went wrong; the execl should have // replaced us. char* err = strerror(errno); if (write(error_pipe, err, strlen(err)) < 0) { // If the write fails, there's nothing we can do. // But this block seems necessary to silence the warning. } _exit(1); } close(output_pipe[1]); return true; } void Subprocess::OnPipeReady() { char buf[4 << 10]; ssize_t len = read(fd_, buf, sizeof(buf)); if (len > 0) { buf_.append(buf, len); } else { if (len < 0) Fatal("read: %s", strerror(errno)); close(fd_); fd_ = -1; } } ExitStatus Subprocess::Finish() { assert(pid_ != -1); int status; if (waitpid(pid_, &status, 0) < 0) Fatal("waitpid(%d): %s", pid_, strerror(errno)); pid_ = -1; if (WIFEXITED(status)) { int exit = WEXITSTATUS(status); if (exit == 0) return ExitSuccess; } else if (WIFSIGNALED(status)) { if (WTERMSIG(status) == SIGINT) return ExitInterrupted; } return ExitFailure; } bool Subprocess::Done() const { return fd_ == -1; } const string& Subprocess::GetOutput() const { return buf_; } bool SubprocessSet::interrupted_; void SubprocessSet::SetInterruptedFlag(int signum) { (void) signum; interrupted_ = true; } SubprocessSet::SubprocessSet() { interrupted_ = false; sigset_t set; sigemptyset(&set); sigaddset(&set, SIGINT); if (sigprocmask(SIG_BLOCK, &set, &old_mask_) < 0) Fatal("sigprocmask: %s", strerror(errno)); struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = SetInterruptedFlag; if (sigaction(SIGINT, &act, &old_act_) < 0) Fatal("sigaction: %s", strerror(errno)); } SubprocessSet::~SubprocessSet() { Clear(); if (sigaction(SIGINT, &old_act_, 0) < 0) Fatal("sigaction: %s", strerror(errno)); if (sigprocmask(SIG_SETMASK, &old_mask_, 0) < 0) Fatal("sigprocmask: %s", strerror(errno)); } Subprocess *SubprocessSet::Add(const string& command) { Subprocess *subprocess = new Subprocess; if (!subprocess->Start(this, command)) { delete subprocess; return 0; } running_.push_back(subprocess); return subprocess; } #ifdef linux bool SubprocessSet::DoWork() { vector<pollfd> fds; nfds_t nfds = 0; for (vector<Subprocess*>::iterator i = running_.begin(); i != running_.end(); ++i) { int fd = (*i)->fd_; if (fd < 0) continue; pollfd pfd = { fd, POLLIN | POLLPRI | POLLRDHUP, 0 }; fds.push_back(pfd); ++nfds; } int ret = ppoll(&fds.front(), nfds, NULL, &old_mask_); if (ret == -1) { if (errno != EINTR) { perror("ninja: ppoll"); return false; } bool interrupted = interrupted_; interrupted_ = false; return interrupted; } nfds_t cur_nfd = 0; for (vector<Subprocess*>::iterator i = running_.begin(); i != running_.end(); ) { int fd = (*i)->fd_; if (fd < 0) continue; assert(fd == fds[cur_nfd].fd); if (fds[cur_nfd++].revents) { (*i)->OnPipeReady(); if ((*i)->Done()) { finished_.push(*i); i = running_.erase(i); continue; } } ++i; } return false; } #else // linux bool SubprocessSet::DoWork() { fd_set set; int nfds = 0; FD_ZERO(&set); for (vector<Subprocess*>::iterator i = running_.begin(); i != running_.end(); ++i) { int fd = (*i)->fd_; if (fd >= 0) { FD_SET(fd, &set); if (nfds < fd+1) nfds = fd+1; } } int ret = pselect(nfds, &set, 0, 0, 0, &old_mask_); if (ret == -1) { if (errno != EINTR) { perror("ninja: pselect"); return false; } bool interrupted = interrupted_; interrupted_ = false; return interrupted; } for (vector<Subprocess*>::iterator i = running_.begin(); i != running_.end(); ) { int fd = (*i)->fd_; if (fd >= 0 && FD_ISSET(fd, &set)) { (*i)->OnPipeReady(); if ((*i)->Done()) { finished_.push(*i); i = running_.erase(i); continue; } } ++i; } return false; } #endif // linux Subprocess* SubprocessSet::NextFinished() { if (finished_.empty()) return NULL; Subprocess* subproc = finished_.front(); finished_.pop(); return subproc; } void SubprocessSet::Clear() { for (vector<Subprocess*>::iterator i = running_.begin(); i != running_.end(); ++i) kill(-(*i)->pid_, SIGINT); for (vector<Subprocess*>::iterator i = running_.begin(); i != running_.end(); ++i) delete *i; running_.clear(); }
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "subprocess.h" #include <algorithm> #include <map> #include <assert.h> #include <errno.h> #include <fcntl.h> #include <poll.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <sys/wait.h> // Older versions of won't find this in <poll.h>. Some versions keep it in // <asm-generic/poll.h>, though attempting to include that will redefine the // pollfd structure. #ifndef POLLRDHUP #define POLLRDHUP 0x2000 #endif #include "util.h" Subprocess::Subprocess() : fd_(-1), pid_(-1) { } Subprocess::~Subprocess() { if (fd_ >= 0) close(fd_); // Reap child if forgotten. if (pid_ != -1) Finish(); } bool Subprocess::Start(SubprocessSet* set, const string& command) { int output_pipe[2]; if (pipe(output_pipe) < 0) Fatal("pipe: %s", strerror(errno)); fd_ = output_pipe[0]; #if !defined(linux) // On linux we use ppoll in DoWork(); elsewhere we use pselect and so must // avoid overly-large FDs. if (fd_ >= static_cast<int>(FD_SETSIZE)) Fatal("pipe: %s", strerror(EMFILE)); #endif // !linux SetCloseOnExec(fd_); pid_ = fork(); if (pid_ < 0) Fatal("fork: %s", strerror(errno)); if (pid_ == 0) { close(output_pipe[0]); // Track which fd we use to report errors on. int error_pipe = output_pipe[1]; do { if (setpgid(0, 0) < 0) break; if (sigaction(SIGINT, &set->old_act_, 0) < 0) break; if (sigprocmask(SIG_SETMASK, &set->old_mask_, 0) < 0) break; // Open /dev/null over stdin. int devnull = open("/dev/null", O_WRONLY); if (devnull < 0) break; if (dup2(devnull, 0) < 0) break; close(devnull); if (dup2(output_pipe[1], 1) < 0 || dup2(output_pipe[1], 2) < 0) break; // Now can use stderr for errors. error_pipe = 2; close(output_pipe[1]); execl("/bin/sh", "/bin/sh", "-c", command.c_str(), (char *) NULL); } while (false); // If we get here, something went wrong; the execl should have // replaced us. char* err = strerror(errno); if (write(error_pipe, err, strlen(err)) < 0) { // If the write fails, there's nothing we can do. // But this block seems necessary to silence the warning. } _exit(1); } close(output_pipe[1]); return true; } void Subprocess::OnPipeReady() { char buf[4 << 10]; ssize_t len = read(fd_, buf, sizeof(buf)); if (len > 0) { buf_.append(buf, len); } else { if (len < 0) Fatal("read: %s", strerror(errno)); close(fd_); fd_ = -1; } } ExitStatus Subprocess::Finish() { assert(pid_ != -1); int status; if (waitpid(pid_, &status, 0) < 0) Fatal("waitpid(%d): %s", pid_, strerror(errno)); pid_ = -1; if (WIFEXITED(status)) { int exit = WEXITSTATUS(status); if (exit == 0) return ExitSuccess; } else if (WIFSIGNALED(status)) { if (WTERMSIG(status) == SIGINT) return ExitInterrupted; } return ExitFailure; } bool Subprocess::Done() const { return fd_ == -1; } const string& Subprocess::GetOutput() const { return buf_; } bool SubprocessSet::interrupted_; void SubprocessSet::SetInterruptedFlag(int signum) { (void) signum; interrupted_ = true; } SubprocessSet::SubprocessSet() { interrupted_ = false; sigset_t set; sigemptyset(&set); sigaddset(&set, SIGINT); if (sigprocmask(SIG_BLOCK, &set, &old_mask_) < 0) Fatal("sigprocmask: %s", strerror(errno)); struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = SetInterruptedFlag; if (sigaction(SIGINT, &act, &old_act_) < 0) Fatal("sigaction: %s", strerror(errno)); } SubprocessSet::~SubprocessSet() { Clear(); if (sigaction(SIGINT, &old_act_, 0) < 0) Fatal("sigaction: %s", strerror(errno)); if (sigprocmask(SIG_SETMASK, &old_mask_, 0) < 0) Fatal("sigprocmask: %s", strerror(errno)); } Subprocess *SubprocessSet::Add(const string& command) { Subprocess *subprocess = new Subprocess; if (!subprocess->Start(this, command)) { delete subprocess; return 0; } running_.push_back(subprocess); return subprocess; } #ifdef linux bool SubprocessSet::DoWork() { vector<pollfd> fds; nfds_t nfds = 0; for (vector<Subprocess*>::iterator i = running_.begin(); i != running_.end(); ++i) { int fd = (*i)->fd_; if (fd < 0) continue; pollfd pfd = { fd, POLLIN | POLLPRI | POLLRDHUP, 0 }; fds.push_back(pfd); ++nfds; } int ret = ppoll(&fds.front(), nfds, NULL, &old_mask_); if (ret == -1) { if (errno != EINTR) { perror("ninja: ppoll"); return false; } bool interrupted = interrupted_; interrupted_ = false; return interrupted; } nfds_t cur_nfd = 0; for (vector<Subprocess*>::iterator i = running_.begin(); i != running_.end(); ) { int fd = (*i)->fd_; if (fd < 0) continue; assert(fd == fds[cur_nfd].fd); if (fds[cur_nfd++].revents) { (*i)->OnPipeReady(); if ((*i)->Done()) { finished_.push(*i); i = running_.erase(i); continue; } } ++i; } return false; } #else // linux bool SubprocessSet::DoWork() { fd_set set; int nfds = 0; FD_ZERO(&set); for (vector<Subprocess*>::iterator i = running_.begin(); i != running_.end(); ++i) { int fd = (*i)->fd_; if (fd >= 0) { FD_SET(fd, &set); if (nfds < fd+1) nfds = fd+1; } } int ret = pselect(nfds, &set, 0, 0, 0, &old_mask_); if (ret == -1) { if (errno != EINTR) { perror("ninja: pselect"); return false; } bool interrupted = interrupted_; interrupted_ = false; return interrupted; } for (vector<Subprocess*>::iterator i = running_.begin(); i != running_.end(); ) { int fd = (*i)->fd_; if (fd >= 0 && FD_ISSET(fd, &set)) { (*i)->OnPipeReady(); if ((*i)->Done()) { finished_.push(*i); i = running_.erase(i); continue; } } ++i; } return false; } #endif // linux Subprocess* SubprocessSet::NextFinished() { if (finished_.empty()) return NULL; Subprocess* subproc = finished_.front(); finished_.pop(); return subproc; } void SubprocessSet::Clear() { for (vector<Subprocess*>::iterator i = running_.begin(); i != running_.end(); ++i) kill(-(*i)->pid_, SIGINT); for (vector<Subprocess*>::iterator i = running_.begin(); i != running_.end(); ++i) delete *i; running_.clear(); }
Fix missing POLLRDHUP constant on older systems.
Fix missing POLLRDHUP constant on older systems. Attempting to compile with g++ 4.1.2 failed because the POLLRDHUP constant was not defined when <poll.h> is included.
C++
apache-2.0
jimon/ninja,ctiller/ninja,hnney/ninja,TheOneRing/ninja,metti/ninja,autopulated/ninja,ThiagoGarciaAlves/ninja,TheOneRing/ninja,ikarienator/ninja,colincross/ninja,moroten/ninja,juntalis/ninja,Maratyszcza/ninja-pypi,jimon/ninja,dendy/ninja,nocnokneo/ninja,hnney/ninja,martine/ninja,barak/ninja,syntheticpp/ninja,sxlin/dist_ninja,sorbits/ninja,ilor/ninja,Maratyszcza/ninja-pypi,iwadon/ninja,okuoku/ninja,mydongistiny/ninja,rnk/ninja,dpwright/ninja,vvvrrooomm/ninja,curinir/ninja,chenyukang/ninja,kissthink/ninja,maruel/ninja,ndsol/subninja,rjogrady/ninja,dorgonman/ninja,yannicklm/ninja,rnk/ninja,chenyukang/ninja,lizh06/ninja,dpwright/ninja,synaptek/ninja,purcell/ninja,barak/ninja,liukd/ninja,mgaunard/ninja,Maratyszcza/ninja-pypi,yannicklm/ninja,moroten/ninja,dpwright/ninja,tfarina/ninja,pathscale/ninja,dorgonman/ninja,barak/ninja,jsternberg/ninja,dpwright/ninja,ninja-build/ninja,rjogrady/ninja,ikarienator/ninja,sxlin/dist_ninja,maruel/ninja,sxlin/dist_ninja,bradking/ninja,ctiller/ninja,bradking/ninja,hnney/ninja,drbo/ninja,mohamed/ninja,vvvrrooomm/ninja,guiquanz/ninja,rnk/ninja,glensc/ninja,mdempsky/ninja,ctiller/ninja,metti/ninja,colincross/ninja,kissthink/ninja,jhanssen/ninja,iwadon/ninja,glensc/ninja,tfarina/ninja,sorbits/ninja,martine/ninja,tfarina/ninja,dabrahams/ninja,bmeurer/ninja,tfarina/ninja,liukd/ninja,liukd/ninja,ikarienator/ninja,bmeurer/ninja,automeka/ninja,dendy/ninja,moroten/ninja,bmeurer/ninja,ndsol/subninja,Qix-/ninja,LuaDist/ninja,ikarienator/ninja,automeka/ninja,nafest/ninja,synaptek/ninja,ilor/ninja,pathscale/ninja,automeka/ninja,jsternberg/ninja,nocnokneo/ninja,kissthink/ninja,ilor/ninja,nico/ninja,guiquanz/ninja,moroten/ninja,vvvrrooomm/ninja,ctiller/ninja,autopulated/ninja,fuchsia-mirror/third_party-ninja,mutac/ninja,nafest/ninja,LuaDist/ninja,fuchsia-mirror/third_party-ninja,LuaDist/ninja,AoD314/ninja,synaptek/ninja,colincross/ninja,drbo/ninja,nickhutchinson/ninja,atetubou/ninja,okuoku/ninja,mdempsky/ninja,fifoforlifo/ninja,Qix-/ninja,sxlin/dist_ninja,ilor/ninja,ThiagoGarciaAlves/ninja,ignatenkobrain/ninja,curinir/ninja,Ju2ender/ninja,autopulated/ninja,iwadon/ninja,syntheticpp/ninja,rjogrady/ninja,kimgr/ninja,dorgonman/ninja,dabrahams/ninja,ThiagoGarciaAlves/ninja,hnney/ninja,synaptek/ninja,fifoforlifo/ninja,atetubou/ninja,juntalis/ninja,TheOneRing/ninja,nickhutchinson/ninja,Ju2ender/ninja,curinir/ninja,okuoku/ninja,nocnokneo/ninja,Ju2ender/ninja,yannicklm/ninja,purcell/ninja,curinir/ninja,mgaunard/ninja,syntheticpp/ninja,fuchsia-mirror/third_party-ninja,Qix-/ninja,jendrikillner/ninja,ignatenkobrain/ninja,AoD314/ninja,purcell/ninja,mutac/ninja,nickhutchinson/ninja,bmeurer/ninja,metti/ninja,nico/ninja,pck/ninja,mdempsky/ninja,nicolasdespres/ninja,LuaDist/ninja,mydongistiny/ninja,nicolasdespres/ninja,kimgr/ninja,kimgr/ninja,mohamed/ninja,sgraham/ninja,jhanssen/ninja,mgaunard/ninja,mgaunard/ninja,fuchsia-mirror/third_party-ninja,ThiagoGarciaAlves/ninja,drbo/ninja,mohamed/ninja,Maratyszcza/ninja-pypi,syntheticpp/ninja,chenyukang/ninja,jimon/ninja,martine/ninja,glensc/ninja,dorgonman/ninja,atetubou/ninja,juntalis/ninja,ndsol/subninja,dendy/ninja,jendrikillner/ninja,bradking/ninja,kissthink/ninja,dabrahams/ninja,iwadon/ninja,pck/ninja,sorbits/ninja,liukd/ninja,jsternberg/ninja,rjogrady/ninja,mohamed/ninja,fifoforlifo/ninja,nico/ninja,lizh06/ninja,atetubou/ninja,pathscale/ninja,martine/ninja,TheOneRing/ninja,jhanssen/ninja,sxlin/dist_ninja,jimon/ninja,lizh06/ninja,drbo/ninja,mydongistiny/ninja,glensc/ninja,mydongistiny/ninja,sgraham/ninja,vvvrrooomm/ninja,yannicklm/ninja,jendrikillner/ninja,guiquanz/ninja,ndsol/subninja,pathscale/ninja,sxlin/dist_ninja,automeka/ninja,autopulated/ninja,sorbits/ninja,metti/ninja,fifoforlifo/ninja,rnk/ninja,purcell/ninja,jhanssen/ninja,colincross/ninja,dabrahams/ninja,Ju2ender/ninja,nico/ninja,bradking/ninja,ignatenkobrain/ninja,maruel/ninja,chenyukang/ninja,ninja-build/ninja,sgraham/ninja,jendrikillner/ninja,mdempsky/ninja,barak/ninja,ninja-build/ninja,AoD314/ninja,juntalis/ninja,nafest/ninja,okuoku/ninja,nafest/ninja,nickhutchinson/ninja,jsternberg/ninja,maruel/ninja,lizh06/ninja,pck/ninja,kimgr/ninja,ignatenkobrain/ninja,ninja-build/ninja,Qix-/ninja,AoD314/ninja,sgraham/ninja,nicolasdespres/ninja,dendy/ninja,pck/ninja,mutac/ninja,sxlin/dist_ninja,nocnokneo/ninja,nicolasdespres/ninja,mutac/ninja,guiquanz/ninja
7b325c36081ab56ce90d95c48323441c0d73348c
src/ui/Window.cpp
src/ui/Window.cpp
#include "Window.h" #include <QtGui> #include "ui_MainWindow.h" #if defined Q_OS_MAC #include "../OSXLocal.h" #endif #include "../Settings.h" #include "../Hearthstone.h" Window::Window() : mUI( new Ui::MainWindow ) { mUI->setupUi( this ); setWindowFlags( (Qt::Tool | Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint | Qt::MSWindowsFixedSizeDialogHint) ); setWindowTitle( qApp->applicationName() ); CreateActions(); CreateTrayIcon(); connect( mTrayIcon, &QSystemTrayIcon::activated, this, &Window::TrayIconActivated ); QActionGroup *group = new QActionGroup( this ); group->setExclusive( true ); mUI->actionSettings->setActionGroup( group ); mUI->actionSettings->setProperty( "pageIndex", 0 ); mUI->actionAccount->setActionGroup( group ); mUI->actionAccount->setProperty( "pageIndex", 1 ); mUI->actionLog->setActionGroup( group ); mUI->actionLog->setProperty( "pageIndex", 2 ); mUI->actionAbout->setActionGroup( group ); mUI->actionAbout->setProperty( "pageIndex", 3 ); mSettingsTab = new SettingsTab( this ); mAccountTab = new AccountTab( this ); mLogTab = new LogTab( this ); mAboutTab = new AboutTab( this ); mTabs[ 0 ] = mSettingsTab; mTabs[ 1 ] = mAccountTab; mTabs[ 2 ] = mLogTab; mTabs[ 3 ] = mAboutTab; QLayout *layout = mUI->mainWidget->layout(); for( int i = 0; i < NUM_TABS; i++ ) { layout->addWidget( mTabs[ i ] ); } TabChanged( 0 ); mUI->actionSettings->setChecked( true ); connect( group, &QActionGroup::triggered, this, &Window::ActionTriggered ); connect( Hearthstone::Instance(), &Hearthstone::GameRequiresRestart, this, &Window::HandleGameClientRestartRequired ); connect( Hearthstone::Instance(), &Hearthstone::GameStopped, this, &Window::HandleGameClientStop ); QTimer::singleShot( 1000, this, &Window::HandleFirstStartCheck ); mUI->toolBar->setContextMenuPolicy( Qt::PreventContextMenu ); #ifdef Q_OS_WIN // This is a fix for // https://bugreports.qt.io/browse/QTBUG-35986 // If the window was never opened, the WM_ENDSESSION event will // not be received by the app (tray icon will disappear // but the app will not close) // So show, then hide it at the beginning // With Qt:Tool the Window is not actually shown show(); hide(); #endif } Window::~Window() { delete mUI; } void Window::ActionTriggered( QAction *action ) { int page = action->property( "pageIndex" ).toInt(); TabChanged( page ); } void Window::TabChanged( int index ) { for( int i = 0; i < NUM_TABS; i++ ) { mTabs[ i ]->hide(); } mTabs[ index ]->show(); resize(0, 0); adjustSize(); } void Window::ShowNotification( const char *title, const char *message ) { #if defined Q_OS_WIN || defined Q_OS_LINUX mTrayIcon->showMessage( title, message ); #elif defined Q_OS_MAC OSX_ShowNotification( title, message ); #endif } void Window::HandleFirstStartCheck() { // Notify user the first time that the app runs in the taskbar QSettings settings; if( !settings.contains("taskbarHint") ) { settings.setValue( "taskbarHint", true ); #if defined Q_OS_WIN || defined Q_OS_LINUX ShowNotification( "Heads up!", "Track-o-Bot runs in your taskbar! Right click the icon for more options." ); #elif defined Q_OS_MAC ShowNotification( "Track-o-Bot", "Track-o-Bot runs in your menu bar! Click the icon for more options." ); #endif } } void Window::TrayIconActivated( QSystemTrayIcon::ActivationReason reason ) { #ifdef Q_OS_WIN if( reason == QSystemTrayIcon::ActivationReason::DoubleClick ) { OpenProfileRequested(); } #elif defined Q_OS_LINUX if( reason == QSystemTrayIcon::DoubleClick ) { OpenProfileRequested(); } else if( reason == QSystemTrayIcon::Trigger ) { RiseAndShine(); } #else UNUSED_ARG( reason ); #endif } void Window::closeEvent( QCloseEvent *event ) { if( mTrayIcon->isVisible() ) { hide(); event->ignore(); } } void Window::CreateActions() { mOpenProfileAction = new QAction( tr( "Open Profile..." ), this ); connect( mOpenProfileAction, &QAction::triggered, this, &Window::OpenProfileRequested ); mShowAction = new QAction( tr( "Settings..." ), this ); connect( mShowAction, &QAction::triggered, this, &Window::RiseAndShine ); mQuitAction = new QAction( tr("Quit"), this ); connect( mQuitAction, &QAction::triggered, qApp, &QCoreApplication::quit ); mGameClientRestartRequiredAction = new QAction( tr("Please restart Hearthstone!" ), this ); mGameClientRestartRequiredAction->setEnabled( false ); #ifdef Q_OS_LINUX mOpenProfileAction->setIcon( QIcon::fromTheme( "applications-internet", QIcon( ":/icons/applications-internet.png" ) ) ); mShowAction->setIcon( QIcon::fromTheme( "preferences-system", QIcon( ":/icons/preferences-system.png" ) ) ); mQuitAction->setIcon( QIcon::fromTheme( "application-exit" , QIcon( ":/icons/system-log-out.png" ) ) ); #endif } void Window::CreateTrayIcon() { /*bool is_linux = true; #if defined Q_OS_WIN || defined Q_OS_MAC is_linux = false; #endif*/ mTrayIconMenu = new QMenu( this); mTrayIconMenu->addAction( mOpenProfileAction ); mTrayIconMenu->addSeparator(); mTrayIconMenu->addAction( mShowAction ); /*bool is_kde_plasma = false; if(is_linux){ QString dm = getenv("DESKTOP_SESSION"); // getenv returns something like /usr/share/xsessions/plasma // so either we match that or we regexp for plasma QRegularExpression plasma_re("plasma$"); QRegularExpressionMatch plasma_match = plasma_re.match(dm); is_kde_plasma = plasma_match.hasMatch(); } if(!is_linux || !is_kde_plasma){*/ mTrayIconMenu->addSeparator(); mTrayIconMenu->addAction( mQuitAction ); //} mTrayIcon = new QSystemTrayIcon( this ); mTrayIcon->setContextMenu (mTrayIconMenu ); #if defined Q_OS_MAC /* QIcon::Mode blackMode = QIcon::Normal; */ /* QIcon::Mode whiteMode = QIcon::Selected; */ /* if( OSX_YosemiteDarkModeEnabled() ) { */ /* blackMode = QIcon::Disabled; */ /* whiteMode = QIcon::Normal; */ /* } */ QIcon icon; icon.addFile( ":/icons/mac_black.png", QSize(), QIcon::Normal ); icon.addFile( ":/icons/[email protected]", QSize(), QIcon::Normal ); /* icon.addFile( ":/icons/mac_white.png", QSize(), whiteMode ); */ /* icon.addFile( ":/icons/[email protected]", QSize(), whiteMode ); */ icon.setIsMask( true ); #elif defined Q_OS_WIN QIcon icon = QIcon( ":/icons/win.ico" ); #elif defined Q_OS_LINUX QIcon icon = QIcon( ":/icons/Track-o-Bot.png" ); icon.addFile( ":/icons/logo.png", QSize() ); #endif mTrayIcon->setIcon( icon ); mTrayIcon->show(); } void Window::RiseAndShine() { show(); raise(); } void Window::OpenProfileRequested() { emit OpenProfile(); } void Window::HandleGameClientRestartRequired() { mTrayIconMenu->insertAction( mOpenProfileAction, mGameClientRestartRequiredAction ); ShowNotification( "Game log updated", "Please restart Hearthstone for changes to take effect!" ); } void Window::HandleGameClientStop() { mTrayIconMenu->removeAction( mGameClientRestartRequiredAction ); }
#include "Window.h" #include <QtGui> #include "ui_MainWindow.h" #if defined Q_OS_MAC #include "../OSXLocal.h" #endif #include "../Settings.h" #include "../Hearthstone.h" Window::Window() : mUI( new Ui::MainWindow ) { mUI->setupUi( this ); setWindowFlags( (Qt::Tool | Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint | Qt::MSWindowsFixedSizeDialogHint) ); setWindowTitle( qApp->applicationName() ); CreateActions(); CreateTrayIcon(); connect( mTrayIcon, &QSystemTrayIcon::activated, this, &Window::TrayIconActivated ); QActionGroup *group = new QActionGroup( this ); group->setExclusive( true ); mUI->actionSettings->setActionGroup( group ); mUI->actionSettings->setProperty( "pageIndex", 0 ); mUI->actionAccount->setActionGroup( group ); mUI->actionAccount->setProperty( "pageIndex", 1 ); mUI->actionLog->setActionGroup( group ); mUI->actionLog->setProperty( "pageIndex", 2 ); mUI->actionAbout->setActionGroup( group ); mUI->actionAbout->setProperty( "pageIndex", 3 ); mSettingsTab = new SettingsTab( this ); mAccountTab = new AccountTab( this ); mLogTab = new LogTab( this ); mAboutTab = new AboutTab( this ); mTabs[ 0 ] = mSettingsTab; mTabs[ 1 ] = mAccountTab; mTabs[ 2 ] = mLogTab; mTabs[ 3 ] = mAboutTab; QLayout *layout = mUI->mainWidget->layout(); for( int i = 0; i < NUM_TABS; i++ ) { layout->addWidget( mTabs[ i ] ); } TabChanged( 0 ); mUI->actionSettings->setChecked( true ); connect( group, &QActionGroup::triggered, this, &Window::ActionTriggered ); connect( Hearthstone::Instance(), &Hearthstone::GameRequiresRestart, this, &Window::HandleGameClientRestartRequired ); connect( Hearthstone::Instance(), &Hearthstone::GameStopped, this, &Window::HandleGameClientStop ); QTimer::singleShot( 1000, this, &Window::HandleFirstStartCheck ); mUI->toolBar->setContextMenuPolicy( Qt::PreventContextMenu ); #ifdef Q_OS_WIN // This is a fix for // https://bugreports.qt.io/browse/QTBUG-35986 // If the window was never opened, the WM_ENDSESSION event will // not be received by the app (tray icon will disappear // but the app will not close) // So show, then hide it at the beginning // With Qt:Tool the Window is not actually shown show(); hide(); #endif } Window::~Window() { delete mUI; } void Window::ActionTriggered( QAction *action ) { int page = action->property( "pageIndex" ).toInt(); TabChanged( page ); } void Window::TabChanged( int index ) { for( int i = 0; i < NUM_TABS; i++ ) { mTabs[ i ]->hide(); } mTabs[ index ]->show(); resize(0, 0); adjustSize(); } void Window::ShowNotification( const char *title, const char *message ) { #if defined Q_OS_WIN || defined Q_OS_LINUX mTrayIcon->showMessage( title, message ); #elif defined Q_OS_MAC OSX_ShowNotification( title, message ); #endif } void Window::HandleFirstStartCheck() { // Notify user the first time that the app runs in the taskbar QSettings settings; if( !settings.contains("taskbarHint") ) { settings.setValue( "taskbarHint", true ); #if defined Q_OS_WIN || defined Q_OS_LINUX ShowNotification( "Heads up!", "Track-o-Bot runs in your taskbar! Right click the icon for more options." ); #elif defined Q_OS_MAC ShowNotification( "Track-o-Bot", "Track-o-Bot runs in your menu bar! Click the icon for more options." ); #endif } } void Window::TrayIconActivated( QSystemTrayIcon::ActivationReason reason ) { #ifdef Q_OS_WIN if( reason == QSystemTrayIcon::ActivationReason::DoubleClick ) { OpenProfileRequested(); } #elif defined Q_OS_LINUX if( reason == QSystemTrayIcon::DoubleClick ) { OpenProfileRequested(); } else if( reason == QSystemTrayIcon::Trigger ) { RiseAndShine(); } #else UNUSED_ARG( reason ); #endif } void Window::closeEvent( QCloseEvent *event ) { if( mTrayIcon->isVisible() ) { hide(); event->ignore(); } } void Window::CreateActions() { mOpenProfileAction = new QAction( tr( "Open Profile..." ), this ); connect( mOpenProfileAction, &QAction::triggered, this, &Window::OpenProfileRequested ); mShowAction = new QAction( tr( "Settings..." ), this ); connect( mShowAction, &QAction::triggered, this, &Window::RiseAndShine ); mQuitAction = new QAction( tr("Quit"), this ); connect( mQuitAction, &QAction::triggered, qApp, &QCoreApplication::quit ); mGameClientRestartRequiredAction = new QAction( tr("Please restart Hearthstone!" ), this ); mGameClientRestartRequiredAction->setEnabled( false ); #ifdef Q_OS_LINUX mOpenProfileAction->setIcon( QIcon::fromTheme( "applications-internet", QIcon( ":/icons/applications-internet.png" ) ) ); mShowAction->setIcon( QIcon::fromTheme( "preferences-system", QIcon( ":/icons/preferences-system.png" ) ) ); mQuitAction->setIcon( QIcon::fromTheme( "application-exit" , QIcon( ":/icons/system-log-out.png" ) ) ); #endif } void Window::CreateTrayIcon() { mTrayIconMenu = new QMenu( this); mTrayIconMenu->addAction( mOpenProfileAction ); mTrayIconMenu->addSeparator(); mTrayIconMenu->addAction( mShowAction ); mTrayIconMenu->addSeparator(); mTrayIconMenu->addAction( mQuitAction ); mTrayIcon = new QSystemTrayIcon( this ); mTrayIcon->setContextMenu (mTrayIconMenu ); #if defined Q_OS_MAC /* QIcon::Mode blackMode = QIcon::Normal; */ /* QIcon::Mode whiteMode = QIcon::Selected; */ /* if( OSX_YosemiteDarkModeEnabled() ) { */ /* blackMode = QIcon::Disabled; */ /* whiteMode = QIcon::Normal; */ /* } */ QIcon icon; icon.addFile( ":/icons/mac_black.png", QSize(), QIcon::Normal ); icon.addFile( ":/icons/[email protected]", QSize(), QIcon::Normal ); /* icon.addFile( ":/icons/mac_white.png", QSize(), whiteMode ); */ /* icon.addFile( ":/icons/[email protected]", QSize(), whiteMode ); */ icon.setIsMask( true ); #elif defined Q_OS_WIN QIcon icon = QIcon( ":/icons/win.ico" ); #elif defined Q_OS_LINUX QIcon icon = QIcon( ":/icons/Track-o-Bot.png" ); icon.addFile( ":/icons/logo.png", QSize() ); #endif mTrayIcon->setIcon( icon ); mTrayIcon->show(); } void Window::RiseAndShine() { show(); raise(); } void Window::OpenProfileRequested() { emit OpenProfile(); } void Window::HandleGameClientRestartRequired() { mTrayIconMenu->insertAction( mOpenProfileAction, mGameClientRestartRequiredAction ); ShowNotification( "Game log updated", "Please restart Hearthstone for changes to take effect!" ); } void Window::HandleGameClientStop() { mTrayIconMenu->removeAction( mGameClientRestartRequiredAction ); }
Remove redundand code.
Remove redundand code.
C++
lgpl-2.1
BOSSoNe0013/track-o-bot,BOSSoNe0013/track-o-bot
79116975c4fd7c766308bc86f2c969d2c6a620f1
src/util_linux.cc
src/util_linux.cc
#include "util.h" namespace doogie { bool Util::OpenContainingFolder(const QString& path) { QFileInfo info(path); return QDesktopServices::openUrl( QUrl::fromLocalFile(info.isDir() ? path : info.path())); } QString Util::ExePath() { QFileInfo pfi(QString::fromLatin1("/proc/%1/exe").arg(getpid())); if (!pfi.exists() || !pfi.isSymLink()) return QString(); return pfi.canonicalFilePath(); } } // namespace doogie
#include "util.h" #include <unistd.h> namespace doogie { bool Util::OpenContainingFolder(const QString& path) { QFileInfo info(path); return QDesktopServices::openUrl( QUrl::fromLocalFile(info.isDir() ? path : info.path())); } QString Util::ExePath() { QFileInfo pfi(QString::fromLatin1("/proc/%1/exe").arg(::getpid())); if (!pfi.exists() || !pfi.isSymLink()) return QString(); return pfi.canonicalFilePath(); } } // namespace doogie
Fix import for getpid
Fix import for getpid
C++
mit
cretz/doogie,cretz/doogie,cretz/doogie,cretz/doogie
0f1a9bc77eb62f4f1b21f9c6527a165b331e5f03
src/finder.cpp
src/finder.cpp
#include "zlib-custom.h" #include "system.h" #include "finder.h" using namespace vm; namespace { const char* append(System* s, const char* a, const char* b, const char* c) { unsigned al = strlen(a); unsigned bl = strlen(b); unsigned cl = strlen(c); char* p = static_cast<char*>(s->allocate(al + bl + cl + 1)); memcpy(p, a, al); memcpy(p + al, b, bl); memcpy(p + al + bl, c, cl + 1); return p; } const char* copy(System* s, const char* a) { unsigned al = strlen(a); char* p = static_cast<char*>(s->allocate(al + 1)); memcpy(p, a, al + 1); return p; } bool equal(const void* a, unsigned al, const void* b, unsigned bl) { if (al == bl) { return memcmp(a, b, al) == 0; } else { return false; } } class Element { public: Element(): next(0) { } virtual ~Element() { } virtual System::Region* find(const char* name) = 0; virtual bool exists(const char* name) = 0; virtual void dispose() = 0; Element* next; }; class DirectoryElement: public Element { public: DirectoryElement(System* s, const char* name): s(s), name(name) { } virtual System::Region* find(const char* name) { const char* file = append(s, this->name, "/", name); System::Region* region; System::Status status = s->map(&region, file); if (status) { fprintf(stderr, "%s not found\n", file); } s->free(file); if (s->success(status)) { return region; } else { return 0; } } virtual bool exists(const char* name) { const char* file = append(s, this->name, "/", name); System::FileType type = s->identify(file); s->free(file); return type != System::DoesNotExist; } virtual void dispose() { s->free(name); s->free(this); } System* s; const char* name; }; class PointerRegion: public System::Region { public: PointerRegion(System* s, const uint8_t* start, size_t length): s(s), start_(start), length_(length) { } virtual const uint8_t* start() { return start_; } virtual size_t length() { return length_; } virtual void dispose() { s->free(this); } System* s; const uint8_t* start_; size_t length_; }; class DataRegion: public System::Region { public: DataRegion(System* s, size_t length): s(s), length_(length) { } virtual const uint8_t* start() { return data; } virtual size_t length() { return length_; } virtual void dispose() { s->free(this); } System* s; size_t length_; uint8_t data[0]; }; class JarIndex { public: static const unsigned HeaderSize = 30; enum CompressionMethod { Stored = 0, Deflated = 8 }; class Node { public: Node(uint32_t hash, const uint8_t* entry, Node* next): hash(hash), entry(entry), next(next) { } uint32_t hash; const uint8_t* entry; Node* next; }; JarIndex(System* s, unsigned capacity): s(s), capacity(capacity), position(0), nodes(static_cast<Node*>(s->allocate(sizeof(Node) * capacity))) { memset(table, 0, sizeof(Node*) * capacity); } static uint16_t get2(const uint8_t* p) { return (static_cast<uint16_t>(p[1]) << 8) | (static_cast<uint16_t>(p[0]) ); } static uint32_t get4(const uint8_t* p) { return (static_cast<uint32_t>(p[3]) << 24) | (static_cast<uint32_t>(p[2]) << 16) | (static_cast<uint32_t>(p[1]) << 8) | (static_cast<uint32_t>(p[0]) ); } static uint32_t signature(const uint8_t* p) { return get4(p); } static uint16_t compressionMethod(const uint8_t* p) { return get2(p + 8); } static uint32_t compressedSize(const uint8_t* p) { return get4(p + 18); } static uint32_t uncompressedSize(const uint8_t* p) { return get4(p + 22); } static uint16_t fileNameLength(const uint8_t* p) { return get2(p + 26); } static uint16_t extraFieldLength(const uint8_t* p) { return get2(p + 28); } static const uint8_t* fileName(const uint8_t* p) { return p + 30; } static const uint8_t* fileData(const uint8_t* p) { return p + HeaderSize + fileNameLength(p) + extraFieldLength(p); } static const uint8_t* endOfEntry(const uint8_t* p) { return fileData(p) + compressedSize(p); } static JarIndex* make(System* s, unsigned capacity) { return new (s->allocate(sizeof(JarIndex) + (sizeof(Node*) * capacity))) JarIndex(s, capacity); } static JarIndex* open(System* s, System::Region* region) { JarIndex* index = make(s, 32); const uint8_t* p = region->start(); const uint8_t* end = p + region->length(); while (p < end) { if (signature(p) == 0x04034b50) { index = index->add(hash(fileName(p), fileNameLength(p)), p); p = endOfEntry(p); } else { break; } } return index; } JarIndex* add(uint32_t hash, const uint8_t* entry) { if (position < capacity) { unsigned i = hash & (capacity - 1); table[i] = new (nodes + (position++)) Node(hash, entry, table[i]); return this; } else { JarIndex* index = make(s, capacity * 2); for (unsigned i = 0; i < capacity; ++i) { index->add(nodes[i].hash, nodes[i].entry); } index->add(hash, entry); dispose(); return index; } } Node* findNode(const char* name) { unsigned length = strlen(name); unsigned i = hash(name) & (capacity - 1); for (Node* n = table[i]; n; n = n->next) { const uint8_t* p = n->entry; if (equal(name, length, fileName(p), fileNameLength(p))) { return n; } } return 0; } System::Region* find(const char* name) { Node* n = findNode(name); if (n) { const uint8_t* p = n->entry; switch (compressionMethod(p)) { case Stored: { return new (s->allocate(sizeof(PointerRegion))) PointerRegion(s, fileData(p), compressedSize(p)); } break; case Deflated: { DataRegion* region = new (s->allocate(sizeof(DataRegion) + uncompressedSize(p))) DataRegion(s, uncompressedSize(p)); z_stream zStream; memset(&zStream, 0, sizeof(z_stream)); zStream.next_in = const_cast<uint8_t*>(fileData(p)); zStream.avail_in = compressedSize(p); zStream.next_out = region->data; zStream.avail_out = region->length(); // -15 means max window size and raw deflate (no zlib wrapper) int r = inflateInit2(&zStream, -15); expect(s, r == Z_OK); r = inflate(&zStream, Z_FINISH); expect(s, r == Z_STREAM_END); inflateEnd(&zStream); return region; } break; default: abort(s); } } return 0; } bool exists(const char* name) { return findNode(name) != 0; } void dispose() { s->free(nodes); s->free(this); } System* s; unsigned capacity; unsigned position; Node* nodes; Node* table[0]; }; class JarElement: public Element { public: JarElement(System* s, const char* name): s(s), name(name), region(0), index(0) { } void init() { if (index == 0) { System::Region* r; if (s->success(s->map(&r, this->name))) { region = r; index = JarIndex::open(s, r); } } } virtual System::Region* find(const char* name) { init(); while (*name == '/') name++; return (index ? index->find(name) : 0); } virtual bool exists(const char* name) { init(); while (*name == '/') name++; return (index ? index->exists(name) : 0); } virtual void dispose() { s->free(name); if (index) { index->dispose(); region->dispose(); } s->free(this); } System* s; const char* name; System::Region* region; JarIndex* index; }; Element* parsePath(System* s, const char* path) { class Tokenizer { public: class Token { public: Token(const char* s, unsigned length): s(s), length(length) { } const char* s; unsigned length; }; Tokenizer(const char* s, char delimiter): s(s), delimiter(delimiter) { } bool hasMore() { while (*s == delimiter) ++s; return *s; } Token next() { const char* p = s; while (*s and *s != delimiter) ++s; return Token(p, s - p); } const char* s; char delimiter; }; Element* first = 0; Element* prev = 0; for (Tokenizer t(path, s->pathSeparator()); t.hasMore();) { Tokenizer::Token token(t.next()); char* name = static_cast<char*>(s->allocate(token.length + 1)); memcpy(name, token.s, token.length); name[token.length] = 0; fprintf(stderr, "path element: %s\n", name); Element* e; switch (s->identify(name)) { case System::File: { e = new (s->allocate(sizeof(JarElement))) JarElement(s, name); } break; case System::Directory: { e = new (s->allocate(sizeof(DirectoryElement))) DirectoryElement(s, name); } break; default: { s->free(name); e = 0; } break; } if (e) { if (prev) { prev->next = e; } else { first = e; } prev = e; } } return first; } class MyFinder: public Finder { public: MyFinder(System* system, const char* path): system(system), path_(parsePath(system, path)), pathString(copy(system, path)) { } virtual System::Region* find(const char* name) { for (Element* e = path_; e; e = e->next) { System::Region* r = e->find(name); if (r) { return r; } } return 0; } virtual bool exists(const char* name) { for (Element* e = path_; e; e = e->next) { if (e->exists(name)) { return true; } } return false; } virtual const char* path() { return pathString; } virtual void dispose() { for (Element* e = path_; e;) { Element* t = e; e = e->next; t->dispose(); } system->free(pathString); system->free(this); } System* system; Element* path_; const char* pathString; }; } // namespace namespace vm { Finder* makeFinder(System* s, const char* path) { return new (s->allocate(sizeof(MyFinder))) MyFinder(s, path); } } // namespace vm
#include "zlib-custom.h" #include "system.h" #include "finder.h" using namespace vm; namespace { const char* append(System* s, const char* a, const char* b, const char* c) { unsigned al = strlen(a); unsigned bl = strlen(b); unsigned cl = strlen(c); char* p = static_cast<char*>(s->allocate(al + bl + cl + 1)); memcpy(p, a, al); memcpy(p + al, b, bl); memcpy(p + al + bl, c, cl + 1); return p; } const char* copy(System* s, const char* a) { unsigned al = strlen(a); char* p = static_cast<char*>(s->allocate(al + 1)); memcpy(p, a, al + 1); return p; } bool equal(const void* a, unsigned al, const void* b, unsigned bl) { if (al == bl) { return memcmp(a, b, al) == 0; } else { return false; } } class Element { public: Element(): next(0) { } virtual ~Element() { } virtual System::Region* find(const char* name) = 0; virtual bool exists(const char* name) = 0; virtual void dispose() = 0; Element* next; }; class DirectoryElement: public Element { public: DirectoryElement(System* s, const char* name): s(s), name(name) { } virtual System::Region* find(const char* name) { const char* file = append(s, this->name, "/", name); System::Region* region; System::Status status = s->map(&region, file); s->free(file); if (s->success(status)) { return region; } else { return 0; } } virtual bool exists(const char* name) { const char* file = append(s, this->name, "/", name); System::FileType type = s->identify(file); s->free(file); return type != System::DoesNotExist; } virtual void dispose() { s->free(name); s->free(this); } System* s; const char* name; }; class PointerRegion: public System::Region { public: PointerRegion(System* s, const uint8_t* start, size_t length): s(s), start_(start), length_(length) { } virtual const uint8_t* start() { return start_; } virtual size_t length() { return length_; } virtual void dispose() { s->free(this); } System* s; const uint8_t* start_; size_t length_; }; class DataRegion: public System::Region { public: DataRegion(System* s, size_t length): s(s), length_(length) { } virtual const uint8_t* start() { return data; } virtual size_t length() { return length_; } virtual void dispose() { s->free(this); } System* s; size_t length_; uint8_t data[0]; }; class JarIndex { public: static const unsigned HeaderSize = 30; enum CompressionMethod { Stored = 0, Deflated = 8 }; class Node { public: Node(uint32_t hash, const uint8_t* entry, Node* next): hash(hash), entry(entry), next(next) { } uint32_t hash; const uint8_t* entry; Node* next; }; JarIndex(System* s, unsigned capacity): s(s), capacity(capacity), position(0), nodes(static_cast<Node*>(s->allocate(sizeof(Node) * capacity))) { memset(table, 0, sizeof(Node*) * capacity); } static uint16_t get2(const uint8_t* p) { return (static_cast<uint16_t>(p[1]) << 8) | (static_cast<uint16_t>(p[0]) ); } static uint32_t get4(const uint8_t* p) { return (static_cast<uint32_t>(p[3]) << 24) | (static_cast<uint32_t>(p[2]) << 16) | (static_cast<uint32_t>(p[1]) << 8) | (static_cast<uint32_t>(p[0]) ); } static uint32_t signature(const uint8_t* p) { return get4(p); } static uint16_t compressionMethod(const uint8_t* p) { return get2(p + 8); } static uint32_t compressedSize(const uint8_t* p) { return get4(p + 18); } static uint32_t uncompressedSize(const uint8_t* p) { return get4(p + 22); } static uint16_t fileNameLength(const uint8_t* p) { return get2(p + 26); } static uint16_t extraFieldLength(const uint8_t* p) { return get2(p + 28); } static const uint8_t* fileName(const uint8_t* p) { return p + 30; } static const uint8_t* fileData(const uint8_t* p) { return p + HeaderSize + fileNameLength(p) + extraFieldLength(p); } static const uint8_t* endOfEntry(const uint8_t* p) { return fileData(p) + compressedSize(p); } static JarIndex* make(System* s, unsigned capacity) { return new (s->allocate(sizeof(JarIndex) + (sizeof(Node*) * capacity))) JarIndex(s, capacity); } static JarIndex* open(System* s, System::Region* region) { JarIndex* index = make(s, 32); const uint8_t* p = region->start(); const uint8_t* end = p + region->length(); while (p < end) { if (signature(p) == 0x04034b50) { index = index->add(hash(fileName(p), fileNameLength(p)), p); p = endOfEntry(p); } else { break; } } return index; } JarIndex* add(uint32_t hash, const uint8_t* entry) { if (position < capacity) { unsigned i = hash & (capacity - 1); table[i] = new (nodes + (position++)) Node(hash, entry, table[i]); return this; } else { JarIndex* index = make(s, capacity * 2); for (unsigned i = 0; i < capacity; ++i) { index->add(nodes[i].hash, nodes[i].entry); } index->add(hash, entry); dispose(); return index; } } Node* findNode(const char* name) { unsigned length = strlen(name); unsigned i = hash(name) & (capacity - 1); for (Node* n = table[i]; n; n = n->next) { const uint8_t* p = n->entry; if (equal(name, length, fileName(p), fileNameLength(p))) { return n; } } return 0; } System::Region* find(const char* name) { Node* n = findNode(name); if (n) { const uint8_t* p = n->entry; switch (compressionMethod(p)) { case Stored: { return new (s->allocate(sizeof(PointerRegion))) PointerRegion(s, fileData(p), compressedSize(p)); } break; case Deflated: { DataRegion* region = new (s->allocate(sizeof(DataRegion) + uncompressedSize(p))) DataRegion(s, uncompressedSize(p)); z_stream zStream; memset(&zStream, 0, sizeof(z_stream)); zStream.next_in = const_cast<uint8_t*>(fileData(p)); zStream.avail_in = compressedSize(p); zStream.next_out = region->data; zStream.avail_out = region->length(); // -15 means max window size and raw deflate (no zlib wrapper) int r = inflateInit2(&zStream, -15); expect(s, r == Z_OK); r = inflate(&zStream, Z_FINISH); expect(s, r == Z_STREAM_END); inflateEnd(&zStream); return region; } break; default: abort(s); } } return 0; } bool exists(const char* name) { return findNode(name) != 0; } void dispose() { s->free(nodes); s->free(this); } System* s; unsigned capacity; unsigned position; Node* nodes; Node* table[0]; }; class JarElement: public Element { public: JarElement(System* s, const char* name): s(s), name(name), region(0), index(0) { } void init() { if (index == 0) { System::Region* r; if (s->success(s->map(&r, this->name))) { region = r; index = JarIndex::open(s, r); } } } virtual System::Region* find(const char* name) { init(); while (*name == '/') name++; return (index ? index->find(name) : 0); } virtual bool exists(const char* name) { init(); while (*name == '/') name++; return (index ? index->exists(name) : 0); } virtual void dispose() { s->free(name); if (index) { index->dispose(); region->dispose(); } s->free(this); } System* s; const char* name; System::Region* region; JarIndex* index; }; Element* parsePath(System* s, const char* path) { class Tokenizer { public: class Token { public: Token(const char* s, unsigned length): s(s), length(length) { } const char* s; unsigned length; }; Tokenizer(const char* s, char delimiter): s(s), delimiter(delimiter) { } bool hasMore() { while (*s == delimiter) ++s; return *s; } Token next() { const char* p = s; while (*s and *s != delimiter) ++s; return Token(p, s - p); } const char* s; char delimiter; }; Element* first = 0; Element* prev = 0; for (Tokenizer t(path, s->pathSeparator()); t.hasMore();) { Tokenizer::Token token(t.next()); char* name = static_cast<char*>(s->allocate(token.length + 1)); memcpy(name, token.s, token.length); name[token.length] = 0; Element* e; switch (s->identify(name)) { case System::File: { e = new (s->allocate(sizeof(JarElement))) JarElement(s, name); } break; case System::Directory: { e = new (s->allocate(sizeof(DirectoryElement))) DirectoryElement(s, name); } break; default: { s->free(name); e = 0; } break; } if (e) { if (prev) { prev->next = e; } else { first = e; } prev = e; } } return first; } class MyFinder: public Finder { public: MyFinder(System* system, const char* path): system(system), path_(parsePath(system, path)), pathString(copy(system, path)) { } virtual System::Region* find(const char* name) { for (Element* e = path_; e; e = e->next) { System::Region* r = e->find(name); if (r) { return r; } } return 0; } virtual bool exists(const char* name) { for (Element* e = path_; e; e = e->next) { if (e->exists(name)) { return true; } } return false; } virtual const char* path() { return pathString; } virtual void dispose() { for (Element* e = path_; e;) { Element* t = e; e = e->next; t->dispose(); } system->free(pathString); system->free(this); } System* system; Element* path_; const char* pathString; }; } // namespace namespace vm { Finder* makeFinder(System* s, const char* path) { return new (s->allocate(sizeof(MyFinder))) MyFinder(s, path); } } // namespace vm
remove debug logging
remove debug logging
C++
isc
getlantern/avian,lostdj/avian,joshuawarner32/avian,ucdseniordesign/avian,lostdj/avian,lwahlmeier/avian,bgould/avian,dicej/avian,badlogic/avian,MaartenR/avian,joshuawarner32/avian,ucdseniordesign/avian,marcinolawski/avian,lwahlmeier/avian,badlogic/avian,bgould/avian,MaartenR/avian,bigfatbrowncat/avian-pack.avian,marcinolawski/avian,dicej/avian,joshuawarner32/avian,MaartenR/avian,dicej/avian,minor-jason/avian,minor-jason/avian,joshuawarner32/avian,lostdj/avian,badlogic/avian,lostdj/avian,dicej/avian,marcinolawski/avian,bgould/avian,MaartenR/avian,bigfatbrowncat/avian-pack.avian,ucdseniordesign/avian,bigfatbrowncat/avian-pack.avian,lwahlmeier/avian,lwahlmeier/avian,marcinolawski/avian,ucdseniordesign/avian,badlogic/avian,bgould/avian,getlantern/avian,minor-jason/avian,getlantern/avian,bigfatbrowncat/avian-pack.avian,getlantern/avian,minor-jason/avian
a4f66441cf4e20f23568c1bc8f303f9882ee2dc3
src/zk_client.cpp
src/zk_client.cpp
// 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. // // See accompanying file LICENSE or visit the Scribe site at: // http://developers.facebook.com/scribe/ // // @author Travis Crawford <[email protected]> #include "common.h" #include "scribe_server.h" #include "zk_client.h" #include "zk_agg_selector.h" using namespace std; using boost::lexical_cast; using boost::shared_ptr; static const int ZOOKEEPER_CONNECT_TIMEOUT_SECONDS = 10; std::string ZKClient::zkAggSelectorKey; /* * Global Zookeeper watcher handles all callbacks. */ void ZKClient::watcher(zhandle_t *zzh, int type, int state, const char *path, void *watcherCtx) { ZKClient * zkClient = static_cast<ZKClient>(watcherCtx); zkClient->state = state; if (state == ZOO_CONNECTED_STATE) { sem_post(&zkClient.connectLatch); } // Zookeeper session established so attempt registration. if ((state == ZOO_CONNECTED_STATE) && (type == ZOO_SESSION_EVENT)) { zkClient->registerTask(); } // Registration znode was deleted so attempt registration. else if ((state == ZOO_CONNECTED_STATE) && (type == ZOO_DELETED_EVENT) && (lexical_cast<string>(path) == zkClient->zkFullRegistrationName)) { zkClient->registerTask(); } else if ((state == ZOO_EXPIRED_SESSION_STATE) && (type == ZOO_SESSION_EVENT)) { zkClient->disconnect(); zkClient->connect(); } // This should never happen. else { LOG_OPER("Received unhandled watch callback: %s %d %d", path, type, state); } } ZKClient::ZKClient() : connectionState(ZOO_EXPIRED_SESSION_STATE) { zh = NULL; if (debug_level) { zoo_set_debug_level(ZOO_LOG_LEVEL_DEBUG); } } ZKClient::~ZKClient() { if (zh != NULL) { zookeeper_close(zh); } } void ZKClient::setAggSelectorStrategy(const std::string & strategy) { zkAggSelectorKey = strategy; } bool ZKClient::connect(const std::string & server, const std::string & registrationPrefix, int handlerPort) { LOG_DEBUG("Connecting to zookeeper."); state = ZOO_CONNECTING_STATE; zkServer = server; zkRegistrationPrefix = registrationPrefix; scribeHandlerPort = handlerPort; // Asynchronously connect to zookeeper, then wait for the connection to be established. sem_init(&sem, 0, 0); zh = zookeeper_init(zkServer.c_str(), watcher, 10000, 0, this, 0); timespec ts; ts.tv_sec = ZOOKEEPER_CONNECT_TIMEOUT_SECONDS; ts.tv_nsec = 0; int result = sem_timedwait(&sem, &ts); return result == 0; } void ZKClient::disconnect() { LOG_DEBUG("Disconnecting from zookeeper."); zookeeper_close(zh); zh = NULL; state = ZOO_EXPIRED_SESSION_STATE; } bool ZKClient::registerTask() { if (zkRegistrationPrefix.empty()) { return false; } LOG_OPER("Registering task in Zookeeper."); char hostname[1024]; hostname[1023] = '\0'; gethostname(hostname, 1023); zkRegistrationName = lexical_cast<string>(hostname) + ":" + lexical_cast<string>(scribeHandlerPort); zkFullRegistrationName = zkRegistrationPrefix + "/" + zkRegistrationName; static string contents = ""; struct Stat stat; char tmp[0]; // Prefixs are created as regular znodes. if (ZOK != zoo_exists(zh, zkRegistrationPrefix.c_str(), 1, &stat)) { size_t index = zkRegistrationPrefix.find("/", 0); while (index < string::npos) { index = zkRegistrationPrefix.find("/", index+1); string prefix = zkRegistrationPrefix.substr(0, index); zoo_create(zh, prefix.c_str(), contents.c_str(), contents.length(), &ZOO_CREATOR_ALL_ACL, 0, tmp, sizeof(tmp)); } } // Register this scribe as an ephemeral node. int ret = zoo_create(zh, zkFullRegistrationName.c_str(), contents.c_str(), contents.length(), &ZOO_CREATOR_ALL_ACL, ZOO_EPHEMERAL, tmp, sizeof(tmp)); if (ZOK == ret) { return true; } else if (ZNODEEXISTS == ret) { if (ZOK == zoo_exists(zh, zkFullRegistrationName.c_str(), 1, &stat)) { LOG_DEBUG("Set watch on znode that already exists: %s", zkFullRegistrationName.c_str()); return true; } else { LOG_OPER("Failed setting watch on znode: %s", zkFullRegistrationName.c_str()); return false; } } LOG_OPER("Registration failed for unknown reason: %s", zkFullRegistrationName.c_str()); return false; } bool ZKClient::updateStatus(std::string& current_status) { struct Stat stat; char tmp[0]; int rc; if (zoo_exists(zh, zkFullRegistrationName.c_str(), 1, &stat) == ZOK) { rc = zoo_set(zh, zkFullRegistrationName.c_str(), current_status.c_str(), current_status.length() + 1, -1); } else { rc = zoo_create(zh, zkFullRegistrationName.c_str(), current_status.c_str(), current_status.length() + 1, &ZOO_CREATOR_ALL_ACL, ZOO_EPHEMERAL, tmp, sizeof(tmp)); } if (rc) { LOG_OPER("Error %d for writing %s to ZK file %s", rc, current_status.c_str(), zkFullRegistrationName.c_str()); } else { LOG_DEBUG("Write %s to ZK file %s", current_status.c_str(), zkFullRegistrationName.c_str()); } return rc == 0; } // Get the best host:port to send messages to at this time. bool ZKClient::getRemoteScribe(const std::string& parentZnode, string& remoteHost, unsigned long& remotePort) { bool ret = false; if (NULL == zh) { LOG_OPER("Not connected to a zookeeper server! Unable to discover remote scribes."); return false; } else if (!zoo_state(zh)) { LOG_OPER("No zookeeper connection state! Unable to discover remote scribes."); return false; } LOG_DEBUG("Getting the best remote scribe."); struct String_vector children; if (zoo_get_children(zh, parentZnode.c_str(), 0, &children) != ZOK || children.count == 0) { LOG_OPER("Unable to discover remote scribes."); return false; } AggSelector *aggSelector = AggSelectorFactory::createAggSelector(zkAggSelectorKey); ret = aggSelector->selectScribeAggregator(children, remoteHost, remotePort); return ret; }
// 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. // // See accompanying file LICENSE or visit the Scribe site at: // http://developers.facebook.com/scribe/ // // @author Travis Crawford <[email protected]> #include "common.h" #include "scribe_server.h" #include "zk_client.h" #include "zk_agg_selector.h" using namespace std; using boost::lexical_cast; using boost::shared_ptr; static const int ZOOKEEPER_CONNECT_TIMEOUT_SECONDS = 10; std::string ZKClient::zkAggSelectorKey; /* * Global Zookeeper watcher handles all callbacks. */ void ZKClient::watcher(zhandle_t *zzh, int type, int state, const char *path, void *watcherCtx) { ZKClient * zkClient = static_cast<ZKClient *>(watcherCtx); zkClient->connectionState = state; if (state == ZOO_CONNECTED_STATE) { sem_post(&zkClient->connectLatch); } // Zookeeper session established so attempt registration. if ((state == ZOO_CONNECTED_STATE) && (type == ZOO_SESSION_EVENT)) { zkClient->registerTask(); } // Registration znode was deleted so attempt registration. else if ((state == ZOO_CONNECTED_STATE) && (type == ZOO_DELETED_EVENT) && (lexical_cast<string>(path) == zkClient->zkFullRegistrationName)) { zkClient->registerTask(); } else if ((state == ZOO_EXPIRED_SESSION_STATE) && (type == ZOO_SESSION_EVENT)) { zkClient->disconnect(); zkClient->connect(zkClient->zkServer, zkClient->zkRegistrationPrefix, zkClient->scribeHandlerPort)); } // This should never happen. else { LOG_OPER("Received unhandled watch callback: %s %d %d", path, type, state); } } ZKClient::ZKClient() : connectionState(ZOO_EXPIRED_SESSION_STATE) { zh = NULL; if (debug_level) { zoo_set_debug_level(ZOO_LOG_LEVEL_DEBUG); } } ZKClient::~ZKClient() { if (zh != NULL) { zookeeper_close(zh); } } void ZKClient::setAggSelectorStrategy(const std::string & strategy) { zkAggSelectorKey = strategy; } bool ZKClient::connect(const std::string & server, const std::string & registrationPrefix, int handlerPort) { LOG_DEBUG("Connecting to zookeeper."); connectionState = ZOO_CONNECTING_STATE; zkServer = server; zkRegistrationPrefix = registrationPrefix; scribeHandlerPort = handlerPort; // Asynchronously connect to zookeeper, then wait for the connection to be established. sem_init(&connectionLatch, 0, 0); zh = zookeeper_init(zkServer.c_str(), watcher, 10000, 0, this, 0); timespec ts; ts.tv_sec = ZOOKEEPER_CONNECT_TIMEOUT_SECONDS; ts.tv_nsec = 0; int result = sem_timedwait(&connectionLatch, &ts); return result == 0; } void ZKClient::disconnect() { LOG_DEBUG("Disconnecting from zookeeper."); zookeeper_close(zh); zh = NULL; state = ZOO_EXPIRED_SESSION_STATE; } bool ZKClient::registerTask() { if (zkRegistrationPrefix.empty()) { return false; } LOG_OPER("Registering task in Zookeeper."); char hostname[1024]; hostname[1023] = '\0'; gethostname(hostname, 1023); zkRegistrationName = lexical_cast<string>(hostname) + ":" + lexical_cast<string>(scribeHandlerPort); zkFullRegistrationName = zkRegistrationPrefix + "/" + zkRegistrationName; static string contents = ""; struct Stat stat; char tmp[0]; // Prefixs are created as regular znodes. if (ZOK != zoo_exists(zh, zkRegistrationPrefix.c_str(), 1, &stat)) { size_t index = zkRegistrationPrefix.find("/", 0); while (index < string::npos) { index = zkRegistrationPrefix.find("/", index+1); string prefix = zkRegistrationPrefix.substr(0, index); zoo_create(zh, prefix.c_str(), contents.c_str(), contents.length(), &ZOO_CREATOR_ALL_ACL, 0, tmp, sizeof(tmp)); } } // Register this scribe as an ephemeral node. int ret = zoo_create(zh, zkFullRegistrationName.c_str(), contents.c_str(), contents.length(), &ZOO_CREATOR_ALL_ACL, ZOO_EPHEMERAL, tmp, sizeof(tmp)); if (ZOK == ret) { return true; } else if (ZNODEEXISTS == ret) { if (ZOK == zoo_exists(zh, zkFullRegistrationName.c_str(), 1, &stat)) { LOG_DEBUG("Set watch on znode that already exists: %s", zkFullRegistrationName.c_str()); return true; } else { LOG_OPER("Failed setting watch on znode: %s", zkFullRegistrationName.c_str()); return false; } } LOG_OPER("Registration failed for unknown reason: %s", zkFullRegistrationName.c_str()); return false; } bool ZKClient::updateStatus(std::string& current_status) { struct Stat stat; char tmp[0]; int rc; if (zoo_exists(zh, zkFullRegistrationName.c_str(), 1, &stat) == ZOK) { rc = zoo_set(zh, zkFullRegistrationName.c_str(), current_status.c_str(), current_status.length() + 1, -1); } else { rc = zoo_create(zh, zkFullRegistrationName.c_str(), current_status.c_str(), current_status.length() + 1, &ZOO_CREATOR_ALL_ACL, ZOO_EPHEMERAL, tmp, sizeof(tmp)); } if (rc) { LOG_OPER("Error %d for writing %s to ZK file %s", rc, current_status.c_str(), zkFullRegistrationName.c_str()); } else { LOG_DEBUG("Write %s to ZK file %s", current_status.c_str(), zkFullRegistrationName.c_str()); } return rc == 0; } // Get the best host:port to send messages to at this time. bool ZKClient::getRemoteScribe(const std::string& parentZnode, string& remoteHost, unsigned long& remotePort) { bool ret = false; if (NULL == zh) { LOG_OPER("Not connected to a zookeeper server! Unable to discover remote scribes."); return false; } else if (!zoo_state(zh)) { LOG_OPER("No zookeeper connection state! Unable to discover remote scribes."); return false; } LOG_DEBUG("Getting the best remote scribe."); struct String_vector children; if (zoo_get_children(zh, parentZnode.c_str(), 0, &children) != ZOK || children.count == 0) { LOG_OPER("Unable to discover remote scribes."); return false; } AggSelector *aggSelector = AggSelectorFactory::createAggSelector(zkAggSelectorKey); ret = aggSelector->selectScribeAggregator(children, remoteHost, remotePort); return ret; }
implement connecting to arbitrary zookeeper nodes in connection config
implement connecting to arbitrary zookeeper nodes in connection config
C++
apache-2.0
betable/scribe,traviscrawford/scribe,betable/scribe,betable/scribe,betable/scribe,kovyrin/scribe,kovyrin/scribe,traviscrawford/scribe,kovyrin/scribe,traviscrawford/scribe,traviscrawford/scribe,kovyrin/scribe,traviscrawford/scribe,betable/scribe,kovyrin/scribe,traviscrawford/scribe
8f0016b3ce858be150dfa87bf3e4a34cb118534c
src/gui/app.cc
src/gui/app.cc
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gui/app.h" #include <boost/process/search_path.hpp> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #include <wx/config.h> #include <wx/filename.h> #include <wx/persist.h> #pragma GCC diagnostic pop #include "gui/main-frame.h" #include "gui/pref-page-general.h" #include "utf8path.h" namespace flint { namespace gui { namespace { class PersistentApp : public wxPersistentObject { public: PersistentApp(App *, wxString &gnuplot_executable); virtual void Save() const override; virtual bool Restore() override; virtual wxString GetKind() const override; virtual wxString GetName() const override; private: wxString &gnuplot_executable_; }; PersistentApp::PersistentApp(App *obj, wxString &gnuplot_executable) : wxPersistentObject(obj) , gnuplot_executable_(gnuplot_executable) { } void PersistentApp::Save() const { SaveValue("gnuplot_executable", gnuplot_executable_); } bool PersistentApp::Restore() { return RestoreValue("gnuplot_executable", &gnuplot_executable_); } wxString PersistentApp::GetKind() const { return "Preference"; } wxString PersistentApp::GetName() const { return "File"; } } bool App::OnInit() { if (!wxApp::OnInit()) return false; checker_ = new wxSingleInstanceChecker; if (checker_->IsAnotherRunning()) { wxLogError("Another instance of this program is already running, aborting."); delete checker_; return false; } SetAppDisplayName("Flint"); SetVendorDisplayName("Flint project"); wxPersistenceManager::Get().RegisterAndRestore(this, new PersistentApp(this, gnuplot_executable_)); wxFileName fileName; fileName.AssignHomeDir(); fileName.AppendDir(".flint"); fileName.AppendDir("2"); fileName.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL); // make sure that it exists fileName.SetCwd(); auto frame = new MainFrame; frame->CentreOnScreen(); frame->Show(); pref_editor_ = nullptr; return true; } int App::OnExit() { wxPersistenceManager::Get().SaveAndUnregister(this); // clean up working directory wxFileName fileName; fileName.AssignHomeDir(); fileName.SetCwd(); // change directory at first fileName.AppendDir(".flint"); fileName.AppendDir("2"); fileName.Rmdir(wxPATH_RMDIR_RECURSIVE); delete checker_; return wxApp::OnExit(); } boost::filesystem::path App::GetGnuplotExecutable() const { boost::filesystem::path p(gnuplot_executable_.ToStdString()); if (p.empty()) { // search executable from PATH p = boost::process::search_path("gnuplot"); } return p; } void App::OnGnuplotExecutable(wxFileDirPickerEvent &event) { gnuplot_executable_ = event.GetPath(); } void App::ShowPreferencesEditor(wxWindow *parent) { if (!pref_editor_) { pref_editor_ = new wxPreferencesEditor; pref_editor_->AddPage(new PrefPageGeneral(gnuplot_executable_)); } pref_editor_->Show(parent); } } } wxIMPLEMENT_APP(flint::gui::App);
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gui/app.h" #include <boost/process/search_path.hpp> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #include <wx/config.h> #include <wx/filename.h> #include <wx/persist.h> #pragma GCC diagnostic pop #include "gui/main-frame.h" #include "gui/pref-page-general.h" #include "utf8path.h" namespace flint { namespace gui { namespace { class PersistentApp : public wxPersistentObject { public: PersistentApp(App *, wxString &gnuplot_executable); virtual void Save() const override; virtual bool Restore() override; virtual wxString GetKind() const override; virtual wxString GetName() const override; private: wxString &gnuplot_executable_; }; PersistentApp::PersistentApp(App *obj, wxString &gnuplot_executable) : wxPersistentObject(obj) , gnuplot_executable_(gnuplot_executable) { } void PersistentApp::Save() const { SaveValue("gnuplot_executable", gnuplot_executable_); } bool PersistentApp::Restore() { return RestoreValue("gnuplot_executable", &gnuplot_executable_); } wxString PersistentApp::GetKind() const { return "Preference"; } wxString PersistentApp::GetName() const { return "File"; } } bool App::OnInit() { if (!wxApp::OnInit()) return false; checker_ = new wxSingleInstanceChecker; if (checker_->IsAnotherRunning()) { wxLogError("Another instance of this program is already running, aborting."); delete checker_; return false; } SetAppDisplayName("Flint"); SetVendorDisplayName("Flint project"); wxPersistenceManager::Get().RegisterAndRestore(this, new PersistentApp(this, gnuplot_executable_)); wxFileName fileName; fileName.AssignHomeDir(); fileName.AppendDir(".flint"); fileName.AppendDir("2"); fileName.Rmdir(wxPATH_RMDIR_RECURSIVE); // clean up working directory at first fileName.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL); // make sure that it exists fileName.SetCwd(); auto frame = new MainFrame; frame->CentreOnScreen(); frame->Show(); pref_editor_ = nullptr; return true; } int App::OnExit() { wxPersistenceManager::Get().SaveAndUnregister(this); delete checker_; return wxApp::OnExit(); } boost::filesystem::path App::GetGnuplotExecutable() const { boost::filesystem::path p(gnuplot_executable_.ToStdString()); if (p.empty()) { // search executable from PATH p = boost::process::search_path("gnuplot"); } return p; } void App::OnGnuplotExecutable(wxFileDirPickerEvent &event) { gnuplot_executable_ = event.GetPath(); } void App::ShowPreferencesEditor(wxWindow *parent) { if (!pref_editor_) { pref_editor_ = new wxPreferencesEditor; pref_editor_->AddPage(new PrefPageGeneral(gnuplot_executable_)); } pref_editor_->Show(parent); } } } wxIMPLEMENT_APP(flint::gui::App);
Clean up working directory at startup, not at closing
Clean up working directory at startup, not at closing
C++
mit
flintproject/Flint,flintproject/Flint
e282b76880691183477caaecdc473b5416468d0c
src/itimer.cpp
src/itimer.cpp
/* * Copyright 2018 Andrei Pangin * * 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 <sys/time.h> #include "itimer.h" #include "os.h" #include "profiler.h" long ITimer::_interval; void ITimer::signalHandler(int signo, siginfo_t* siginfo, void* ucontext) { Profiler::_instance.recordSample(ucontext, _interval, 0, NULL); } Error ITimer::start(Arguments& args) { if (args._interval < 0) { return Error("interval must be positive"); } _interval = args._interval ? args._interval : DEFAULT_INTERVAL; OS::installSignalHandler(SIGPROF, signalHandler); long sec = _interval / 1000000000; long usec = (_interval % 1000000000) / 1000; struct itimerval tv = {{sec, usec}, {sec, usec}}; setitimer(ITIMER_PROF, &tv, NULL); return Error::OK; } void ITimer::stop() { struct itimerval tv = {{0, 0}, {0, 0}}; setitimer(ITIMER_PROF, &tv, NULL); }
/* * Copyright 2018 Andrei Pangin * * 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 <sys/time.h> #include "itimer.h" #include "os.h" #include "profiler.h" long ITimer::_interval; void ITimer::signalHandler(int signo, siginfo_t* siginfo, void* ucontext) { Profiler::_instance.recordSample(ucontext, _interval, 0, NULL); } Error ITimer::start(Arguments& args) { if (args._interval < 0) { return Error("interval must be positive"); } _interval = args._interval ? args._interval : DEFAULT_INTERVAL; OS::installSignalHandler(SIGPROF, signalHandler); long sec = _interval / 1000000000; long usec = (_interval % 1000000000) / 1000; struct itimerval tv = {{sec, usec}, {sec, usec}}; if (setitimer(ITIMER_PROF, &tv, NULL) != 0) { return Error("ITIMER_PROF is not supported on this system"); } return Error::OK; } void ITimer::stop() { struct itimerval tv = {{0, 0}, {0, 0}}; setitimer(ITIMER_PROF, &tv, NULL); }
Add an error message if ITIMER_PROF is not supported
#286: Add an error message if ITIMER_PROF is not supported
C++
apache-2.0
jvm-profiling-tools/async-profiler,jvm-profiling-tools/async-profiler,apangin/async-profiler,apangin/async-profiler,apangin/async-profiler,jvm-profiling-tools/async-profiler,apangin/async-profiler,jvm-profiling-tools/async-profiler,jvm-profiling-tools/async-profiler
4f0f86fed90cd2fcdba12d2597546c9fa22429f4
libvast/src/command.cpp
libvast/src/command.cpp
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/command.hpp" #include "vast/logger.hpp" namespace vast { command::command() : parent_(nullptr) { // nop } command::command(command* parent, std::string_view name) : parent_{parent}, name_{name} { // nop } command::~command() { // nop } //int command::run(caf::actor_system& sys, XXoption_mapXX& options, //argument_iterator begin, argument_iterator end) { //VAST_TRACE(VAST_ARG(options), VAST_ARG("args", begin, end)); //// Split the arguments. //auto args = caf::message_builder{begin, end}.move_to_message(); //auto [local_args, subcmd, subcmd_args] = separate_args(args); //begin += local_args.size(); //// Parse arguments for this command. //auto res = local_args.extract_opts(opts_); //if (res.opts.count("help") != 0) { //std::cout << res.helptext << std::endl; //if (!nested_.empty()) { //std::cout << "\nSubcommands:\n"; //for (auto& kvp : nested_) //std::cout << " " << kvp.first << "\n"; //} //std::cout << std::endl; //return EXIT_SUCCESS; //} //// Populate the map with our key/value pairs for all options. //for (auto& kvp : kvps_) //options.emplace(kvp()); //// Check whether the options allow for further processing. //switch (proceed(sys, options, begin, end)) { //default: //// nop //break; //case stop_successful: //return EXIT_SUCCESS; //case stop_with_error: //return EXIT_FAILURE; //} //// Invoke run_impl if no subcommand was defined. //if (subcmd.empty()) { //VAST_ASSERT(subcmd_args.empty()); //return run_impl(sys, options, begin, end); //} //// Consume CLI arguments if we have arguments but don't have subcommands. //if (nested_.empty()) { //return run_impl(sys, options, begin, end); //} //// Dispatch to subcommand. //auto i = nested_.find(subcmd); //if (i == nested_.end()) { //std::cerr << "no such command: " << full_name() << " " << subcmd //<< std::endl //<< std::endl; //usage(); //return EXIT_FAILURE; //} //return i->second->run(sys, options, begin + 1, end); //} int command::run(caf::actor_system& sys, option_map& options, argument_iterator begin, argument_iterator end) { // Parse arguments for this command. VAST_TRACE(VAST_ARG(options), VAST_ARG("args", begin, end)); auto [state, position] = opts_.parse(options, begin, end); bool has_subcommand; switch(state) { default: // TODO: examine what went wrong and inform the user std::cerr << "something went wrong!!!" << std::endl; std::cerr << "parser state: " << static_cast<int>(state) << std::endl; std::cerr << usage() << std::endl;; return EXIT_FAILURE; case option_declaration_set::parse_state::successful: has_subcommand = false; break; case option_declaration_set::parse_state::begin_is_not_an_option: if (position == end) has_subcommand = false; has_subcommand = true; break; } // Check for help option. if (get_or<boolean>(options, "help", false)) { std::cerr << usage() << std::endl;; return EXIT_SUCCESS; } // Check whether the options allow for further processing. switch (proceed(sys, options, position, end)) { default: // nop break; case stop_successful: return EXIT_SUCCESS; case stop_with_error: return EXIT_FAILURE; } // Invoke run_impl if no subcommand was defined. if (!has_subcommand) return run_impl(sys, options, position, end); // Consume CLI arguments if we have arguments but don't have subcommands. if (nested_.empty()) return run_impl(sys, options, position, end); // Dispatch to subcommand. auto i = nested_.find(*position); if (i == nested_.end()) { std::cerr << "no such command: " << full_name() << " " << *position << std::endl << std::endl; std::cerr << usage() << std::endl;; return EXIT_FAILURE; } return i->second->run(sys, options, position + 1, end); } //int command::run(caf::actor_system& sys, argument_iterator begin, //argument_iterator end) { //XXoption_mapXX options; //return run(sys, options, begin, end); //} int command::run(caf::actor_system& sys, argument_iterator begin, argument_iterator end) { option_map options; return run(sys, options, begin, end); } std::string command::usage() { std::stringstream result; result << opts_.usage() << "\n"; result << "\nSubcommands:\n"; for (auto& kvp : nested_) result << " " << kvp.first << "\n"; return result.str(); } std::string command::full_name() { std::string result; if (is_root()) return result; result = parent_->full_name(); if (!result.empty()) result += ' '; result += name_; return result; } std::string command::name() { return std::string{name_}; } bool command::is_root() const noexcept { return parent_ == nullptr; } //command::proceed_result command::proceed(caf::actor_system&, //XXoption_mapXX& options, //argument_iterator begin, //argument_iterator end) { //VAST_UNUSED(options, begin, end); //VAST_TRACE(VAST_ARG(options), VAST_ARG("args", begin, end)); //return proceed_ok; //} command::proceed_result command::proceed(caf::actor_system&, option_map& options, argument_iterator begin, argument_iterator end) { VAST_UNUSED(options, begin, end); VAST_TRACE(VAST_ARG(options), VAST_ARG("args", begin, end)); return proceed_ok; } //int command::run_impl(caf::actor_system&, XXoption_mapXX& options, //argument_iterator begin, argument_iterator end) { //VAST_UNUSED(options, begin, end); //VAST_TRACE(VAST_ARG(options), VAST_ARG("args", begin, end)); //usage(); //return EXIT_FAILURE; //} int command::run_impl(caf::actor_system&, option_map& options, argument_iterator begin, argument_iterator end) { VAST_UNUSED(options, begin, end); VAST_TRACE(VAST_ARG(options), VAST_ARG("args", begin, end)); usage(); return EXIT_FAILURE; } //std::tuple<caf::message, std::string, caf::message> //command::separate_args(const caf::message& args) { //auto arg = [&](size_t i) -> const std::string& { //VAST_ASSERT(args.match_element<std::string>(i)); //return args.get_as<std::string>(i); //}; //size_t pos = 0; //while (pos < args.size()) { //if (arg(pos).compare(0, 2, "--") == 0) { //// Simply skip over long options. //++pos; //} else if (arg(pos).compare(0, 1, "-") == 0) { //// We assume short options always have an argument. //// TODO: we could look into the argument instead of just assuming it //// always take an argument. //pos += 2; //} else { //// Found the end of the options list. //return std::make_tuple(args.take(pos), arg(pos), args.drop(pos+ 1)); //} //} //return std::make_tuple(args, "", caf::none); //} expected<void> command::add_opt(std::string_view name, std::string_view description, data default_value) { return opts_.add(name, description, std::move(default_value)); } } // namespace vast
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/command.hpp" #include "vast/logger.hpp" namespace vast { command::command() : parent_(nullptr) { // nop } command::command(command* parent, std::string_view name) : parent_{parent}, name_{name} { // nop } command::~command() { // nop } //int command::run(caf::actor_system& sys, XXoption_mapXX& options, //argument_iterator begin, argument_iterator end) { //VAST_TRACE(VAST_ARG(options), VAST_ARG("args", begin, end)); //// Split the arguments. //auto args = caf::message_builder{begin, end}.move_to_message(); //auto [local_args, subcmd, subcmd_args] = separate_args(args); //begin += local_args.size(); //// Parse arguments for this command. //auto res = local_args.extract_opts(opts_); //if (res.opts.count("help") != 0) { //std::cout << res.helptext << std::endl; //if (!nested_.empty()) { //std::cout << "\nSubcommands:\n"; //for (auto& kvp : nested_) //std::cout << " " << kvp.first << "\n"; //} //std::cout << std::endl; //return EXIT_SUCCESS; //} //// Populate the map with our key/value pairs for all options. //for (auto& kvp : kvps_) //options.emplace(kvp()); //// Check whether the options allow for further processing. //switch (proceed(sys, options, begin, end)) { //default: //// nop //break; //case stop_successful: //return EXIT_SUCCESS; //case stop_with_error: //return EXIT_FAILURE; //} //// Invoke run_impl if no subcommand was defined. //if (subcmd.empty()) { //VAST_ASSERT(subcmd_args.empty()); //return run_impl(sys, options, begin, end); //} //// Consume CLI arguments if we have arguments but don't have subcommands. //if (nested_.empty()) { //return run_impl(sys, options, begin, end); //} //// Dispatch to subcommand. //auto i = nested_.find(subcmd); //if (i == nested_.end()) { //std::cerr << "no such command: " << full_name() << " " << subcmd //<< std::endl //<< std::endl; //usage(); //return EXIT_FAILURE; //} //return i->second->run(sys, options, begin + 1, end); //} int command::run(caf::actor_system& sys, option_map& options, argument_iterator begin, argument_iterator end) { VAST_TRACE(VAST_ARG(std::string(name_)), VAST_ARG("args", begin, end), VAST_ARG(options)); // Parse arguments for this command. auto [state, position] = opts_.parse(options, begin, end); bool has_subcommand; switch(state) { default: // TODO: examine what went wrong and inform the user std::cerr << "something went wrong!!!" << std::endl; std::cerr << "parser state: " << static_cast<int>(state) << std::endl; std::cerr << usage() << std::endl;; return EXIT_FAILURE; case option_declaration_set::parse_state::successful: has_subcommand = false; break; case option_declaration_set::parse_state::begin_is_not_an_option: if (position == end) has_subcommand = false; has_subcommand = true; break; } // Check for help option. if (get_or<boolean>(options, "help", false)) { std::cerr << usage() << std::endl;; return EXIT_SUCCESS; } // Check whether the options allow for further processing. switch (proceed(sys, options, position, end)) { default: // nop break; case stop_successful: return EXIT_SUCCESS; case stop_with_error: return EXIT_FAILURE; } // Invoke run_impl if no subcommand was defined. if (!has_subcommand) return run_impl(sys, options, position, end); // Consume CLI arguments if we have arguments but don't have subcommands. if (nested_.empty()) return run_impl(sys, options, position, end); // Dispatch to subcommand. auto i = nested_.find(*position); if (i == nested_.end()) { std::cerr << "no such command: " << full_name() << " " << *position << std::endl << std::endl; std::cerr << usage() << std::endl;; return EXIT_FAILURE; } return i->second->run(sys, options, position + 1, end); } //int command::run(caf::actor_system& sys, argument_iterator begin, //argument_iterator end) { //XXoption_mapXX options; //return run(sys, options, begin, end); //} int command::run(caf::actor_system& sys, argument_iterator begin, argument_iterator end) { option_map options; return run(sys, options, begin, end); } std::string command::usage() { std::stringstream result; result << opts_.usage() << "\n"; result << "\nSubcommands:\n"; for (auto& kvp : nested_) result << " " << kvp.first << "\n"; return result.str(); } std::string command::full_name() { std::string result; if (is_root()) return result; result = parent_->full_name(); if (!result.empty()) result += ' '; result += name_; return result; } std::string command::name() { return std::string{name_}; } bool command::is_root() const noexcept { return parent_ == nullptr; } //command::proceed_result command::proceed(caf::actor_system&, //XXoption_mapXX& options, //argument_iterator begin, //argument_iterator end) { //VAST_UNUSED(options, begin, end); //VAST_TRACE(VAST_ARG(options), VAST_ARG("args", begin, end)); //return proceed_ok; //} command::proceed_result command::proceed(caf::actor_system&, option_map& options, argument_iterator begin, argument_iterator end) { VAST_UNUSED(options, begin, end); VAST_TRACE(VAST_ARG(std::string{name_}), VAST_ARG("args", begin, end), VAST_ARG(options)); return proceed_ok; } //int command::run_impl(caf::actor_system&, XXoption_mapXX& options, //argument_iterator begin, argument_iterator end) { //VAST_UNUSED(options, begin, end); //VAST_TRACE(VAST_ARG(options), VAST_ARG("args", begin, end)); //usage(); //return EXIT_FAILURE; //} int command::run_impl(caf::actor_system&, option_map& options, argument_iterator begin, argument_iterator end) { VAST_UNUSED(options, begin, end); VAST_TRACE(VAST_ARG(std::string{name_}), VAST_ARG("args", begin, end), VAST_ARG(options)); usage(); return EXIT_FAILURE; } //std::tuple<caf::message, std::string, caf::message> //command::separate_args(const caf::message& args) { //auto arg = [&](size_t i) -> const std::string& { //VAST_ASSERT(args.match_element<std::string>(i)); //return args.get_as<std::string>(i); //}; //size_t pos = 0; //while (pos < args.size()) { //if (arg(pos).compare(0, 2, "--") == 0) { //// Simply skip over long options. //++pos; //} else if (arg(pos).compare(0, 1, "-") == 0) { //// We assume short options always have an argument. //// TODO: we could look into the argument instead of just assuming it //// always take an argument. //pos += 2; //} else { //// Found the end of the options list. //return std::make_tuple(args.take(pos), arg(pos), args.drop(pos+ 1)); //} //} //return std::make_tuple(args, "", caf::none); //} expected<void> command::add_opt(std::string_view name, std::string_view description, data default_value) { return opts_.add(name, description, std::move(default_value)); } } // namespace vast
Improve trace log output of command
Improve trace log output of command
C++
bsd-3-clause
mavam/vast,vast-io/vast,mavam/vast,vast-io/vast,mavam/vast,vast-io/vast,vast-io/vast,vast-io/vast,mavam/vast
381a121fcbbfd5f15e03fbd290a75e4bc9fba45d
linc/linc_timestamp.cpp
linc/linc_timestamp.cpp
#include "./linc_timestamp.h" #include <sys/time.h> #include <stdint.h> #ifdef HX_LINUX #include <unistd.h> #include <stdio.h> #endif #ifdef HX_MACOS #include <mach/mach_time.h> #include <mach-o/dyld.h> #include <CoreServices/CoreServices.h> #endif #ifdef IPHONE #include <QuartzCore/QuartzCore.h> #endif #ifdef ANDROID #include <time.h> #endif namespace linc { namespace timestamp { static double t0 = 0; double now() { #if defined(HX_MACOS) static double time_scale = 0.0; if (time_scale == 0.0) { mach_timebase_info_data_t info; mach_timebase_info(&info); time_scale = 1e-9 * (double)info.numer / info.denom; } double r = mach_absolute_time() * time_scale; return mach_absolute_time() * time_scale; #else #if defined(IPHONE) double t = CACurrentMediaTime(); #elif defined(GPH) || defined(HX_LINUX) || defined(EMSCRIPTEN) struct timeval tv; if( gettimeofday(&tv,NULL) ) { return 0; } double t = ( tv.tv_sec + ((double)tv.tv_usec) / 1000000.0 ); #else struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); double t = ( ts.tv_sec + ((double)ts.tv_nsec)*1e-9 ); #endif if (t0 == 0) { t0 = t; } return t - t0; #endif } //now() } //timestamp namespace } //linc
#include "./linc_timestamp.h" // Originally adapted for snow from nme // https://github.com/underscorediscovery/snow // https://github.com/haxenme/nme #include <sys/time.h> #include <stdint.h> #ifdef HX_LINUX #include <unistd.h> #include <stdio.h> #endif #ifdef HX_MACOS #include <mach/mach_time.h> #include <mach-o/dyld.h> #include <CoreServices/CoreServices.h> #endif #ifdef IPHONE #include <QuartzCore/QuartzCore.h> #endif #ifdef ANDROID #include <time.h> #endif namespace linc { namespace timestamp { static double t0 = 0; double now() { #if defined(HX_MACOS) static double time_scale = 0.0; if (time_scale == 0.0) { mach_timebase_info_data_t info; mach_timebase_info(&info); time_scale = 1e-9 * (double)info.numer / info.denom; } double r = mach_absolute_time() * time_scale; return mach_absolute_time() * time_scale; #else #if defined(IPHONE) double t = CACurrentMediaTime(); #elif defined(GPH) || defined(HX_LINUX) || defined(EMSCRIPTEN) struct timeval tv; if( gettimeofday(&tv,NULL) ) { return 0; } double t = ( tv.tv_sec + ((double)tv.tv_usec) / 1000000.0 ); #else struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); double t = ( ts.tv_sec + ((double)ts.tv_nsec)*1e-9 ); #endif if (t0 == 0) { t0 = t; } return t - t0; #endif } //now() } //timestamp namespace } //linc
Update linc_timestamp.cpp
Update linc_timestamp.cpp
C++
mit
snowkit/linc_timestamp
5586c020c9b9819062306522b76b09561d91d50e
src/memory.cpp
src/memory.cpp
//===------------------------ memory.cpp ----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "memory" _LIBCPP_BEGIN_NAMESPACE_STD namespace { template <class T> inline T increment(T& t) _NOEXCEPT { return __sync_add_and_fetch(&t, 1); } template <class T> inline T decrement(T& t) _NOEXCEPT { return __sync_add_and_fetch(&t, -1); } } // namespace const allocator_arg_t allocator_arg = allocator_arg_t(); bad_weak_ptr::~bad_weak_ptr() _NOEXCEPT {} const char* bad_weak_ptr::what() const _NOEXCEPT { return "bad_weak_ptr"; } __shared_count::~__shared_count() { } void __shared_count::__add_shared() _NOEXCEPT { increment(__shared_owners_); } bool __shared_count::__release_shared() _NOEXCEPT { if (decrement(__shared_owners_) == -1) { __on_zero_shared(); return true; } return false; } __shared_weak_count::~__shared_weak_count() { } void __shared_weak_count::__add_shared() _NOEXCEPT { __shared_count::__add_shared(); } void __shared_weak_count::__add_weak() _NOEXCEPT { increment(__shared_weak_owners_); } void __shared_weak_count::__release_shared() _NOEXCEPT { if (__shared_count::__release_shared()) __release_weak(); } void __shared_weak_count::__release_weak() _NOEXCEPT { if (decrement(__shared_weak_owners_) == -1) __on_zero_shared_weak(); } __shared_weak_count* __shared_weak_count::lock() _NOEXCEPT { long object_owners = __shared_owners_; while (object_owners != -1) { if (__sync_bool_compare_and_swap(&__shared_owners_, object_owners, object_owners+1)) { __add_weak(); return this; } object_owners = __shared_owners_; } return 0; } #ifndef _LIBCPP_NO_RTTI const void* __shared_weak_count::__get_deleter(const type_info&) const _NOEXCEPT { return 0; } #endif // _LIBCPP_NO_RTTI void declare_reachable(void*) { } void declare_no_pointers(char*, size_t) { } void undeclare_no_pointers(char*, size_t) { } pointer_safety get_pointer_safety() _NOEXCEPT { return pointer_safety::relaxed; } void* __undeclare_reachable(void* p) { return p; } void* align(size_t alignment, size_t size, void*& ptr, size_t& space) { void* r = nullptr; if (size <= space) { char* p1 = static_cast<char*>(ptr); char* p2 = (char*)((size_t)(p1 + (alignment - 1)) & -alignment); size_t d = static_cast<size_t>(p2 - p1); if (d <= space - size) { r = p2; ptr = r; space -= d; } } return r; } _LIBCPP_END_NAMESPACE_STD
//===------------------------ memory.cpp ----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "memory" _LIBCPP_BEGIN_NAMESPACE_STD namespace { template <class T> inline T increment(T& t) _NOEXCEPT { return __sync_add_and_fetch(&t, 1); } template <class T> inline T decrement(T& t) _NOEXCEPT { return __sync_add_and_fetch(&t, -1); } } // namespace const allocator_arg_t allocator_arg = allocator_arg_t(); bad_weak_ptr::~bad_weak_ptr() _NOEXCEPT {} const char* bad_weak_ptr::what() const _NOEXCEPT { return "bad_weak_ptr"; } __shared_count::~__shared_count() { } void __shared_count::__add_shared() _NOEXCEPT { increment(__shared_owners_); } bool __shared_count::__release_shared() _NOEXCEPT { if (decrement(__shared_owners_) == -1) { __on_zero_shared(); return true; } return false; } __shared_weak_count::~__shared_weak_count() { } void __shared_weak_count::__add_shared() _NOEXCEPT { __shared_count::__add_shared(); } void __shared_weak_count::__add_weak() _NOEXCEPT { increment(__shared_weak_owners_); } void __shared_weak_count::__release_shared() _NOEXCEPT { if (__shared_count::__release_shared()) __release_weak(); } void __shared_weak_count::__release_weak() _NOEXCEPT { if (decrement(__shared_weak_owners_) == -1) __on_zero_shared_weak(); } __shared_weak_count* __shared_weak_count::lock() _NOEXCEPT { long object_owners = __shared_owners_; while (object_owners != -1) { if (__sync_bool_compare_and_swap(&__shared_owners_, object_owners, object_owners+1)) return this; object_owners = __shared_owners_; } return 0; } #ifndef _LIBCPP_NO_RTTI const void* __shared_weak_count::__get_deleter(const type_info&) const _NOEXCEPT { return 0; } #endif // _LIBCPP_NO_RTTI void declare_reachable(void*) { } void declare_no_pointers(char*, size_t) { } void undeclare_no_pointers(char*, size_t) { } pointer_safety get_pointer_safety() _NOEXCEPT { return pointer_safety::relaxed; } void* __undeclare_reachable(void* p) { return p; } void* align(size_t alignment, size_t size, void*& ptr, size_t& space) { void* r = nullptr; if (size <= space) { char* p1 = static_cast<char*>(ptr); char* p2 = (char*)((size_t)(p1 + (alignment - 1)) & -alignment); size_t d = static_cast<size_t>(p2 - p1); if (d <= space - size) { r = p2; ptr = r; space -= d; } } return r; } _LIBCPP_END_NAMESPACE_STD
Fix memory leak in converting weak_ptr to shared_ptr
Fix memory leak in converting weak_ptr to shared_ptr git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@147298 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx
7462a70d714ff507d6a7c59228b23ec8d7584754
src/net_tcp.cc
src/net_tcp.cc
/* Copyright (c) 2009-2010 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // RAMCloud pragma [CPPLINT=0] #include <config.h> #ifdef TCP_NET #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <assert.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <rcrpc.h> #include <Net.h> static int rc_tcp_net_accept(struct rc_net *net) { assert(net->server); assert(net->listen_fd != -1); if (net->connection_fd != -1) { return 0; } int cfd = accept(net->listen_fd, NULL, NULL); if (cfd == -1) { return -1; } // maybe we should check if dstsin matches the socket we accepted net->connection_fd = cfd; return 0; } void rc_net_init(struct rc_net *ret, const char *srcaddr, uint16_t srcport, const char *dstaddr, uint16_t dstport) { ret->server = false; ret->client = false; ret->listen_fd = -1; ret->connection_fd = -1; ret->srcsin.sin_family = AF_INET; ret->srcsin.sin_port = htons(srcport); inet_aton(srcaddr, &ret->srcsin.sin_addr); ret->dstsin.sin_family = AF_INET; ret->dstsin.sin_port = htons(dstport); inet_aton(dstaddr, &ret->dstsin.sin_addr); } int rc_net_connect(struct rc_net *net) { assert(!net->server); assert(net->connection_fd == -1); net->client = true; int fd = socket(PF_INET, SOCK_STREAM, 0); if (fd == -1) { // errno already set from socket return -1; } if (connect(fd, (struct sockaddr *)&net->dstsin, sizeof(net->dstsin)) == -1) { // store errno in case close fails int e = errno; close(fd); errno = e; return -1; } net->connection_fd = fd; return 0; } int rc_net_listen(struct rc_net *net) { assert(!net->client); assert(net->listen_fd == -1); assert(net->connection_fd == -1); net->server = true; int fd = socket(PF_INET, SOCK_STREAM, 0); if (fd == -1) { // errno already set from socket return -1; } int optval = 1; (void) setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval); if (bind(fd, (struct sockaddr *)&net->srcsin, sizeof(net->srcsin)) == -1) { // store errno in case close fails int e = errno; close(fd); errno = e; return -1; } if (listen(fd, 1) == -1) { // store errno in case close fails int e = errno; close(fd); errno = e; return -1; } net->listen_fd = fd; return 0; } int rc_net_close(struct rc_net *net) { if (net->connection_fd != -1) { close(net->connection_fd); net->connection_fd = -1; } if (net->server && net->listen_fd != -1) { close(net->listen_fd); net->listen_fd = -1; } net->client = false; net->server = false; return 0; } int rc_net_send(struct rc_net *net, void *buf, size_t len) { if (net->server && rc_tcp_net_accept(net) == -1) { return -1; } if (send(net->connection_fd, buf, len, 0) == -1) { // errno already set from send fprintf(stderr, "send failure %s:%d: %s\n", __FILE__, __LINE__, strerror(errno)); return -1; } return 0; } int rc_net_send_rpc(struct rc_net *net, struct rcrpc_any *rpc) { return rc_net_send(net, rpc, rpc->header.len); } int rc_net_recv(struct rc_net *net, void **buf, size_t *buflen) { if (net->server && rc_tcp_net_accept(net) == -1) { return -1; } static char recvbuf[MAX_RPC_LEN]; ssize_t len; if (*buflen == 0x239058) { // called from recv_rpc len = recv(net->connection_fd, recvbuf, RCRPC_HEADER_LEN, MSG_PEEK|MSG_WAITALL); if (len == -1) { // errno already set from recv return -1; } else if (len == 0) { // "peer performed orderly shutdown" close(net->connection_fd); net->connection_fd = -1; return rc_net_recv(net, buf, buflen); } else { assert(len == RCRPC_HEADER_LEN); } uint64_t rpc_len = ((struct rcrpc_header*) recvbuf)->len; assert(rpc_len >= RCRPC_HEADER_LEN); len = recv(net->connection_fd, recvbuf, rpc_len, MSG_WAITALL); if (len == -1) { // errno already set from recv return -1; } else if (len == 0) { // "peer performed orderly shutdown" close(net->connection_fd); net->connection_fd = -1; return rc_net_recv(net, buf, buflen); } else { assert(len > 0); assert((uint64_t) len == rpc_len); } } else { len = recv(net->connection_fd, recvbuf, sizeof(recvbuf), 0); if (len == -1) { // errno already set from recv return -1; } else if (len == 0) { // "peer performed orderly shutdown" close(net->connection_fd); net->connection_fd = -1; return rc_net_recv(net, buf, buflen); } } *buf = (void *)recvbuf; *buflen = len; return 0; } int rc_net_recv_rpc(struct rc_net *net, struct rcrpc_any **rpc) { size_t len = 0x239058; // magic value for rc_net_recv to check int r = rc_net_recv(net, (void **)rpc, &len); if (r == 0) { assert(len == (*rpc)->header.len); } return r; } #endif
/* Copyright (c) 2009-2010 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // RAMCloud pragma [CPPLINT=0] #include <config.h> #ifdef TCP_NET #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <rcrpc.h> #include <Net.h> using RAMCloud::assert; static int rc_tcp_net_accept(struct rc_net *net) { assert(net->server); assert(net->listen_fd != -1); if (net->connection_fd != -1) { return 0; } int cfd = accept(net->listen_fd, NULL, NULL); if (cfd == -1) { return -1; } // maybe we should check if dstsin matches the socket we accepted net->connection_fd = cfd; return 0; } void rc_net_init(struct rc_net *ret, const char *srcaddr, uint16_t srcport, const char *dstaddr, uint16_t dstport) { ret->server = false; ret->client = false; ret->listen_fd = -1; ret->connection_fd = -1; ret->srcsin.sin_family = AF_INET; ret->srcsin.sin_port = htons(srcport); inet_aton(srcaddr, &ret->srcsin.sin_addr); ret->dstsin.sin_family = AF_INET; ret->dstsin.sin_port = htons(dstport); inet_aton(dstaddr, &ret->dstsin.sin_addr); } int rc_net_connect(struct rc_net *net) { assert(!net->server); assert(net->connection_fd == -1); net->client = true; int fd = socket(PF_INET, SOCK_STREAM, 0); if (fd == -1) { // errno already set from socket return -1; } if (connect(fd, (struct sockaddr *)&net->dstsin, sizeof(net->dstsin)) == -1) { // store errno in case close fails int e = errno; close(fd); errno = e; return -1; } net->connection_fd = fd; return 0; } int rc_net_listen(struct rc_net *net) { assert(!net->client); assert(net->listen_fd == -1); assert(net->connection_fd == -1); net->server = true; int fd = socket(PF_INET, SOCK_STREAM, 0); if (fd == -1) { // errno already set from socket return -1; } int optval = 1; (void) setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval); if (bind(fd, (struct sockaddr *)&net->srcsin, sizeof(net->srcsin)) == -1) { // store errno in case close fails int e = errno; close(fd); errno = e; return -1; } if (listen(fd, 1) == -1) { // store errno in case close fails int e = errno; close(fd); errno = e; return -1; } net->listen_fd = fd; return 0; } int rc_net_close(struct rc_net *net) { if (net->connection_fd != -1) { close(net->connection_fd); net->connection_fd = -1; } if (net->server && net->listen_fd != -1) { close(net->listen_fd); net->listen_fd = -1; } net->client = false; net->server = false; return 0; } int rc_net_send(struct rc_net *net, void *buf, size_t len) { if (net->server && rc_tcp_net_accept(net) == -1) { return -1; } if (send(net->connection_fd, buf, len, 0) == -1) { // errno already set from send fprintf(stderr, "send failure %s:%d: %s\n", __FILE__, __LINE__, strerror(errno)); return -1; } return 0; } int rc_net_send_rpc(struct rc_net *net, struct rcrpc_any *rpc) { return rc_net_send(net, rpc, rpc->header.len); } int rc_net_recv(struct rc_net *net, void **buf, size_t *buflen) { if (net->server && rc_tcp_net_accept(net) == -1) { return -1; } static char recvbuf[MAX_RPC_LEN]; ssize_t len; if (*buflen == 0x239058) { // called from recv_rpc len = recv(net->connection_fd, recvbuf, RCRPC_HEADER_LEN, MSG_PEEK|MSG_WAITALL); if (len == -1) { // errno already set from recv return -1; } else if (len == 0) { // "peer performed orderly shutdown" close(net->connection_fd); net->connection_fd = -1; return rc_net_recv(net, buf, buflen); } else { assert(len == RCRPC_HEADER_LEN); } uint64_t rpc_len = ((struct rcrpc_header*) recvbuf)->len; assert(rpc_len >= RCRPC_HEADER_LEN); len = recv(net->connection_fd, recvbuf, rpc_len, MSG_WAITALL); if (len == -1) { // errno already set from recv return -1; } else if (len == 0) { // "peer performed orderly shutdown" close(net->connection_fd); net->connection_fd = -1; return rc_net_recv(net, buf, buflen); } else { assert(len > 0); assert((uint64_t) len == rpc_len); } } else { len = recv(net->connection_fd, recvbuf, sizeof(recvbuf), 0); if (len == -1) { // errno already set from recv return -1; } else if (len == 0) { // "peer performed orderly shutdown" close(net->connection_fd); net->connection_fd = -1; return rc_net_recv(net, buf, buflen); } } *buf = (void *)recvbuf; *buflen = len; return 0; } int rc_net_recv_rpc(struct rc_net *net, struct rcrpc_any **rpc) { size_t len = 0x239058; // magic value for rc_net_recv to check int r = rc_net_recv(net, (void **)rpc, &len); if (r == 0) { assert(len == (*rpc)->header.len); } return r; } #endif
Fix build with TCP_NET
Fix build with TCP_NET
C++
isc
behnamm/cs244b_project,IMCG/RamCloud,mrdiegoa/ramcloud,DavidLi2010/ramcloud,DavidLi2010/ramcloud,taschik/ramcloud-load-manager,taschik/ramcloud,matrix207/RAMCloud,QingkaiLu/RAMCloud,behnamm/cs244b_project,Frank-Wu/RamCloud,rstutsman/RAMCloud,SMatsushi/RAMCloud,taschik/ramcloud-load-manager,taschik/ramcloud-load-manager,SMatsushi/RAMCloud,QingkaiLu/RAMCloud,jblomer/ramcloud,anirajk/RAMCloud,jblomer/ramcloud,utah-scs/RAMCloud,taschik/ramcloud-load-manager,alexandermerritt/ramcloud,behnamm/cs244b_project,IMCG/RamCloud,QingkaiLu/RAMCloud,jcarreira/ramcloud,anirajk/RAMCloud,jblomer/ramcloud,rstutsman/RAMCloud,anirajk/RAMCloud,SMatsushi/RAMCloud,mrdiegoa/ramcloud,behnamm/cs244b_project,jblomer/ramcloud,QingkaiLu/RAMCloud,Frank-Wu/RamCloud,alexandermerritt/ramcloud,taschik/ramcloud,behnamm/cs244b_project,y-higuchi/ramcloud,alexandermerritt/ramcloud,jcarreira/ramcloud,SMatsushi/RAMCloud,DavidLi2010/ramcloud,jblomer/ramcloud,jcarreira/ramcloud,y-higuchi/ramcloud,IMCG/RamCloud,anirajk/RAMCloud,utah-scs/RAMCloud,taschik/ramcloud,y-higuchi/ramcloud,matrix207/RAMCloud,QingkaiLu/RAMCloud,alexandermerritt/ramcloud,taschik/ramcloud-load-manager,Frank-Wu/RamCloud,mrdiegoa/ramcloud,IMCG/RamCloud,Frank-Wu/RamCloud,y-higuchi/ramcloud,rstutsman/RAMCloud,alexandermerritt/ramcloud,QingkaiLu/RAMCloud,jcarreira/ramcloud,DavidLi2010/ramcloud,mrdiegoa/ramcloud,y-higuchi/ramcloud,rstutsman/RAMCloud,taschik/ramcloud,Frank-Wu/RamCloud,matrix207/RAMCloud,mrdiegoa/ramcloud,Frank-Wu/RamCloud,rstutsman/RAMCloud,jcarreira/ramcloud,jcarreira/ramcloud,utah-scs/RAMCloud,SMatsushi/RAMCloud,alexandermerritt/ramcloud,behnamm/cs244b_project,matrix207/RAMCloud,DavidLi2010/ramcloud,y-higuchi/ramcloud,SMatsushi/RAMCloud,utah-scs/RAMCloud,matrix207/RAMCloud,rstutsman/RAMCloud,anirajk/RAMCloud,jblomer/ramcloud,utah-scs/RAMCloud,matrix207/RAMCloud,DavidLi2010/ramcloud,IMCG/RamCloud,anirajk/RAMCloud,taschik/ramcloud,IMCG/RamCloud,mrdiegoa/ramcloud,utah-scs/RAMCloud
4eace75d2ff12d0329d0fca962150d783e332c14
sound/tag.hpp
sound/tag.hpp
#pragma once //=====================================================================// /*! @file @brief Audio タグ・クラス @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/fixed_string.hpp" namespace sound { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タグ情報 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct tag_t { typedef utils::fixed_string<128> STR128; typedef utils::fixed_string<16> STR16; typedef utils::fixed_string<8> STR8; private: STR128 album_; ///< アルバム名 STR128 title_; ///< タイトル(曲名) STR128 artist_; ///< アーティスト STR16 year_; ///< リリース年 STR8 disc_; ///< ディスク STR8 track_; ///< トラック public: //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 画像情報 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct apic_t { uint8_t typ_; char ext_[4]; uint32_t ofs_; uint32_t len_; apic_t() : typ_(0), ext_{ 0 }, ofs_(0), len_(0) { } }; private: apic_t apic_; public: //-------------------------------------------------------------// /*! @brief コンストラクター */ //-------------------------------------------------------------// tag_t() noexcept : apic_() { clear(); } //-------------------------------------------------------------// /*! @brief クリア */ //-------------------------------------------------------------// void clear() noexcept { album_.clear(); title_.clear(); artist_.clear(); year_.clear(); disc_.clear(); track_.clear(); } //-------------------------------------------------------------// /*! @brief アルバムへの参照 @return アルバム */ //-------------------------------------------------------------// STR128& at_album() noexcept { return album_; } //-------------------------------------------------------------// /*! @brief アルバムへの参照 (RO) @return アルバム */ //-------------------------------------------------------------// const STR128& get_album() const noexcept { return album_; } //-------------------------------------------------------------// /*! @brief タイトルへの参照 @return タイトル */ //-------------------------------------------------------------// STR128& at_title() noexcept { return title_; } //-------------------------------------------------------------// /*! @brief タイトルへの参照 (RO) @return タイトル */ //-------------------------------------------------------------// const STR128& get_title() const noexcept { return title_; } //-------------------------------------------------------------// /*! @brief アーティストへの参照 @return アーティスト */ //-------------------------------------------------------------// STR128& at_artist() noexcept { return artist_; } //-------------------------------------------------------------// /*! @brief アーティストへの参照 (RO) @return アーティスト */ //-------------------------------------------------------------// const STR128& get_artist() const noexcept { return artist_; } //-------------------------------------------------------------// /*! @brief 年への参照 @return 年 */ //-------------------------------------------------------------// STR16& at_year() noexcept { return year_; } //-------------------------------------------------------------// /*! @brief 年への参照 (RO) @return 年 */ //-------------------------------------------------------------// const STR16& get_year() const noexcept { return year_; } //-------------------------------------------------------------// /*! @brief ディスクへの参照 @return ディスク */ //-------------------------------------------------------------// STR8& at_disc() noexcept { return disc_; } //-------------------------------------------------------------// /*! @brief ディスクへの参照 (RO) @return ディスク */ //-------------------------------------------------------------// const STR8& get_disc() const noexcept { return disc_; } //-------------------------------------------------------------// /*! @brief トラックへの参照 @return トラック */ //-------------------------------------------------------------// STR8& at_track() noexcept { return track_; } //-------------------------------------------------------------// /*! @brief トラックへの参照 (RO) @return トラック */ //-------------------------------------------------------------// const STR8& get_track() const noexcept { return track_; } //-------------------------------------------------------------// /*! @brief アルバム画像情報への参照 @return アルバム画像情報 */ //-------------------------------------------------------------// apic_t& at_apic() noexcept { return apic_; } //-------------------------------------------------------------// /*! @brief アルバム画像情報への参照 (RO) @return アルバム画像情報 */ //-------------------------------------------------------------// const apic_t& get_apic() const noexcept { return apic_; } }; }
#pragma once //=====================================================================// /*! @file @brief Audio タグ・クラス @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/fixed_string.hpp" namespace sound { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タグ情報 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct tag_t { typedef utils::fixed_string<128> STR128; typedef utils::fixed_string<16> STR16; typedef utils::fixed_string<8> STR8; private: STR128 album_; ///< アルバム名 STR128 title_; ///< タイトル(曲名) STR128 artist_; ///< アーティスト STR16 year_; ///< リリース年 STR8 disc_; ///< ディスク STR8 track_; ///< トラック public: //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 画像情報 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct apic_t { uint8_t typ_; char ext_[4]; uint32_t ofs_; uint32_t len_; apic_t() : typ_(0), ext_{ 0 }, ofs_(0), len_(0) { } }; private: apic_t apic_; public: //-------------------------------------------------------------// /*! @brief コンストラクター */ //-------------------------------------------------------------// tag_t() noexcept : apic_() { clear(); } //-------------------------------------------------------------// /*! @brief クリア */ //-------------------------------------------------------------// void clear() noexcept { album_.clear(); title_.clear(); artist_.clear(); year_.clear(); disc_.clear(); track_.clear(); apic_ = apic_t(); } //-------------------------------------------------------------// /*! @brief アルバムへの参照 @return アルバム */ //-------------------------------------------------------------// STR128& at_album() noexcept { return album_; } //-------------------------------------------------------------// /*! @brief アルバムへの参照 (RO) @return アルバム */ //-------------------------------------------------------------// const STR128& get_album() const noexcept { return album_; } //-------------------------------------------------------------// /*! @brief タイトルへの参照 @return タイトル */ //-------------------------------------------------------------// STR128& at_title() noexcept { return title_; } //-------------------------------------------------------------// /*! @brief タイトルへの参照 (RO) @return タイトル */ //-------------------------------------------------------------// const STR128& get_title() const noexcept { return title_; } //-------------------------------------------------------------// /*! @brief アーティストへの参照 @return アーティスト */ //-------------------------------------------------------------// STR128& at_artist() noexcept { return artist_; } //-------------------------------------------------------------// /*! @brief アーティストへの参照 (RO) @return アーティスト */ //-------------------------------------------------------------// const STR128& get_artist() const noexcept { return artist_; } //-------------------------------------------------------------// /*! @brief 年への参照 @return 年 */ //-------------------------------------------------------------// STR16& at_year() noexcept { return year_; } //-------------------------------------------------------------// /*! @brief 年への参照 (RO) @return 年 */ //-------------------------------------------------------------// const STR16& get_year() const noexcept { return year_; } //-------------------------------------------------------------// /*! @brief ディスクへの参照 @return ディスク */ //-------------------------------------------------------------// STR8& at_disc() noexcept { return disc_; } //-------------------------------------------------------------// /*! @brief ディスクへの参照 (RO) @return ディスク */ //-------------------------------------------------------------// const STR8& get_disc() const noexcept { return disc_; } //-------------------------------------------------------------// /*! @brief トラックへの参照 @return トラック */ //-------------------------------------------------------------// STR8& at_track() noexcept { return track_; } //-------------------------------------------------------------// /*! @brief トラックへの参照 (RO) @return トラック */ //-------------------------------------------------------------// const STR8& get_track() const noexcept { return track_; } //-------------------------------------------------------------// /*! @brief アルバム画像情報への参照 @return アルバム画像情報 */ //-------------------------------------------------------------// apic_t& at_apic() noexcept { return apic_; } //-------------------------------------------------------------// /*! @brief アルバム画像情報への参照 (RO) @return アルバム画像情報 */ //-------------------------------------------------------------// const apic_t& get_apic() const noexcept { return apic_; } }; }
clear for apic-struct
update: clear for apic-struct
C++
bsd-3-clause
hirakuni45/RX,hirakuni45/RX,hirakuni45/RX,hirakuni45/RX
2ea4b12b7121c2fb891d1051c33d3d5abd10f8eb
Common/DataModel/Testing/Cxx/TestCompositeDataSets.cxx
Common/DataModel/Testing/Cxx/TestCompositeDataSets.cxx
/*========================================================================= Program: Visualization Toolkit Module: TestCompositeDataSets.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkDataObjectTree.h" #include "vtkUniformGridAMR.h" #include "vtkSmartPointer.h" #include "vtkMultiBlockDataSet.h" #include "vtkUniformGrid.h" #include "vtkCompositeDataIterator.h" #include "vtkDataObjectTreeIterator.h" bool TestEmptyAMRIterator() { for(int init=0; init<2; init++) { for(int op=0; op<2; op++) { vtkSmartPointer<vtkUniformGridAMR> a = vtkSmartPointer<vtkUniformGridAMR>::New(); if(init==1) { a->Initialize(); } vtkSmartPointer<vtkCompositeDataIterator> iter; iter.TakeReference(a->NewIterator()); iter->SetSkipEmptyNodes(op); int numIteration=0; for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { numIteration++; } if(numIteration!=0) { return false; } } } return true; } //Test converting AMR to a multiblock data structure //and associated APIs bool TestAMRToMultiBlock() { vtkSmartPointer<vtkUniformGridAMR> a = vtkSmartPointer<vtkUniformGridAMR>::New(); int blocksPerLevel[3] = {1,4,9}; a->Initialize(3, blocksPerLevel); for(unsigned int i=0; i<a->GetNumberOfLevels();i++) { for(unsigned int j=0; j<a->GetNumberOfDataSets(i); j++) { vtkSmartPointer<vtkUniformGrid> grid = vtkSmartPointer<vtkUniformGrid>::New(); a->SetDataSet(i,j, grid); } } vtkSmartPointer<vtkMultiBlockDataSet> b= vtkSmartPointer<vtkMultiBlockDataSet>::New(); b->CopyStructure(a); vtkSmartPointer<vtkCompositeDataIterator> aIter; aIter.TakeReference(a->NewIterator()); aIter->SkipEmptyNodesOff(); for (aIter->InitTraversal(); !aIter->IsDoneWithTraversal(); aIter->GoToNextItem()) { b->SetDataSet(aIter, aIter->GetCurrentDataObject()); vtkDataObject* obj = b->GetDataSet(aIter); vtkUniformGrid* grid = vtkUniformGrid::SafeDownCast(obj); if(!grid) { return false; } } unsigned int numBlocks = 0; vtkSmartPointer<vtkCompositeDataIterator> bIter; bIter.TakeReference(b->NewIterator()); aIter->SkipEmptyNodesOff(); for (aIter->InitTraversal(); !aIter->IsDoneWithTraversal(); aIter->GoToNextItem()) { numBlocks++; } if(numBlocks!=a->GetTotalNumberOfBlocks()) { return false; } return true; } //------------------------------------------------------------------------------ int TestCompositeDataSets(int , char *[]) { int errors = 0; errors+= !TestAMRToMultiBlock(); errors+= !TestEmptyAMRIterator(); return( errors ); }
/*========================================================================= Program: Visualization Toolkit Module: TestCompositeDataSets.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkCompositeDataIterator.h" #include "vtkDataObjectTree.h" #include "vtkDataObjectTreeIterator.h" #include "vtkInformation.h" #include "vtkMultiBlockDataSet.h" #include "vtkNew.h" #include "vtkSmartPointer.h" #include "vtkStdString.h" #include "vtkUniformGrid.h" #include "vtkUniformGridAMR.h" #include <iostream> #include <vector> // Test DataObjectTreeIterator-specific methods bool TestDataObjectTreeIterator() { bool ok = true; vtkNew<vtkMultiBlockDataSet> data; int blocksPerLevel[3] = {1,4,9}; std::vector<vtkSmartPointer<vtkMultiBlockDataSet> > blocks; blocks.push_back(data.GetPointer()); unsigned levelStart = 0; unsigned levelEnd = 1; int numLevels = sizeof(blocksPerLevel) / sizeof(blocksPerLevel[0]); int numLeaves = 0; int numNodes = 0; vtkStdString blockName("Rolf"); for (int level = 1; level < numLevels; ++level) { int nblocks=blocksPerLevel[level]; for (unsigned parent = levelStart; parent < levelEnd; ++parent) { blocks[parent]->SetNumberOfBlocks(nblocks); for (int block=0; block < nblocks; ++block, ++numNodes) { if (level == numLevels - 1) { vtkNew<vtkUniformGrid> child; blocks[parent]->SetBlock( block, block % 2 ? NULL : child.GetPointer()); blocks[parent]->GetMetaData(block)->Set( vtkCompositeDataSet::NAME(), blockName.c_str()); ++numLeaves; } else { vtkNew<vtkMultiBlockDataSet> child; blocks[parent]->SetBlock(block, child.GetPointer()); blocks.push_back(child.GetPointer()); } } } levelStart = levelEnd; levelEnd = blocks.size(); } vtkSmartPointer<vtkDataObjectTreeIterator> it; it.TakeReference(data->NewTreeIterator()); int counter; it->VisitOnlyLeavesOn(); it->SkipEmptyNodesOff(); counter = 0; for (it->InitTraversal(); !it->IsDoneWithTraversal(); it->GoToNextItem()) { ++counter; if (blockName != it->GetCurrentMetaData()->Get(vtkCompositeDataSet::NAME())) { cerr << "Unnamed leaf node!\n"; ok = false; } } cout << "Expecting " << numLeaves << " leaf nodes got " << counter << endl;; ok |= counter == numLeaves; it->VisitOnlyLeavesOff(); it->SkipEmptyNodesOff(); counter = 0; for (it->InitTraversal(); !it->IsDoneWithTraversal(); it->GoToNextItem()) { ++counter; } cout << "Expecting " << numNodes << " total nodes got " << counter << endl;; ok |= counter == numNodes; it->VisitOnlyLeavesOff(); it->TraverseSubTreeOff(); it->SkipEmptyNodesOff(); counter = 0; for (it->InitTraversal(); !it->IsDoneWithTraversal(); it->GoToNextItem()) { ++counter; } cout << "Expecting " << blocksPerLevel[1] << " top-level nodes got " << counter << endl;; ok |= counter == blocksPerLevel[1]; return ok; } bool TestEmptyAMRIterator() { for(int init=0; init<2; init++) { for(int op=0; op<2; op++) { vtkSmartPointer<vtkUniformGridAMR> a = vtkSmartPointer<vtkUniformGridAMR>::New(); if(init==1) { a->Initialize(); } vtkSmartPointer<vtkCompositeDataIterator> iter; iter.TakeReference(a->NewIterator()); iter->SetSkipEmptyNodes(op); int numIteration=0; for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { numIteration++; } if(numIteration!=0) { return false; } } } return true; } //Test converting AMR to a multiblock data structure //and associated APIs bool TestAMRToMultiBlock() { vtkSmartPointer<vtkUniformGridAMR> a = vtkSmartPointer<vtkUniformGridAMR>::New(); int blocksPerLevel[3] = {1,4,9}; a->Initialize(3, blocksPerLevel); for(unsigned int i=0; i<a->GetNumberOfLevels();i++) { for(unsigned int j=0; j<a->GetNumberOfDataSets(i); j++) { vtkSmartPointer<vtkUniformGrid> grid = vtkSmartPointer<vtkUniformGrid>::New(); a->SetDataSet(i,j, grid); } } vtkSmartPointer<vtkMultiBlockDataSet> b= vtkSmartPointer<vtkMultiBlockDataSet>::New(); b->CopyStructure(a); vtkSmartPointer<vtkCompositeDataIterator> aIter; aIter.TakeReference(a->NewIterator()); aIter->SkipEmptyNodesOff(); for (aIter->InitTraversal(); !aIter->IsDoneWithTraversal(); aIter->GoToNextItem()) { b->SetDataSet(aIter, aIter->GetCurrentDataObject()); vtkDataObject* obj = b->GetDataSet(aIter); vtkUniformGrid* grid = vtkUniformGrid::SafeDownCast(obj); if(!grid) { return false; } } unsigned int numBlocks = 0; vtkSmartPointer<vtkCompositeDataIterator> bIter; bIter.TakeReference(b->NewIterator()); aIter->SkipEmptyNodesOff(); for (aIter->InitTraversal(); !aIter->IsDoneWithTraversal(); aIter->GoToNextItem()) { numBlocks++; } if(numBlocks!=a->GetTotalNumberOfBlocks()) { return false; } return true; } //------------------------------------------------------------------------------ int TestCompositeDataSets(int , char *[]) { int errors = 0; errors+= !TestDataObjectTreeIterator(); errors+= !TestAMRToMultiBlock(); errors+= !TestEmptyAMRIterator(); return( errors ); }
Make Bill less unhappy; test more.
Make Bill less unhappy; test more. Change-Id: Ib74174d7767a68740acee8a403cc0d7402c6a4dc
C++
bsd-3-clause
johnkit/vtk-dev,jmerkow/VTK,mspark93/VTK,demarle/VTK,hendradarwin/VTK,johnkit/vtk-dev,aashish24/VTK-old,msmolens/VTK,hendradarwin/VTK,SimVascular/VTK,SimVascular/VTK,ashray/VTK-EVM,SimVascular/VTK,aashish24/VTK-old,sankhesh/VTK,SimVascular/VTK,berendkleinhaneveld/VTK,johnkit/vtk-dev,gram526/VTK,jmerkow/VTK,mspark93/VTK,keithroe/vtkoptix,biddisco/VTK,candy7393/VTK,biddisco/VTK,msmolens/VTK,msmolens/VTK,candy7393/VTK,ashray/VTK-EVM,mspark93/VTK,demarle/VTK,SimVascular/VTK,mspark93/VTK,hendradarwin/VTK,keithroe/vtkoptix,gram526/VTK,ashray/VTK-EVM,hendradarwin/VTK,sumedhasingla/VTK,biddisco/VTK,biddisco/VTK,collects/VTK,aashish24/VTK-old,collects/VTK,biddisco/VTK,collects/VTK,gram526/VTK,hendradarwin/VTK,candy7393/VTK,collects/VTK,ashray/VTK-EVM,berendkleinhaneveld/VTK,berendkleinhaneveld/VTK,msmolens/VTK,keithroe/vtkoptix,sankhesh/VTK,candy7393/VTK,collects/VTK,hendradarwin/VTK,demarle/VTK,sumedhasingla/VTK,keithroe/vtkoptix,berendkleinhaneveld/VTK,SimVascular/VTK,sankhesh/VTK,demarle/VTK,msmolens/VTK,sankhesh/VTK,gram526/VTK,sumedhasingla/VTK,jmerkow/VTK,biddisco/VTK,demarle/VTK,biddisco/VTK,sumedhasingla/VTK,hendradarwin/VTK,jmerkow/VTK,sankhesh/VTK,jmerkow/VTK,keithroe/vtkoptix,aashish24/VTK-old,berendkleinhaneveld/VTK,aashish24/VTK-old,keithroe/vtkoptix,ashray/VTK-EVM,demarle/VTK,jmerkow/VTK,berendkleinhaneveld/VTK,candy7393/VTK,sankhesh/VTK,demarle/VTK,mspark93/VTK,keithroe/vtkoptix,sumedhasingla/VTK,mspark93/VTK,candy7393/VTK,ashray/VTK-EVM,sankhesh/VTK,gram526/VTK,candy7393/VTK,johnkit/vtk-dev,gram526/VTK,keithroe/vtkoptix,sumedhasingla/VTK,jmerkow/VTK,SimVascular/VTK,johnkit/vtk-dev,collects/VTK,demarle/VTK,jmerkow/VTK,sumedhasingla/VTK,SimVascular/VTK,sumedhasingla/VTK,candy7393/VTK,gram526/VTK,msmolens/VTK,aashish24/VTK-old,johnkit/vtk-dev,mspark93/VTK,sankhesh/VTK,msmolens/VTK,gram526/VTK,ashray/VTK-EVM,mspark93/VTK,berendkleinhaneveld/VTK,ashray/VTK-EVM,johnkit/vtk-dev,msmolens/VTK
4452ff76b79b3a9acdcd15ba6e751117889db3fb
paddle/fluid/framework/details/op_handle_base.cc
paddle/fluid/framework/details/op_handle_base.cc
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/framework/details/op_handle_base.h" namespace paddle { namespace framework { namespace details { std::string OpHandleBase::DebugString() const { std::stringstream ss; ss << "("; for (auto *var : inputs_) { ss << var->DebugString() << ", "; } ss << ") --> ("; for (auto *var : outputs_) { ss << var->DebugString() << ", "; } ss << ")\n"; return ss.str(); } OpHandleBase::~OpHandleBase() { #ifdef PADDLE_WITH_CUDA for (auto &ev : events_) { PADDLE_ENFORCE(cudaEventDestroy(ev.second)); } #endif } void OpHandleBase::Run(bool use_event) { #ifdef PADDLE_WITH_CUDA if (events_.empty() && use_event) { for (auto &p : dev_ctxes_) { int dev_id = boost::get<platform::CUDAPlace>(p.first).device; PADDLE_ENFORCE(cudaSetDevice(dev_id)); PADDLE_ENFORCE( cudaEventCreateWithFlags(&events_[dev_id], cudaEventDisableTiming)); } } #else PADDLE_ENFORCE(!use_event); #endif RunImpl(); } void OpHandleBase::Wait(platform::DeviceContext *waited_dev) { #ifdef PADDLE_WITH_CUDA if (platform::is_cpu_place(waited_dev->GetPlace()) || events_.empty()) { for (auto &dev_ctx : dev_ctxes_) { dev_ctx.second->Wait(); } } else { auto stream = static_cast<platform::CUDADeviceContext *>(waited_dev)->stream(); for (auto &ev : events_) { PADDLE_ENFORCE(cudaStreamWaitEvent(stream, ev.second, 0)); } } #else for (auto &dev_ctx : dev_ctxes_) { dev_ctx.second->Wait(); } #endif } void OpHandleBase::AddInput(VarHandleBase *in) { this->inputs_.emplace_back(in); in->pending_ops_.insert(this); } void OpHandleBase::AddOutput(VarHandleBase *out) { outputs_.emplace_back(out); out->generated_op_ = this; } void OpHandleBase::RunAndRecordEvent(const std::function<void()> &callback) { #ifdef PADDLE_WITH_CUDA if (!events_.empty()) { // Use event std::function<void()> method = callback; for (auto &p : dev_ctxes_) { method = [method, p, this]() { static_cast<platform::CUDADeviceContext *>(p.second)->RecordEvent( events_.at(boost::get<platform::CUDAPlace>(p.first).device), method); }; } method(); } else { #endif callback(); #ifdef PADDLE_WITH_CUDA } #endif } void OpHandleBase::RunAndRecordEvent(platform::Place p, const std::function<void()> &callback) { if (platform::is_cpu_place(p) || events_.empty()) { callback(); } else { #ifdef PADDLE_WITH_CUDA auto *ctx = dev_ctxes_.at(p); auto *cuda_ctx = static_cast<platform::CUDADeviceContext *>(ctx); cuda_ctx->RecordEvent(events_.at(boost::get<platform::CUDAPlace>(p).device), callback); #else PADDLE_THROW("Not implemented"); #endif } } } // namespace details } // namespace framework } // namespace paddle
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/framework/details/op_handle_base.h" namespace paddle { namespace framework { namespace details { std::string OpHandleBase::DebugString() const { std::stringstream ss; ss << "("; for (auto *var : inputs_) { ss << var->DebugString() << ", "; } ss << ") --> ("; for (auto *var : outputs_) { ss << var->DebugString() << ", "; } ss << ")\n"; return ss.str(); } OpHandleBase::~OpHandleBase() { #ifdef PADDLE_WITH_CUDA for (auto &ev : events_) { PADDLE_ENFORCE(cudaEventDestroy(ev.second)); } #endif } void OpHandleBase::Run(bool use_event) { #ifdef PADDLE_WITH_CUDA if (events_.empty() && use_event) { for (auto &p : dev_ctxes_) { int dev_id = boost::get<platform::CUDAPlace>(p.first).device; PADDLE_ENFORCE(cudaSetDevice(dev_id)); PADDLE_ENFORCE( cudaEventCreateWithFlags(&events_[dev_id], cudaEventDisableTiming)); } } #else PADDLE_ENFORCE(!use_event); #endif RunImpl(); } void OpHandleBase::Wait(platform::DeviceContext *waited_dev) { #ifdef PADDLE_WITH_CUDA if (platform::is_cpu_place(waited_dev->GetPlace()) || events_.empty()) { for (auto &dev_ctx : dev_ctxes_) { dev_ctx.second->Wait(); } } else { auto stream = static_cast<platform::CUDADeviceContext *>(waited_dev)->stream(); for (auto &ev : events_) { PADDLE_ENFORCE(cudaStreamWaitEvent(stream, ev.second, 0)); } } #else for (auto &dev_ctx : dev_ctxes_) { dev_ctx.second->Wait(); } #endif } void OpHandleBase::AddInput(VarHandleBase *in) { this->inputs_.emplace_back(in); in->pending_ops_.insert(this); } void OpHandleBase::AddOutput(VarHandleBase *out) { outputs_.emplace_back(out); out->generated_op_ = this; } void OpHandleBase::RunAndRecordEvent(const std::function<void()> &callback) { #ifdef PADDLE_WITH_CUDA if (!events_.empty()) { // Use event std::function<void()> method = callback; for (auto &p : dev_ctxes_) { method = [method, p, this]() { static_cast<platform::CUDADeviceContext *>(p.second)->RecordEvent( events_.at(boost::get<platform::CUDAPlace>(p.first).device), method); }; } method(); } else { #endif callback(); #ifdef PADDLE_WITH_CUDA } #endif } void OpHandleBase::RunAndRecordEvent(platform::Place p, const std::function<void()> &callback) { #ifdef PADDLE_WITH_CUDA if (platform::is_cpu_place(p) || events_.empty()) { callback(); } else { auto *ctx = dev_ctxes_.at(p); auto *cuda_ctx = static_cast<platform::CUDADeviceContext *>(ctx); cuda_ctx->RecordEvent(events_.at(boost::get<platform::CUDAPlace>(p).device), callback); } #else callback(); #endif } } // namespace details } // namespace framework } // namespace paddle
Fix CPU compile
Fix CPU compile
C++
apache-2.0
chengduoZH/Paddle,chengduoZH/Paddle,putcn/Paddle,baidu/Paddle,jacquesqiao/Paddle,tensor-tang/Paddle,luotao1/Paddle,Canpio/Paddle,reyoung/Paddle,QiJune/Paddle,putcn/Paddle,PaddlePaddle/Paddle,lcy-seso/Paddle,PaddlePaddle/Paddle,pkuyym/Paddle,reyoung/Paddle,PaddlePaddle/Paddle,lcy-seso/Paddle,baidu/Paddle,putcn/Paddle,chengduoZH/Paddle,QiJune/Paddle,QiJune/Paddle,pkuyym/Paddle,Canpio/Paddle,reyoung/Paddle,luotao1/Paddle,Canpio/Paddle,jacquesqiao/Paddle,lcy-seso/Paddle,Canpio/Paddle,reyoung/Paddle,jacquesqiao/Paddle,PaddlePaddle/Paddle,QiJune/Paddle,lcy-seso/Paddle,reyoung/Paddle,luotao1/Paddle,reyoung/Paddle,tensor-tang/Paddle,tensor-tang/Paddle,QiJune/Paddle,jacquesqiao/Paddle,luotao1/Paddle,luotao1/Paddle,pkuyym/Paddle,baidu/Paddle,PaddlePaddle/Paddle,baidu/Paddle,jacquesqiao/Paddle,luotao1/Paddle,putcn/Paddle,putcn/Paddle,pkuyym/Paddle,PaddlePaddle/Paddle,chengduoZH/Paddle,tensor-tang/Paddle,Canpio/Paddle,PaddlePaddle/Paddle,lcy-seso/Paddle,putcn/Paddle,Canpio/Paddle,tensor-tang/Paddle,lcy-seso/Paddle,QiJune/Paddle,pkuyym/Paddle,pkuyym/Paddle,baidu/Paddle,luotao1/Paddle,Canpio/Paddle,jacquesqiao/Paddle,Canpio/Paddle,chengduoZH/Paddle
8845d406a45a0765c6ffb62705568b58a8e61756
wfs-fuse/wfs-fuse.cpp
wfs-fuse/wfs-fuse.cpp
#define FUSE_USE_VERSION 31 #include <fuse.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <stddef.h> #include <assert.h> #include <string> #include <wfslib/WfsLib.h> static std::shared_ptr<Wfs> wfs; static int wfs_getattr(const char *path, struct stat *stbuf) { memset(stbuf, 0, sizeof(struct stat)); auto item = wfs->GetObject(path); if (!item) return -ENOENT; if (item->IsDirectory()) { stbuf->st_mode = S_IFDIR | 0755; stbuf->st_nlink = 2 + std::dynamic_pointer_cast<Directory>(item)->GetItemsCount(); } else if (item->IsLink()) { stbuf->st_mode = S_IFLNK | 0777; stbuf->st_nlink = 1; stbuf->st_size = 0; // TODO } else if (item->IsFile()) { stbuf->st_mode = S_IFREG | 0444; stbuf->st_nlink = 1; stbuf->st_size = std::dynamic_pointer_cast<File>(item)->GetSize(); } else { // Should not happen return -ENOENT; } return 0; } static int wfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { (void) offset; (void) fi; auto item = wfs->GetObject(path); if (!item || !item->IsDirectory()) return -ENOENT; filler(buf, ".", NULL, 0); filler(buf, "..", NULL, 0); for (auto item : *std::dynamic_pointer_cast<Directory>(item)) { filler(buf, item->GetName().c_str(), NULL, 0); } return 0; } static int wfs_open(const char *path, struct fuse_file_info *fi) { if (!wfs->GetObject(path)) return -ENOENT; if ((fi->flags & O_ACCMODE) != O_RDONLY) return -EACCES; return 0; } static int wfs_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { (void) fi; auto item = wfs->GetObject(path); if (!item || !item->IsFile()) return -ENOENT; File::stream stream(std::dynamic_pointer_cast<File>(item)); stream.seekg(offset, stream.beg); stream.read(buf, size); return static_cast<int>(stream.gcount()); } int wfs_readlink(const char *path, char *buf, size_t size) { // TODO auto item = wfs->GetObject(path); if (!item || !item->IsLink()) return -ENOENT; // TODO return -ENOENT; } static const char *usage = "usage: wfs-fuse <device_file> <mountpoint> --otp <otp_path> [--seeprom <seeprom_path>] [--usb] [--mlc] [fuse options]\n" "\n" "options:\n" " --help|-h print this help message\n" " --otp <path> otp file\n" " --seeprom <path> seeprom file (required if usb)\n" " --usb device is usb (default)\n" " --mlc device is mlc\n" " -d -o debug enable debug output (implies -f)\n" " -o default_permissions check access permission instead the operation system\n" " -o allow_other allow access to the mount for all users\n" " -f foreground operation\n" " -s disable multi-threaded operation\n" "\n"; struct wfs_param { char *file; char *otp; char *seeprom; int is_usb; int is_mlc; int is_help; }; #define WFS_OPT(t, p) { t, offsetof(struct wfs_param, p), 1 } static const struct fuse_opt wfs_opts[] = { WFS_OPT("--otp %s", otp), WFS_OPT("--seeprom %s", seeprom), WFS_OPT("--usb", is_usb), WFS_OPT("--mlc", is_mlc), FUSE_OPT_KEY("-h", 0), FUSE_OPT_KEY("--help", 0), FUSE_OPT_END }; static int wfs_process_arg(void *data, const char *arg, int key, struct fuse_args *outargs) { struct wfs_param *param = static_cast<wfs_param*>(data); (void)outargs; (void)arg; switch (key) { case 0: param->is_help = 1; fprintf(stderr, "%s", usage); return fuse_opt_add_arg(outargs, "-ho"); case FUSE_OPT_KEY_NONOPT: if( !param->file ) { param->file = strdup(arg); return 0; } return 1; default: return 1; } } int main(int argc, char *argv[]) { struct fuse_args args = FUSE_ARGS_INIT(argc, argv); struct wfs_param param = { NULL, NULL, NULL, 0, 0, 0 }; if (argc < 3) { fprintf(stderr, "%s", usage); return 1; } if (fuse_opt_parse(&args, &param, wfs_opts, wfs_process_arg)) { printf("failed to parse option\n"); return 1; } if (param.is_help) { return 0; } if (!param.otp) { printf("Missing otp file (--otp)\n"); return 1; } if (!param.is_mlc && !param.seeprom) { printf("Missing seeprom file (--seeprom)\n"); return 1; } if (param.is_usb && param.is_mlc) { printf("Can't specify both --mlc and --usb\n"); return 1; } try { std::vector<uint8_t> key; std::unique_ptr<OTP> otp; // open otp try { otp.reset(OTP::LoadFromFile(param.otp)); } catch (std::exception& e) { std::cerr << "Failed to open OTP: " << e.what() << std::endl; return 1; } if (param.is_mlc) { // mlc key = otp->GetMLCKey(); } else { // usb std::unique_ptr<SEEPROM> seeprom; try { seeprom.reset(SEEPROM::LoadFromFile(param.seeprom)); } catch (std::exception& e) { std::cerr << "Failed to open SEEPROM: " << e.what() << std::endl; return 1; } key = seeprom->GetUSBKey(*otp); } auto device = std::make_shared<FileDevice>(param.file, 9); Wfs::DetectDeviceSectorSizeAndCount(device, key); wfs.reset(new Wfs(device, key)); } catch (std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } struct fuse_operations wfs_oper = {0}; wfs_oper.getattr = wfs_getattr; wfs_oper.readdir = wfs_readdir; wfs_oper.open = wfs_open; wfs_oper.read = wfs_read; wfs_oper.readlink = wfs_readlink; return fuse_main(args.argc, args.argv, &wfs_oper, NULL); }
#define FUSE_USE_VERSION 31 #include <fuse.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <stddef.h> #include <assert.h> #include <string> #include <mutex> #include <wfslib/WfsLib.h> static std::shared_ptr<Wfs> wfs; struct locked_stream { std::unique_ptr<File::stream> stream; std::mutex lock; }; static int wfs_getattr(const char *path, struct stat *stbuf) { memset(stbuf, 0, sizeof(struct stat)); auto item = wfs->GetObject(path); if (!item) return -ENOENT; if (item->IsDirectory()) { stbuf->st_mode = S_IFDIR | 0755; stbuf->st_nlink = 2 + std::dynamic_pointer_cast<Directory>(item)->GetItemsCount(); } else if (item->IsLink()) { stbuf->st_mode = S_IFLNK | 0777; stbuf->st_nlink = 1; stbuf->st_size = 0; // TODO } else if (item->IsFile()) { stbuf->st_mode = S_IFREG | 0444; stbuf->st_nlink = 1; stbuf->st_size = std::dynamic_pointer_cast<File>(item)->GetSize(); } else { // Should not happen return -ENOENT; } return 0; } static int wfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { (void) offset; (void) fi; auto item = wfs->GetObject(path); if (!item || !item->IsDirectory()) return -ENOENT; filler(buf, ".", NULL, 0); filler(buf, "..", NULL, 0); for (auto item : *std::dynamic_pointer_cast<Directory>(item)) { filler(buf, item->GetName().c_str(), NULL, 0); } return 0; } static int wfs_open(const char *path, struct fuse_file_info *fi) { auto item = wfs->GetObject(path); if (!item->IsFile()) return -ENOENT; if ((fi->flags & O_ACCMODE) != O_RDONLY) return -EACCES; fi->fh = reinterpret_cast<uint64_t>(new locked_stream { std::unique_ptr<File::stream>(new File::stream(std::dynamic_pointer_cast<File>(item))) }); return 0; } static int wfs_release(const char *path, struct fuse_file_info *fi) { (void) path; delete reinterpret_cast<locked_stream *>(fi->fh); return 0; } static int wfs_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { (void) path; auto stream = reinterpret_cast<locked_stream *>(fi->fh); std::lock_guard<std::mutex> guard(stream->lock); stream->stream->seekg(offset, stream->stream->beg); stream->stream->read(buf, size); return static_cast<int>(stream->stream->gcount()); } int wfs_readlink(const char *path, char *buf, size_t size) { // TODO auto item = wfs->GetObject(path); if (!item || !item->IsLink()) return -ENOENT; // TODO return -ENOENT; } static const char *usage = "usage: wfs-fuse <device_file> <mountpoint> --otp <otp_path> [--seeprom <seeprom_path>] [--usb] [--mlc] [fuse options]\n" "\n" "options:\n" " --help|-h print this help message\n" " --otp <path> otp file\n" " --seeprom <path> seeprom file (required if usb)\n" " --usb device is usb (default)\n" " --mlc device is mlc\n" " -d -o debug enable debug output (implies -f)\n" " -o default_permissions check access permission instead the operation system\n" " -o allow_other allow access to the mount for all users\n" " -f foreground operation\n" " -s disable multi-threaded operation\n" "\n"; struct wfs_param { char *file; char *otp; char *seeprom; int is_usb; int is_mlc; int is_help; }; #define WFS_OPT(t, p) { t, offsetof(struct wfs_param, p), 1 } static const struct fuse_opt wfs_opts[] = { WFS_OPT("--otp %s", otp), WFS_OPT("--seeprom %s", seeprom), WFS_OPT("--usb", is_usb), WFS_OPT("--mlc", is_mlc), FUSE_OPT_KEY("-h", 0), FUSE_OPT_KEY("--help", 0), FUSE_OPT_END }; static int wfs_process_arg(void *data, const char *arg, int key, struct fuse_args *outargs) { struct wfs_param *param = static_cast<wfs_param*>(data); (void)outargs; (void)arg; switch (key) { case 0: param->is_help = 1; fprintf(stderr, "%s", usage); return fuse_opt_add_arg(outargs, "-ho"); case FUSE_OPT_KEY_NONOPT: if( !param->file ) { param->file = strdup(arg); return 0; } return 1; default: return 1; } } int main(int argc, char *argv[]) { struct fuse_args args = FUSE_ARGS_INIT(argc, argv); struct wfs_param param = { NULL, NULL, NULL, 0, 0, 0 }; if (argc < 3) { fprintf(stderr, "%s", usage); return 1; } if (fuse_opt_parse(&args, &param, wfs_opts, wfs_process_arg)) { printf("failed to parse option\n"); return 1; } if (param.is_help) { return 0; } if (!param.otp) { printf("Missing otp file (--otp)\n"); return 1; } if (!param.is_mlc && !param.seeprom) { printf("Missing seeprom file (--seeprom)\n"); return 1; } if (param.is_usb && param.is_mlc) { printf("Can't specify both --mlc and --usb\n"); return 1; } try { std::vector<uint8_t> key; std::unique_ptr<OTP> otp; // open otp try { otp.reset(OTP::LoadFromFile(param.otp)); } catch (std::exception& e) { std::cerr << "Failed to open OTP: " << e.what() << std::endl; return 1; } if (param.is_mlc) { // mlc key = otp->GetMLCKey(); } else { // usb std::unique_ptr<SEEPROM> seeprom; try { seeprom.reset(SEEPROM::LoadFromFile(param.seeprom)); } catch (std::exception& e) { std::cerr << "Failed to open SEEPROM: " << e.what() << std::endl; return 1; } key = seeprom->GetUSBKey(*otp); } auto device = std::make_shared<FileDevice>(param.file, 9); Wfs::DetectDeviceSectorSizeAndCount(device, key); wfs.reset(new Wfs(device, key)); } catch (std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } struct fuse_operations wfs_oper = {0}; wfs_oper.getattr = wfs_getattr; wfs_oper.readdir = wfs_readdir; wfs_oper.open = wfs_open; wfs_oper.release = wfs_release; wfs_oper.read = wfs_read; wfs_oper.readlink = wfs_readlink; return fuse_main(args.argc, args.argv, &wfs_oper, NULL); }
Create the file stream on file opening (much faster reading)
wfs-fuse: Create the file stream on file opening (much faster reading)
C++
mit
koolkdev/wfslib,koolkdev/wfslib
9c67381dbc48e9814fc05d6b38065069fe3307f9
gm/strokerect.cpp
gm/strokerect.cpp
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkPath.h" #define STROKE_WIDTH SkIntToScalar(20) static void draw_path(SkCanvas* canvas, const SkPath& path, const SkRect& rect, SkPaint::Join join, int doFill) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(doFill ? SkPaint::kStrokeAndFill_Style : SkPaint::kStroke_Style); paint.setColor(sk_tool_utils::color_to_565(SK_ColorGRAY)); paint.setStrokeWidth(STROKE_WIDTH); paint.setStrokeJoin(join); canvas->drawRect(rect, paint); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(0); paint.setColor(SK_ColorRED); canvas->drawPath(path, paint); paint.setStrokeWidth(3); paint.setStrokeJoin(SkPaint::kMiter_Join); int n = path.countPoints(); SkAutoTArray<SkPoint> points(n); path.getPoints(points.get(), n); canvas->drawPoints(SkCanvas::kPoints_PointMode, n, points.get(), paint); } /* * Test calling SkStroker for rectangles. Cases to cover: * * geometry: normal, small (smaller than stroke-width), empty, inverted * joint-type for the corners */ class StrokeRectGM : public skiagm::GM { public: StrokeRectGM() {} protected: SkString onShortName() override { return SkString("strokerect"); } SkISize onISize() override { return SkISize::Make(1024, 740); } void onDraw(SkCanvas* canvas) override { canvas->drawColor(SK_ColorWHITE); canvas->translate(STROKE_WIDTH*3/2, STROKE_WIDTH*3/2); SkPaint paint; paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(STROKE_WIDTH); static const SkPaint::Join gJoins[] = { SkPaint::kMiter_Join, SkPaint::kRound_Join, SkPaint::kBevel_Join }; static const SkScalar W = 80; static const SkScalar H = 80; static const SkRect gRects[] = { { 0, 0, W, H }, { W, 0, 0, H }, { 0, H, W, 0 }, { 0, 0, STROKE_WIDTH, H }, { 0, 0, W, STROKE_WIDTH }, { 0, 0, STROKE_WIDTH/2, STROKE_WIDTH/2 }, { 0, 0, W, 0 }, { 0, 0, 0, H }, { 0, 0, 0, 0 }, { 0, 0, W, FLT_EPSILON }, { 0, 0, FLT_EPSILON, H }, { 0, 0, FLT_EPSILON, FLT_EPSILON }, }; for (int doFill = 0; doFill <= 1; ++doFill) { for (size_t i = 0; i < SK_ARRAY_COUNT(gJoins); ++i) { SkPaint::Join join = gJoins[i]; paint.setStrokeJoin(join); SkAutoCanvasRestore acr(canvas, true); for (size_t j = 0; j < SK_ARRAY_COUNT(gRects); ++j) { const SkRect& r = gRects[j]; SkPath path, fillPath; path.addRect(r); paint.getFillPath(path, &fillPath); draw_path(canvas, fillPath, r, join, doFill); canvas->translate(W + 2 * STROKE_WIDTH, 0); } acr.restore(); canvas->translate(0, H + 2 * STROKE_WIDTH); } paint.setStyle(SkPaint::kStrokeAndFill_Style); } } private: typedef GM INHERITED; }; DEF_GM(return new StrokeRectGM;) /////////////////////////////////////////////////////////////////////////////////////////////////// /* * Exercise rect-stroking (which is specialized from paths) when the resulting stroke-width is * non-square. See https://bugs.chromium.org/p/skia/issues/detail?id=5408 */ DEF_SIMPLE_GM(strokerect_anisotropic_5408, canvas, 200, 50) { SkPaint p; p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(6); canvas->scale(10, 1); SkRect r = SkRect::MakeXYWH(5, 20, 10, 10); canvas->drawRect(r, p); }
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkPath.h" #define STROKE_WIDTH SkIntToScalar(20) static void draw_path(SkCanvas* canvas, const SkPath& path, const SkRect& rect, SkPaint::Join join, int doFill) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(doFill ? SkPaint::kStrokeAndFill_Style : SkPaint::kStroke_Style); paint.setColor(sk_tool_utils::color_to_565(SK_ColorGRAY)); paint.setStrokeWidth(STROKE_WIDTH); paint.setStrokeJoin(join); canvas->drawRect(rect, paint); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(0); paint.setColor(SK_ColorRED); canvas->drawPath(path, paint); paint.setStrokeWidth(3); paint.setStrokeJoin(SkPaint::kMiter_Join); int n = path.countPoints(); SkAutoTArray<SkPoint> points(n); path.getPoints(points.get(), n); canvas->drawPoints(SkCanvas::kPoints_PointMode, n, points.get(), paint); } /* * Test calling SkStroker for rectangles. Cases to cover: * * geometry: normal, small (smaller than stroke-width), empty, inverted * joint-type for the corners */ class StrokeRectGM : public skiagm::GM { public: StrokeRectGM() {} protected: SkString onShortName() override { return SkString("strokerect"); } SkISize onISize() override { return SkISize::Make(1400, 740); } void onDraw(SkCanvas* canvas) override { canvas->drawColor(SK_ColorWHITE); canvas->translate(STROKE_WIDTH*3/2, STROKE_WIDTH*3/2); SkPaint paint; paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(STROKE_WIDTH); static const SkPaint::Join gJoins[] = { SkPaint::kMiter_Join, SkPaint::kRound_Join, SkPaint::kBevel_Join }; static const SkScalar W = 80; static const SkScalar H = 80; static const SkRect gRects[] = { { 0, 0, W, H }, { W, 0, 0, H }, { 0, H, W, 0 }, { 0, 0, STROKE_WIDTH, H }, { 0, 0, W, STROKE_WIDTH }, { 0, 0, STROKE_WIDTH/2, STROKE_WIDTH/2 }, { 0, 0, W, 0 }, { 0, 0, 0, H }, { 0, 0, 0, 0 }, { 0, 0, W, FLT_EPSILON }, { 0, 0, FLT_EPSILON, H }, { 0, 0, FLT_EPSILON, FLT_EPSILON }, }; for (int doFill = 0; doFill <= 1; ++doFill) { for (size_t i = 0; i < SK_ARRAY_COUNT(gJoins); ++i) { SkPaint::Join join = gJoins[i]; paint.setStrokeJoin(join); SkAutoCanvasRestore acr(canvas, true); for (size_t j = 0; j < SK_ARRAY_COUNT(gRects); ++j) { const SkRect& r = gRects[j]; SkPath path, fillPath; path.addRect(r); paint.getFillPath(path, &fillPath); draw_path(canvas, fillPath, r, join, doFill); canvas->translate(W + 2 * STROKE_WIDTH, 0); } acr.restore(); canvas->translate(0, H + 2 * STROKE_WIDTH); } paint.setStyle(SkPaint::kStrokeAndFill_Style); } } private: typedef GM INHERITED; }; DEF_GM(return new StrokeRectGM;) /////////////////////////////////////////////////////////////////////////////////////////////////// /* * Exercise rect-stroking (which is specialized from paths) when the resulting stroke-width is * non-square. See https://bugs.chromium.org/p/skia/issues/detail?id=5408 */ DEF_SIMPLE_GM(strokerect_anisotropic_5408, canvas, 200, 50) { SkPaint p; p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(6); canvas->scale(10, 1); SkRect r = SkRect::MakeXYWH(5, 20, 10, 10); canvas->drawRect(r, p); }
Enlarge strokerect GM size to reveal hidden content GOLD_TRYBOT_URL= https://gold.skia.org/search?issue=2126723002
Enlarge strokerect GM size to reveal hidden content GOLD_TRYBOT_URL= https://gold.skia.org/search?issue=2126723002 Review-Url: https://codereview.chromium.org/2126723002
C++
bsd-3-clause
Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,rubenvb/skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,google/skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,google/skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,google/skia,HalCanary/skia-hc,rubenvb/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,google/skia,google/skia,rubenvb/skia,google/skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,google/skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,google/skia,HalCanary/skia-hc,rubenvb/skia,rubenvb/skia,aosp-mirror/platform_external_skia,google/skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,rubenvb/skia,HalCanary/skia-hc,rubenvb/skia,google/skia
c85a337fe2c6d883b0102c21dac358d0e952407c
x_client.cpp
x_client.cpp
#include "x_client.hpp" x_client::x_client(x_connection & c, const xcb_window_t & window) : _c(c), _window(window) { _c.register_handler(XCB_CONFIGURE_NOTIFY, this); _c.update_input(_window, XCB_EVENT_MASK_STRUCTURE_NOTIFY); update_geometry(); get_net_wm_desktop(); update_parent_window(); update_name_window_pixmap(); } x_client::~x_client(void) { _c.deregister_handler(XCB_CONFIGURE_NOTIFY, this); } rectangle & x_client::rect(void) { return _rectangle; } const rectangle & x_client::rect(void) const { return _rectangle; } xcb_window_t & x_client::window(void) { return _window; } const xcb_window_t & x_client::window(void) const { return _window; } xcb_window_t & x_client::parent(void) { return _parent; } const xcb_window_t & x_client::parent(void) const { return _parent; } xcb_window_t & x_client::name_window_pixmap(void) { return _name_window_pixmap; } const xcb_window_t & x_client::name_window_pixmap(void) const { return _name_window_pixmap; } unsigned int x_client::net_wm_desktop(void) const { return _net_wm_desktop; } void x_client::update_geometry(void) { xcb_get_geometry_reply_t * geometry_reply = xcb_get_geometry_reply(_c(), xcb_get_geometry(_c(), _window), NULL); _rectangle.x() = geometry_reply->x; _rectangle.y() = geometry_reply->y; _rectangle.width() = geometry_reply->width; _rectangle.height() = geometry_reply->height; delete geometry_reply; } bool x_client::handle(xcb_generic_event_t * ge) { if (XCB_CONFIGURE_NOTIFY == (ge->response_type & ~0x80)) { xcb_configure_notify_event_t * e = (xcb_configure_notify_event_t *)ge; if (e->window == _window) { _rectangle.x() = e->x; _rectangle.y() = e->y; _rectangle.width() = e->width; _rectangle.height() = e->height; } if (e->window == _c.root_window() || e->window == _window) { update_parent_window(); update_name_window_pixmap(); } return true; } return false; } // private void x_client::get_net_wm_desktop(void) { std::string atom_name = "_NET_WM_DESKTOP"; xcb_intern_atom_cookie_t atom_cookie = xcb_intern_atom(_c(), false, atom_name.length(), atom_name.c_str()); xcb_intern_atom_reply_t * atom_reply = xcb_intern_atom_reply(_c(), atom_cookie, NULL); xcb_get_property_cookie_t property_cookie = xcb_get_property(_c(), false, _window, atom_reply->atom, XCB_ATOM_CARDINAL, 0, 32); delete atom_reply; xcb_generic_error_t * error = NULL; xcb_get_property_reply_t * property_reply = xcb_get_property_reply(_c(), property_cookie, &error); if (error || property_reply->value_len == 0) { delete error; _net_wm_desktop = 0; } else { _net_wm_desktop = *(unsigned int *)xcb_get_property_value(property_reply); } delete property_reply; } void x_client::update_parent_window(void) { xcb_window_t next_parent = _window; while (next_parent != _c.root_window() && next_parent != XCB_NONE) { _parent = next_parent; next_parent = std::get<0>(_c.query_tree(next_parent)); } } void x_client::update_name_window_pixmap(void) { xcb_free_pixmap(_c(), _name_window_pixmap); _name_window_pixmap = xcb_generate_id(_c()); xcb_void_cookie_t c = xcb_composite_name_window_pixmap_checked( _c(), _parent, _name_window_pixmap); xcb_generic_error_t * e = xcb_request_check(_c(), c); if (e) { delete e; _name_window_pixmap = XCB_NONE; } } // free functions std::list<x_client> make_x_clients(x_connection & c, const std::vector<xcb_window_t> & windows) { std::list<x_client> x_clients; for (auto & window : windows) { x_clients.emplace_back(c, window); } return x_clients; } bool operator==(const x_client & x_client, const xcb_window_t & window) { return x_client._window == window; } bool operator==(const xcb_window_t & window, const x_client & x_client) { return x_client == window; }
#include "x_client.hpp" x_client::x_client(x_connection & c, const xcb_window_t & window) : _c(c), _window(window) { _c.register_handler(XCB_CONFIGURE_NOTIFY, this); _c.update_input(_window, XCB_EVENT_MASK_STRUCTURE_NOTIFY); update_geometry(); get_net_wm_desktop(); update_parent_window(); update_name_window_pixmap(); } x_client::~x_client(void) { _c.deregister_handler(XCB_CONFIGURE_NOTIFY, this); } rectangle & x_client::rect(void) { return _rectangle; } const rectangle & x_client::rect(void) const { return _rectangle; } xcb_window_t & x_client::window(void) { return _window; } const xcb_window_t & x_client::window(void) const { return _window; } xcb_window_t & x_client::parent(void) { return _parent; } const xcb_window_t & x_client::parent(void) const { return _parent; } xcb_window_t & x_client::name_window_pixmap(void) { return _name_window_pixmap; } const xcb_window_t & x_client::name_window_pixmap(void) const { return _name_window_pixmap; } unsigned int x_client::net_wm_desktop(void) const { return _net_wm_desktop; } void x_client::update_geometry(void) { xcb_get_geometry_reply_t * geometry_reply = xcb_get_geometry_reply(_c(), xcb_get_geometry(_c(), _window), NULL); _rectangle.x() = geometry_reply->x; _rectangle.y() = geometry_reply->y; _rectangle.width() = geometry_reply->width; _rectangle.height() = geometry_reply->height; delete geometry_reply; } bool x_client::handle(xcb_generic_event_t * ge) { if (XCB_CONFIGURE_NOTIFY == (ge->response_type & ~0x80)) { xcb_configure_notify_event_t * e = (xcb_configure_notify_event_t *)ge; if (e->window == _window) { _rectangle.x() = e->x; _rectangle.y() = e->y; _rectangle.width() = e->width; _rectangle.height() = e->height; } if (e->window == _c.root_window() || e->window == _window) { update_parent_window(); update_name_window_pixmap(); } return true; } return false; } // private void x_client::get_net_wm_desktop(void) { std::string atom_name = "_NET_WM_DESKTOP"; xcb_intern_atom_cookie_t atom_cookie = xcb_intern_atom(_c(), false, atom_name.length(), atom_name.c_str()); xcb_intern_atom_reply_t * atom_reply = xcb_intern_atom_reply(_c(), atom_cookie, NULL); xcb_get_property_cookie_t property_cookie = xcb_get_property(_c(), false, _window, atom_reply->atom, XCB_ATOM_CARDINAL, 0, 32); delete atom_reply; xcb_generic_error_t * error = NULL; xcb_get_property_reply_t * property_reply = xcb_get_property_reply(_c(), property_cookie, &error); if (error || property_reply->value_len == 0) { delete error; _net_wm_desktop = 0; } else { _net_wm_desktop = *(unsigned int *)xcb_get_property_value(property_reply); } delete property_reply; } void x_client::update_parent_window(void) { xcb_window_t next_parent = _window; while (next_parent != _c.root_window() && next_parent != XCB_NONE) { _parent = next_parent; next_parent = std::get<0>(_c.query_tree(next_parent)); } } void x_client::update_name_window_pixmap(void) { xcb_free_pixmap(_c(), _name_window_pixmap); _name_window_pixmap = xcb_generate_id(_c()); xcb_void_cookie_t c = xcb_composite_name_window_pixmap_checked( _c(), _parent, _name_window_pixmap); xcb_generic_error_t * error = xcb_request_check(_c(), c); if (error) { delete error; _name_window_pixmap = XCB_NONE; } } // free functions std::list<x_client> make_x_clients(x_connection & c, const std::vector<xcb_window_t> & windows) { std::list<x_client> x_clients; for (auto & window : windows) { x_clients.emplace_back(c, window); } return x_clients; } bool operator==(const x_client & x_client, const xcb_window_t & window) { return x_client._window == window; } bool operator==(const xcb_window_t & window, const x_client & x_client) { return x_client == window; }
Rename variable
Rename variable
C++
bsd-3-clause
jotrk/x-choyce,jotrk/x-choyce
a42ed48e843bd9a4300b9bceaabbe00db92234f0
gm/ycbcrimage.cpp
gm/ycbcrimage.cpp
/* * Copyright 2020 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm/gm.h" // This test only works with the Vulkan backend. #ifdef SK_VULKAN #include "include/core/SkCanvas.h" #include "include/core/SkImage.h" #include "include/core/SkPaint.h" #include "include/core/SkSize.h" #include "include/core/SkString.h" #include "include/gpu/GrDirectContext.h" #include "tools/gpu/vk/VkYcbcrSamplerHelper.h" static void release_ycbcrhelper(void* releaseContext) { VkYcbcrSamplerHelper* ycbcrHelper = reinterpret_cast<VkYcbcrSamplerHelper*>(releaseContext); delete ycbcrHelper; } namespace skiagm { // This GM exercises the native YCbCr image format on Vulkan class YCbCrImageGM : public GpuGM { public: YCbCrImageGM() { this->setBGColor(0xFFCCCCCC); } protected: SkString onShortName() override { return SkString("ycbcrimage"); } SkISize onISize() override { return SkISize::Make(2*kPad+kImageSize, 2*kPad+kImageSize); } DrawResult createYCbCrImage(GrDirectContext* dContext, SkString* errorMsg) { std::unique_ptr<VkYcbcrSamplerHelper> ycbcrHelper(new VkYcbcrSamplerHelper(dContext)); if (!ycbcrHelper->isYCbCrSupported()) { *errorMsg = "YCbCr sampling not supported."; return skiagm::DrawResult::kSkip; } if (!ycbcrHelper->createBackendTexture(kImageSize, kImageSize)) { *errorMsg = "Failed to create I420 backend texture."; return skiagm::DrawResult::kFail; } SkASSERT(!fYCbCrImage); fYCbCrImage = SkImage::MakeFromTexture(dContext, ycbcrHelper->backendTexture(), kTopLeft_GrSurfaceOrigin, kRGB_888x_SkColorType, kPremul_SkAlphaType, nullptr, release_ycbcrhelper, ycbcrHelper.get()); if (!fYCbCrImage) { *errorMsg = "Failed to create I420 image."; return DrawResult::kFail; } ycbcrHelper.release(); return DrawResult::kOk; } DrawResult onGpuSetup(GrDirectContext* context, SkString* errorMsg) override { if (!context || context->abandoned()) { return DrawResult::kSkip; } if (context->backend() != GrBackendApi::kVulkan) { *errorMsg = "This GM requires a Vulkan context."; return DrawResult::kSkip; } DrawResult result = this->createYCbCrImage(context, errorMsg); if (result != DrawResult::kOk) { return result; } return DrawResult::kOk; } void onGpuTeardown() override { fYCbCrImage = nullptr; } DrawResult onDraw(GrRecordingContext*, GrSurfaceDrawContext*, SkCanvas* canvas, SkString*) override { SkASSERT(fYCbCrImage); canvas->drawImage(fYCbCrImage, kPad, kPad, SkSamplingOptions(SkFilterMode::kLinear)); return DrawResult::kOk; } private: static const int kImageSize = 112; static const int kPad = 8; sk_sp<SkImage> fYCbCrImage; using INHERITED = GpuGM; }; ////////////////////////////////////////////////////////////////////////////// DEF_GM(return new YCbCrImageGM;) } // namespace skiagm #endif // SK_VULKAN
/* * Copyright 2020 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm/gm.h" // This test only works with the Vulkan backend. #ifdef SK_VULKAN #include "include/core/SkCanvas.h" #include "include/core/SkImage.h" #include "include/core/SkPaint.h" #include "include/core/SkSize.h" #include "include/core/SkString.h" #include "include/gpu/GrDirectContext.h" #include "tools/gpu/vk/VkYcbcrSamplerHelper.h" static void release_ycbcrhelper(void* releaseContext) { VkYcbcrSamplerHelper* ycbcrHelper = reinterpret_cast<VkYcbcrSamplerHelper*>(releaseContext); delete ycbcrHelper; } namespace skiagm { // This GM exercises the native YCbCr image format on Vulkan class YCbCrImageGM : public GpuGM { public: YCbCrImageGM() { this->setBGColor(0xFFCCCCCC); } protected: SkString onShortName() override { return SkString("ycbcrimage"); } SkISize onISize() override { return SkISize::Make(2*kPad+kImageSize, 2*kPad+kImageSize); } DrawResult createYCbCrImage(GrDirectContext* dContext, SkString* errorMsg) { std::unique_ptr<VkYcbcrSamplerHelper> ycbcrHelper(new VkYcbcrSamplerHelper(dContext)); if (!ycbcrHelper->isYCbCrSupported()) { *errorMsg = "YCbCr sampling not supported."; return skiagm::DrawResult::kSkip; } if (!ycbcrHelper->createBackendTexture(kImageSize, kImageSize)) { *errorMsg = "Failed to create I420 backend texture."; return skiagm::DrawResult::kFail; } SkASSERT(!fYCbCrImage); fYCbCrImage = SkImage::MakeFromTexture(dContext, ycbcrHelper->backendTexture(), kTopLeft_GrSurfaceOrigin, kRGB_888x_SkColorType, kPremul_SkAlphaType, nullptr, release_ycbcrhelper, ycbcrHelper.get()); ycbcrHelper.release(); if (!fYCbCrImage) { *errorMsg = "Failed to create I420 image."; return DrawResult::kFail; } return DrawResult::kOk; } DrawResult onGpuSetup(GrDirectContext* context, SkString* errorMsg) override { if (!context || context->abandoned()) { return DrawResult::kSkip; } if (context->backend() != GrBackendApi::kVulkan) { *errorMsg = "This GM requires a Vulkan context."; return DrawResult::kSkip; } DrawResult result = this->createYCbCrImage(context, errorMsg); if (result != DrawResult::kOk) { return result; } return DrawResult::kOk; } void onGpuTeardown() override { fYCbCrImage = nullptr; } DrawResult onDraw(GrRecordingContext*, GrSurfaceDrawContext*, SkCanvas* canvas, SkString*) override { SkASSERT(fYCbCrImage); canvas->drawImage(fYCbCrImage, kPad, kPad, SkSamplingOptions(SkFilterMode::kLinear)); return DrawResult::kOk; } private: static const int kImageSize = 112; static const int kPad = 8; sk_sp<SkImage> fYCbCrImage; using INHERITED = GpuGM; }; ////////////////////////////////////////////////////////////////////////////// DEF_GM(return new YCbCrImageGM;) } // namespace skiagm #endif // SK_VULKAN
Fix a double free problem in YCbCrImageGM::createYCbCrImage()
Fix a double free problem in YCbCrImageGM::createYCbCrImage() If SkImage::MakeFromTexture() fails, the reelase_ycbcrhelper will also be called, so ycbcrHelper.release() should be always called. Change-Id: I104e02155da653bcb465723cbead595f16459fca Reviewed-on: https://skia-review.googlesource.com/c/skia/+/379848 Commit-Queue: Peng Huang <[email protected]> Commit-Queue: Brian Salomon <[email protected]> Reviewed-by: Brian Salomon <[email protected]>
C++
bsd-3-clause
google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,google/skia,google/skia,google/skia,aosp-mirror/platform_external_skia,google/skia,google/skia,aosp-mirror/platform_external_skia,google/skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia
acc2e2ad6d229af016e4b6030763950d268f5417
sql/sql_db.cc
sql/sql_db.cc
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* create and drop of databases */ #include "mysql_priv.h" #include "sql_acl.h" #include <my_dir.h> #include <m_ctype.h> #ifdef __WIN__ #include <direct.h> #endif static long mysql_rm_known_files(THD *thd, MY_DIR *dirp, const char *db, const char *path, uint level); /* db-name is already validated when we come here */ int mysql_create_db(THD *thd, char *db, uint create_options, bool silent) { char path[FN_REFLEN+16]; MY_DIR *dirp; long result=1; int error = 0; DBUG_ENTER("mysql_create_db"); VOID(pthread_mutex_lock(&LOCK_mysql_create_db)); // do not create database if another thread is holding read lock if (wait_if_global_read_lock(thd,0)) { error= -1; goto exit2; } /* Check directory */ (void)sprintf(path,"%s/%s", mysql_data_home, db); unpack_dirname(path,path); // Convert if not unix if ((dirp = my_dir(path,MYF(MY_DONT_SORT)))) { my_dirend(dirp); if (!(create_options & HA_LEX_CREATE_IF_NOT_EXISTS)) { my_error(ER_DB_CREATE_EXISTS,MYF(0),db); error = -1; goto exit; } result = 0; } else { strend(path)[-1]=0; // Remove last '/' from path if (my_mkdir(path,0777,MYF(0)) < 0) { my_error(ER_CANT_CREATE_DB,MYF(0),db,my_errno); error = -1; goto exit; } } if (!silent) { if (!thd->query) { thd->query = path; thd->query_length = (uint) (strxmov(path,"create database ", db, NullS)- path); } { mysql_update_log.write(thd,thd->query, thd->query_length); if (mysql_bin_log.is_open()) { Query_log_event qinfo(thd, thd->query); mysql_bin_log.write(&qinfo); } } if (thd->query == path) { thd->query = 0; // just in case thd->query_length = 0; } send_ok(&thd->net, result); } exit: start_waiting_global_read_lock(thd); exit2: VOID(pthread_mutex_unlock(&LOCK_mysql_create_db)); DBUG_RETURN(error); } const char *del_exts[]= {".frm", ".BAK", NullS}; static TYPELIB deletable_extentions= {array_elements(del_exts)-1,"del_exts", del_exts}; const char *known_exts[]= {".ISM",".ISD",".ISM",".MRG",".MYI",".MYD", ".db", NullS}; static TYPELIB known_extentions= {array_elements(del_exts)-1,"del_exts", known_exts}; /* Drop all tables in a database. db-name is already validated when we come here If thd == 0, do not write any messages; This is useful in replication when we want to remove a stale database before replacing it with the new one */ int mysql_rm_db(THD *thd,char *db,bool if_exists, bool silent) { long deleted=0; int error = 0; char path[FN_REFLEN+16]; MY_DIR *dirp; DBUG_ENTER("mysql_rm_db"); VOID(pthread_mutex_lock(&LOCK_mysql_create_db)); // do not drop database if another thread is holding read lock if (wait_if_global_read_lock(thd,0)) { error= -1; goto exit2; } (void) sprintf(path,"%s/%s",mysql_data_home,db); unpack_dirname(path,path); // Convert if not unix /* See if the directory exists */ if (!(dirp = my_dir(path,MYF(MY_DONT_SORT)))) { if (!if_exists) { error= -1; my_error(ER_DB_DROP_EXISTS,MYF(0),db); } else if (!silent) send_ok(&thd->net,0); goto exit; } remove_db_from_cache(db); error = -1; if ((deleted=mysql_rm_known_files(thd, dirp, db, path,0)) >= 0 && thd) { ha_drop_database(path); if (!silent) { if (!thd->query) { thd->query = path; thd->query_length = (uint) (strxmov(path,"drop database ", db, NullS)- path); } mysql_update_log.write(thd, thd->query, thd->query_length); if (mysql_bin_log.is_open()) { Query_log_event qinfo(thd, thd->query); mysql_bin_log.write(&qinfo); } if (thd->query == path) { thd->query = 0; // just in case thd->query_length = 0; } send_ok(&thd->net,(ulong) deleted); } error = 0; } exit: start_waiting_global_read_lock(thd); exit2: VOID(pthread_mutex_unlock(&LOCK_mysql_create_db)); DBUG_RETURN(error); } /* Removes files with known extensions plus all found subdirectories that are 2 digits (raid directories). thd MUST be set when calling this function! */ static long mysql_rm_known_files(THD *thd, MY_DIR *dirp, const char *db, const char *org_path, uint level) { long deleted=0; ulong found_other_files=0; char filePath[FN_REFLEN]; TABLE_LIST *tot_list=0, **tot_list_next; DBUG_ENTER("mysql_rm_known_files"); DBUG_PRINT("enter",("path: %s", org_path)); tot_list_next= &tot_list; for (uint idx=2 ; idx < (uint) dirp->number_off_files && !thd->killed ; idx++) { FILEINFO *file=dirp->dir_entry+idx; DBUG_PRINT("info",("Examining: %s", file->name)); /* Check if file is a raid directory */ if (isdigit(file->name[0]) && isdigit(file->name[1]) && !file->name[2] && !level) { char newpath[FN_REFLEN]; MY_DIR *new_dirp; strxmov(newpath,org_path,"/",file->name,NullS); unpack_filename(newpath,newpath); if ((new_dirp = my_dir(newpath,MYF(MY_DONT_SORT)))) { DBUG_PRINT("my",("New subdir found: %s", newpath)); if ((mysql_rm_known_files(thd, new_dirp, NullS, newpath,1)) < 0) { my_dirend(dirp); DBUG_RETURN(-1); } } continue; } if (find_type(fn_ext(file->name),&deletable_extentions,1+2) <= 0) { if (find_type(fn_ext(file->name),&known_extentions,1+2) <= 0) found_other_files++; continue; } strxmov(filePath,org_path,"/",file->name,NullS); if (db && !my_strcasecmp(fn_ext(file->name), reg_ext)) { /* Drop the table nicely */ *fn_ext(file->name)=0; // Remove extension TABLE_LIST *table_list=(TABLE_LIST*) thd->calloc(sizeof(*table_list)+ strlen(db)+strlen(file->name)+2); if (!table_list) { my_dirend(dirp); DBUG_RETURN(-1); } table_list->db= (char*) (table_list+1); strmov(table_list->real_name=strmov(table_list->db,db)+1, file->name); /* Link into list */ (*tot_list_next)= table_list; tot_list_next= &table_list->next; } else { if (my_delete_with_symlink(filePath,MYF(MY_WME))) { my_dirend(dirp); DBUG_RETURN(-1); } deleted++; } } my_dirend(dirp); if (thd->killed || (tot_list && mysql_rm_table_part2(thd, tot_list, 1, 1))) DBUG_RETURN(-1); /* If the directory is a symbolic link, remove the link first, then remove the directory the symbolic link pointed at */ if (!found_other_files) { char tmp_path[FN_REFLEN]; char *path=unpack_filename(tmp_path,org_path); #ifdef HAVE_READLINK int linkcount = readlink(path,filePath,sizeof(filePath)-1); if (linkcount > 0) // If the path was a symbolic link { *(filePath + linkcount) = '\0'; if (my_delete(path,MYF(!level ? MY_WME : 0))) { /* Don't give errors if we can't delete 'RAID' directory */ if (level) DBUG_RETURN(deleted); DBUG_RETURN(-1); } path=filePath; } #endif /* Remove last FN_LIBCHAR to not cause a problem on OS/2 */ char *pos=strend(path); if (pos > path && pos[-1] == FN_LIBCHAR) *--pos=0; /* Don't give errors if we can't delete 'RAID' directory */ if (rmdir(path) < 0 && !level) { my_error(ER_DB_DROP_RMDIR, MYF(0), path, errno); DBUG_RETURN(-1); } } DBUG_RETURN(deleted); } bool mysql_change_db(THD *thd,const char *name) { int length; char *dbname=my_strdup((char*) name,MYF(MY_WME)); char path[FN_REFLEN]; uint db_access; DBUG_ENTER("mysql_change_db"); if (!dbname || !(length=stripp_sp(dbname))) { x_free(dbname); /* purecov: inspected */ send_error(&thd->net,ER_NO_DB_ERROR); /* purecov: inspected */ DBUG_RETURN(1); /* purecov: inspected */ } if ((length > NAME_LEN) || check_db_name(dbname)) { net_printf(&thd->net,ER_WRONG_DB_NAME, dbname); x_free(dbname); DBUG_RETURN(1); } DBUG_PRINT("info",("Use database: %s", dbname)); if (test_all_bits(thd->master_access,DB_ACLS)) db_access=DB_ACLS; else db_access= (acl_get(thd->host,thd->ip,(char*) &thd->remote.sin_addr, thd->priv_user,dbname) | thd->master_access); if (!(db_access & DB_ACLS) && (!grant_option || check_grant_db(thd,dbname))) { net_printf(&thd->net,ER_DBACCESS_DENIED_ERROR, thd->priv_user, thd->host_or_ip, dbname); mysql_log.write(thd,COM_INIT_DB,ER(ER_DBACCESS_DENIED_ERROR), thd->priv_user, thd->host_or_ip, dbname); my_free(dbname,MYF(0)); DBUG_RETURN(1); } (void) sprintf(path,"%s/%s",mysql_data_home,dbname); length=unpack_dirname(path,path); // Convert if not unix if (length && path[length-1] == FN_LIBCHAR) path[length-1]=0; // remove ending '\' if (access(path,F_OK)) { net_printf(&thd->net,ER_BAD_DB_ERROR,dbname); my_free(dbname,MYF(0)); DBUG_RETURN(1); } send_ok(&thd->net); x_free(thd->db); thd->db=dbname; thd->db_access=db_access; DBUG_RETURN(0); }
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* create and drop of databases */ #include "mysql_priv.h" #include "sql_acl.h" #include <my_dir.h> #include <m_ctype.h> #ifdef __WIN__ #include <direct.h> #endif static long mysql_rm_known_files(THD *thd, MY_DIR *dirp, const char *db, const char *path, uint level); /* db-name is already validated when we come here */ int mysql_create_db(THD *thd, char *db, uint create_options, bool silent) { char path[FN_REFLEN+16]; MY_DIR *dirp; long result=1; int error = 0; DBUG_ENTER("mysql_create_db"); VOID(pthread_mutex_lock(&LOCK_mysql_create_db)); // do not create database if another thread is holding read lock if (wait_if_global_read_lock(thd,0)) { error= -1; goto exit2; } /* Check directory */ (void)sprintf(path,"%s/%s", mysql_data_home, db); unpack_dirname(path,path); // Convert if not unix if ((dirp = my_dir(path,MYF(MY_DONT_SORT)))) { my_dirend(dirp); if (!(create_options & HA_LEX_CREATE_IF_NOT_EXISTS)) { my_error(ER_DB_CREATE_EXISTS,MYF(0),db); error = -1; goto exit; } result = 0; } else { strend(path)[-1]=0; // Remove last '/' from path if (my_mkdir(path,0777,MYF(0)) < 0) { my_error(ER_CANT_CREATE_DB,MYF(0),db,my_errno); error = -1; goto exit; } } if (!silent) { if (!thd->query) { thd->query = path; thd->query_length = (uint) (strxmov(path,"create database ", db, NullS)- path); } { mysql_update_log.write(thd,thd->query, thd->query_length); if (mysql_bin_log.is_open()) { Query_log_event qinfo(thd, thd->query); mysql_bin_log.write(&qinfo); } } if (thd->query == path) { thd->query = 0; // just in case thd->query_length = 0; } send_ok(&thd->net, result); } exit: start_waiting_global_read_lock(thd); exit2: VOID(pthread_mutex_unlock(&LOCK_mysql_create_db)); DBUG_RETURN(error); } const char *del_exts[]= {".frm", ".BAK", ".TMD", NullS}; static TYPELIB deletable_extentions= {array_elements(del_exts)-1,"del_exts", del_exts}; const char *known_exts[]= {".ISM",".ISD",".ISM",".MRG",".MYI",".MYD",".db",NullS}; static TYPELIB known_extentions= {array_elements(known_exts)-1,"known_exts", known_exts}; /* Drop all tables in a database. db-name is already validated when we come here If thd == 0, do not write any messages; This is useful in replication when we want to remove a stale database before replacing it with the new one */ int mysql_rm_db(THD *thd,char *db,bool if_exists, bool silent) { long deleted=0; int error = 0; char path[FN_REFLEN+16]; MY_DIR *dirp; DBUG_ENTER("mysql_rm_db"); VOID(pthread_mutex_lock(&LOCK_mysql_create_db)); // do not drop database if another thread is holding read lock if (wait_if_global_read_lock(thd,0)) { error= -1; goto exit2; } (void) sprintf(path,"%s/%s",mysql_data_home,db); unpack_dirname(path,path); // Convert if not unix /* See if the directory exists */ if (!(dirp = my_dir(path,MYF(MY_DONT_SORT)))) { if (!if_exists) { error= -1; my_error(ER_DB_DROP_EXISTS,MYF(0),db); } else if (!silent) send_ok(&thd->net,0); goto exit; } remove_db_from_cache(db); error = -1; if ((deleted=mysql_rm_known_files(thd, dirp, db, path,0)) >= 0 && thd) { ha_drop_database(path); if (!silent) { if (!thd->query) { thd->query = path; thd->query_length = (uint) (strxmov(path,"drop database ", db, NullS)- path); } mysql_update_log.write(thd, thd->query, thd->query_length); if (mysql_bin_log.is_open()) { Query_log_event qinfo(thd, thd->query); mysql_bin_log.write(&qinfo); } if (thd->query == path) { thd->query = 0; // just in case thd->query_length = 0; } send_ok(&thd->net,(ulong) deleted); } error = 0; } exit: start_waiting_global_read_lock(thd); exit2: VOID(pthread_mutex_unlock(&LOCK_mysql_create_db)); DBUG_RETURN(error); } /* Removes files with known extensions plus all found subdirectories that are 2 digits (raid directories). thd MUST be set when calling this function! */ static long mysql_rm_known_files(THD *thd, MY_DIR *dirp, const char *db, const char *org_path, uint level) { long deleted=0; ulong found_other_files=0; char filePath[FN_REFLEN]; TABLE_LIST *tot_list=0, **tot_list_next; DBUG_ENTER("mysql_rm_known_files"); DBUG_PRINT("enter",("path: %s", org_path)); tot_list_next= &tot_list; for (uint idx=2 ; idx < (uint) dirp->number_off_files && !thd->killed ; idx++) { FILEINFO *file=dirp->dir_entry+idx; DBUG_PRINT("info",("Examining: %s", file->name)); /* Check if file is a raid directory */ if (isdigit(file->name[0]) && isdigit(file->name[1]) && !file->name[2] && !level) { char newpath[FN_REFLEN]; MY_DIR *new_dirp; strxmov(newpath,org_path,"/",file->name,NullS); unpack_filename(newpath,newpath); if ((new_dirp = my_dir(newpath,MYF(MY_DONT_SORT)))) { DBUG_PRINT("my",("New subdir found: %s", newpath)); if ((mysql_rm_known_files(thd, new_dirp, NullS, newpath,1)) < 0) { my_dirend(dirp); DBUG_RETURN(-1); } } continue; } if (find_type(fn_ext(file->name),&deletable_extentions,1+2) <= 0) { if (find_type(fn_ext(file->name),&known_extentions,1+2) <= 0) found_other_files++; continue; } strxmov(filePath,org_path,"/",file->name,NullS); if (db && !my_strcasecmp(fn_ext(file->name), reg_ext)) { /* Drop the table nicely */ *fn_ext(file->name)=0; // Remove extension TABLE_LIST *table_list=(TABLE_LIST*) thd->calloc(sizeof(*table_list)+ strlen(db)+strlen(file->name)+2); if (!table_list) { my_dirend(dirp); DBUG_RETURN(-1); } table_list->db= (char*) (table_list+1); strmov(table_list->real_name=strmov(table_list->db,db)+1, file->name); /* Link into list */ (*tot_list_next)= table_list; tot_list_next= &table_list->next; } else { if (my_delete_with_symlink(filePath,MYF(MY_WME))) { my_dirend(dirp); DBUG_RETURN(-1); } deleted++; } } my_dirend(dirp); if (thd->killed || (tot_list && mysql_rm_table_part2(thd, tot_list, 1, 1))) DBUG_RETURN(-1); /* If the directory is a symbolic link, remove the link first, then remove the directory the symbolic link pointed at */ if (!found_other_files) { char tmp_path[FN_REFLEN]; char *path=unpack_filename(tmp_path,org_path); #ifdef HAVE_READLINK int linkcount = readlink(path,filePath,sizeof(filePath)-1); if (linkcount > 0) // If the path was a symbolic link { *(filePath + linkcount) = '\0'; if (my_delete(path,MYF(!level ? MY_WME : 0))) { /* Don't give errors if we can't delete 'RAID' directory */ if (level) DBUG_RETURN(deleted); DBUG_RETURN(-1); } path=filePath; } #endif /* Remove last FN_LIBCHAR to not cause a problem on OS/2 */ char *pos=strend(path); if (pos > path && pos[-1] == FN_LIBCHAR) *--pos=0; /* Don't give errors if we can't delete 'RAID' directory */ if (rmdir(path) < 0 && !level) { my_error(ER_DB_DROP_RMDIR, MYF(0), path, errno); DBUG_RETURN(-1); } } DBUG_RETURN(deleted); } bool mysql_change_db(THD *thd,const char *name) { int length; char *dbname=my_strdup((char*) name,MYF(MY_WME)); char path[FN_REFLEN]; uint db_access; DBUG_ENTER("mysql_change_db"); if (!dbname || !(length=stripp_sp(dbname))) { x_free(dbname); /* purecov: inspected */ send_error(&thd->net,ER_NO_DB_ERROR); /* purecov: inspected */ DBUG_RETURN(1); /* purecov: inspected */ } if ((length > NAME_LEN) || check_db_name(dbname)) { net_printf(&thd->net,ER_WRONG_DB_NAME, dbname); x_free(dbname); DBUG_RETURN(1); } DBUG_PRINT("info",("Use database: %s", dbname)); if (test_all_bits(thd->master_access,DB_ACLS)) db_access=DB_ACLS; else db_access= (acl_get(thd->host,thd->ip,(char*) &thd->remote.sin_addr, thd->priv_user,dbname) | thd->master_access); if (!(db_access & DB_ACLS) && (!grant_option || check_grant_db(thd,dbname))) { net_printf(&thd->net,ER_DBACCESS_DENIED_ERROR, thd->priv_user, thd->host_or_ip, dbname); mysql_log.write(thd,COM_INIT_DB,ER(ER_DBACCESS_DENIED_ERROR), thd->priv_user, thd->host_or_ip, dbname); my_free(dbname,MYF(0)); DBUG_RETURN(1); } (void) sprintf(path,"%s/%s",mysql_data_home,dbname); length=unpack_dirname(path,path); // Convert if not unix if (length && path[length-1] == FN_LIBCHAR) path[length-1]=0; // remove ending '\' if (access(path,F_OK)) { net_printf(&thd->net,ER_BAD_DB_ERROR,dbname); my_free(dbname,MYF(0)); DBUG_RETURN(1); } send_ok(&thd->net); x_free(thd->db); thd->db=dbname; thd->db_access=db_access; DBUG_RETURN(0); }
Remove .TMD files on DROP DATABASE.
Remove .TMD files on DROP DATABASE.
C++
lgpl-2.1
flynn1973/mariadb-aix,natsys/mariadb_10.2,davidl-zend/zenddbi,flynn1973/mariadb-aix,natsys/mariadb_10.2,flynn1973/mariadb-aix,flynn1973/mariadb-aix,slanterns/server,ollie314/server,davidl-zend/zenddbi,davidl-zend/zenddbi,ollie314/server,flynn1973/mariadb-aix,davidl-zend/zenddbi,natsys/mariadb_10.2,ollie314/server,davidl-zend/zenddbi,natsys/mariadb_10.2,natsys/mariadb_10.2,davidl-zend/zenddbi,natsys/mariadb_10.2,ollie314/server,davidl-zend/zenddbi,flynn1973/mariadb-aix,flynn1973/mariadb-aix,flynn1973/mariadb-aix,flynn1973/mariadb-aix,natsys/mariadb_10.2,davidl-zend/zenddbi,ollie314/server,ollie314/server,natsys/mariadb_10.2,natsys/mariadb_10.2,davidl-zend/zenddbi,davidl-zend/zenddbi,ollie314/server,ollie314/server,ollie314/server,flynn1973/mariadb-aix,ollie314/server,davidl-zend/zenddbi,natsys/mariadb_10.2,natsys/mariadb_10.2,flynn1973/mariadb-aix,ollie314/server
6f646b9d5538c4e9809f2cdcddadeb972317abad
src/Graph.cxx
src/Graph.cxx
#include "lwtnn/Graph.hh" #include "lwtnn/Exceptions.hh" #include "lwtnn/Stack.hh" #include <set> namespace lwt { // Sources VectorSource::VectorSource(const std::vector<VectorXd>&& vv): m_inputs(std::move(vv)) { } VectorXd VectorSource::at(size_t index) const { if (index >= m_inputs.size()) { throw NNEvaluationException( "VectorSource: no source vector defined at " + std::to_string(index)); } return m_inputs.at(index); }; DummySource::DummySource(const std::vector<size_t>& input_sizes): m_sizes(input_sizes) { } VectorXd DummySource::at(size_t index) const { if (index >= m_sizes.size()) { throw NNEvaluationException( "Dummy Source: no size defined at " + std::to_string(index)); } size_t n_entries = m_sizes.at(index); VectorXd vec(n_entries); for (int iii = 0; iii < n_entries; iii++) { vec(iii) = iii; } return vec; } // Nodes InputNode::InputNode(size_t index, size_t n_outputs): m_index(index), m_n_outputs(n_outputs) { } VectorXd InputNode::compute(const ISource& source) const { VectorXd output = source.at(m_index); if (output.rows() != m_n_outputs) { std::string len = std::to_string(output.rows()); std::string found = std::to_string(m_n_outputs); throw NNEvaluationException( "Found vector of length " + len + ", expected " + found); } return output; } size_t InputNode::n_outputs() const { return m_n_outputs; } FeedForwardNode::FeedForwardNode(const Stack* stack, const INode* source): m_stack(stack), m_source(source) { } VectorXd FeedForwardNode::compute(const ISource& source) const { return m_stack->compute(m_source->compute(source)); } size_t FeedForwardNode::n_outputs() const { return m_stack->n_outputs(); } ConcatenateNode::ConcatenateNode(const std::vector<const INode*>& sources): m_sources(sources), m_n_outputs(0) { for (const auto source: sources) { m_n_outputs += source->n_outputs(); } } VectorXd ConcatenateNode::compute(const ISource& source) const { VectorXd output(m_n_outputs); size_t offset = 0; for (const auto node: m_sources) { VectorXd input = node->compute(source); size_t n_elements = input.rows(); assert(n_elements == node->n_outputs()); output.segment(offset, n_elements) = input; offset += n_elements; } assert(offset = m_n_outputs); return output; } size_t ConcatenateNode::n_outputs() const { return m_n_outputs; } } namespace { using namespace lwt; void throw_cfg(std::string msg, size_t index) { throw NNConfigurationException(msg + " " + std::to_string(index)); } // NOTE: you own this pointer! INode* get_feedforward_node(const NodeConfig& node, const std::vector<LayerConfig>& layers, const std::map<size_t, INode*>& node_map, std::map<size_t, Stack*>& stack_map, std::vector<Stack*>& m_stacks) { size_t n_source = node.sources.size(); if (n_source != 1) throw_cfg("need one source, found", n_source); INode* source = node_map.at(node.sources.at(0)); int layer_n = node.index; if (layer_n < 0) throw_cfg("negative layer number", layer_n); if (layer_n >= layers.size()) throw_cfg("no layer number", layer_n); if (!stack_map.count(layer_n)) { m_stacks.push_back( new Stack(source->n_outputs(), {layers.at(layer_n)})); stack_map[layer_n] = m_stacks.back(); } return new FeedForwardNode(stack_map.at(layer_n), source); } void build_node(size_t iii, const std::vector<NodeConfig>& nodes, const std::vector<LayerConfig>& layers, std::vector<INode*>& m_nodes, std::vector<Stack*>& m_stacks, std::map<size_t, INode*>& node_map, std::map<size_t, Stack*>& stack_map, std::set<size_t> cycle_check = {}) { if (node_map.count(iii)) return; if (iii >= nodes.size()) throw_cfg("no node index", iii); const NodeConfig& node = nodes.at(iii); // if it's an input, build and return if (node.type == NodeConfig::Type::INPUT) { size_t n_inputs = node.sources.size(); if (n_inputs != 1) throw_cfg( "input node needs need one source, got", n_inputs); if (node.index < 0) throw_cfg( "input node needs positive index, got", node.index); m_nodes.push_back(new InputNode(node.sources.at(0), node.index)); node_map[iii] = m_nodes.back(); return; } // otherwise build all the inputs first if (cycle_check.count(iii)) { throw NNConfigurationException("found cycle in graph"); } cycle_check.insert(iii); for (size_t source_node: node.sources) { build_node(source_node, nodes, layers, m_nodes, m_stacks, node_map, stack_map, cycle_check); } // build feed forward layer if (node.type == NodeConfig::Type::FEED_FORWARD) { m_nodes.push_back( get_feedforward_node(node, layers, node_map, stack_map, m_stacks)); node_map[iii] = m_nodes.back(); return; } // build concatenate layer if (node.type == NodeConfig::Type::CONCATENATE) { std::vector<const INode*> in_nodes; for (size_t source_node: node.sources) { in_nodes.push_back(node_map.at(source_node)); } m_nodes.push_back(new ConcatenateNode(in_nodes)); node_map[iii] = m_nodes.back(); return; } throw NNConfigurationException("unknown node type"); } } namespace lwt { // graph Graph::Graph() { m_stacks.push_back(new Stack); Stack* stack = m_stacks.back(); m_nodes.push_back(new InputNode(0, 2)); INode* source1 = m_nodes.back(); m_nodes.push_back(new InputNode(1, 2)); INode* source2 = m_nodes.back(); m_nodes.push_back(new ConcatenateNode({source1, source2})); INode* cat = m_nodes.back(); m_nodes.push_back(new FeedForwardNode(stack, cat)); } Graph::Graph(const std::vector<NodeConfig>& nodes, const std::vector<LayerConfig>& layers) { std::map<size_t, INode*> node_map; std::map<size_t, Stack*> stack_map; for (size_t iii = 0; iii < nodes.size(); iii++) { build_node(iii, nodes, layers, m_nodes, m_stacks, node_map, stack_map); } assert(node_map.size() == nodes.size()); } Graph::~Graph() { for (auto node: m_nodes) { delete node; node = 0; } for (auto stack: m_stacks) { delete stack; stack = 0; } } VectorXd Graph::compute(const ISource& source, size_t node_number) const { if (node_number >= m_nodes.size()) { throw NNEvaluationException( "Graph: no node at " + std::to_string(node_number)); } return m_nodes.at(node_number)->compute(source); } VectorXd Graph::compute(const ISource& source) const { assert(m_nodes.size() > 0); return m_nodes.back()->compute(source); } }
#include "lwtnn/Graph.hh" #include "lwtnn/Exceptions.hh" #include "lwtnn/Stack.hh" #include <set> namespace lwt { // Sources VectorSource::VectorSource(const std::vector<VectorXd>&& vv): m_inputs(std::move(vv)) { } VectorXd VectorSource::at(size_t index) const { if (index >= m_inputs.size()) { throw NNEvaluationException( "VectorSource: no source vector defined at " + std::to_string(index)); } return m_inputs.at(index); } DummySource::DummySource(const std::vector<size_t>& input_sizes): m_sizes(input_sizes) { } VectorXd DummySource::at(size_t index) const { if (index >= m_sizes.size()) { throw NNEvaluationException( "Dummy Source: no size defined at " + std::to_string(index)); } size_t n_entries = m_sizes.at(index); VectorXd vec(n_entries); for (size_t iii = 0; iii < n_entries; iii++) { vec(iii) = iii; } return vec; } // Nodes InputNode::InputNode(size_t index, size_t n_outputs): m_index(index), m_n_outputs(n_outputs) { } VectorXd InputNode::compute(const ISource& source) const { VectorXd output = source.at(m_index); assert(output.rows() > 0); if (static_cast<size_t>(output.rows()) != m_n_outputs) { std::string len = std::to_string(output.rows()); std::string found = std::to_string(m_n_outputs); throw NNEvaluationException( "Found vector of length " + len + ", expected " + found); } return output; } size_t InputNode::n_outputs() const { return m_n_outputs; } FeedForwardNode::FeedForwardNode(const Stack* stack, const INode* source): m_stack(stack), m_source(source) { } VectorXd FeedForwardNode::compute(const ISource& source) const { return m_stack->compute(m_source->compute(source)); } size_t FeedForwardNode::n_outputs() const { return m_stack->n_outputs(); } ConcatenateNode::ConcatenateNode(const std::vector<const INode*>& sources): m_sources(sources), m_n_outputs(0) { for (const auto source: sources) { m_n_outputs += source->n_outputs(); } } VectorXd ConcatenateNode::compute(const ISource& source) const { VectorXd output(m_n_outputs); size_t offset = 0; for (const auto node: m_sources) { VectorXd input = node->compute(source); size_t n_elements = input.rows(); assert(n_elements == node->n_outputs()); output.segment(offset, n_elements) = input; offset += n_elements; } assert(offset = m_n_outputs); return output; } size_t ConcatenateNode::n_outputs() const { return m_n_outputs; } } namespace { using namespace lwt; void throw_cfg(std::string msg, size_t index) { throw NNConfigurationException(msg + " " + std::to_string(index)); } // NOTE: you own this pointer! INode* get_feedforward_node(const NodeConfig& node, const std::vector<LayerConfig>& layers, const std::map<size_t, INode*>& node_map, std::map<size_t, Stack*>& stack_map, std::vector<Stack*>& m_stacks) { size_t n_source = node.sources.size(); if (n_source != 1) throw_cfg("need one source, found", n_source); INode* source = node_map.at(node.sources.at(0)); int layer_n = node.index; if (layer_n < 0) throw_cfg("negative layer number", layer_n); if (static_cast<size_t>(layer_n) >= layers.size()) { throw_cfg("no layer number", layer_n); } if (!stack_map.count(layer_n)) { m_stacks.push_back( new Stack(source->n_outputs(), {layers.at(layer_n)})); stack_map[layer_n] = m_stacks.back(); } return new FeedForwardNode(stack_map.at(layer_n), source); } void build_node(size_t iii, const std::vector<NodeConfig>& nodes, const std::vector<LayerConfig>& layers, std::vector<INode*>& m_nodes, std::vector<Stack*>& m_stacks, std::map<size_t, INode*>& node_map, std::map<size_t, Stack*>& stack_map, std::set<size_t> cycle_check = {}) { if (node_map.count(iii)) return; if (iii >= nodes.size()) throw_cfg("no node index", iii); const NodeConfig& node = nodes.at(iii); // if it's an input, build and return if (node.type == NodeConfig::Type::INPUT) { size_t n_inputs = node.sources.size(); if (n_inputs != 1) throw_cfg( "input node needs need one source, got", n_inputs); if (node.index < 0) throw_cfg( "input node needs positive index, got", node.index); m_nodes.push_back(new InputNode(node.sources.at(0), node.index)); node_map[iii] = m_nodes.back(); return; } // otherwise build all the inputs first if (cycle_check.count(iii)) { throw NNConfigurationException("found cycle in graph"); } cycle_check.insert(iii); for (size_t source_node: node.sources) { build_node(source_node, nodes, layers, m_nodes, m_stacks, node_map, stack_map, cycle_check); } // build feed forward layer if (node.type == NodeConfig::Type::FEED_FORWARD) { m_nodes.push_back( get_feedforward_node(node, layers, node_map, stack_map, m_stacks)); node_map[iii] = m_nodes.back(); return; } // build concatenate layer if (node.type == NodeConfig::Type::CONCATENATE) { std::vector<const INode*> in_nodes; for (size_t source_node: node.sources) { in_nodes.push_back(node_map.at(source_node)); } m_nodes.push_back(new ConcatenateNode(in_nodes)); node_map[iii] = m_nodes.back(); return; } throw NNConfigurationException("unknown node type"); } } namespace lwt { // graph Graph::Graph() { m_stacks.push_back(new Stack); Stack* stack = m_stacks.back(); m_nodes.push_back(new InputNode(0, 2)); INode* source1 = m_nodes.back(); m_nodes.push_back(new InputNode(1, 2)); INode* source2 = m_nodes.back(); m_nodes.push_back(new ConcatenateNode({source1, source2})); INode* cat = m_nodes.back(); m_nodes.push_back(new FeedForwardNode(stack, cat)); } Graph::Graph(const std::vector<NodeConfig>& nodes, const std::vector<LayerConfig>& layers) { std::map<size_t, INode*> node_map; std::map<size_t, Stack*> stack_map; for (size_t iii = 0; iii < nodes.size(); iii++) { build_node(iii, nodes, layers, m_nodes, m_stacks, node_map, stack_map); } assert(node_map.size() == nodes.size()); } Graph::~Graph() { for (auto node: m_nodes) { delete node; node = 0; } for (auto stack: m_stacks) { delete stack; stack = 0; } } VectorXd Graph::compute(const ISource& source, size_t node_number) const { if (node_number >= m_nodes.size()) { throw NNEvaluationException( "Graph: no node at " + std::to_string(node_number)); } return m_nodes.at(node_number)->compute(source); } VectorXd Graph::compute(const ISource& source) const { assert(m_nodes.size() > 0); return m_nodes.back()->compute(source); } }
Fix pedantic compiler warnings
Fix pedantic compiler warnings
C++
mit
jwsmithers/lwtnn,lwtnn/lwtnn,jwsmithers/lwtnn,jwsmithers/lwtnn,lwtnn/lwtnn,lwtnn/lwtnn
77bb3dc462d2a34e5657c1e83fb0f1fb211e1e75
Visualization_Library_SDK/src/vlGraphics/Rendering.cpp
Visualization_Library_SDK/src/vlGraphics/Rendering.cpp
/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.com */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without modification, */ /* are permitted provided that the following conditions are met: */ /* */ /* - Redistributions of source code must retain the above copyright notice, this */ /* list of conditions and the following disclaimer. */ /* */ /* - Redistributions in binary form must reproduce the above copyright notice, this */ /* list of conditions and the following disclaimer in the documentation and/or */ /* other materials provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */ /* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /**************************************************************************************/ #include <vlGraphics/Rendering.hpp> #include <vlGraphics/OpenGLContext.hpp> #include <vlGraphics/Renderer.hpp> #include <vlGraphics/SceneManager.hpp> #include <vlGraphics/RenderQueue.hpp> #include <vlGraphics/GLSL.hpp> #include <vlCore/Log.hpp> #include <vlCore/Say.hpp> using namespace vl; //------------------------------------------------------------------------------ Rendering::Rendering(): mAutomaticResourceInit(true), mCullingEnabled(true), mEvaluateLOD(true), mShaderAnimationEnabled(true), mNearFarClippingPlanesOptimized(false) { #ifndef NDEBUG mObjectName = className(); #endif mRenderQueueSorter = new RenderQueueSorterStandard; mActorQueue = new ActorCollection; mRenderQueue = new RenderQueue; mSceneManagers = new Collection<SceneManager>; mCamera = new Camera; mTransform = new Transform; mRenderers.push_back( new Renderer ); } //------------------------------------------------------------------------------ Rendering& Rendering::operator=(const Rendering& other) { RenderingAbstract::operator=(other); mEnableMask = other.mEnableMask; mAutomaticResourceInit = other.mAutomaticResourceInit; mCullingEnabled = other.mCullingEnabled; mEvaluateLOD = other.mEvaluateLOD; mShaderAnimationEnabled = other.mShaderAnimationEnabled; mNearFarClippingPlanesOptimized = other.mNearFarClippingPlanesOptimized; mRenderQueueSorter = other.mRenderQueueSorter; /*mActorQueue = other.mActorQueue;*/ /*mRenderQueue = other.mRenderQueue;*/ *mSceneManagers = *other.mSceneManagers; mRenderers = other.mRenderers; mCamera = other.mCamera; mTransform = other.mTransform; return *this; } //------------------------------------------------------------------------------ void Rendering::render() { VL_CHECK_OGL(); VL_CHECK(camera()); VL_CHECK(camera()->viewport()); // if rendering is disabled skip all. if ( enableMask() == 0 ) return; // enter/exit behavior contract class InOutContract { Rendering* mRendering; OpenGLContext* mOpenGLContext; public: InOutContract(Rendering* rendering): mRendering(rendering) { // as stated in the documentation all the renderers must target the same OpenGLContext mOpenGLContext = mRendering->renderers()[0]->renderTarget()->openglContext(); // activate OpenGL context mOpenGLContext->makeCurrent(); // render states ]shield[ mOpenGLContext->resetContextStates(); // pre rendering callback mRendering->dispatchOnRenderingStarted(); // check user-generated errors. VL_CHECK_OGL() } ~InOutContract() { // post rendering callback mRendering->dispatchOnRenderingFinished(); // check user-generated errors. VL_CHECK_OGL() // render states ]shield[ mOpenGLContext->resetContextStates(); } }; InOutContract contract(this); // --------------- rendering --------------- if (renderers().empty()) { vl::Log::error("Rendering::render(): no Renderer specified for this Rendering!\n"); VL_TRAP(); return; } if (!renderers()[0]->renderTarget()) { vl::Log::error("Rendering::render(): no RendererTarget specified for Renderer #0!\n"); VL_TRAP(); return; } if (!renderers()[0]->renderTarget()->openglContext()) { vl::Log::error("Rendering::render(): invalid RenderTarget for Renderer #0, OpenGLContext is NULL!\n"); VL_TRAP(); return; } if (sceneManagers()->empty()) return; if (!camera()) return; if (!camera()->viewport()) return; // transform if (transform() != NULL) transform()->computeWorldMatrixRecursive( camera() ); // camera transform update (can be redundant) if (camera()->followedTransform()) camera()->setInverseViewMatrix( camera()->followedTransform()->worldMatrix() ); VL_CHECK_OGL() // culling & actor queue filling camera()->computeFrustumPlanes(); // if near/far clipping planes optimization is enabled don't perform far-culling if (nearFarClippingPlanesOptimized()) { // perform only near culling with plane at distance 0 camera()->frustum().planes().resize(5); camera()->frustum().planes()[4] = Plane( camera()->inverseViewMatrix().getT(), camera()->inverseViewMatrix().getZ()); } actorQueue()->clear(); for(int i=0; i<sceneManagers()->size(); ++i) { if ( isEnabled(sceneManagers()->at(i)->enableMask()) ) { if (cullingEnabled() && sceneManagers()->at(i)->cullingEnabled()) { if (sceneManagers()->at(i)->boundsDirty()) sceneManagers()->at(i)->computeBounds(); // try to cull the scene with both bsphere and bbox bool visible = !camera()->frustum().cull(sceneManagers()->at(i)->boundingSphere()) && !camera()->frustum().cull(sceneManagers()->at(i)->boundingBox()); if ( visible ) sceneManagers()->at(i)->extractVisibleActors( *actorQueue(), camera() ); } else sceneManagers()->at(i)->extractActors( *actorQueue() ); } } // collect near/far clipping planes optimization information if (nearFarClippingPlanesOptimized()) { Sphere world_bounding_sphere; for(int i=0; i<actorQueue()->size(); ++i) world_bounding_sphere += actorQueue()->at(i)->boundingSphere(); // compute the optimized camera()->computeNearFarOptimizedProjMatrix(world_bounding_sphere); // recompute frustum planes to account for new near/far values camera()->computeFrustumPlanes(); } // render queue filling renderQueue()->clear(); fillRenderQueue( actorQueue() ); // sort the rendering queue according to this renderer sorting algorithm if (renderQueueSorter()) renderQueue()->sort( renderQueueSorter(), camera() ); // --- RENDER THE QUEUE: loop through the renderers, feeding the output of one as input for the next --- const RenderQueue* render_queue = renderQueue(); for(size_t i=0; i<renderers().size(); ++i) { if (renderers()[i]) { if (renderers()[i]->renderTarget() == NULL) { vl::Log::error( Say("Rendering::render(): no RendererTarget specified for Renderer #%n!\n") << i ); VL_TRAP(); continue; } if (renderers()[i]->renderTarget()->openglContext() == NULL) { vl::Log::error( Say("Rendering::render(): invalid RenderTarget for Renderer #%n, OpenGLContext is NULL!\n") << i ); VL_TRAP(); continue; } // loop the rendering render_queue = renderers()[i]->render( render_queue, camera(), frameClock() ); } } VL_CHECK_OGL() } //------------------------------------------------------------------------------ void Rendering::fillRenderQueue( ActorCollection* actor_list ) { if (actor_list == NULL) return; if (actor_list->empty()) return; if (camera() == NULL) return; if (enableMask() == 0) return; RenderQueue* list = renderQueue(); std::set<Shader*> shader_set; // iterate actor list for(int iactor=0; iactor < actor_list->size(); iactor++) { Actor* actor = actor_list->at(iactor); VL_CHECK(actor->lod(0)) if ( !isEnabled(actor->enableMask()) ) continue; // update the Actor's bounds actor->computeBounds(); Effect* effect = actor->effect(); VL_CHECK(effect) // effect override for( std::map< unsigned int, ref<Effect> >::const_iterator eom_it = mEffectOverrideMask.begin(); eom_it != mEffectOverrideMask.end(); ++eom_it ) { if (eom_it->first & actor->enableMask()) effect = eom_it->second.get(); } if ( !isEnabled(effect->enableMask()) ) continue; // --------------- LOD evaluation --------------- int effect_lod = effect->evaluateLOD( actor, camera() ); int geometry_lod = 0; if ( evaluateLOD() ) geometry_lod = actor->evaluateLOD( camera() ); // --------------- M U L T I P A S S I N G --------------- RenderToken* prev_pass = NULL; const int pass_count = effect->lod(effect_lod)->size(); for(int ipass=0; ipass<pass_count; ++ipass) { // setup the shader to be used for this pass Shader* shader = effect->lod(effect_lod)->at(ipass); // --------------- fill render token --------------- // create a render token RenderToken* tok = list->newToken(prev_pass != NULL); // multipass chain: implemented as a linked list if ( prev_pass != NULL ) prev_pass->mNextPass = tok; prev_pass = tok; tok->mNextPass = NULL; // track the current state tok->mActor = actor; tok->mRenderable = actor->lod(geometry_lod).get(); // set the shader used (multipassing shader or effect->shader()) tok->mShader = shader; if ( shaderAnimationEnabled() ) { VL_CHECK(frameClock() >= 0) if( frameClock() >= 0 ) { // note that the condition is != as opposed to < if ( shader->lastUpdateTime() != frameClock() && shader->shaderAnimator() && shader->shaderAnimator()->isEnabled() ) { // update shader->shaderAnimator()->updateShader( shader, camera(), frameClock() ); // note that we update this after shader->setLastUpdateTime( frameClock() ); } } } if ( automaticResourceInit() && shader_set.find(shader) == shader_set.end() ) { shader_set.insert(shader); // link GLSLProgram if (shader->glslProgram()) { shader->glslProgram()->linkProgram(); VL_CHECK( shader->glslProgram()->linked() ); } // lazy texture creation if ( shader->gocRenderStateSet() ) { const std::vector< ref<RenderState> >& states = shader->gocRenderStateSet()->renderStates(); for( size_t i=0; i<states.size(); ++i ) { if (states[i]->type() >= RS_TextureUnit0 && states[i]->type() < RS_TextureUnit0+VL_MAX_TEXTURE_UNITS) { TextureUnit* tex_unit = dynamic_cast<TextureUnit*>( states[i].get() ); VL_CHECK(tex_unit); if (tex_unit) { if (tex_unit->texture() && tex_unit->texture()->setupParams()) tex_unit->texture()->createTexture(); } } } } } tok->mEffectRenderRank = effect->renderRank(); } } } //------------------------------------------------------------------------------
/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.com */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without modification, */ /* are permitted provided that the following conditions are met: */ /* */ /* - Redistributions of source code must retain the above copyright notice, this */ /* list of conditions and the following disclaimer. */ /* */ /* - Redistributions in binary form must reproduce the above copyright notice, this */ /* list of conditions and the following disclaimer in the documentation and/or */ /* other materials provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */ /* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /**************************************************************************************/ #include <vlGraphics/Rendering.hpp> #include <vlGraphics/OpenGLContext.hpp> #include <vlGraphics/Renderer.hpp> #include <vlGraphics/SceneManager.hpp> #include <vlGraphics/RenderQueue.hpp> #include <vlGraphics/GLSL.hpp> #include <vlCore/Log.hpp> #include <vlCore/Say.hpp> using namespace vl; //------------------------------------------------------------------------------ Rendering::Rendering(): mAutomaticResourceInit(true), mCullingEnabled(true), mEvaluateLOD(true), mShaderAnimationEnabled(true), mNearFarClippingPlanesOptimized(false) { #ifndef NDEBUG mObjectName = className(); #endif mRenderQueueSorter = new RenderQueueSorterStandard; mActorQueue = new ActorCollection; mRenderQueue = new RenderQueue; mSceneManagers = new Collection<SceneManager>; mCamera = new Camera; mTransform = new Transform; mRenderers.push_back( new Renderer ); } //------------------------------------------------------------------------------ Rendering& Rendering::operator=(const Rendering& other) { RenderingAbstract::operator=(other); mEnableMask = other.mEnableMask; mAutomaticResourceInit = other.mAutomaticResourceInit; mCullingEnabled = other.mCullingEnabled; mEvaluateLOD = other.mEvaluateLOD; mShaderAnimationEnabled = other.mShaderAnimationEnabled; mNearFarClippingPlanesOptimized = other.mNearFarClippingPlanesOptimized; mRenderQueueSorter = other.mRenderQueueSorter; /*mActorQueue = other.mActorQueue;*/ /*mRenderQueue = other.mRenderQueue;*/ *mSceneManagers = *other.mSceneManagers; mRenderers = other.mRenderers; mCamera = other.mCamera; mTransform = other.mTransform; return *this; } //------------------------------------------------------------------------------ void Rendering::render() { VL_CHECK(camera()); VL_CHECK(camera()->viewport()); // if rendering is disabled skip all. if ( enableMask() == 0 ) return; // enter/exit behavior contract class InOutContract { Rendering* mRendering; OpenGLContext* mOpenGLContext; public: InOutContract(Rendering* rendering): mRendering(rendering) { // as stated in the documentation all the renderers must target the same OpenGLContext mOpenGLContext = mRendering->renderers()[0]->renderTarget()->openglContext(); // activate OpenGL context mOpenGLContext->makeCurrent(); VL_CHECK_OGL(); // the first check must be done when the context is active! // render states ]shield[ mOpenGLContext->resetContextStates(); // pre rendering callback mRendering->dispatchOnRenderingStarted(); // check user-generated errors. VL_CHECK_OGL() } ~InOutContract() { // post rendering callback mRendering->dispatchOnRenderingFinished(); // check user-generated errors. VL_CHECK_OGL() // render states ]shield[ mOpenGLContext->resetContextStates(); } }; InOutContract contract(this); // --------------- rendering --------------- if (renderers().empty()) { vl::Log::error("Rendering::render(): no Renderer specified for this Rendering!\n"); VL_TRAP(); return; } if (!renderers()[0]->renderTarget()) { vl::Log::error("Rendering::render(): no RendererTarget specified for Renderer #0!\n"); VL_TRAP(); return; } if (!renderers()[0]->renderTarget()->openglContext()) { vl::Log::error("Rendering::render(): invalid RenderTarget for Renderer #0, OpenGLContext is NULL!\n"); VL_TRAP(); return; } if (sceneManagers()->empty()) return; if (!camera()) return; if (!camera()->viewport()) return; // transform if (transform() != NULL) transform()->computeWorldMatrixRecursive( camera() ); // camera transform update (can be redundant) if (camera()->followedTransform()) camera()->setInverseViewMatrix( camera()->followedTransform()->worldMatrix() ); VL_CHECK_OGL() // culling & actor queue filling camera()->computeFrustumPlanes(); // if near/far clipping planes optimization is enabled don't perform far-culling if (nearFarClippingPlanesOptimized()) { // perform only near culling with plane at distance 0 camera()->frustum().planes().resize(5); camera()->frustum().planes()[4] = Plane( camera()->inverseViewMatrix().getT(), camera()->inverseViewMatrix().getZ()); } actorQueue()->clear(); for(int i=0; i<sceneManagers()->size(); ++i) { if ( isEnabled(sceneManagers()->at(i)->enableMask()) ) { if (cullingEnabled() && sceneManagers()->at(i)->cullingEnabled()) { if (sceneManagers()->at(i)->boundsDirty()) sceneManagers()->at(i)->computeBounds(); // try to cull the scene with both bsphere and bbox bool visible = !camera()->frustum().cull(sceneManagers()->at(i)->boundingSphere()) && !camera()->frustum().cull(sceneManagers()->at(i)->boundingBox()); if ( visible ) sceneManagers()->at(i)->extractVisibleActors( *actorQueue(), camera() ); } else sceneManagers()->at(i)->extractActors( *actorQueue() ); } } // collect near/far clipping planes optimization information if (nearFarClippingPlanesOptimized()) { Sphere world_bounding_sphere; for(int i=0; i<actorQueue()->size(); ++i) world_bounding_sphere += actorQueue()->at(i)->boundingSphere(); // compute the optimized camera()->computeNearFarOptimizedProjMatrix(world_bounding_sphere); // recompute frustum planes to account for new near/far values camera()->computeFrustumPlanes(); } // render queue filling renderQueue()->clear(); fillRenderQueue( actorQueue() ); // sort the rendering queue according to this renderer sorting algorithm if (renderQueueSorter()) renderQueue()->sort( renderQueueSorter(), camera() ); // --- RENDER THE QUEUE: loop through the renderers, feeding the output of one as input for the next --- const RenderQueue* render_queue = renderQueue(); for(size_t i=0; i<renderers().size(); ++i) { if (renderers()[i]) { if (renderers()[i]->renderTarget() == NULL) { vl::Log::error( Say("Rendering::render(): no RendererTarget specified for Renderer #%n!\n") << i ); VL_TRAP(); continue; } if (renderers()[i]->renderTarget()->openglContext() == NULL) { vl::Log::error( Say("Rendering::render(): invalid RenderTarget for Renderer #%n, OpenGLContext is NULL!\n") << i ); VL_TRAP(); continue; } // loop the rendering render_queue = renderers()[i]->render( render_queue, camera(), frameClock() ); } } VL_CHECK_OGL() } //------------------------------------------------------------------------------ void Rendering::fillRenderQueue( ActorCollection* actor_list ) { if (actor_list == NULL) return; if (actor_list->empty()) return; if (camera() == NULL) return; if (enableMask() == 0) return; RenderQueue* list = renderQueue(); std::set<Shader*> shader_set; // iterate actor list for(int iactor=0; iactor < actor_list->size(); iactor++) { Actor* actor = actor_list->at(iactor); VL_CHECK(actor->lod(0)) if ( !isEnabled(actor->enableMask()) ) continue; // update the Actor's bounds actor->computeBounds(); Effect* effect = actor->effect(); VL_CHECK(effect) // effect override for( std::map< unsigned int, ref<Effect> >::const_iterator eom_it = mEffectOverrideMask.begin(); eom_it != mEffectOverrideMask.end(); ++eom_it ) { if (eom_it->first & actor->enableMask()) effect = eom_it->second.get(); } if ( !isEnabled(effect->enableMask()) ) continue; // --------------- LOD evaluation --------------- int effect_lod = effect->evaluateLOD( actor, camera() ); int geometry_lod = 0; if ( evaluateLOD() ) geometry_lod = actor->evaluateLOD( camera() ); // --------------- M U L T I P A S S I N G --------------- RenderToken* prev_pass = NULL; const int pass_count = effect->lod(effect_lod)->size(); for(int ipass=0; ipass<pass_count; ++ipass) { // setup the shader to be used for this pass Shader* shader = effect->lod(effect_lod)->at(ipass); // --------------- fill render token --------------- // create a render token RenderToken* tok = list->newToken(prev_pass != NULL); // multipass chain: implemented as a linked list if ( prev_pass != NULL ) prev_pass->mNextPass = tok; prev_pass = tok; tok->mNextPass = NULL; // track the current state tok->mActor = actor; tok->mRenderable = actor->lod(geometry_lod).get(); // set the shader used (multipassing shader or effect->shader()) tok->mShader = shader; if ( shaderAnimationEnabled() ) { VL_CHECK(frameClock() >= 0) if( frameClock() >= 0 ) { // note that the condition is != as opposed to < if ( shader->lastUpdateTime() != frameClock() && shader->shaderAnimator() && shader->shaderAnimator()->isEnabled() ) { // update shader->shaderAnimator()->updateShader( shader, camera(), frameClock() ); // note that we update this after shader->setLastUpdateTime( frameClock() ); } } } if ( automaticResourceInit() && shader_set.find(shader) == shader_set.end() ) { shader_set.insert(shader); // link GLSLProgram if (shader->glslProgram()) { shader->glslProgram()->linkProgram(); VL_CHECK( shader->glslProgram()->linked() ); } // lazy texture creation if ( shader->gocRenderStateSet() ) { const std::vector< ref<RenderState> >& states = shader->gocRenderStateSet()->renderStates(); for( size_t i=0; i<states.size(); ++i ) { if (states[i]->type() >= RS_TextureUnit0 && states[i]->type() < RS_TextureUnit0+VL_MAX_TEXTURE_UNITS) { TextureUnit* tex_unit = dynamic_cast<TextureUnit*>( states[i].get() ); VL_CHECK(tex_unit); if (tex_unit) { if (tex_unit->texture() && tex_unit->texture()->setupParams()) tex_unit->texture()->createTexture(); } } } } } tok->mEffectRenderRank = effect->renderRank(); } } } //------------------------------------------------------------------------------
check gl errors when context is active.
check gl errors when context is active.
C++
bsd-2-clause
Wulfire/visualizationlibrary,MicBosi/visualizationlibrary,Wulfire/visualizationlibrary,MicBosi/visualizationlibrary,MicBosi/visualizationlibrary,Wulfire/visualizationlibrary
2a0fb4ffdc5c2852362059c89ab247eefef2cf14
SDK/src/NDK/LuaBinding_SDK.cpp
SDK/src/NDK/LuaBinding_SDK.cpp
// Copyright (C) 2016 Jrme Leclercq, Arnaud Cadot // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include <NDK/LuaBinding.hpp> #include <NDK/LuaAPI.hpp> namespace Ndk { /*! * \brief Binds SDK module to Lua */ void LuaBinding::BindSDK() { /*********************************** Ndk::Application **********************************/ #ifndef NDK_SERVER //application.SetMethod("AddWindow", &Application::AddWindow); #endif application.BindMethod("AddWorld", [] (Nz::LuaInstance& instance, Application* application) -> int { instance.Push(application->AddWorld().CreateHandle()); return 1; }); application.BindMethod("GetUpdateTime", &Application::GetUpdateTime); application.BindMethod("Quit", &Application::Quit); /*********************************** Ndk::Console **********************************/ #ifndef NDK_SERVER consoleClass.Inherit<Nz::Node>(nodeClass, [] (ConsoleHandle* handle) -> Nz::Node* { return handle->GetObject(); }); consoleClass.BindMethod("AddLine", &Console::AddLine, Nz::Color::White); consoleClass.BindMethod("Clear", &Console::Clear); consoleClass.BindMethod("GetCharacterSize", &Console::GetCharacterSize); consoleClass.BindMethod("GetHistory", &Console::GetHistory); consoleClass.BindMethod("GetHistoryBackground", &Console::GetHistoryBackground); consoleClass.BindMethod("GetInput", &Console::GetInput); consoleClass.BindMethod("GetInputBackground", &Console::GetInputBackground); consoleClass.BindMethod("GetSize", &Console::GetSize); consoleClass.BindMethod("GetTextFont", &Console::GetTextFont); consoleClass.BindMethod("IsVisible", &Console::IsVisible); consoleClass.BindMethod("SendCharacter", &Console::SendCharacter); //consoleClass.SetMethod("SendEvent", &Console::SendEvent); consoleClass.BindMethod("SetCharacterSize", &Console::SetCharacterSize); consoleClass.BindMethod("SetSize", &Console::SetSize); consoleClass.BindMethod("SetTextFont", &Console::SetTextFont); consoleClass.BindMethod("Show", &Console::Show, true); #endif /*********************************** Ndk::Entity **********************************/ entityClass.BindMethod("Enable", &Entity::Enable); entityClass.BindMethod("GetId", &Entity::GetId); entityClass.BindMethod("GetWorld", &Entity::GetWorld); entityClass.BindMethod("Kill", &Entity::Kill); entityClass.BindMethod("IsEnabled", &Entity::IsEnabled); entityClass.BindMethod("IsValid", &Entity::IsValid); entityClass.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents); entityClass.BindMethod("__tostring", &EntityHandle::ToString); entityClass.BindMethod("AddComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int { ComponentBinding* binding = QueryComponentIndex(instance); return binding->adder(instance, handle); }); entityClass.BindMethod("GetComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int { ComponentBinding* binding = QueryComponentIndex(instance); return binding->getter(instance, handle->GetComponent(binding->index)); }); entityClass.BindMethod("RemoveComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int { ComponentBinding* binding = QueryComponentIndex(instance); handle->RemoveComponent(binding->index); return 0; }); /*********************************** Ndk::NodeComponent **********************************/ nodeComponent.Inherit<Nz::Node>(nodeClass, [] (NodeComponentHandle* handle) -> Nz::Node* { return handle->GetObject(); }); /*********************************** Ndk::VelocityComponent **********************************/ velocityComponent.SetGetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) { std::size_t length; const char* member = lua.CheckString(1, &length); if (std::strcmp(member, "Linear") == 0) { lua.Push(instance->linearVelocity); return true; } return false; }); velocityComponent.SetSetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) { std::size_t length; const char* member = lua.CheckString(1, &length); int argIndex = 2; if (std::strcmp(member, "Linear") == 0) { instance->linearVelocity = lua.Check<Nz::Vector3f>(&argIndex); return true; } return false; }); /*********************************** Ndk::World **********************************/ worldClass.BindMethod("CreateEntity", &World::CreateEntity); worldClass.BindMethod("CreateEntities", &World::CreateEntities); worldClass.BindMethod("Clear", &World::Clear); #ifndef NDK_SERVER /*********************************** Ndk::GraphicsComponent **********************************/ graphicsComponent.BindMethod("Attach", &GraphicsComponent::Attach, 0); #endif // Components functions m_componentBinding.resize(BaseComponent::GetMaxComponentIndex()); BindComponent<NodeComponent>("Node"); BindComponent<VelocityComponent>("Velocity"); #ifndef NDK_SERVER BindComponent<GraphicsComponent>("Graphics"); #endif } /*! * \brief Registers the classes that will be used by the Lua instance * * \param instance Lua instance that will interact with the SDK classes */ void LuaBinding::RegisterSDK(Nz::LuaInstance& instance) { // Classes application.Register(instance); entityClass.Register(instance); nodeComponent.Register(instance); velocityComponent.Register(instance); worldClass.Register(instance); #ifndef NDK_SERVER consoleClass.Register(instance); graphicsComponent.Register(instance); #endif // Enums // ComponentType (fake enumeration to expose component indexes) instance.PushTable(0, m_componentBinding.size()); { for (const ComponentBinding& entry : m_componentBinding) { if (entry.name.IsEmpty()) continue; instance.PushField(entry.name, entry.index); } } instance.SetGlobal("ComponentType"); } /*! * \brief Gets the index of the component * \return A pointer to the binding linked to a component * * \param instance Lua instance that will interact with the component * \param argIndex Index of the component */ LuaBinding::ComponentBinding* LuaBinding::QueryComponentIndex(Nz::LuaInstance& instance, int argIndex) { switch (instance.GetType(argIndex)) { case Nz::LuaType_Number: { ComponentIndex componentIndex = instance.Check<ComponentIndex>(&argIndex); if (componentIndex > m_componentBinding.size()) { instance.Error("Invalid component index"); return nullptr; } ComponentBinding& binding = m_componentBinding[componentIndex]; if (binding.name.IsEmpty()) { instance.Error("Invalid component index"); return nullptr; } return &binding; } case Nz::LuaType_String: { const char* key = instance.CheckString(argIndex); auto it = m_componentBindingByName.find(key); if (it == m_componentBindingByName.end()) { instance.Error("Invalid component name"); return nullptr; } return &m_componentBinding[it->second]; } } instance.Error("Invalid component index at #" + Nz::String::Number(argIndex)); return nullptr; } }
// Copyright (C) 2016 Jrme Leclercq, Arnaud Cadot // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include <NDK/LuaBinding.hpp> #include <NDK/LuaAPI.hpp> namespace Ndk { /*! * \brief Binds SDK module to Lua */ void LuaBinding::BindSDK() { /*********************************** Ndk::Application **********************************/ #ifndef NDK_SERVER //application.SetMethod("AddWindow", &Application::AddWindow); #endif application.BindMethod("AddWorld", [] (Nz::LuaInstance& instance, Application* application) -> int { instance.Push(application->AddWorld().CreateHandle()); return 1; }); application.BindMethod("GetUpdateTime", &Application::GetUpdateTime); application.BindMethod("Quit", &Application::Quit); /*********************************** Ndk::Console **********************************/ #ifndef NDK_SERVER consoleClass.Inherit<Nz::Node>(nodeClass, [] (ConsoleHandle* handle) -> Nz::Node* { return handle->GetObject(); }); consoleClass.BindMethod("AddLine", &Console::AddLine, Nz::Color::White); consoleClass.BindMethod("Clear", &Console::Clear); consoleClass.BindMethod("GetCharacterSize", &Console::GetCharacterSize); consoleClass.BindMethod("GetHistory", &Console::GetHistory); consoleClass.BindMethod("GetHistoryBackground", &Console::GetHistoryBackground); consoleClass.BindMethod("GetInput", &Console::GetInput); consoleClass.BindMethod("GetInputBackground", &Console::GetInputBackground); consoleClass.BindMethod("GetSize", &Console::GetSize); consoleClass.BindMethod("GetTextFont", &Console::GetTextFont); consoleClass.BindMethod("IsVisible", &Console::IsVisible); consoleClass.BindMethod("SendCharacter", &Console::SendCharacter); //consoleClass.SetMethod("SendEvent", &Console::SendEvent); consoleClass.BindMethod("SetCharacterSize", &Console::SetCharacterSize); consoleClass.BindMethod("SetSize", &Console::SetSize); consoleClass.BindMethod("SetTextFont", &Console::SetTextFont); consoleClass.BindMethod("Show", &Console::Show, true); #endif /*********************************** Ndk::Entity **********************************/ entityClass.BindMethod("Enable", &Entity::Enable, true); entityClass.BindMethod("GetId", &Entity::GetId); entityClass.BindMethod("GetWorld", &Entity::GetWorld); entityClass.BindMethod("Kill", &Entity::Kill); entityClass.BindMethod("IsEnabled", &Entity::IsEnabled); entityClass.BindMethod("IsValid", &Entity::IsValid); entityClass.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents); entityClass.BindMethod("__tostring", &EntityHandle::ToString); entityClass.BindMethod("AddComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int { ComponentBinding* binding = QueryComponentIndex(instance); return binding->adder(instance, handle); }); entityClass.BindMethod("GetComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int { ComponentBinding* binding = QueryComponentIndex(instance); return binding->getter(instance, handle->GetComponent(binding->index)); }); entityClass.BindMethod("RemoveComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int { ComponentBinding* binding = QueryComponentIndex(instance); handle->RemoveComponent(binding->index); return 0; }); /*********************************** Ndk::NodeComponent **********************************/ nodeComponent.Inherit<Nz::Node>(nodeClass, [] (NodeComponentHandle* handle) -> Nz::Node* { return handle->GetObject(); }); /*********************************** Ndk::VelocityComponent **********************************/ velocityComponent.SetGetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) { std::size_t length; const char* member = lua.CheckString(1, &length); if (std::strcmp(member, "Linear") == 0) { lua.Push(instance->linearVelocity); return true; } return false; }); velocityComponent.SetSetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) { std::size_t length; const char* member = lua.CheckString(1, &length); int argIndex = 2; if (std::strcmp(member, "Linear") == 0) { instance->linearVelocity = lua.Check<Nz::Vector3f>(&argIndex); return true; } return false; }); /*********************************** Ndk::World **********************************/ worldClass.BindMethod("CreateEntity", &World::CreateEntity); worldClass.BindMethod("CreateEntities", &World::CreateEntities); worldClass.BindMethod("Clear", &World::Clear); #ifndef NDK_SERVER /*********************************** Ndk::GraphicsComponent **********************************/ graphicsComponent.BindMethod("Attach", &GraphicsComponent::Attach, 0); #endif // Components functions m_componentBinding.resize(BaseComponent::GetMaxComponentIndex()); BindComponent<NodeComponent>("Node"); BindComponent<VelocityComponent>("Velocity"); #ifndef NDK_SERVER BindComponent<GraphicsComponent>("Graphics"); #endif } /*! * \brief Registers the classes that will be used by the Lua instance * * \param instance Lua instance that will interact with the SDK classes */ void LuaBinding::RegisterSDK(Nz::LuaInstance& instance) { // Classes application.Register(instance); entityClass.Register(instance); nodeComponent.Register(instance); velocityComponent.Register(instance); worldClass.Register(instance); #ifndef NDK_SERVER consoleClass.Register(instance); graphicsComponent.Register(instance); #endif // Enums // ComponentType (fake enumeration to expose component indexes) instance.PushTable(0, m_componentBinding.size()); { for (const ComponentBinding& entry : m_componentBinding) { if (entry.name.IsEmpty()) continue; instance.PushField(entry.name, entry.index); } } instance.SetGlobal("ComponentType"); } /*! * \brief Gets the index of the component * \return A pointer to the binding linked to a component * * \param instance Lua instance that will interact with the component * \param argIndex Index of the component */ LuaBinding::ComponentBinding* LuaBinding::QueryComponentIndex(Nz::LuaInstance& instance, int argIndex) { switch (instance.GetType(argIndex)) { case Nz::LuaType_Number: { ComponentIndex componentIndex = instance.Check<ComponentIndex>(&argIndex); if (componentIndex > m_componentBinding.size()) { instance.Error("Invalid component index"); return nullptr; } ComponentBinding& binding = m_componentBinding[componentIndex]; if (binding.name.IsEmpty()) { instance.Error("Invalid component index"); return nullptr; } return &binding; } case Nz::LuaType_String: { const char* key = instance.CheckString(argIndex); auto it = m_componentBindingByName.find(key); if (it == m_componentBindingByName.end()) { instance.Error("Invalid component name"); return nullptr; } return &m_componentBinding[it->second]; } } instance.Error("Invalid component index at #" + Nz::String::Number(argIndex)); return nullptr; } }
Fix Entity::Enable default argument
Sdk/Binding: Fix Entity::Enable default argument Former-commit-id: 82181122fca24b99e78ba927c71ce9237b1b3674 [formerly ef758ac2d0aac925dbcd6e72effc21b9effa83c0] [formerly 2555ac6b28f36b220aea76f2aeb0012536665058 [formerly b28da55971c4db17ddbf7fd6bacd8c03d02ffcbd]] Former-commit-id: 8a84469ff40d37e114fbdee8c3fa16a3748ca010 [formerly 3f3cfc52071d469150feeaf2f7cdff8c33a8f46f] Former-commit-id: 8f522f2357b7564229ebdea1e8d4a2b3cc223366
C++
mit
DigitalPulseSoftware/NazaraEngine
02eb5b8f1204d8ee80d487ef79f9aaba03df8984
plugins/input/shape/shape_io.cpp
plugins/input/shape/shape_io.cpp
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "shape_io.hpp" // mapnik #include <mapnik/datasource.hpp> // boost #include <boost/filesystem/operations.hpp> #include <boost/make_shared.hpp> using mapnik::datasource_exception; using mapnik::geometry_type; const std::string shape_io::SHP = ".shp"; const std::string shape_io::DBF = ".dbf"; const std::string shape_io::INDEX = ".index"; shape_io::shape_io(const std::string& shape_name, bool open_index) : type_(shape_null), shp_(shape_name + SHP), dbf_(shape_name + DBF), reclength_(0), id_(0) { bool ok = (shp_.is_open() && dbf_.is_open()); if (! ok) { throw datasource_exception("Shape Plugin: cannot read shape file '" + shape_name + "'"); } if (open_index) { try { index_= boost::make_shared<shape_file>(shape_name + INDEX); } catch (...) { #ifdef MAPNIK_DEBUG std::clog << "Shape Plugin: warning - could not open index: '" + shape_name + INDEX + "'" << std::endl; #endif } } } shape_io::~shape_io() {} void shape_io::move_to(int pos) { shp_.seek(pos); id_ = shp_.read_xdr_integer(); reclength_ = shp_.read_xdr_integer(); type_ = shp_.read_ndr_integer(); if (type_ != shape_null && type_ != shape_point && type_ != shape_pointm && type_ != shape_pointz) { shp_.read_envelope(cur_extent_); } } int shape_io::type() const { return type_; } const box2d<double>& shape_io::current_extent() const { return cur_extent_; } shape_file& shape_io::shp() { return shp_; } #if 0 shape_file& shape_io::shx() { return shx_; } #endif dbf_file& shape_io::dbf() { return dbf_; } void shape_io::read_polyline(mapnik::geometry_container & geom) { shape_file::record_type record(reclength_ * 2 - 36); shp_.read_record(record); int num_parts = record.read_ndr_integer(); int num_points = record.read_ndr_integer(); if (num_parts == 1) { geometry_type* line = new geometry_type(mapnik::LineString); record.skip(4); double x = record.read_double(); double y = record.read_double(); line->move_to(x, y); for (int i = 1; i < num_points; ++i) { x = record.read_double(); y = record.read_double(); line->line_to(x, y); } geom.push_back(line); } else { std::vector<int> parts(num_parts); for (int i = 0; i < num_parts; ++i) { parts[i] = record.read_ndr_integer(); } int start, end; for (int k = 0; k < num_parts; ++k) { geometry_type* line = new geometry_type(mapnik::LineString); start = parts[k]; if (k == num_parts - 1) { end = num_points; } else { end = parts[k + 1]; } double x = record.read_double(); double y = record.read_double(); line->move_to(x, y); for (int j = start + 1; j < end; ++j) { x = record.read_double(); y = record.read_double(); line->line_to(x, y); } geom.push_back(line); } } // z-range //double z0=record.read_double(); //double z1=record.read_double(); //for (int i=0;i<num_points;++i) // { // double z=record.read_double(); // } // m-range //double m0=record.read_double(); //double m1=record.read_double(); //for (int i=0;i<num_points;++i) //{ // double m=record.read_double(); //} } void shape_io::read_polygon(mapnik::geometry_container & geom) { shape_file::record_type record(reclength_ * 2 - 36); shp_.read_record(record); int num_parts = record.read_ndr_integer(); int num_points = record.read_ndr_integer(); std::vector<int> parts(num_parts); for (int i = 0; i < num_parts; ++i) { parts[i] = record.read_ndr_integer(); } for (int k = 0; k < num_parts; k++) { geometry_type* poly = new geometry_type(mapnik::Polygon); int start = parts[k]; int end; if (k == num_parts - 1) { end = num_points; } else { end = parts[k + 1]; } double x = record.read_double(); double y = record.read_double(); poly->move_to(x, y); for (int j=start+1;j<end;j++) { x = record.read_double(); y = record.read_double(); poly->line_to(x, y); } geom.push_back(poly); } // z-range //double z0=record.read_double(); //double z1=record.read_double(); //for (int i=0;i<num_points;++i) //{ // double z=record.read_double(); //} // m-range //double m0=record.read_double(); //double m1=record.read_double(); //for (int i=0;i<num_points;++i) //{ // double m=record.read_double(); //} }
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "shape_io.hpp" // mapnik #include <mapnik/datasource.hpp> // boost #include <boost/filesystem/operations.hpp> #include <boost/make_shared.hpp> using mapnik::datasource_exception; using mapnik::geometry_type; const std::string shape_io::SHP = ".shp"; const std::string shape_io::DBF = ".dbf"; const std::string shape_io::INDEX = ".index"; shape_io::shape_io(const std::string& shape_name, bool open_index) : type_(shape_null), shp_(shape_name + SHP), dbf_(shape_name + DBF), reclength_(0), id_(0) { bool ok = (shp_.is_open() && dbf_.is_open()); if (! ok) { throw datasource_exception("Shape Plugin: cannot read shape file '" + shape_name + "'"); } if (open_index) { try { index_= boost::make_shared<shape_file>(shape_name + INDEX); } catch (...) { #ifdef MAPNIK_DEBUG std::clog << "Shape Plugin: warning - could not open index: '" + shape_name + INDEX + "'" << std::endl; #endif } } } shape_io::~shape_io() {} void shape_io::move_to(int pos) { shp_.seek(pos); id_ = shp_.read_xdr_integer(); reclength_ = shp_.read_xdr_integer(); type_ = shp_.read_ndr_integer(); if (type_ != shape_null && type_ != shape_point && type_ != shape_pointm && type_ != shape_pointz) { shp_.read_envelope(cur_extent_); } } int shape_io::type() const { return type_; } const box2d<double>& shape_io::current_extent() const { return cur_extent_; } shape_file& shape_io::shp() { return shp_; } #if 0 shape_file& shape_io::shx() { return shx_; } #endif dbf_file& shape_io::dbf() { return dbf_; } void shape_io::read_polyline(mapnik::geometry_container & geom) { shape_file::record_type record(reclength_ * 2 - 36); shp_.read_record(record); int num_parts = record.read_ndr_integer(); int num_points = record.read_ndr_integer(); if (num_parts == 1) { geometry_type* line = new geometry_type(mapnik::LineString); record.skip(4); double x = record.read_double(); double y = record.read_double(); line->move_to(x, y); for (int i = 1; i < num_points; ++i) { x = record.read_double(); y = record.read_double(); line->line_to(x, y); } geom.push_back(line); } else { std::vector<int> parts(num_parts); for (int i = 0; i < num_parts; ++i) { parts[i] = record.read_ndr_integer(); } int start, end; for (int k = 0; k < num_parts; ++k) { geometry_type* line = new geometry_type(mapnik::LineString); start = parts[k]; if (k == num_parts - 1) { end = num_points; } else { end = parts[k + 1]; } double x = record.read_double(); double y = record.read_double(); line->move_to(x, y); for (int j = start + 1; j < end; ++j) { x = record.read_double(); y = record.read_double(); line->line_to(x, y); } geom.push_back(line); } } // z-range //double z0=record.read_double(); //double z1=record.read_double(); //for (int i=0;i<num_points;++i) // { // double z=record.read_double(); // } // m-range //double m0=record.read_double(); //double m1=record.read_double(); //for (int i=0;i<num_points;++i) //{ // double m=record.read_double(); //} } void shape_io::read_polygon(mapnik::geometry_container & geom) { shape_file::record_type record(reclength_ * 2 - 36); shp_.read_record(record); int num_parts = record.read_ndr_integer(); int num_points = record.read_ndr_integer(); std::vector<int> parts(num_parts); for (int i = 0; i < num_parts; ++i) { parts[i] = record.read_ndr_integer(); } geometry_type* poly = new geometry_type(mapnik::Polygon); for (int k = 0; k < num_parts; k++) { int start = parts[k]; int end; if (k == num_parts - 1) { end = num_points; } else { end = parts[k + 1]; } double x = record.read_double(); double y = record.read_double(); if (k > 0 && !poly->hit_test(x,y,0)) { geom.push_back(poly); poly = new geometry_type(mapnik::Polygon); } poly->move_to(x, y); for (int j=start+1;j<end;j++) { x = record.read_double(); y = record.read_double(); poly->line_to(x, y); } } geom.push_back(poly); // z-range //double z0=record.read_double(); //double z1=record.read_double(); //for (int i=0;i<num_points;++i) //{ // double z=record.read_double(); //} // m-range //double m0=record.read_double(); //double m1=record.read_double(); //for (int i=0;i<num_points;++i) //{ // double m=record.read_double(); //} }
check if multiple parts are interior rings or separate polygons. Currently only test if first coordinate inside exterior ring and assume first ring is exterior.
shape: check if multiple parts are interior rings or separate polygons. Currently only test if first coordinate inside exterior ring and assume first ring is exterior. If this approach is not robust enough we can calculate ring orientations instead. Shape file convention is: CW - exterior, CCW - interior. very simple
C++
lgpl-2.1
qianwenming/mapnik,rouault/mapnik,whuaegeanse/mapnik,tomhughes/python-mapnik,qianwenming/mapnik,lightmare/mapnik,garnertb/python-mapnik,Uli1/mapnik,pramsey/mapnik,sebastic/python-mapnik,naturalatlas/mapnik,rouault/mapnik,mapycz/mapnik,sebastic/python-mapnik,Airphrame/mapnik,stefanklug/mapnik,jwomeara/mapnik,pramsey/mapnik,qianwenming/mapnik,lightmare/mapnik,CartoDB/mapnik,zerebubuth/mapnik,manz/python-mapnik,mapnik/python-mapnik,CartoDB/mapnik,mbrukman/mapnik,yohanboniface/python-mapnik,Uli1/mapnik,jwomeara/mapnik,stefanklug/mapnik,sebastic/python-mapnik,garnertb/python-mapnik,mbrukman/mapnik,Airphrame/mapnik,zerebubuth/mapnik,whuaegeanse/mapnik,strk/mapnik,mapycz/python-mapnik,kapouer/mapnik,manz/python-mapnik,naturalatlas/mapnik,naturalatlas/mapnik,mbrukman/mapnik,yohanboniface/python-mapnik,whuaegeanse/mapnik,manz/python-mapnik,naturalatlas/mapnik,tomhughes/python-mapnik,tomhughes/mapnik,mapycz/python-mapnik,mapnik/mapnik,Mappy/mapnik,cjmayo/mapnik,jwomeara/mapnik,stefanklug/mapnik,mapycz/mapnik,pnorman/mapnik,cjmayo/mapnik,kapouer/mapnik,rouault/mapnik,jwomeara/mapnik,yiqingj/work,pramsey/mapnik,pramsey/mapnik,pnorman/mapnik,mbrukman/mapnik,yiqingj/work,Mappy/mapnik,qianwenming/mapnik,lightmare/mapnik,davenquinn/python-mapnik,strk/mapnik,Uli1/mapnik,yiqingj/work,mapnik/mapnik,strk/mapnik,Airphrame/mapnik,tomhughes/mapnik,garnertb/python-mapnik,cjmayo/mapnik,mapnik/mapnik,whuaegeanse/mapnik,yohanboniface/python-mapnik,tomhughes/mapnik,Mappy/mapnik,stefanklug/mapnik,Airphrame/mapnik,kapouer/mapnik,mapnik/mapnik,mapycz/mapnik,yiqingj/work,mapnik/python-mapnik,mapnik/python-mapnik,pnorman/mapnik,kapouer/mapnik,Uli1/mapnik,CartoDB/mapnik,pnorman/mapnik,davenquinn/python-mapnik,tomhughes/python-mapnik,davenquinn/python-mapnik,Mappy/mapnik,strk/mapnik,tomhughes/mapnik,lightmare/mapnik,zerebubuth/mapnik,qianwenming/mapnik,cjmayo/mapnik,rouault/mapnik
8c9d7399a65d31d1c1098165233ff3c4940715f8
plugins/latex/latexguiclient.cpp
plugins/latex/latexguiclient.cpp
/* latexguiclient.cpp - Kopete LaTeX plugin Copyright (c) 2003-2005 by Olivier Goffart <[email protected]> Kopete (c) 2003-2005 by the Kopete developers <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <qvariant.h> #include <kaction.h> #include <klocale.h> #include <kmessagebox.h> #include <kicon.h> #include <qimage.h> #include <qregexp.h> #include "kopetechatsession.h" #include "kopeteview.h" #include "kopetemessage.h" #include "latexplugin.h" #include "latexguiclient.h" #include <kactioncollection.h> LatexGUIClient::LatexGUIClient( Kopete::ChatSession *parent ) : QObject( parent), KXMLGUIClient( parent ) { setComponentData( LatexPlugin::plugin()->componentData() ); connect( LatexPlugin::plugin(), SIGNAL( destroyed( QObject * ) ), this, SLOT( deleteLater() ) ); m_manager = parent; KAction *previewAction = new KAction( KIcon("latex"), i18n( "Preview Latex Images" ), this ); actionCollection()->addAction( "latexPreview", previewAction ); previewAction->setShortcut( KShortcut(Qt::CTRL + Qt::Key_L) ); connect(previewAction, SIGNAL( triggered(bool) ), this, SLOT( slotPreview() ) ); setXMLFile( "latexchatui.rc" ); } LatexGUIClient::~LatexGUIClient() { } void LatexGUIClient::slotPreview() { if ( !m_manager->view() ) return; Kopete::Message msg = m_manager->view()->currentMessage(); const QString messageText = msg.plainBody(); if(!messageText.contains("$$")) //we haven't found any latex strings { KMessageBox::sorry(m_manager->view()->mainWidget() , i18n("The message you are typing does not contain any LaTeX. A LaTeX formula must be enclosed within two pairs of dollar signs: $$formula$$ "), i18n("No LaTeX Formula") ); return; } const QString oldBody = msg.plainBody(); msg=Kopete::Message( msg.from() , msg.to() ); msg.setHtmlBody( i18n("<b>Preview of the LaTeX message :</b> <br />%1", oldBody) ); msg.setDirection( Kopete::Message::Internal ); m_manager->appendMessage(msg) ; } #include "latexguiclient.moc" // vim: set noet ts=4 sts=4 sw=4:
/* latexguiclient.cpp - Kopete LaTeX plugin Copyright (c) 2003-2005 by Olivier Goffart <[email protected]> Kopete (c) 2003-2005 by the Kopete developers <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <qvariant.h> #include <kaction.h> #include <klocale.h> #include <kmessagebox.h> #include <kicon.h> #include <qimage.h> #include <qregexp.h> #include "kopetechatsession.h" #include "kopeteview.h" #include "kopetemessage.h" #include "latexplugin.h" #include "latexguiclient.h" #include <kactioncollection.h> LatexGUIClient::LatexGUIClient( Kopete::ChatSession *parent ) : QObject( parent), KXMLGUIClient( parent ) { setComponentData( LatexPlugin::plugin()->componentData() ); connect( LatexPlugin::plugin(), SIGNAL( destroyed( QObject * ) ), this, SLOT( deleteLater() ) ); m_manager = parent; KAction *previewAction = new KAction( KIcon("latex"), i18n( "Preview Latex Images" ), this ); actionCollection()->addAction( "latexPreview", previewAction ); previewAction->setShortcut( KShortcut(Qt::CTRL + Qt::Key_L) ); connect(previewAction, SIGNAL( triggered(bool) ), this, SLOT( slotPreview() ) ); setXMLFile( "latexchatui.rc" ); } LatexGUIClient::~LatexGUIClient() { } void LatexGUIClient::slotPreview() { if ( !m_manager->view() ) return; Kopete::Message msg = m_manager->view()->currentMessage(); const QString messageText = msg.plainBody(); if(!messageText.contains("$$")) //we haven't found any latex strings { KMessageBox::sorry(m_manager->view()->mainWidget() , i18n("The message you are typing does not contain any LaTeX. A LaTeX formula must be enclosed within two pairs of dollar signs: $$formula$$ "), i18n("No LaTeX Formula") ); return; } const QString oldBody = msg.escapedBody(); msg=Kopete::Message( msg.from() , msg.to() ); msg.setHtmlBody( i18n("<b>Preview of the LaTeX message :</b> <br />%1", oldBody) ); msg.setDirection( Kopete::Message::Internal ); m_manager->appendMessage(msg) ; } #include "latexguiclient.moc" // vim: set noet ts=4 sts=4 sw=4:
Enable html text in latex preview message
Enable html text in latex preview message svn path=/trunk/KDE/kdenetwork/kopete/; revision=1203888
C++
lgpl-2.1
josh-wambua/kopete,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,josh-wambua/kopete
a9b36c942fad35cc8fa821c97589910f1f12e152
chrome/browser/process_singleton_win.cc
chrome/browser/process_singleton_win.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/process_singleton.h" #include "base/base_paths.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/utf_string_conversions.h" #include "base/win/scoped_handle.h" #include "base/win/wrapped_window_proc.h" #include "chrome/browser/ui/simple_message_box.h" #include "chrome/common/chrome_constants.h" #include "chrome/installer/util/wmi.h" #include "content/public/common/result_codes.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/win/hwnd_util.h" namespace { // Checks the visibility of the enumerated window and signals once a visible // window has been found. BOOL CALLBACK BrowserWindowEnumeration(HWND window, LPARAM param) { bool* result = reinterpret_cast<bool*>(param); *result = IsWindowVisible(window) != 0; // Stops enumeration if a visible window has been found. return !*result; } // This function thunks to the object's version of the windowproc, taking in // consideration that there are several messages being dispatched before // WM_NCCREATE which we let windows handle. LRESULT CALLBACK ThunkWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { ProcessSingleton* singleton = reinterpret_cast<ProcessSingleton*>(ui::GetWindowUserData(hwnd)); if (message == WM_NCCREATE) { CREATESTRUCT* cs = reinterpret_cast<CREATESTRUCT*>(lparam); singleton = reinterpret_cast<ProcessSingleton*>(cs->lpCreateParams); CHECK(singleton); ui::SetWindowUserData(hwnd, singleton); } else if (!singleton) { return ::DefWindowProc(hwnd, message, wparam, lparam); } return singleton->WndProc(hwnd, message, wparam, lparam); } bool ParseCommandLine(const COPYDATASTRUCT* cds, CommandLine* parsed_command_line, FilePath* current_directory) { // We should have enough room for the shortest command (min_message_size) // and also be a multiple of wchar_t bytes. The shortest command // possible is L"START\0\0" (empty current directory and command line). static const int min_message_size = 7; if (cds->cbData < min_message_size * sizeof(wchar_t) || cds->cbData % sizeof(wchar_t) != 0) { LOG(WARNING) << "Invalid WM_COPYDATA, length = " << cds->cbData; return false; } // We split the string into 4 parts on NULLs. DCHECK(cds->lpData); const std::wstring msg(static_cast<wchar_t*>(cds->lpData), cds->cbData / sizeof(wchar_t)); const std::wstring::size_type first_null = msg.find_first_of(L'\0'); if (first_null == 0 || first_null == std::wstring::npos) { // no NULL byte, don't know what to do LOG(WARNING) << "Invalid WM_COPYDATA, length = " << msg.length() << ", first null = " << first_null; return false; } // Decode the command, which is everything until the first NULL. if (msg.substr(0, first_null) == L"START") { // Another instance is starting parse the command line & do what it would // have done. VLOG(1) << "Handling STARTUP request from another process"; const std::wstring::size_type second_null = msg.find_first_of(L'\0', first_null + 1); if (second_null == std::wstring::npos || first_null == msg.length() - 1 || second_null == msg.length()) { LOG(WARNING) << "Invalid format for start command, we need a string in 4 " "parts separated by NULLs"; return false; } // Get current directory. *current_directory = FilePath(msg.substr(first_null + 1, second_null - first_null)); const std::wstring::size_type third_null = msg.find_first_of(L'\0', second_null + 1); if (third_null == std::wstring::npos || third_null == msg.length()) { LOG(WARNING) << "Invalid format for start command, we need a string in 4 " "parts separated by NULLs"; } // Get command line. const std::wstring cmd_line = msg.substr(second_null + 1, third_null - second_null); *parsed_command_line = CommandLine::FromString(cmd_line); return true; } return false; } } // namespace // Microsoft's Softricity virtualization breaks the sandbox processes. // So, if we detect the Softricity DLL we use WMI Win32_Process.Create to // break out of the virtualization environment. // http://code.google.com/p/chromium/issues/detail?id=43650 bool ProcessSingleton::EscapeVirtualization(const FilePath& user_data_dir) { if (::GetModuleHandle(L"sftldr_wow64.dll") || ::GetModuleHandle(L"sftldr.dll")) { int process_id; if (!installer::WMIProcess::Launch(GetCommandLineW(), &process_id)) return false; is_virtualized_ = true; // The new window was spawned from WMI, and won't be in the foreground. // So, first we sleep while the new chrome.exe instance starts (because // WaitForInputIdle doesn't work here). Then we poll for up to two more // seconds and make the window foreground if we find it (or we give up). HWND hwnd = 0; ::Sleep(90); for (int tries = 200; tries; --tries) { hwnd = FindWindowEx(HWND_MESSAGE, NULL, chrome::kMessageWindowClass, user_data_dir.value().c_str()); if (hwnd) { ::SetForegroundWindow(hwnd); break; } ::Sleep(10); } return true; } return false; } // Look for a Chrome instance that uses the same profile directory. // If there isn't one, create a message window with its title set to // the profile directory path. ProcessSingleton::ProcessSingleton(const FilePath& user_data_dir) : window_(NULL), locked_(false), foreground_window_(NULL), is_virtualized_(false) { remote_window_ = FindWindowEx(HWND_MESSAGE, NULL, chrome::kMessageWindowClass, user_data_dir.value().c_str()); if (!remote_window_ && !EscapeVirtualization(user_data_dir)) { // Make sure we will be the one and only process creating the window. // We use a named Mutex since we are protecting against multi-process // access. As documented, it's clearer to NOT request ownership on creation // since it isn't guaranteed we will get it. It is better to create it // without ownership and explicitly get the ownership afterward. std::wstring mutex_name(L"Local\\ChromeProcessSingletonStartup!"); base::win::ScopedHandle only_me( CreateMutex(NULL, FALSE, mutex_name.c_str())); DCHECK(only_me.Get() != NULL) << "GetLastError = " << GetLastError(); // This is how we acquire the mutex (as opposed to the initial ownership). DWORD result = WaitForSingleObject(only_me, INFINITE); DCHECK(result == WAIT_OBJECT_0) << "Result = " << result << "GetLastError = " << GetLastError(); // We now own the mutex so we are the only process that can create the // window at this time, but we must still check if someone created it // between the time where we looked for it above and the time the mutex // was given to us. remote_window_ = FindWindowEx(HWND_MESSAGE, NULL, chrome::kMessageWindowClass, user_data_dir.value().c_str()); if (!remote_window_) { HINSTANCE hinst = base::GetModuleFromAddress(&ThunkWndProc); WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpfnWndProc = base::win::WrappedWindowProc<ThunkWndProc>; wc.hInstance = hinst; wc.lpszClassName = chrome::kMessageWindowClass; ATOM clazz = ::RegisterClassEx(&wc); DCHECK(clazz); // Set the window's title to the path of our user data directory so other // Chrome instances can decide if they should forward to us or not. window_ = ::CreateWindow(MAKEINTATOM(clazz), user_data_dir.value().c_str(), 0, 0, 0, 0, 0, HWND_MESSAGE, 0, hinst, this); CHECK(window_); } BOOL success = ReleaseMutex(only_me); DCHECK(success) << "GetLastError = " << GetLastError(); } } ProcessSingleton::~ProcessSingleton() { Cleanup(); } ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() { if (is_virtualized_) return PROCESS_NOTIFIED; // We already spawned the process in this case. else if (!remote_window_) return PROCESS_NONE; // Found another window, send our command line to it // format is "START\0<<<current directory>>>\0<<<commandline>>>". std::wstring to_send(L"START\0", 6); // want the NULL in the string. FilePath cur_dir; if (!PathService::Get(base::DIR_CURRENT, &cur_dir)) return PROCESS_NONE; to_send.append(cur_dir.value()); to_send.append(L"\0", 1); // Null separator. to_send.append(GetCommandLineW()); to_send.append(L"\0", 1); // Null separator. // Allow the current running browser window making itself the foreground // window (otherwise it will just flash in the taskbar). DWORD process_id = 0; DWORD thread_id = GetWindowThreadProcessId(remote_window_, &process_id); // It is possible that the process owning this window may have died by now. if (!thread_id || !process_id) { remote_window_ = NULL; return PROCESS_NONE; } AllowSetForegroundWindow(process_id); COPYDATASTRUCT cds; cds.dwData = 0; cds.cbData = static_cast<DWORD>((to_send.length() + 1) * sizeof(wchar_t)); cds.lpData = const_cast<wchar_t*>(to_send.c_str()); DWORD_PTR result = 0; if (SendMessageTimeout(remote_window_, WM_COPYDATA, NULL, reinterpret_cast<LPARAM>(&cds), SMTO_ABORTIFHUNG, kTimeoutInSeconds * 1000, &result)) { // It is possible that the process owning this window may have died by now. if (!result) { remote_window_ = NULL; return PROCESS_NONE; } return PROCESS_NOTIFIED; } // It is possible that the process owning this window may have died by now. if (!IsWindow(remote_window_)) { remote_window_ = NULL; return PROCESS_NONE; } // The window is hung. Scan for every window to find a visible one. bool visible_window = false; EnumThreadWindows(thread_id, &BrowserWindowEnumeration, reinterpret_cast<LPARAM>(&visible_window)); // If there is a visible browser window, ask the user before killing it. if (visible_window && browser::ShowMessageBox(NULL, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME), l10n_util::GetStringUTF16(IDS_BROWSER_HUNGBROWSER_MESSAGE), browser::MESSAGE_BOX_TYPE_QUESTION) == browser::MESSAGE_BOX_RESULT_NO) { // The user denied. Quit silently. return PROCESS_NOTIFIED; } // Time to take action. Kill the browser process. base::KillProcessById(process_id, content::RESULT_CODE_HUNG, true); remote_window_ = NULL; return PROCESS_NONE; } ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessOrCreate( const NotificationCallback& notification_callback) { NotifyResult result = NotifyOtherProcess(); if (result != PROCESS_NONE) return result; return Create(notification_callback) ? PROCESS_NONE : PROFILE_IN_USE; } // On Windows, there is no need to call Create() since the message // window is created in the constructor but to avoid having more // platform specific code in browser_main.cc we tolerate calls to // Create(). bool ProcessSingleton::Create( const NotificationCallback& notification_callback) { DCHECK(!remote_window_); DCHECK(notification_callback_.is_null()); if (window_ != NULL) notification_callback_ = notification_callback; return window_ != NULL; } void ProcessSingleton::Cleanup() { // Window classes registered by DLLs are not cleaned up automatically on // process exit, so we must unregister at the earliest chance possible. // During the fast shutdown sequence, ProcessSingleton::Cleanup() is // called if our process was the first to start. Therefore we try cleaning // up here, and again in the destructor if needed to catch as many cases // as possible. if (window_) { ::DestroyWindow(window_); ::UnregisterClass(chrome::kMessageWindowClass, base::GetModuleFromAddress(&ThunkWndProc)); window_ = NULL; } } LRESULT ProcessSingleton::OnCopyData(HWND hwnd, const COPYDATASTRUCT* cds) { // If locked, it means we are not ready to process this message because // we are probably in a first run critical phase. if (locked_) { #if defined(USE_AURA) NOTIMPLEMENTED(); #else // Attempt to place ourselves in the foreground / flash the task bar. if (foreground_window_ != NULL && IsWindow(foreground_window_)) { SetForegroundWindow(foreground_window_); } else { // Read the command line and store it. It will be replayed when the // ProcessSingleton becomes unlocked. CommandLine parsed_command_line(CommandLine::NO_PROGRAM); FilePath current_directory; if (ParseCommandLine(cds, &parsed_command_line, &current_directory)) saved_startup_messages_.push_back( std::make_pair(parsed_command_line.argv(), current_directory)); } #endif return TRUE; } CommandLine parsed_command_line(CommandLine::NO_PROGRAM); FilePath current_directory; if (!ParseCommandLine(cds, &parsed_command_line, &current_directory)) return TRUE; return notification_callback_.Run(parsed_command_line, current_directory) ? TRUE : FALSE; } LRESULT ProcessSingleton::WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { switch (message) { case WM_COPYDATA: return OnCopyData(reinterpret_cast<HWND>(wparam), reinterpret_cast<COPYDATASTRUCT*>(lparam)); default: break; } return ::DefWindowProc(hwnd, message, wparam, lparam); }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/process_singleton.h" #include "base/base_paths.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/utf_string_conversions.h" #include "base/win/scoped_handle.h" #include "base/win/wrapped_window_proc.h" #include "chrome/browser/ui/simple_message_box.h" #include "chrome/common/chrome_constants.h" #include "chrome/installer/util/wmi.h" #include "content/public/common/result_codes.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/win/hwnd_util.h" namespace { // Checks the visibility of the enumerated window and signals once a visible // window has been found. BOOL CALLBACK BrowserWindowEnumeration(HWND window, LPARAM param) { bool* result = reinterpret_cast<bool*>(param); *result = IsWindowVisible(window) != 0; // Stops enumeration if a visible window has been found. return !*result; } // This function thunks to the object's version of the windowproc, taking in // consideration that there are several messages being dispatched before // WM_NCCREATE which we let windows handle. LRESULT CALLBACK ThunkWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { ProcessSingleton* singleton = reinterpret_cast<ProcessSingleton*>(ui::GetWindowUserData(hwnd)); if (message == WM_NCCREATE) { CREATESTRUCT* cs = reinterpret_cast<CREATESTRUCT*>(lparam); singleton = reinterpret_cast<ProcessSingleton*>(cs->lpCreateParams); CHECK(singleton); ui::SetWindowUserData(hwnd, singleton); } else if (!singleton) { return ::DefWindowProc(hwnd, message, wparam, lparam); } return singleton->WndProc(hwnd, message, wparam, lparam); } bool ParseCommandLine(const COPYDATASTRUCT* cds, CommandLine* parsed_command_line, FilePath* current_directory) { // We should have enough room for the shortest command (min_message_size) // and also be a multiple of wchar_t bytes. The shortest command // possible is L"START\0\0" (empty current directory and command line). static const int min_message_size = 7; if (cds->cbData < min_message_size * sizeof(wchar_t) || cds->cbData % sizeof(wchar_t) != 0) { LOG(WARNING) << "Invalid WM_COPYDATA, length = " << cds->cbData; return false; } // We split the string into 4 parts on NULLs. DCHECK(cds->lpData); const std::wstring msg(static_cast<wchar_t*>(cds->lpData), cds->cbData / sizeof(wchar_t)); const std::wstring::size_type first_null = msg.find_first_of(L'\0'); if (first_null == 0 || first_null == std::wstring::npos) { // no NULL byte, don't know what to do LOG(WARNING) << "Invalid WM_COPYDATA, length = " << msg.length() << ", first null = " << first_null; return false; } // Decode the command, which is everything until the first NULL. if (msg.substr(0, first_null) == L"START") { // Another instance is starting parse the command line & do what it would // have done. VLOG(1) << "Handling STARTUP request from another process"; const std::wstring::size_type second_null = msg.find_first_of(L'\0', first_null + 1); if (second_null == std::wstring::npos || first_null == msg.length() - 1 || second_null == msg.length()) { LOG(WARNING) << "Invalid format for start command, we need a string in 4 " "parts separated by NULLs"; return false; } // Get current directory. *current_directory = FilePath(msg.substr(first_null + 1, second_null - first_null)); const std::wstring::size_type third_null = msg.find_first_of(L'\0', second_null + 1); if (third_null == std::wstring::npos || third_null == msg.length()) { LOG(WARNING) << "Invalid format for start command, we need a string in 4 " "parts separated by NULLs"; } // Get command line. const std::wstring cmd_line = msg.substr(second_null + 1, third_null - second_null); *parsed_command_line = CommandLine::FromString(cmd_line); return true; } return false; } } // namespace // Microsoft's Softricity virtualization breaks the sandbox processes. // So, if we detect the Softricity DLL we use WMI Win32_Process.Create to // break out of the virtualization environment. // http://code.google.com/p/chromium/issues/detail?id=43650 bool ProcessSingleton::EscapeVirtualization(const FilePath& user_data_dir) { if (::GetModuleHandle(L"sftldr_wow64.dll") || ::GetModuleHandle(L"sftldr.dll")) { int process_id; if (!installer::WMIProcess::Launch(GetCommandLineW(), &process_id)) return false; is_virtualized_ = true; // The new window was spawned from WMI, and won't be in the foreground. // So, first we sleep while the new chrome.exe instance starts (because // WaitForInputIdle doesn't work here). Then we poll for up to two more // seconds and make the window foreground if we find it (or we give up). HWND hwnd = 0; ::Sleep(90); for (int tries = 200; tries; --tries) { hwnd = FindWindowEx(HWND_MESSAGE, NULL, chrome::kMessageWindowClass, user_data_dir.value().c_str()); if (hwnd) { ::SetForegroundWindow(hwnd); break; } ::Sleep(10); } return true; } return false; } // Look for a Chrome instance that uses the same profile directory. // If there isn't one, create a message window with its title set to // the profile directory path. ProcessSingleton::ProcessSingleton(const FilePath& user_data_dir) : window_(NULL), locked_(false), foreground_window_(NULL), is_virtualized_(false) { remote_window_ = FindWindowEx(HWND_MESSAGE, NULL, chrome::kMessageWindowClass, user_data_dir.value().c_str()); if (!remote_window_ && !EscapeVirtualization(user_data_dir)) { // Make sure we will be the one and only process creating the window. // We use a named Mutex since we are protecting against multi-process // access. As documented, it's clearer to NOT request ownership on creation // since it isn't guaranteed we will get it. It is better to create it // without ownership and explicitly get the ownership afterward. std::wstring mutex_name(L"Local\\ChromeProcessSingletonStartup!"); base::win::ScopedHandle only_me( CreateMutex(NULL, FALSE, mutex_name.c_str())); DCHECK(only_me.Get() != NULL) << "GetLastError = " << GetLastError(); // This is how we acquire the mutex (as opposed to the initial ownership). DWORD result = WaitForSingleObject(only_me, INFINITE); DCHECK(result == WAIT_OBJECT_0) << "Result = " << result << "GetLastError = " << GetLastError(); // We now own the mutex so we are the only process that can create the // window at this time, but we must still check if someone created it // between the time where we looked for it above and the time the mutex // was given to us. remote_window_ = FindWindowEx(HWND_MESSAGE, NULL, chrome::kMessageWindowClass, user_data_dir.value().c_str()); if (!remote_window_) { HINSTANCE hinst = base::GetModuleFromAddress(&ThunkWndProc); WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpfnWndProc = base::win::WrappedWindowProc<ThunkWndProc>; wc.hInstance = hinst; wc.lpszClassName = chrome::kMessageWindowClass; ATOM clazz = ::RegisterClassEx(&wc); DCHECK(clazz); // Set the window's title to the path of our user data directory so other // Chrome instances can decide if they should forward to us or not. window_ = ::CreateWindow(MAKEINTATOM(clazz), user_data_dir.value().c_str(), 0, 0, 0, 0, 0, HWND_MESSAGE, 0, hinst, this); CHECK(window_); } BOOL success = ReleaseMutex(only_me); DCHECK(success) << "GetLastError = " << GetLastError(); } } ProcessSingleton::~ProcessSingleton() { // We need to unregister the window as late as possible so that we can detect // another instance of chrome running. Otherwise we may end up writing out // data while a new chrome is starting up. if (window_) { ::DestroyWindow(window_); ::UnregisterClass(chrome::kMessageWindowClass, base::GetModuleFromAddress(&ThunkWndProc)); } } ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() { if (is_virtualized_) return PROCESS_NOTIFIED; // We already spawned the process in this case. else if (!remote_window_) return PROCESS_NONE; // Found another window, send our command line to it // format is "START\0<<<current directory>>>\0<<<commandline>>>". std::wstring to_send(L"START\0", 6); // want the NULL in the string. FilePath cur_dir; if (!PathService::Get(base::DIR_CURRENT, &cur_dir)) return PROCESS_NONE; to_send.append(cur_dir.value()); to_send.append(L"\0", 1); // Null separator. to_send.append(GetCommandLineW()); to_send.append(L"\0", 1); // Null separator. // Allow the current running browser window making itself the foreground // window (otherwise it will just flash in the taskbar). DWORD process_id = 0; DWORD thread_id = GetWindowThreadProcessId(remote_window_, &process_id); // It is possible that the process owning this window may have died by now. if (!thread_id || !process_id) { remote_window_ = NULL; return PROCESS_NONE; } AllowSetForegroundWindow(process_id); COPYDATASTRUCT cds; cds.dwData = 0; cds.cbData = static_cast<DWORD>((to_send.length() + 1) * sizeof(wchar_t)); cds.lpData = const_cast<wchar_t*>(to_send.c_str()); DWORD_PTR result = 0; if (SendMessageTimeout(remote_window_, WM_COPYDATA, NULL, reinterpret_cast<LPARAM>(&cds), SMTO_ABORTIFHUNG, kTimeoutInSeconds * 1000, &result)) { // It is possible that the process owning this window may have died by now. if (!result) { remote_window_ = NULL; return PROCESS_NONE; } return PROCESS_NOTIFIED; } // It is possible that the process owning this window may have died by now. if (!IsWindow(remote_window_)) { remote_window_ = NULL; return PROCESS_NONE; } // The window is hung. Scan for every window to find a visible one. bool visible_window = false; EnumThreadWindows(thread_id, &BrowserWindowEnumeration, reinterpret_cast<LPARAM>(&visible_window)); // If there is a visible browser window, ask the user before killing it. if (visible_window && browser::ShowMessageBox(NULL, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME), l10n_util::GetStringUTF16(IDS_BROWSER_HUNGBROWSER_MESSAGE), browser::MESSAGE_BOX_TYPE_QUESTION) == browser::MESSAGE_BOX_RESULT_NO) { // The user denied. Quit silently. return PROCESS_NOTIFIED; } // Time to take action. Kill the browser process. base::KillProcessById(process_id, content::RESULT_CODE_HUNG, true); remote_window_ = NULL; return PROCESS_NONE; } ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessOrCreate( const NotificationCallback& notification_callback) { NotifyResult result = NotifyOtherProcess(); if (result != PROCESS_NONE) return result; return Create(notification_callback) ? PROCESS_NONE : PROFILE_IN_USE; } // On Windows, there is no need to call Create() since the message // window is created in the constructor but to avoid having more // platform specific code in browser_main.cc we tolerate calls to // Create(). bool ProcessSingleton::Create( const NotificationCallback& notification_callback) { DCHECK(!remote_window_); DCHECK(notification_callback_.is_null()); if (window_ != NULL) notification_callback_ = notification_callback; return window_ != NULL; } void ProcessSingleton::Cleanup() { } LRESULT ProcessSingleton::OnCopyData(HWND hwnd, const COPYDATASTRUCT* cds) { // If locked, it means we are not ready to process this message because // we are probably in a first run critical phase. if (locked_) { #if defined(USE_AURA) NOTIMPLEMENTED(); #else // Attempt to place ourselves in the foreground / flash the task bar. if (foreground_window_ != NULL && IsWindow(foreground_window_)) { SetForegroundWindow(foreground_window_); } else { // Read the command line and store it. It will be replayed when the // ProcessSingleton becomes unlocked. CommandLine parsed_command_line(CommandLine::NO_PROGRAM); FilePath current_directory; if (ParseCommandLine(cds, &parsed_command_line, &current_directory)) saved_startup_messages_.push_back( std::make_pair(parsed_command_line.argv(), current_directory)); } #endif return TRUE; } CommandLine parsed_command_line(CommandLine::NO_PROGRAM); FilePath current_directory; if (!ParseCommandLine(cds, &parsed_command_line, &current_directory)) return TRUE; return notification_callback_.Run(parsed_command_line, current_directory) ? TRUE : FALSE; } LRESULT ProcessSingleton::WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { switch (message) { case WM_COPYDATA: return OnCopyData(reinterpret_cast<HWND>(wparam), reinterpret_cast<COPYDATASTRUCT*>(lparam)); default: break; } return ::DefWindowProc(hwnd, message, wparam, lparam); }
Move the window destruction and registration out of cleanup and into BrowserProcessImpl::EndSession to make sure it happens after profiles are written out.
Move the window destruction and registration out of cleanup and into BrowserProcessImpl::EndSession to make sure it happens after profiles are written out. BUG=127607 TEST=Run on slow computer, open three or more profiles, exit from wrench menu, immediately open chrome again. There should be no reports of profile corruption and logs should show that profile writing is not occuring after second chrome starts. Review URL: https://chromiumcodereview.appspot.com/10542151 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@142682 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,markYoungH/chromium.src,jaruba/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,keishi/chromium,markYoungH/chromium.src,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,Chilledheart/chromium,zcbenz/cefode-chromium,Jonekee/chromium.src,dednal/chromium.src,nacl-webkit/chrome_deps,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,Just-D/chromium-1,dushu1203/chromium.src,nacl-webkit/chrome_deps,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,mogoweb/chromium-crosswalk,Jonekee/chromium.src,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,mogoweb/chromium-crosswalk,littlstar/chromium.src,ltilve/chromium,mogoweb/chromium-crosswalk,markYoungH/chromium.src,M4sse/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,keishi/chromium,nacl-webkit/chrome_deps,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,hujiajie/pa-chromium,Jonekee/chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,jaruba/chromium.src,Just-D/chromium-1,ltilve/chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,dednal/chromium.src,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk,hujiajie/pa-chromium,jaruba/chromium.src,Just-D/chromium-1,dednal/chromium.src,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,M4sse/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,keishi/chromium,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,ltilve/chromium,hujiajie/pa-chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,Just-D/chromium-1,patrickm/chromium.src,Chilledheart/chromium,patrickm/chromium.src,ChromiumWebApps/chromium,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,dednal/chromium.src,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,anirudhSK/chromium,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,dednal/chromium.src,Jonekee/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,nacl-webkit/chrome_deps,Just-D/chromium-1,dushu1203/chromium.src,anirudhSK/chromium,ltilve/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,littlstar/chromium.src,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,hujiajie/pa-chromium,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,keishi/chromium,krieger-od/nwjs_chromium.src,jaruba/chromium.src,fujunwei/chromium-crosswalk,keishi/chromium,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,ondra-novak/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,jaruba/chromium.src,markYoungH/chromium.src,mogoweb/chromium-crosswalk,Chilledheart/chromium,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,dushu1203/chromium.src,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,dednal/chromium.src,Chilledheart/chromium,ChromiumWebApps/chromium,littlstar/chromium.src,patrickm/chromium.src,dushu1203/chromium.src,ondra-novak/chromium.src,ltilve/chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,patrickm/chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,keishi/chromium,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,M4sse/chromium.src,dushu1203/chromium.src,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,zcbenz/cefode-chromium,anirudhSK/chromium,anirudhSK/chromium,anirudhSK/chromium,littlstar/chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,chuan9/chromium-crosswalk,keishi/chromium,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,keishi/chromium,jaruba/chromium.src,dednal/chromium.src,keishi/chromium,axinging/chromium-crosswalk,ltilve/chromium,timopulkkinen/BubbleFish,jaruba/chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,dushu1203/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,chuan9/chromium-crosswalk,keishi/chromium,ltilve/chromium,keishi/chromium
1e28e5ee56739a717494392b2a7a2566d280fc75
src/Image.cpp
src/Image.cpp
/** * Bob Somers * [email protected] * CPE 473, Winter 2010 * Cal Poly, San Luis Obispo */ #include "Image.h" Image::Image(int width, int height) { _width = width; _height = height; _max = 1.0; _pixmap = (Color*)malloc(sizeof(Color) * _width * _height); } Image::~Image() { free(_pixmap); } void Image::WriteTga(const char *outfile, bool scale_color) { FILE *fp = fopen(outfile, "w"); if (fp == NULL) { perror("ERROR: Image::WriteTga() failed to open file for writing!\n"); exit(EXIT_FAILURE); } // write 24-bit uncompressed targa header // thanks to Paul Bourke (http://local.wasp.uwa.edu.au/~pbourke/dataformats/tga/) putc(0, fp); putc(0, fp); putc(2, fp); // type is uncompressed RGB putc(0, fp); putc(0, fp); putc(0, fp); putc(0, fp); putc(0, fp); putc(0, fp); // x origin, low byte putc(0, fp); // x origin, high byte putc(0, fp); // y origin, low byte putc(0, fp); // y origin, high byte putc(_width & 0xff, fp); // width, low byte putc((_width & 0xff00) >> 8, fp); // width, high byte putc(_height & 0xff, fp); // height, low byte putc((_height & 0xff00) >> 8, fp); // height, high byte putc(24, fp); // 24-bit color depth putc(0, fp); // write the raw pixel data in groups of 3 bytes (BGR order) for (int y = 0; y < _height; y++) { for (int x = 0; x < _width; x++) { // if color scaling is on, scale 0.0 -> _max as a 0 -> 255 unsigned byte unsigned char rbyte, gbyte, bbyte; Color* color = _pixmap + (x * _width + y); if (scale_color) { rbyte = (unsigned char)((color->r / _max) * 255); gbyte = (unsigned char)((color->g / _max) * 255); bbyte = (unsigned char)((color->b / _max) * 255); } else { double r = (color->r > 1.0) ? 1.0 : color->r; double g = (color->g > 1.0) ? 1.0 : color->g; double b = (color->b > 1.0) ? 1.0 : color->b; rbyte = (unsigned char)(r * 255); gbyte = (unsigned char)(g * 255); bbyte = (unsigned char)(b * 255); } putc(bbyte, fp); putc(gbyte, fp); putc(rbyte, fp); } } fclose(fp); } void Image::GenTestPattern() { Color pxl(0.0, 0.0, 0.0, 0.0); int i, j, color; float radius, dist; // draw a rotating color checkerboard (RGB) in a 25x25 pixel grid for (int x = 0; x < _width; x++) { for (int y = 0; y < _height; y++) { i = x / 25; j = y / 25; color = (i + j) % 3; switch (color) { case 0: // red pxl.r = 1.0; pxl.g = 0.0; pxl.b = 0.0; break; case 1: // green pxl.r = 0.0; pxl.g = 1.0; pxl.b = 0.0; break; case 2: // blue pxl.r = 0.0; pxl.g = 0.0; pxl.b = 1.0; break; } pixel(x, y, pxl); } } // draw a black circle in the top left quadrant (centered at (i, j)) pxl.r = 0.0; pxl.g = 0.0; pxl.b = 0.0; i = _width / 4; j = 3 * _height / 4; radius = (((float)_width / 4.0) < ((float)_height / 4.0)) ? (float)_width / 4.0 : (float)_height / 4.0; for (int x = 0; x < _width; x++) { for (int y = 0; y < _height; y++) { dist = sqrtf((float)((x - i) * (x - i)) + (float)((y - j) * (y - j))); if (dist <= (float)radius) { pixel(x, y, pxl); } } } // draw a white circle in the lower right quadrant (centered at (i, j)) pxl.r = 1.0; pxl.g = 1.0; pxl.b = 1.0; i = 3 * _width / 4; j = _height / 4; radius = (((float)_width / 4.0) < ((float)_height / 4.0)) ? (float)_width / 4.0 : (float)_height / 4.0; for (int x = 0; x < _width; x++) { for (int y = 0; y < _height; y++) { dist = sqrtf((float)((x - i) * (x - i)) + (float)((y - j) * (y - j))); if (dist <= (float)radius) { pixel(x, y, pxl); } } } } Color Image::pixel(int x, int y) { if (x < 0 || x > _width - 1 || y < 0 || y > _height - 1) { // catostrophically fail fprintf(stderr, "ERROR: Image::pixel(%d, %d) outside range of the image!\n", x, y); exit(EXIT_FAILURE); } return _pixmap[x * _width + y]; } void Image::pixel(int x, int y, Color pxl) { if (x < 0 || x > _width - 1 || y < 0 || y > _height - 1) { // catostrophically fail fprintf(stderr, "ERROR: Image::pixel(%d, %d, pixel) outside range of the image!\n", x, y); exit(EXIT_FAILURE); } _pixmap[x * _width + y] = pxl; // update the max color if necessary _max = (pxl.r > _max) ? pxl.r : _max; _max = (pxl.g > _max) ? pxl.g : _max; _max = (pxl.b > _max) ? pxl.b : _max; }
/** * Bob Somers * [email protected] * CPE 473, Winter 2010 * Cal Poly, San Luis Obispo */ #include "Image.h" Image::Image(int width, int height) { _width = width; _height = height; _max = 1.0; _pixmap = (Color*)malloc(sizeof(Color) * _width * _height); } Image::~Image() { free(_pixmap); } void Image::WriteTga(const char *outfile, bool scale_color) { FILE *fp = fopen(outfile, "w"); if (fp == NULL) { perror("ERROR: Image::WriteTga() failed to open file for writing!\n"); exit(EXIT_FAILURE); } // write 24-bit uncompressed targa header // thanks to Paul Bourke (http://local.wasp.uwa.edu.au/~pbourke/dataformats/tga/) putc(0, fp); putc(0, fp); putc(2, fp); // type is uncompressed RGB putc(0, fp); putc(0, fp); putc(0, fp); putc(0, fp); putc(0, fp); putc(0, fp); // x origin, low byte putc(0, fp); // x origin, high byte putc(0, fp); // y origin, low byte putc(0, fp); // y origin, high byte putc(_width & 0xff, fp); // width, low byte putc((_width & 0xff00) >> 8, fp); // width, high byte putc(_height & 0xff, fp); // height, low byte putc((_height & 0xff00) >> 8, fp); // height, high byte putc(24, fp); // 24-bit color depth putc(0, fp); // write the raw pixel data in groups of 3 bytes (BGR order) for (int y = 0; y < _height; y++) { for (int x = 0; x < _width; x++) { // if color scaling is on, scale 0.0 -> _max as a 0 -> 255 unsigned byte unsigned char rbyte, gbyte, bbyte; Color* color = _pixmap + (x * _height + y); if (scale_color) { rbyte = (unsigned char)((color->r / _max) * 255); gbyte = (unsigned char)((color->g / _max) * 255); bbyte = (unsigned char)((color->b / _max) * 255); } else { double r = (color->r > 1.0) ? 1.0 : color->r; double g = (color->g > 1.0) ? 1.0 : color->g; double b = (color->b > 1.0) ? 1.0 : color->b; rbyte = (unsigned char)(r * 255); gbyte = (unsigned char)(g * 255); bbyte = (unsigned char)(b * 255); } putc(bbyte, fp); putc(gbyte, fp); putc(rbyte, fp); } } fclose(fp); } void Image::GenTestPattern() { Color pxl(0.0, 0.0, 0.0, 0.0); int i, j, color; float radius, dist; // draw a rotating color checkerboard (RGB) in a 25x25 pixel grid for (int x = 0; x < _width; x++) { for (int y = 0; y < _height; y++) { i = x / 25; j = y / 25; color = (i + j) % 3; switch (color) { case 0: // red pxl.r = 1.0; pxl.g = 0.0; pxl.b = 0.0; break; case 1: // green pxl.r = 0.0; pxl.g = 1.0; pxl.b = 0.0; break; case 2: // blue pxl.r = 0.0; pxl.g = 0.0; pxl.b = 1.0; break; } pixel(x, y, pxl); } } // draw a black circle in the top left quadrant (centered at (i, j)) pxl.r = 0.0; pxl.g = 0.0; pxl.b = 0.0; i = _width / 4; j = 3 * _height / 4; radius = (((float)_width / 4.0) < ((float)_height / 4.0)) ? (float)_width / 4.0 : (float)_height / 4.0; for (int x = 0; x < _width; x++) { for (int y = 0; y < _height; y++) { dist = sqrtf((float)((x - i) * (x - i)) + (float)((y - j) * (y - j))); if (dist <= (float)radius) { pixel(x, y, pxl); } } } // draw a white circle in the lower right quadrant (centered at (i, j)) pxl.r = 1.0; pxl.g = 1.0; pxl.b = 1.0; i = 3 * _width / 4; j = _height / 4; radius = (((float)_width / 4.0) < ((float)_height / 4.0)) ? (float)_width / 4.0 : (float)_height / 4.0; for (int x = 0; x < _width; x++) { for (int y = 0; y < _height; y++) { dist = sqrtf((float)((x - i) * (x - i)) + (float)((y - j) * (y - j))); if (dist <= (float)radius) { pixel(x, y, pxl); } } } } Color Image::pixel(int x, int y) { if (x < 0 || x > _width - 1 || y < 0 || y > _height - 1) { // catostrophically fail fprintf(stderr, "ERROR: Image::pixel(%d, %d) outside range of the image!\n", x, y); exit(EXIT_FAILURE); } return _pixmap[x * _height + y]; } void Image::pixel(int x, int y, Color pxl) { if (x < 0 || x > _width - 1 || y < 0 || y > _height - 1) { // catostrophically fail fprintf(stderr, "ERROR: Image::pixel(%d, %d, pixel) outside range of the image!\n", x, y); exit(EXIT_FAILURE); } _pixmap[x * _height + y] = pxl; // update the max color if necessary _max = (pxl.r > _max) ? pxl.r : _max; _max = (pxl.g > _max) ? pxl.g : _max; _max = (pxl.b > _max) ? pxl.b : _max; }
Fix image pixel calculation
Fix image pixel calculation
C++
apache-2.0
raulcesar/RayTracer,marczych/RayTracer,marczych/RayTracer,raulcesar/RayTracer,marczych/RayTracer,raulcesar/RayTracer,raulcesar/RayTracer,marczych/RayTracer,marczych/RayTracer
55774a90caac46dd9b540557aa8d9c47c86c2fba
tree/dataframe/test/datasource_more.cxx
tree/dataframe/test/datasource_more.cxx
#include <ROOT/RDataFrame.hxx> #include <ROOT/RMakeUnique.hxx> #include <TROOT.h> #include <TSystem.h> #include "RNonCopiableColumnDS.hxx" #include "RStreamingDS.hxx" #include "RArraysDS.hxx" #include "ROOTUnitTestSupport.h" #include "gtest/gtest.h" using namespace ROOT::RDF; TEST(RNonCopiableColumnDS, UseNonCopiableColumnType) { std::unique_ptr<RDataSource> tds(new RNonCopiableColumnDS()); ROOT::RDataFrame tdf(std::move(tds)); auto getNCVal = [](RNonCopiableColumnDS::NonCopiable_t &nc) { return nc.fValue; }; auto m = *tdf.Define("val", getNCVal, {RNonCopiableColumnDS::fgColumnName}).Min<RNonCopiableColumnDS::NonCopiable_t::type>("val"); RNonCopiableColumnDS::NonCopiable_t dummy; EXPECT_EQ(dummy.fValue, m); } TEST(RStreamingDS, MultipleEntryRanges) { ROOT::RDataFrame tdf(std::make_unique<RStreamingDS>()); auto c = tdf.Count(); auto ansmin = tdf.Min<int>("ans"); auto ansmax = tdf.Max("ans"); EXPECT_EQ(*c, 4ull); EXPECT_EQ(*ansmin, *ansmax); EXPECT_EQ(*ansmin, 42); } TEST(RArraysDS, ShortSyntaxForCollectionSizes) { ROOT::RDataFrame df(std::make_unique<RArraysDS>()); // GetColumnNames must hide column "__rdf_sizeof_var"... EXPECT_EQ(df.GetColumnNames(), std::vector<std::string>{"var"}); // ...but it must nonetheless be a valid column EXPECT_EQ(df.GetColumnType("#var"), "std::size_t"); EXPECT_EQ(df.GetColumnType("var"), "std::vector<int>"); EXPECT_EQ(df.Take<std::size_t>("#var").GetValue(), std::vector<std::size_t>{1ull}); EXPECT_EQ(df.Take<std::vector<int>>("var").GetValue(), std::vector<std::vector<int>>{{42}}); } TEST(RArraysDS, SnapshotAndShortSyntaxForCollectionSizes) { const auto fname = "snapshotandshortsyntaxforcollectionsizes.root"; ROOT::RDataFrame df(std::make_unique<RArraysDS>()); // Snapshot must ignore the #var columns df.Snapshot("t", fname); TFile f(fname); auto *t = f.Get<TTree>("t"); auto *blist = t->GetListOfBranches(); EXPECT_EQ(blist->GetEntries(), 1u); EXPECT_STREQ(blist->At(0)->GetName(), "var"); // Snapshot must throw if #var is passed explicitly EXPECT_THROW(df.Snapshot<std::size_t>("t", fname, {"#var"}), std::runtime_error); // ...and work if the Snapshot is performed via an Alias const auto nvar = df.Alias("nvar", "#var").Snapshot<std::size_t>("t", fname, {"nvar"})->Take<std::size_t>("nvar").GetValue(); EXPECT_EQ(nvar, std::vector<std::size_t>{1}); gSystem->Unlink(fname); } TEST(RArraysDS, CacheAndShortSyntaxForCollectionSizes) { ROOT::RDataFrame df(std::make_unique<RArraysDS>()); // Cache must ignore the #var columns auto cached = df.Cache(); EXPECT_EQ(cached.GetColumnNames(), std::vector<std::string>{"var"}); // Cache must throw if #var is passed explicitly... EXPECT_THROW(df.Cache<std::size_t>({"#var"}), std::runtime_error); // ...and work if the caching is performed via an Alias const auto nvar = df.Alias("nvar", "#var").Cache<std::size_t>({"nvar"}).Take<std::size_t>("nvar").GetValue(); EXPECT_EQ(nvar, std::vector<std::size_t>{1}); } #ifdef R__USE_IMT TEST(RStreamingDS, MultipleEntryRangesMT) { ROOT::EnableImplicitMT(2); ROOT::RDataFrame tdf(std::make_unique<RStreamingDS>()); auto c = tdf.Count(); auto ansmin = tdf.Min<int>("ans"); auto ansmax = tdf.Max("ans"); EXPECT_EQ(*c, 8ull); // TStreamingDS provides 4 entries per slot EXPECT_EQ(*ansmin, *ansmax); EXPECT_EQ(*ansmin, 42); ROOT::DisableImplicitMT(); } #endif
#include <ROOT/RDataFrame.hxx> #include <ROOT/RMakeUnique.hxx> #include <TROOT.h> #include <TSystem.h> #include "RNonCopiableColumnDS.hxx" #include "RStreamingDS.hxx" #include "RArraysDS.hxx" #include "ROOTUnitTestSupport.h" #include "gtest/gtest.h" using namespace ROOT::RDF; TEST(RNonCopiableColumnDS, UseNonCopiableColumnType) { std::unique_ptr<RDataSource> tds(new RNonCopiableColumnDS()); ROOT::RDataFrame tdf(std::move(tds)); auto getNCVal = [](RNonCopiableColumnDS::NonCopiable_t &nc) { return nc.fValue; }; auto m = *tdf.Define("val", getNCVal, {RNonCopiableColumnDS::fgColumnName}).Min<RNonCopiableColumnDS::NonCopiable_t::type>("val"); RNonCopiableColumnDS::NonCopiable_t dummy; EXPECT_EQ(dummy.fValue, m); } TEST(RStreamingDS, MultipleEntryRanges) { ROOT::RDataFrame tdf(std::make_unique<RStreamingDS>()); auto c = tdf.Count(); auto ansmin = tdf.Min<int>("ans"); auto ansmax = tdf.Max("ans"); EXPECT_EQ(*c, 4ull); EXPECT_EQ(*ansmin, *ansmax); EXPECT_EQ(*ansmin, 42); } TEST(RArraysDS, ShortSyntaxForCollectionSizes) { ROOT::RDataFrame df(std::make_unique<RArraysDS>()); // GetColumnNames must hide column "__rdf_sizeof_var"... EXPECT_EQ(df.GetColumnNames(), std::vector<std::string>{"var"}); // ...but it must nonetheless be a valid column EXPECT_EQ(df.GetColumnType("#var"), "std::size_t"); EXPECT_EQ(df.GetColumnType("var"), "std::vector<int>"); EXPECT_EQ(df.Take<std::size_t>("#var").GetValue(), std::vector<std::size_t>{1ull}); EXPECT_EQ(df.Take<std::vector<int>>("var").GetValue(), std::vector<std::vector<int>>{{42}}); } TEST(RArraysDS, SnapshotAndShortSyntaxForCollectionSizes) { const auto fname = "snapshotandshortsyntaxforcollectionsizes.root"; ROOT::RDataFrame df(std::make_unique<RArraysDS>()); // Snapshot must ignore the #var columns df.Snapshot("t", fname); TFile f(fname); auto *t = f.Get<TTree>("t"); auto *blist = t->GetListOfBranches(); EXPECT_EQ(blist->GetEntries(), 1u); EXPECT_STREQ(blist->At(0)->GetName(), "var"); f.Close(); // Windows does not allow deletion/recreation of files that are still in use. // Snapshot must throw if #var is passed explicitly EXPECT_THROW(df.Snapshot<std::size_t>("t", fname, {"#var"}), std::runtime_error); // ...and work if the Snapshot is performed via an Alias const auto nvar = df.Alias("nvar", "#var").Snapshot<std::size_t>("t", fname, {"nvar"})->Take<std::size_t>("nvar").GetValue(); EXPECT_EQ(nvar, std::vector<std::size_t>{1}); gSystem->Unlink(fname); } TEST(RArraysDS, CacheAndShortSyntaxForCollectionSizes) { ROOT::RDataFrame df(std::make_unique<RArraysDS>()); // Cache must ignore the #var columns auto cached = df.Cache(); EXPECT_EQ(cached.GetColumnNames(), std::vector<std::string>{"var"}); // Cache must throw if #var is passed explicitly... EXPECT_THROW(df.Cache<std::size_t>({"#var"}), std::runtime_error); // ...and work if the caching is performed via an Alias const auto nvar = df.Alias("nvar", "#var").Cache<std::size_t>({"nvar"}).Take<std::size_t>("nvar").GetValue(); EXPECT_EQ(nvar, std::vector<std::size_t>{1}); } #ifdef R__USE_IMT TEST(RStreamingDS, MultipleEntryRangesMT) { ROOT::EnableImplicitMT(2); ROOT::RDataFrame tdf(std::make_unique<RStreamingDS>()); auto c = tdf.Count(); auto ansmin = tdf.Min<int>("ans"); auto ansmax = tdf.Max("ans"); EXPECT_EQ(*c, 8ull); // TStreamingDS provides 4 entries per slot EXPECT_EQ(*ansmin, *ansmax); EXPECT_EQ(*ansmin, 42); ROOT::DisableImplicitMT(); } #endif
Fix datasource_more test failures on Windows
[DF] Fix datasource_more test failures on Windows
C++
lgpl-2.1
olifre/root,olifre/root,olifre/root,olifre/root,olifre/root,olifre/root,olifre/root,olifre/root,olifre/root,olifre/root,olifre/root
bde0599aeb75994997a1df722224e7ddcf7b2b46
tree/forest/v7/inc/ROOT/RForestUtil.hxx
tree/forest/v7/inc/ROOT/RForestUtil.hxx
/// \file ROOT/RForestUtil.hxx /// \ingroup Forest ROOT7 /// \author Jakob Blomer <[email protected]> /// \date 2018-10-04 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_RForestUtil #define ROOT7_RForestUtil #include <cstdint> #include <string> #include <vector> namespace ROOT { namespace Experimental { /** * Used in unit tests to serialize and deserialize classes with TClass */ struct RForestTest { float a = 0.0; std::vector<float> v1; std::vector<std::vector<float>> v2; std::string s; }; /// Integer type long enough to hold the maximum number of entries in a column using ForestIndex_t = std::uint64_t; constexpr ForestIndex_t kInvalidForestIndex = std::uint64_t(-1); /// Integer type long enough to hold the maximum number of entries in a single cluster using ClusterIndex_t = std::uint32_t; constexpr ClusterIndex_t kInvalidClusterIndex = std::uint32_t(-1); /// Uniquely identifies a physical column within the scope of the current process, used to tag pages using ColumnId_t = std::int64_t; constexpr ColumnId_t kInvalidColumnId = -1; } // namespace Experimental } // namespace ROOT #endif
/// \file ROOT/RForestUtil.hxx /// \ingroup Forest ROOT7 /// \author Jakob Blomer <[email protected]> /// \date 2018-10-04 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_RForestUtil #define ROOT7_RForestUtil #include <cstdint> #include <string> #include <vector> namespace ROOT { namespace Experimental { /** * Used in unit tests to serialize and deserialize classes with TClass */ struct RForestTest { float a = 0.0; std::vector<float> v1; std::vector<std::vector<float>> v2; std::string s; }; /// Integer type long enough to hold the maximum number of entries in a column using ForestIndex_t = std::uint64_t; constexpr ForestIndex_t kInvalidForestIndex = std::uint64_t(-1); /// Wrap the 32bit integer in a struct in order to avoid template specialization clash with std::uint32_t struct RClusterIndex { RClusterIndex() : fValue(0) {} explicit constexpr RClusterIndex(std::uint32_t value) : fValue(value) {} RClusterIndex& operator =(const std::uint32_t value) { fValue = value; return *this; } RClusterIndex& operator +=(const std::uint32_t value) { fValue += value; return *this; } operator std::uint32_t() const { return fValue; } std::uint32_t fValue; }; using ClusterIndex_t = RClusterIndex; constexpr ClusterIndex_t kInvalidClusterIndex(std::uint32_t(-1)); /// Uniquely identifies a physical column within the scope of the current process, used to tag pages using ColumnId_t = std::int64_t; constexpr ColumnId_t kInvalidColumnId = -1; } // namespace Experimental } // namespace ROOT #endif
define ClusterIndex_t
[forest] define ClusterIndex_t
C++
lgpl-2.1
root-mirror/root,olifre/root,karies/root,olifre/root,root-mirror/root,olifre/root,karies/root,olifre/root,olifre/root,olifre/root,karies/root,root-mirror/root,olifre/root,root-mirror/root,root-mirror/root,olifre/root,karies/root,karies/root,root-mirror/root,root-mirror/root,karies/root,olifre/root,olifre/root,karies/root,karies/root,root-mirror/root,olifre/root,karies/root,root-mirror/root,karies/root,root-mirror/root,karies/root,root-mirror/root
16350a730f515c675d9e61439722b193913f0a84
Siv3D/src/Siv3D/Font/CFont.cpp
Siv3D/src/Siv3D/Font/CFont.cpp
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2021 Ryo Suzuki // Copyright (c) 2016-2021 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/Font.hpp> # include <Siv3D/Error.hpp> # include <Siv3D/Resource.hpp> # include <Siv3D/ShaderCommon.hpp> # include <Siv3D/ScopedCustomShader2D.hpp> # include <Siv3D/EngineLog.hpp> # include "CFont.hpp" # include "GlyphCache/IGlyphCache.hpp" namespace s3d { namespace detail { [[nodiscard]] constexpr StringView ToString(const FontStyle style) noexcept { switch (style) { case FontStyle::Default: return U"Default"; case FontStyle::Bold: return U"Bold"; case FontStyle::Italic: return U"Italic"; case FontStyle::BoldItalic: return U"BoldItalic"; case FontStyle::Bitmap: return U"Bitmap"; case FontStyle::BoldBitmap: return U"BoldBitmap"; case FontStyle::ItalicBitmap: return U"ItalicBitmap"; default: return U"BoldItalicBitmap"; } } } CFont::CFont() { // do nothing } CFont::~CFont() { LOG_SCOPED_TRACE(U"CFont::~CFont()"); m_fonts.destroy(); if (m_freeType) { FT_Done_FreeType(m_freeType); } } void CFont::init() { LOG_SCOPED_TRACE(U"CFont::init()"); if (const FT_Error error = FT_Init_FreeType(&m_freeType)) { throw EngineError{ U"FT_Init_FreeType() failed" }; } // null Font を管理に登録 { // null Font を作成 auto nullFont = std::make_unique<FontData>(FontData::Null{}); if (not nullFont->isInitialized()) // もし作成に失敗していたら { throw EngineError(U"Null Font initialization failed"); } // 管理に登録 m_fonts.setNullData(std::move(nullFont)); } m_shaders = std::make_unique<FontShader>(); m_shaders->bitmapFont = HLSL{ Resource(U"engine/shader/d3d11/bitmapfont.ps") } | GLSL{ Resource(U"engine/shader/glsl/bitmapfont.frag"), { { U"PSConstants2D", 0 } } } | MSL{ U"PS_Shape" }; // [Siv3D Todo] m_shaders->sdfFont = HLSL{ Resource(U"engine/shader/d3d11/sdffont.ps") } | GLSL{ Resource(U"engine/shader/glsl/sdffont.frag"), { { U"PSConstants2D", 0 } } } | MSL{ U"PS_Shape" }; // [Siv3D Todo] m_shaders->msdfFont = HLSL{ Resource(U"engine/shader/d3d11/msdffont.ps") } | GLSL{ Resource(U"engine/shader/glsl/msdffont.frag"), { { U"PSConstants2D", 0 } } } | MSL{ U"PS_Shape" }; // [Siv3D Todo] if ((not m_shaders->bitmapFont) || (not m_shaders->sdfFont) || (not m_shaders->msdfFont)) { throw EngineError(U"CFont::init(): Failed to load font shaders"); } } Font::IDType CFont::create(const FilePathView path, const FontMethod fontMethod, const int32 fontSize, const FontStyle style) { // Font を作成 auto font = std::make_unique<FontData>(m_freeType, path, fontMethod, fontSize, style); if (not font->isInitialized()) // もし作成に失敗していたら { return Font::IDType::NullAsset(); } const auto& prop = font->getProperty(); const String fontName = (prop.styleName) ? (prop.familiyName + U' ' + prop.styleName) : (prop.familiyName); const String info = U"(`{0}`, size: {1}, style: {2}, ascender: {3}, descender: {4})"_fmt(fontName, prop.fontPixelSize, detail::ToString(prop.style), prop.ascender, prop.descender); // Font を管理に登録 return m_fonts.add(std::move(font), info); } void CFont::release(const Font::IDType handleID) { m_fonts.erase(handleID); } const FontFaceProperty& CFont::getProperty(const Font::IDType handleID) { return m_fonts[handleID]->getProperty(); } FontMethod CFont::getMethod(const Font::IDType handleID) { return m_fonts[handleID]->getMethod(); } void CFont::setBufferThickness(const Font::IDType handleID, const int32 thickness) { return m_fonts[handleID]->getGlyphCache().setBufferWidth(thickness); } int32 CFont::getBufferThickness(const Font::IDType handleID) { return m_fonts[handleID]->getGlyphCache().getBufferWidth(); } bool CFont::hasGlyph(const Font::IDType handleID, StringView ch) { return m_fonts[handleID]->hasGlyph(ch); } GlyphIndex CFont::getGlyphIndex(const Font::IDType handleID, const StringView ch) { return m_fonts[handleID]->getGlyphIndex(ch); } Array<GlyphCluster> CFont::getGlyphClusters(const Font::IDType handleID, const StringView s) { return m_fonts[handleID]->getGlyphClusters(s); } GlyphInfo CFont::getGlyphInfo(const Font::IDType handleID, const StringView ch) { const auto& font = m_fonts[handleID]; return font->getGlyphInfoByGlyphIndex(font->getGlyphIndex(ch)); } OutlineGlyph CFont::renderOutline(const Font::IDType handleID, const StringView ch, const CloseRing closeRing) { const auto& font = m_fonts[handleID]; return font->renderOutlineByGlyphIndex(font->getGlyphIndex(ch), closeRing); } OutlineGlyph CFont::renderOutlineByGlyphIndex(const Font::IDType handleID, const GlyphIndex glyphIndex, const CloseRing closeRing) { return m_fonts[handleID]->renderOutlineByGlyphIndex(glyphIndex, closeRing); } Array<OutlineGlyph> CFont::renderOutlines(const Font::IDType handleID, const StringView s, const CloseRing closeRing) { return m_fonts[handleID]->renderOutlines(s, closeRing); } BitmapGlyph CFont::renderBitmap(const Font::IDType handleID, const StringView s) { const auto& font = m_fonts[handleID]; return font->renderBitmapByGlyphIndex(font->getGlyphIndex(s)); } BitmapGlyph CFont::renderBitmapByGlyphIndex(const Font::IDType handleID, const GlyphIndex glyphIndex) { return m_fonts[handleID]->renderBitmapByGlyphIndex(glyphIndex); } SDFGlyph CFont::renderSDF(const Font::IDType handleID, const StringView s, const int32 buffer) { const auto& font = m_fonts[handleID]; return font->renderSDFByGlyphIndex(font->getGlyphIndex(s), buffer); } SDFGlyph CFont::renderSDFByGlyphIndex(const Font::IDType handleID, const GlyphIndex glyphIndex, const int32 buffer) { return m_fonts[handleID]->renderSDFByGlyphIndex(glyphIndex, buffer); } MSDFGlyph CFont::renderMSDF(const Font::IDType handleID, const StringView s, const int32 buffer) { const auto& font = m_fonts[handleID]; return font->renderMSDFByGlyphIndex(font->getGlyphIndex(s), buffer); } MSDFGlyph CFont::renderMSDFByGlyphIndex(const Font::IDType handleID, const GlyphIndex glyphIndex, const int32 buffer) { return m_fonts[handleID]->renderMSDFByGlyphIndex(glyphIndex, buffer); } bool CFont::preload(const Font::IDType handleID, const StringView chars) { const auto& font = m_fonts[handleID]; return font->getGlyphCache().preload(*font, chars); } const Texture& CFont::getTexture(const Font::IDType handleID) { return m_fonts[handleID]->getGlyphCache().getTexture(); } RectF CFont::draw(const Font::IDType handleID, const StringView s, const Vec2& pos, const double fontSize, const ColorF& color, const double lineHeightScale) { const auto& font = m_fonts[handleID]; { ScopedCustomShader2D ps{ m_shaders->getFontShader(font->getMethod()) }; return m_fonts[handleID]->getGlyphCache().draw(*font, s, pos, fontSize, color, lineHeightScale); } } }
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2021 Ryo Suzuki // Copyright (c) 2016-2021 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/Font.hpp> # include <Siv3D/Error.hpp> # include <Siv3D/Resource.hpp> # include <Siv3D/ShaderCommon.hpp> # include <Siv3D/ScopedCustomShader2D.hpp> # include <Siv3D/EngineLog.hpp> # include "CFont.hpp" # include "GlyphCache/IGlyphCache.hpp" namespace s3d { namespace detail { [[nodiscard]] constexpr StringView ToString(const FontStyle style) noexcept { switch (style) { case FontStyle::Default: return U"Default"; case FontStyle::Bold: return U"Bold"; case FontStyle::Italic: return U"Italic"; case FontStyle::BoldItalic: return U"BoldItalic"; case FontStyle::Bitmap: return U"Bitmap"; case FontStyle::BoldBitmap: return U"BoldBitmap"; case FontStyle::ItalicBitmap: return U"ItalicBitmap"; default: return U"BoldItalicBitmap"; } } } CFont::CFont() { // do nothing } CFont::~CFont() { LOG_SCOPED_TRACE(U"CFont::~CFont()"); m_fonts.destroy(); if (m_freeType) { FT_Done_FreeType(m_freeType); } } void CFont::init() { LOG_SCOPED_TRACE(U"CFont::init()"); if (const FT_Error error = FT_Init_FreeType(&m_freeType)) { throw EngineError{ U"FT_Init_FreeType() failed" }; } // null Font を管理に登録 { // null Font を作成 auto nullFont = std::make_unique<FontData>(FontData::Null{}); if (not nullFont->isInitialized()) // もし作成に失敗していたら { throw EngineError(U"Null Font initialization failed"); } // 管理に登録 m_fonts.setNullData(std::move(nullFont)); } m_shaders = std::make_unique<FontShader>(); m_shaders->bitmapFont = HLSL{ Resource(U"engine/shader/d3d11/bitmapfont.ps") } | GLSL{ Resource(U"engine/shader/glsl/bitmapfont.frag"), { { U"PSConstants2D", 0 } } } | ESSL{ Resource(U"engine/shader/glsl/bitmapfont.frag"), { { U"PSConstants2D", 0 } } } | MSL{ U"PS_Shape" }; // [Siv3D Todo] m_shaders->sdfFont = HLSL{ Resource(U"engine/shader/d3d11/sdffont.ps") } | GLSL{ Resource(U"engine/shader/glsl/sdffont.frag"), { { U"PSConstants2D", 0 } } } | ESSL{ Resource(U"engine/shader/glsl/sdffont.frag"), { { U"PSConstants2D", 0 } } } | MSL{ U"PS_Shape" }; // [Siv3D Todo] m_shaders->msdfFont = HLSL{ Resource(U"engine/shader/d3d11/msdffont.ps") } | GLSL{ Resource(U"engine/shader/glsl/msdffont.frag"), { { U"PSConstants2D", 0 } } } | ESSL{ Resource(U"engine/shader/glsl/msdffont.frag"), { { U"PSConstants2D", 0 } } } | MSL{ U"PS_Shape" }; // [Siv3D Todo] if ((not m_shaders->bitmapFont) || (not m_shaders->sdfFont) || (not m_shaders->msdfFont)) { throw EngineError(U"CFont::init(): Failed to load font shaders"); } } Font::IDType CFont::create(const FilePathView path, const FontMethod fontMethod, const int32 fontSize, const FontStyle style) { // Font を作成 auto font = std::make_unique<FontData>(m_freeType, path, fontMethod, fontSize, style); if (not font->isInitialized()) // もし作成に失敗していたら { return Font::IDType::NullAsset(); } const auto& prop = font->getProperty(); const String fontName = (prop.styleName) ? (prop.familiyName + U' ' + prop.styleName) : (prop.familiyName); const String info = U"(`{0}`, size: {1}, style: {2}, ascender: {3}, descender: {4})"_fmt(fontName, prop.fontPixelSize, detail::ToString(prop.style), prop.ascender, prop.descender); // Font を管理に登録 return m_fonts.add(std::move(font), info); } void CFont::release(const Font::IDType handleID) { m_fonts.erase(handleID); } const FontFaceProperty& CFont::getProperty(const Font::IDType handleID) { return m_fonts[handleID]->getProperty(); } FontMethod CFont::getMethod(const Font::IDType handleID) { return m_fonts[handleID]->getMethod(); } void CFont::setBufferThickness(const Font::IDType handleID, const int32 thickness) { return m_fonts[handleID]->getGlyphCache().setBufferWidth(thickness); } int32 CFont::getBufferThickness(const Font::IDType handleID) { return m_fonts[handleID]->getGlyphCache().getBufferWidth(); } bool CFont::hasGlyph(const Font::IDType handleID, StringView ch) { return m_fonts[handleID]->hasGlyph(ch); } GlyphIndex CFont::getGlyphIndex(const Font::IDType handleID, const StringView ch) { return m_fonts[handleID]->getGlyphIndex(ch); } Array<GlyphCluster> CFont::getGlyphClusters(const Font::IDType handleID, const StringView s) { return m_fonts[handleID]->getGlyphClusters(s); } GlyphInfo CFont::getGlyphInfo(const Font::IDType handleID, const StringView ch) { const auto& font = m_fonts[handleID]; return font->getGlyphInfoByGlyphIndex(font->getGlyphIndex(ch)); } OutlineGlyph CFont::renderOutline(const Font::IDType handleID, const StringView ch, const CloseRing closeRing) { const auto& font = m_fonts[handleID]; return font->renderOutlineByGlyphIndex(font->getGlyphIndex(ch), closeRing); } OutlineGlyph CFont::renderOutlineByGlyphIndex(const Font::IDType handleID, const GlyphIndex glyphIndex, const CloseRing closeRing) { return m_fonts[handleID]->renderOutlineByGlyphIndex(glyphIndex, closeRing); } Array<OutlineGlyph> CFont::renderOutlines(const Font::IDType handleID, const StringView s, const CloseRing closeRing) { return m_fonts[handleID]->renderOutlines(s, closeRing); } BitmapGlyph CFont::renderBitmap(const Font::IDType handleID, const StringView s) { const auto& font = m_fonts[handleID]; return font->renderBitmapByGlyphIndex(font->getGlyphIndex(s)); } BitmapGlyph CFont::renderBitmapByGlyphIndex(const Font::IDType handleID, const GlyphIndex glyphIndex) { return m_fonts[handleID]->renderBitmapByGlyphIndex(glyphIndex); } SDFGlyph CFont::renderSDF(const Font::IDType handleID, const StringView s, const int32 buffer) { const auto& font = m_fonts[handleID]; return font->renderSDFByGlyphIndex(font->getGlyphIndex(s), buffer); } SDFGlyph CFont::renderSDFByGlyphIndex(const Font::IDType handleID, const GlyphIndex glyphIndex, const int32 buffer) { return m_fonts[handleID]->renderSDFByGlyphIndex(glyphIndex, buffer); } MSDFGlyph CFont::renderMSDF(const Font::IDType handleID, const StringView s, const int32 buffer) { const auto& font = m_fonts[handleID]; return font->renderMSDFByGlyphIndex(font->getGlyphIndex(s), buffer); } MSDFGlyph CFont::renderMSDFByGlyphIndex(const Font::IDType handleID, const GlyphIndex glyphIndex, const int32 buffer) { return m_fonts[handleID]->renderMSDFByGlyphIndex(glyphIndex, buffer); } bool CFont::preload(const Font::IDType handleID, const StringView chars) { const auto& font = m_fonts[handleID]; return font->getGlyphCache().preload(*font, chars); } const Texture& CFont::getTexture(const Font::IDType handleID) { return m_fonts[handleID]->getGlyphCache().getTexture(); } RectF CFont::draw(const Font::IDType handleID, const StringView s, const Vec2& pos, const double fontSize, const ColorF& color, const double lineHeightScale) { const auto& font = m_fonts[handleID]; { ScopedCustomShader2D ps{ m_shaders->getFontShader(font->getMethod()) }; return m_fonts[handleID]->getGlyphCache().draw(*font, s, pos, fontSize, color, lineHeightScale); } } }
Add GLSL ES 3.0 Font Shader File Loading to CFont
[共通] Add GLSL ES 3.0 Font Shader File Loading to CFont
C++
mit
Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D
a9b23f0bd6bfde8fa0da95c8972c240e12473f5f
src/pbview.cpp
src/pbview.cpp
#include "pbview.h" #include <cstdio> #include <cstring> #include <curses.h> #include <iostream> #include <sstream> #include "config.h" #include "configcontainer.h" #include "dllist.h" #include "download.h" #include "formatstring.h" #include "help.h" #include "logger.h" #include "pbcontroller.h" #include "poddlthread.h" #include "strprintf.h" #include "utils.h" using namespace newsboat; namespace podboat { PbView::PbView(PbController* c) : ctrl(c) , dllist_form(dllist_str) , help_form(help_str) , keys(0) { if (getenv("ESCDELAY") == nullptr) { set_escdelay(25); } } PbView::~PbView() { Stfl::reset(); } void PbView::run(bool auto_download) { bool quit = false; set_dllist_keymap_hint(); do { if (ctrl->view_update_necessary()) { double total_kbps = ctrl->get_total_kbps(); char parbuf[128] = ""; if (ctrl->get_maxdownloads() > 1) { snprintf(parbuf, sizeof(parbuf), _(" - %u parallel downloads"), ctrl->get_maxdownloads()); } char buf[1024]; snprintf(buf, sizeof(buf), _("Queue (%u downloads in progress, %u total) " "- %.2f kb/s total%s"), static_cast<unsigned int>( ctrl->downloads_in_progress()), static_cast<unsigned int>( ctrl->downloads().size()), total_kbps, parbuf); dllist_form.set("head", buf); LOG(Level::DEBUG, "PbView::run: updating view... " "downloads().size() " "= %u", ctrl->downloads().size()); std::string code = "{list"; std::string formatstring = ctrl->get_formatstr(); unsigned int width = utils::to_u(dllist_form.get("feeds:w")); unsigned int i = 0; for (const auto& dl : ctrl->downloads()) { auto lbuf = format_line(formatstring, dl, i, width); code.append( strprintf::fmt("{listitem[%u] text:%s}", i, Stfl::quote(lbuf))); i++; } code.append("}"); dllist_form.modify("dls", "replace_inner", code); ctrl->set_view_update_necessary(false); } const char* event = dllist_form.run(500); if (auto_download) { if (ctrl->get_maxdownloads() > ctrl->downloads_in_progress()) { ctrl->start_downloads(); } } if (!event || strcmp(event, "TIMEOUT") == 0) continue; Operation op = keys->get_operation(event, "podbeuter"); if (dllist_form.get("msg").length() > 0) { dllist_form.set("msg", ""); ctrl->set_view_update_necessary(true); } switch (op) { case OP_PB_TOGGLE_DLALL: auto_download = !auto_download; break; case OP_HARDQUIT: case OP_QUIT: if (ctrl->downloads_in_progress() > 0) { dllist_form.set("msg", _("Error: can't quit: download(s) in " "progress.")); ctrl->set_view_update_necessary(true); } else { quit = true; } break; case OP_PB_MOREDL: ctrl->increase_parallel_downloads(); break; case OP_PB_LESSDL: ctrl->decrease_parallel_downloads(); break; case OP_PB_DOWNLOAD: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { if (ctrl->downloads()[idx].status() != DlStatus::DOWNLOADING) { std::thread t{PodDlThread( &ctrl->downloads()[idx], ctrl->get_cfgcont())}; t.detach(); } } } break; case OP_PB_PLAY: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { DlStatus status = ctrl->downloads()[idx].status(); if (status == DlStatus::FINISHED || status == DlStatus::PLAYED || status == DlStatus::READY) { ctrl->play_file(ctrl->downloads()[idx] .filename()); ctrl->downloads()[idx].set_status( DlStatus::PLAYED); } else { dllist_form.set("msg", _("Error: download needs to be " "finished before the file " "can be played.")); } } } break; case OP_PB_MARK_FINISHED: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { DlStatus status = ctrl->downloads()[idx].status(); if (status == DlStatus::PLAYED) { ctrl->downloads()[idx].set_status( DlStatus::FINISHED); } } } break; case OP_PB_CANCEL: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { if (ctrl->downloads()[idx].status() == DlStatus::DOWNLOADING) { ctrl->downloads()[idx].set_status( DlStatus::CANCELLED); } } } break; case OP_PB_DELETE: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { if (ctrl->downloads()[idx].status() != DlStatus::DOWNLOADING) { ctrl->downloads()[idx].set_status( DlStatus::DELETED); } } } break; case OP_PB_PURGE: if (ctrl->downloads_in_progress() > 0) { dllist_form.set("msg", _("Error: unable to perform operation: " "download(s) in progress.")); } else { ctrl->reload_queue(true); } ctrl->set_view_update_necessary(true); break; case OP_HELP: run_help(); break; default: break; } } while (!quit); } void PbView::set_bindings() { if (keys) { std::string upkey("** "); upkey.append(keys->getkey(OP_SK_UP, "podbeuter")); std::string downkey("** "); downkey.append(keys->getkey(OP_SK_DOWN, "podbeuter")); std::string pgupkey("** "); pgupkey.append(keys->getkey(OP_SK_PGUP, "podbeuter")); std::string pgdownkey("** "); pgdownkey.append(keys->getkey(OP_SK_PGDOWN, "podbeuter")); std::string homekey("** "); homekey.append(keys->getkey(OP_SK_HOME, "podbeuter")); std::string endkey("** "); endkey.append(keys->getkey(OP_SK_END, "podbeuter")); dllist_form.set("bind_up", upkey); dllist_form.set("bind_down", downkey); dllist_form.set("bind_page_up", pgupkey); dllist_form.set("bind_page_down", pgdownkey); dllist_form.set("bind_home", homekey); dllist_form.set("bind_end", endkey); help_form.set("bind_up", upkey); help_form.set("bind_down", downkey); help_form.set("bind_page_up", pgupkey); help_form.set("bind_page_down", pgdownkey); help_form.set("bind_home", homekey); help_form.set("bind_end", endkey); } } void PbView::run_help() { set_help_keymap_hint(); help_form.set("head", _("Help")); std::vector<KeyMapDesc> descs; keys->get_keymap_descriptions(descs, KM_PODBOAT); std::string code = "{list"; for (const auto& desc : descs) { std::string line = "{listitem text:"; std::string descline; descline.append(desc.key); descline.append(8 - desc.key.length(), ' '); descline.append(desc.cmd); descline.append(24 - desc.cmd.length(), ' '); descline.append(desc.desc); line.append(Stfl::quote(descline)); line.append("}"); code.append(line); } code.append("}"); help_form.modify("helptext", "replace_inner", code); bool quit = false; do { const char* event = help_form.run(0); if (!event) continue; Operation op = keys->get_operation(event, "help"); switch (op) { case OP_HARDQUIT: case OP_QUIT: quit = true; break; default: break; } } while (!quit); } std::string PbView::prepare_keymaphint(KeyMapHintEntry* hints) { std::string keymap_hint; for (int i = 0; hints[i].op != OP_NIL; ++i) { keymap_hint.append(keys->getkey(hints[i].op, "podbeuter")); keymap_hint.append(":"); keymap_hint.append(hints[i].text); keymap_hint.append(" "); } return keymap_hint; } void PbView::set_help_keymap_hint() { KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_NIL, nullptr}}; std::string keymap_hint = prepare_keymaphint(hints); help_form.set("help", keymap_hint); } void PbView::set_dllist_keymap_hint() { KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_PB_DOWNLOAD, _("Download")}, {OP_PB_CANCEL, _("Cancel")}, {OP_PB_DELETE, _("Delete")}, {OP_PB_PURGE, _("Purge Finished")}, {OP_PB_TOGGLE_DLALL, _("Toggle Automatic Download")}, {OP_PB_PLAY, _("Play")}, {OP_PB_MARK_FINISHED, _("Mark as Finished")}, {OP_HELP, _("Help")}, {OP_NIL, nullptr}}; std::string keymap_hint = prepare_keymaphint(hints); dllist_form.set("help", keymap_hint); } std::string PbView::format_line(const std::string& podlist_format, const Download& dl, unsigned int pos, unsigned int width) { FmtStrFormatter fmt; fmt.register_fmt('i', strprintf::fmt("%u", pos + 1)); fmt.register_fmt('d', strprintf::fmt("%.1f", dl.current_size() / (1024 * 1024))); fmt.register_fmt( 't', strprintf::fmt("%.1f", dl.total_size() / (1024 * 1024))); fmt.register_fmt('p', strprintf::fmt("%.1f", dl.percents_finished())); fmt.register_fmt('k', strprintf::fmt("%.2f", dl.kbps())); fmt.register_fmt('S', strprintf::fmt("%s", dl.status_text())); fmt.register_fmt('u', strprintf::fmt("%s", dl.url())); fmt.register_fmt('F', strprintf::fmt("%s", dl.filename())); fmt.register_fmt('b', strprintf::fmt("%s", dl.basename())); auto formattedLine = fmt.do_format(podlist_format, width); return formattedLine; } } // namespace podboat
#include "pbview.h" #include <cstdio> #include <cstring> #include <curses.h> #include <iostream> #include <sstream> #include "config.h" #include "configcontainer.h" #include "dllist.h" #include "download.h" #include "formatstring.h" #include "help.h" #include "logger.h" #include "pbcontroller.h" #include "poddlthread.h" #include "strprintf.h" #include "utils.h" using namespace newsboat; namespace podboat { PbView::PbView(PbController* c) : ctrl(c) , dllist_form(dllist_str) , help_form(help_str) , keys(0) { if (getenv("ESCDELAY") == nullptr) { set_escdelay(25); } } PbView::~PbView() { Stfl::reset(); } void PbView::run(bool auto_download) { bool quit = false; set_dllist_keymap_hint(); do { if (ctrl->view_update_necessary()) { double total_kbps = ctrl->get_total_kbps(); char parbuf[128] = ""; if (ctrl->get_maxdownloads() > 1) { snprintf(parbuf, sizeof(parbuf), _(" - %u parallel downloads"), ctrl->get_maxdownloads()); } char buf[1024]; snprintf(buf, sizeof(buf), _("Queue (%u downloads in progress, %u total) " "- %.2f kb/s total%s"), static_cast<unsigned int>( ctrl->downloads_in_progress()), static_cast<unsigned int>( ctrl->downloads().size()), total_kbps, parbuf); dllist_form.set("head", buf); LOG(Level::DEBUG, "PbView::run: updating view... " "downloads().size() " "= %u", ctrl->downloads().size()); std::string code = "{list"; std::string formatstring = ctrl->get_formatstr(); dllist_form.run(-3); // compute all widget dimensions unsigned int width = utils::to_u(dllist_form.get("dls:w")); unsigned int i = 0; for (const auto& dl : ctrl->downloads()) { auto lbuf = format_line(formatstring, dl, i, width); code.append( strprintf::fmt("{listitem[%u] text:%s}", i, Stfl::quote(lbuf))); i++; } code.append("}"); dllist_form.modify("dls", "replace_inner", code); ctrl->set_view_update_necessary(false); } const char* event = dllist_form.run(500); if (auto_download) { if (ctrl->get_maxdownloads() > ctrl->downloads_in_progress()) { ctrl->start_downloads(); } } if (!event || strcmp(event, "TIMEOUT") == 0) continue; Operation op = keys->get_operation(event, "podbeuter"); if (dllist_form.get("msg").length() > 0) { dllist_form.set("msg", ""); ctrl->set_view_update_necessary(true); } switch (op) { case OP_PB_TOGGLE_DLALL: auto_download = !auto_download; break; case OP_HARDQUIT: case OP_QUIT: if (ctrl->downloads_in_progress() > 0) { dllist_form.set("msg", _("Error: can't quit: download(s) in " "progress.")); ctrl->set_view_update_necessary(true); } else { quit = true; } break; case OP_PB_MOREDL: ctrl->increase_parallel_downloads(); break; case OP_PB_LESSDL: ctrl->decrease_parallel_downloads(); break; case OP_PB_DOWNLOAD: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { if (ctrl->downloads()[idx].status() != DlStatus::DOWNLOADING) { std::thread t{PodDlThread( &ctrl->downloads()[idx], ctrl->get_cfgcont())}; t.detach(); } } } break; case OP_PB_PLAY: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { DlStatus status = ctrl->downloads()[idx].status(); if (status == DlStatus::FINISHED || status == DlStatus::PLAYED || status == DlStatus::READY) { ctrl->play_file(ctrl->downloads()[idx] .filename()); ctrl->downloads()[idx].set_status( DlStatus::PLAYED); } else { dllist_form.set("msg", _("Error: download needs to be " "finished before the file " "can be played.")); } } } break; case OP_PB_MARK_FINISHED: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { DlStatus status = ctrl->downloads()[idx].status(); if (status == DlStatus::PLAYED) { ctrl->downloads()[idx].set_status( DlStatus::FINISHED); } } } break; case OP_PB_CANCEL: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { if (ctrl->downloads()[idx].status() == DlStatus::DOWNLOADING) { ctrl->downloads()[idx].set_status( DlStatus::CANCELLED); } } } break; case OP_PB_DELETE: { std::istringstream os(dllist_form.get("dlposname")); int idx = -1; os >> idx; if (idx != -1) { if (ctrl->downloads()[idx].status() != DlStatus::DOWNLOADING) { ctrl->downloads()[idx].set_status( DlStatus::DELETED); } } } break; case OP_PB_PURGE: if (ctrl->downloads_in_progress() > 0) { dllist_form.set("msg", _("Error: unable to perform operation: " "download(s) in progress.")); } else { ctrl->reload_queue(true); } ctrl->set_view_update_necessary(true); break; case OP_HELP: run_help(); break; default: break; } } while (!quit); } void PbView::set_bindings() { if (keys) { std::string upkey("** "); upkey.append(keys->getkey(OP_SK_UP, "podbeuter")); std::string downkey("** "); downkey.append(keys->getkey(OP_SK_DOWN, "podbeuter")); std::string pgupkey("** "); pgupkey.append(keys->getkey(OP_SK_PGUP, "podbeuter")); std::string pgdownkey("** "); pgdownkey.append(keys->getkey(OP_SK_PGDOWN, "podbeuter")); std::string homekey("** "); homekey.append(keys->getkey(OP_SK_HOME, "podbeuter")); std::string endkey("** "); endkey.append(keys->getkey(OP_SK_END, "podbeuter")); dllist_form.set("bind_up", upkey); dllist_form.set("bind_down", downkey); dllist_form.set("bind_page_up", pgupkey); dllist_form.set("bind_page_down", pgdownkey); dllist_form.set("bind_home", homekey); dllist_form.set("bind_end", endkey); help_form.set("bind_up", upkey); help_form.set("bind_down", downkey); help_form.set("bind_page_up", pgupkey); help_form.set("bind_page_down", pgdownkey); help_form.set("bind_home", homekey); help_form.set("bind_end", endkey); } } void PbView::run_help() { set_help_keymap_hint(); help_form.set("head", _("Help")); std::vector<KeyMapDesc> descs; keys->get_keymap_descriptions(descs, KM_PODBOAT); std::string code = "{list"; for (const auto& desc : descs) { std::string line = "{listitem text:"; std::string descline; descline.append(desc.key); descline.append(8 - desc.key.length(), ' '); descline.append(desc.cmd); descline.append(24 - desc.cmd.length(), ' '); descline.append(desc.desc); line.append(Stfl::quote(descline)); line.append("}"); code.append(line); } code.append("}"); help_form.modify("helptext", "replace_inner", code); bool quit = false; do { const char* event = help_form.run(0); if (!event) continue; Operation op = keys->get_operation(event, "help"); switch (op) { case OP_HARDQUIT: case OP_QUIT: quit = true; break; default: break; } } while (!quit); } std::string PbView::prepare_keymaphint(KeyMapHintEntry* hints) { std::string keymap_hint; for (int i = 0; hints[i].op != OP_NIL; ++i) { keymap_hint.append(keys->getkey(hints[i].op, "podbeuter")); keymap_hint.append(":"); keymap_hint.append(hints[i].text); keymap_hint.append(" "); } return keymap_hint; } void PbView::set_help_keymap_hint() { KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_NIL, nullptr}}; std::string keymap_hint = prepare_keymaphint(hints); help_form.set("help", keymap_hint); } void PbView::set_dllist_keymap_hint() { KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_PB_DOWNLOAD, _("Download")}, {OP_PB_CANCEL, _("Cancel")}, {OP_PB_DELETE, _("Delete")}, {OP_PB_PURGE, _("Purge Finished")}, {OP_PB_TOGGLE_DLALL, _("Toggle Automatic Download")}, {OP_PB_PLAY, _("Play")}, {OP_PB_MARK_FINISHED, _("Mark as Finished")}, {OP_HELP, _("Help")}, {OP_NIL, nullptr}}; std::string keymap_hint = prepare_keymaphint(hints); dllist_form.set("help", keymap_hint); } std::string PbView::format_line(const std::string& podlist_format, const Download& dl, unsigned int pos, unsigned int width) { FmtStrFormatter fmt; fmt.register_fmt('i', strprintf::fmt("%u", pos + 1)); fmt.register_fmt('d', strprintf::fmt("%.1f", dl.current_size() / (1024 * 1024))); fmt.register_fmt( 't', strprintf::fmt("%.1f", dl.total_size() / (1024 * 1024))); fmt.register_fmt('p', strprintf::fmt("%.1f", dl.percents_finished())); fmt.register_fmt('k', strprintf::fmt("%.2f", dl.kbps())); fmt.register_fmt('S', strprintf::fmt("%s", dl.status_text())); fmt.register_fmt('u', strprintf::fmt("%s", dl.url())); fmt.register_fmt('F', strprintf::fmt("%s", dl.filename())); fmt.register_fmt('b', strprintf::fmt("%s", dl.basename())); auto formattedLine = fmt.do_format(podlist_format, width); return formattedLine; } } // namespace podboat
Fix spacer formatter in podlist-format
Fix spacer formatter in podlist-format The problem was two-fold: 1. a typo: the code was copy-pasted from FeedListFormaction, and "feeds:w" wasn't changed to "dls:s". I checked, and there are no other typos of this kind in this file; 2. the first time the loop is run, the widgets aren't painted yet, so they don't know their size. This can be rectified by force-repainting them, say, by downloading something. To fix the first run, I stuck a force-recalculation there. Shouldn't be a performance bottleneck since repaints don't happen often (every second during downloads, and as fast as user types commands). Fixes #434.
C++
mit
newsboat/newsboat,der-lyse/newsboat,newsboat/newsboat,newsboat/newsboat,der-lyse/newsboat,der-lyse/newsboat,newsboat/newsboat,der-lyse/newsboat,der-lyse/newsboat,der-lyse/newsboat,newsboat/newsboat,newsboat/newsboat,der-lyse/newsboat,der-lyse/newsboat,newsboat/newsboat,newsboat/newsboat
21cd751111e32f54995bed5aa0de0db85cfb8681
libsrc/spatialdata/spatialdb/UserFunctionDB.cc
libsrc/spatialdata/spatialdb/UserFunctionDB.cc
// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard, U.S. Geological Survey // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2017 University of California, Davis // // See COPYING for license information. // // ---------------------------------------------------------------------- // #include <portinfo> #include "spatialdata/spatialdb/UserFunctionDB.hh" // Implementation of class methods #include "spatialdata/geocoords/CoordSys.hh" // USES CoordSys #include "spatialdata/geocoords/Converter.hh" // USES Converter #include "spatialdata/units/Parser.hh" // USES Parser #include <sstream> // USES std::ostringstream #include <stdexcept> // USES std::runtime_error #include <cassert> // USES assert() // ---------------------------------------------------------------------- namespace spatialdata { namespace spatialdb { class UserFunctionDB::QueryFn1D : public UserFunctionDB::QueryFn { public: QueryFn1D(UserFunctionDB::userfn1D_type fn) : _fn(fn) {}; int query(double* value, const double* coords, const int dim) { if (!value || !coords || 1 != dim) { return 1; } *value = _fn(coords[0]); return 0; }; private: UserFunctionDB::userfn1D_type _fn; }; class UserFunctionDB::QueryFn2D : public UserFunctionDB::QueryFn { public: QueryFn2D(UserFunctionDB::userfn2D_type fn) : _fn(fn) {}; int query(double* value, const double* coords, const int dim) { if (!value || !coords || 2 != dim) { return 1; } *value = _fn(coords[0], coords[1]); return 0; }; private: UserFunctionDB::userfn2D_type _fn; }; class UserFunctionDB::QueryFn3D : public UserFunctionDB::QueryFn { public: QueryFn3D(UserFunctionDB::userfn3D_type fn) : _fn(fn) {}; int query(double* value, const double* coords, const int dim) { if (!value || !coords || 3 != dim) { return 1; } *value = _fn(coords[0], coords[1], coords[2]); return 0; }; private: UserFunctionDB::userfn3D_type _fn; }; } // namespace spatialdb } // namespace spatialdata // ---------------------------------------------------------------------- // Constructor spatialdata::spatialdb::UserFunctionDB::UserFunctionDB(void) : _queryFunctions(NULL), _cs(NULL), _querySize(0) { // constructor } // constructor // ---------------------------------------------------------------------- // Destructor spatialdata::spatialdb::UserFunctionDB::~UserFunctionDB(void) { delete[] _queryFunctions; _queryFunctions = NULL; _querySize = 0; for (function_map::iterator iter=_functions.begin(); iter != _functions.end(); ++iter) { delete iter->second.fn; iter->second.fn = NULL; } // for delete _cs; _cs = NULL; } // destructor // ---------------------------------------------------------------------- // Add function/value to database in 1-D. void spatialdata::spatialdb::UserFunctionDB::addValue(const char* name, userfn1D_type fn, const char* units) { _checkAdd(name, (void*)fn, units); UserData data; data.fn = new QueryFn1D(fn); data.units = units; data.scale = 0.0; _functions[name] = data; } // addValue // ---------------------------------------------------------------------- // Add function/value to database in 2-D. void spatialdata::spatialdb::UserFunctionDB::addValue(const char* name, userfn2D_type fn, const char* units) { _checkAdd(name, (void*)fn, units); UserData data; data.fn = new QueryFn2D(fn); data.units = units; data.scale = 0.0; _functions[name] = data; } // addValue // ---------------------------------------------------------------------- // Add function/value to database in 3-D. void spatialdata::spatialdb::UserFunctionDB::addValue(const char* name, userfn3D_type fn, const char* units) { _checkAdd(name, (void*)fn, units); UserData data; data.fn = new QueryFn3D(fn); data.units = units; data.scale = 0.0; _functions[name] = data; } // addValue // ---------------------------------------------------------------------- // Open the database and prepare for querying. void spatialdata::spatialdb::UserFunctionDB::open(void) { // Compute conversion to SI units. spatialdata::units::Parser parser; const std::string& none = "none"; for (function_map::iterator iter=_functions.begin(); iter != _functions.end(); ++iter) { if (none != iter->second.units) { iter->second.scale = parser.parse(iter->second.units.c_str()); } else { iter->second.scale = 1.0; } // if/else } // for _checkCompatibility(); } // open // ---------------------------------------------------------------------- // Close the database. void spatialdata::spatialdb::UserFunctionDB::close(void) { delete[] _queryFunctions; _queryFunctions = NULL; } // close // ---------------------------------------------------------------------- // Set values to be returned by queries. void spatialdata::spatialdb::UserFunctionDB::queryVals(const char* const* names, const int numVals) { if (0 == numVals) { std::ostringstream msg; msg << "Number of values for query in spatial database " << label() << "\n must be positive.\n"; throw std::runtime_error(msg.str()); } // if assert(names && 0 < numVals); _querySize = numVals; delete[] _queryFunctions; _queryFunctions = numVals > 0 ? new UserData*[numVals] : NULL; for (int iVal=0; iVal < numVals; ++iVal) { const function_map::iterator iter = _functions.find(names[iVal]); if (_functions.end() == iter) { std::ostringstream msg; msg << "Could not find value '" << names[iVal] << "' in spatial database '" << label() << "'. Available values are:"; for (function_map::iterator viter = _functions.begin(); viter != _functions.end(); ++viter) { msg << "\n " << viter->first; } // for msg << "\n"; throw std::runtime_error(msg.str()); } // if _queryFunctions[iVal] = &iter->second; } // for } // queryVals // ---------------------------------------------------------------------- // Query the database. int spatialdata::spatialdb::UserFunctionDB::query(double* vals, const int numVals, const double* coords, const int numDims, const spatialdata::geocoords::CoordSys* csQuery) { // query const int querySize = _querySize; assert(_cs); if (0 == querySize) { std::ostringstream msg; msg << "Values to be returned by spatial database " << label() << " have not been set. Please call queryVals() before query().\n"; throw std::runtime_error(msg.str()); } else if (numVals != querySize) { std::ostringstream msg; msg << "Number of values to be returned by spatial database " << label() << " (" << querySize << ") does not match size of array provided (" << numVals << ").\n"; throw std::runtime_error(msg.str()); } else if (numDims != _cs->spaceDim()) { std::ostringstream msg; msg << "Spatial dimension (" << numDims << ") does not match spatial dimension of spatial database (" << _cs->spaceDim() << ")."; throw std::runtime_error(msg.str()); } // if // Convert coordinates assert(numDims <= 3); double xyz[3]; memcpy(xyz, coords, numDims*sizeof(double)); spatialdata::geocoords::Converter::convert(xyz, 1, numDims, _cs, csQuery); int queryFlag = 0; for (int iVal=0; iVal < querySize; ++iVal) { assert(_queryFunctions[iVal]->fn); queryFlag = _queryFunctions[iVal]->fn->query(&vals[iVal], xyz, numDims); if (queryFlag) { break; } vals[iVal] *= _queryFunctions[iVal]->scale; // Convert to SI units. } // for return queryFlag; } // query // ---------------------------------------------------------------------- // Set filename containing data. void spatialdata::spatialdb::UserFunctionDB::coordsys(const geocoords::CoordSys& cs) { // coordsys delete _cs; _cs = cs.clone(); assert(_cs); _cs->initialize(); } // coordsys // ---------------------------------------------------------------------- void spatialdata::spatialdb::UserFunctionDB::_checkAdd(const char* name, void* fn, const char* units) const { if (!name) { std::ostringstream msg; msg << "NULL name passed to addValue() for spatial database " << label() << "."; throw std::logic_error(msg.str()); } // if if (!units) { std::ostringstream msg; msg << "NULL units passed to addValue() for spatial database " << label() << "."; throw std::logic_error(msg.str()); } // if // Verify user function for value does not already exist. const function_map::const_iterator& iter = _functions.find(name); if (iter != _functions.end()) { std::ostringstream msg; msg << "Cannot add user function for value " << name << " to spatial database " << label() << ". User function for value already exists."; throw std::runtime_error(msg.str()); } // if if (!fn) { std::ostringstream msg; msg << "Cannot add NULL user function for value " << name << " to spatial database " << label() << "."; throw std::runtime_error(msg.str()); } // if } // _checkAdd // ---------------------------------------------------------------------- // Check compatibility of spatial database parameters. void spatialdata::spatialdb::UserFunctionDB::_checkCompatibility(void) const { // _checkCompatibility // Verify that we can call all user functions for given spatial dimension. if (!_cs) { std::ostringstream msg; msg << "Coordinate system has not been set for spatial database " << label() << "."; throw std::runtime_error(msg.str()); } // if double coords[3] = { 0.0, 0.0, 0.0 }; const int spaceDim = _cs->spaceDim(); assert(0 < spaceDim && spaceDim <= 3); double value; for (function_map::const_iterator iter = _functions.begin(); iter != _functions.end(); ++iter) { assert(iter->second.fn); const int flag = iter->second.fn->query(&value, coords, spaceDim); if (flag) { std::ostringstream msg; msg << "Error encountered in verifying compatibility for user function " << iter->second.fn << " for value '" << iter->first << "' in spatial database " << label() << "."; throw std::runtime_error(msg.str()); } // if } // for } // _checkCompatibility // End of file
// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard, U.S. Geological Survey // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2017 University of California, Davis // // See COPYING for license information. // // ---------------------------------------------------------------------- // #include <portinfo> #include "spatialdata/spatialdb/UserFunctionDB.hh" // Implementation of class methods // Include ios here to avoid some Python/gcc issues #include <ios> #include "spatialdata/geocoords/CoordSys.hh" // USES CoordSys #include "spatialdata/geocoords/Converter.hh" // USES Converter #include "spatialdata/units/Parser.hh" // USES Parser #include <stdexcept> // USES std::runtime_error #include <sstream> // USES std::ostringstream #include <cassert> // USES assert() // ---------------------------------------------------------------------- namespace spatialdata { namespace spatialdb { class UserFunctionDB::QueryFn1D : public UserFunctionDB::QueryFn { public: QueryFn1D(UserFunctionDB::userfn1D_type fn) : _fn(fn) {}; int query(double* value, const double* coords, const int dim) { if (!value || !coords || 1 != dim) { return 1; } *value = _fn(coords[0]); return 0; }; private: UserFunctionDB::userfn1D_type _fn; }; class UserFunctionDB::QueryFn2D : public UserFunctionDB::QueryFn { public: QueryFn2D(UserFunctionDB::userfn2D_type fn) : _fn(fn) {}; int query(double* value, const double* coords, const int dim) { if (!value || !coords || 2 != dim) { return 1; } *value = _fn(coords[0], coords[1]); return 0; }; private: UserFunctionDB::userfn2D_type _fn; }; class UserFunctionDB::QueryFn3D : public UserFunctionDB::QueryFn { public: QueryFn3D(UserFunctionDB::userfn3D_type fn) : _fn(fn) {}; int query(double* value, const double* coords, const int dim) { if (!value || !coords || 3 != dim) { return 1; } *value = _fn(coords[0], coords[1], coords[2]); return 0; }; private: UserFunctionDB::userfn3D_type _fn; }; } // namespace spatialdb } // namespace spatialdata // ---------------------------------------------------------------------- // Constructor spatialdata::spatialdb::UserFunctionDB::UserFunctionDB(void) : _queryFunctions(NULL), _cs(NULL), _querySize(0) { // constructor } // constructor // ---------------------------------------------------------------------- // Destructor spatialdata::spatialdb::UserFunctionDB::~UserFunctionDB(void) { delete[] _queryFunctions; _queryFunctions = NULL; _querySize = 0; for (function_map::iterator iter=_functions.begin(); iter != _functions.end(); ++iter) { delete iter->second.fn; iter->second.fn = NULL; } // for delete _cs; _cs = NULL; } // destructor // ---------------------------------------------------------------------- // Add function/value to database in 1-D. void spatialdata::spatialdb::UserFunctionDB::addValue(const char* name, userfn1D_type fn, const char* units) { _checkAdd(name, (void*)fn, units); UserData data; data.fn = new QueryFn1D(fn); data.units = units; data.scale = 0.0; _functions[name] = data; } // addValue // ---------------------------------------------------------------------- // Add function/value to database in 2-D. void spatialdata::spatialdb::UserFunctionDB::addValue(const char* name, userfn2D_type fn, const char* units) { _checkAdd(name, (void*)fn, units); UserData data; data.fn = new QueryFn2D(fn); data.units = units; data.scale = 0.0; _functions[name] = data; } // addValue // ---------------------------------------------------------------------- // Add function/value to database in 3-D. void spatialdata::spatialdb::UserFunctionDB::addValue(const char* name, userfn3D_type fn, const char* units) { _checkAdd(name, (void*)fn, units); UserData data; data.fn = new QueryFn3D(fn); data.units = units; data.scale = 0.0; _functions[name] = data; } // addValue // ---------------------------------------------------------------------- // Open the database and prepare for querying. void spatialdata::spatialdb::UserFunctionDB::open(void) { // Compute conversion to SI units. spatialdata::units::Parser parser; const std::string& none = "none"; for (function_map::iterator iter=_functions.begin(); iter != _functions.end(); ++iter) { if (none != iter->second.units) { iter->second.scale = parser.parse(iter->second.units.c_str()); } else { iter->second.scale = 1.0; } // if/else } // for _checkCompatibility(); } // open // ---------------------------------------------------------------------- // Close the database. void spatialdata::spatialdb::UserFunctionDB::close(void) { delete[] _queryFunctions; _queryFunctions = NULL; } // close // ---------------------------------------------------------------------- // Set values to be returned by queries. void spatialdata::spatialdb::UserFunctionDB::queryVals(const char* const* names, const int numVals) { if (0 == numVals) { std::ostringstream msg; msg << "Number of values for query in spatial database " << label() << "\n must be positive.\n"; throw std::runtime_error(msg.str()); } // if assert(names && 0 < numVals); _querySize = numVals; delete[] _queryFunctions; _queryFunctions = numVals > 0 ? new UserData*[numVals] : NULL; for (int iVal=0; iVal < numVals; ++iVal) { const function_map::iterator iter = _functions.find(names[iVal]); if (_functions.end() == iter) { std::ostringstream msg; msg << "Could not find value '" << names[iVal] << "' in spatial database '" << label() << "'. Available values are:"; for (function_map::iterator viter = _functions.begin(); viter != _functions.end(); ++viter) { msg << "\n " << viter->first; } // for msg << "\n"; throw std::runtime_error(msg.str()); } // if _queryFunctions[iVal] = &iter->second; } // for } // queryVals // ---------------------------------------------------------------------- // Query the database. int spatialdata::spatialdb::UserFunctionDB::query(double* vals, const int numVals, const double* coords, const int numDims, const spatialdata::geocoords::CoordSys* csQuery) { // query const int querySize = _querySize; assert(_cs); if (0 == querySize) { std::ostringstream msg; msg << "Values to be returned by spatial database " << label() << " have not been set. Please call queryVals() before query().\n"; throw std::runtime_error(msg.str()); } else if (numVals != querySize) { std::ostringstream msg; msg << "Number of values to be returned by spatial database " << label() << " (" << querySize << ") does not match size of array provided (" << numVals << ").\n"; throw std::runtime_error(msg.str()); } else if (numDims != _cs->spaceDim()) { std::ostringstream msg; msg << "Spatial dimension (" << numDims << ") does not match spatial dimension of spatial database (" << _cs->spaceDim() << ")."; throw std::runtime_error(msg.str()); } // if // Convert coordinates assert(numDims <= 3); double xyz[3]; memcpy(xyz, coords, numDims*sizeof(double)); spatialdata::geocoords::Converter::convert(xyz, 1, numDims, _cs, csQuery); int queryFlag = 0; for (int iVal=0; iVal < querySize; ++iVal) { assert(_queryFunctions[iVal]->fn); queryFlag = _queryFunctions[iVal]->fn->query(&vals[iVal], xyz, numDims); if (queryFlag) { break; } vals[iVal] *= _queryFunctions[iVal]->scale; // Convert to SI units. } // for return queryFlag; } // query // ---------------------------------------------------------------------- // Set filename containing data. void spatialdata::spatialdb::UserFunctionDB::coordsys(const geocoords::CoordSys& cs) { // coordsys delete _cs; _cs = cs.clone(); assert(_cs); _cs->initialize(); } // coordsys // ---------------------------------------------------------------------- void spatialdata::spatialdb::UserFunctionDB::_checkAdd(const char* name, void* fn, const char* units) const { if (!name) { std::ostringstream msg; msg << "NULL name passed to addValue() for spatial database " << label() << "."; throw std::logic_error(msg.str()); } // if if (!units) { std::ostringstream msg; msg << "NULL units passed to addValue() for spatial database " << label() << "."; throw std::logic_error(msg.str()); } // if // Verify user function for value does not already exist. const function_map::const_iterator& iter = _functions.find(name); if (iter != _functions.end()) { std::ostringstream msg; msg << "Cannot add user function for value " << name << " to spatial database " << label() << ". User function for value already exists."; throw std::runtime_error(msg.str()); } // if if (!fn) { std::ostringstream msg; msg << "Cannot add NULL user function for value " << name << " to spatial database " << label() << "."; throw std::runtime_error(msg.str()); } // if } // _checkAdd // ---------------------------------------------------------------------- // Check compatibility of spatial database parameters. void spatialdata::spatialdb::UserFunctionDB::_checkCompatibility(void) const { // _checkCompatibility // Verify that we can call all user functions for given spatial dimension. if (!_cs) { std::ostringstream msg; msg << "Coordinate system has not been set for spatial database " << label() << "."; throw std::runtime_error(msg.str()); } // if double coords[3] = { 0.0, 0.0, 0.0 }; const int spaceDim = _cs->spaceDim(); assert(0 < spaceDim && spaceDim <= 3); double value; for (function_map::const_iterator iter = _functions.begin(); iter != _functions.end(); ++iter) { assert(iter->second.fn); const int flag = iter->second.fn->query(&value, coords, spaceDim); if (flag) { std::ostringstream msg; msg << "Error encountered in verifying compatibility for user function " << iter->second.fn << " for value '" << iter->first << "' in spatial database " << label() << "."; throw std::runtime_error(msg.str()); } // if } // for } // _checkCompatibility // End of file
Add ios include to avoid Python/gcc issue.
Add ios include to avoid Python/gcc issue.
C++
mit
geodynamics/spatialdata,geodynamics/spatialdata,geodynamics/spatialdata,geodynamics/spatialdata
c1b71d930486145072710a62b7756e8de4255e03
projects/libusb/libusb_fuzzer.cc
projects/libusb/libusb_fuzzer.cc
// Copyright 2020 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 // // 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 <fuzzer/FuzzedDataProvider.h> #include <algorithm> #include <cstddef> #include <cstdint> #include "libusb/libusb.h" #include "libusb/libusbi.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { struct libusb_transfer *transfer; FuzzedDataProvider stream(data, size); uint8_t bmRequestType = stream.ConsumeIntegral<uint8_t>(); uint8_t bRequest = stream.ConsumeIntegral<uint8_t>(); uint16_t wValue = stream.ConsumeIntegral<uint16_t>(); uint16_t wIndex = stream.ConsumeIntegral<uint16_t>(); uint16_t wLength = stream.ConsumeIntegral<uint16_t>(); std::vector<char> data_ = stream.ConsumeRemainingBytes<char>(); unsigned char* buffer = reinterpret_cast<unsigned char*>(data_.data()); transfer = libusb_alloc_transfer(0); if (!transfer) { return LIBUSB_ERROR_NO_MEM; } if (!buffer) { libusb_free_transfer(transfer); return LIBUSB_ERROR_NO_MEM; } libusb_fill_control_setup( buffer, bmRequestType, bRequest, wValue, wIndex, wLength); libusb_free_transfer(transfer); return 0; }
// Copyright 2020 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 // // 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 <fuzzer/FuzzedDataProvider.h> #include <algorithm> #include <cstddef> #include <cstdint> #include "libusb/libusb.h" #include "libusb/libusbi.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { struct libusb_transfer *transfer = NULL; FuzzedDataProvider stream(data, size); uint8_t bmRequestType = stream.ConsumeIntegral<uint8_t>(); uint8_t bRequest = stream.ConsumeIntegral<uint8_t>(); uint16_t wValue = stream.ConsumeIntegral<uint16_t>(); uint16_t wIndex = stream.ConsumeIntegral<uint16_t>(); uint16_t wLength = stream.ConsumeIntegral<uint16_t>(); std::string input = stream.ConsumeRandomLengthString(); const char *d = input.c_str(); transfer = libusb_alloc_transfer(0); if (!transfer) { return LIBUSB_ERROR_NO_MEM; } libusb_fill_control_setup((unsigned char *)d, bmRequestType, bRequest, wValue, wIndex, wLength); // Cleanup. // We cannot call libusb_free_transfer as no callbacks has occurred. Calling // libusb_free_transfer without this will trigger false positive errors. struct usbi_transfer *itransfer = LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer); usbi_mutex_destroy(&itransfer->lock); size_t priv_size = PTR_ALIGN(usbi_backend.transfer_priv_size); unsigned char *ptr = (unsigned char *)itransfer - priv_size; free(ptr); return 0; }
fix build and fuzzer. (#6259)
libusb: fix build and fuzzer. (#6259)
C++
apache-2.0
google/oss-fuzz,skia-dev/oss-fuzz,robertswiecki/oss-fuzz,robertswiecki/oss-fuzz,googlefonts/oss-fuzz,robertswiecki/oss-fuzz,google/oss-fuzz,googlefonts/oss-fuzz,googlefonts/oss-fuzz,skia-dev/oss-fuzz,google/oss-fuzz,robertswiecki/oss-fuzz,google/oss-fuzz,googlefonts/oss-fuzz,googlefonts/oss-fuzz,googlefonts/oss-fuzz,googlefonts/oss-fuzz,skia-dev/oss-fuzz,robertswiecki/oss-fuzz,robertswiecki/oss-fuzz,google/oss-fuzz,google/oss-fuzz,skia-dev/oss-fuzz,robertswiecki/oss-fuzz,skia-dev/oss-fuzz,skia-dev/oss-fuzz,robertswiecki/oss-fuzz,googlefonts/oss-fuzz,skia-dev/oss-fuzz,google/oss-fuzz,google/oss-fuzz,googlefonts/oss-fuzz,robertswiecki/oss-fuzz,robertswiecki/oss-fuzz,googlefonts/oss-fuzz,google/oss-fuzz,google/oss-fuzz,skia-dev/oss-fuzz,robertswiecki/oss-fuzz,skia-dev/oss-fuzz,google/oss-fuzz,skia-dev/oss-fuzz,skia-dev/oss-fuzz
781ca4e4ebd35dba5012a86ef68921d0b6b9d74b
content/browser/streams/stream_registry.cc
content/browser/streams/stream_registry.cc
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/streams/stream_registry.h" #include "content/browser/streams/stream.h" namespace content { namespace { // The maximum size of memory each StreamRegistry instance is allowed to use // for its Stream instances. const size_t kDefaultMaxMemoryUsage = 1024 * 1024 * 1024U; // 1GiB } StreamRegistry::StreamRegistry() : total_memory_usage_(0), max_memory_usage_(kDefaultMaxMemoryUsage) { } StreamRegistry::~StreamRegistry() { } void StreamRegistry::RegisterStream(scoped_refptr<Stream> stream) { DCHECK(CalledOnValidThread()); DCHECK(stream.get()); DCHECK(!stream->url().is_empty()); streams_[stream->url()] = stream; } scoped_refptr<Stream> StreamRegistry::GetStream(const GURL& url) { DCHECK(CalledOnValidThread()); StreamMap::const_iterator stream = streams_.find(url); if (stream != streams_.end()) return stream->second; return NULL; } bool StreamRegistry::CloneStream(const GURL& url, const GURL& src_url) { DCHECK(CalledOnValidThread()); scoped_refptr<Stream> stream(GetStream(src_url)); if (stream.get()) { streams_[url] = stream; return true; } return false; } void StreamRegistry::UnregisterStream(const GURL& url) { DCHECK(CalledOnValidThread()); StreamMap::iterator iter = streams_.find(url); if (iter == streams_.end()) return; size_t buffered_bytes = iter->second->last_total_buffered_bytes(); DCHECK_LE(buffered_bytes, total_memory_usage_); total_memory_usage_ -= buffered_bytes; streams_.erase(url); } bool StreamRegistry::UpdateMemoryUsage(const GURL& url, size_t current_size, size_t increase) { DCHECK(CalledOnValidThread()); StreamMap::iterator iter = streams_.find(url); // A Stream must be registered with its parent registry to get memory. if (iter == streams_.end()) return false; size_t last_size = iter->second->last_total_buffered_bytes(); DCHECK_LE(last_size, total_memory_usage_); size_t usage_of_others = total_memory_usage_ - last_size; DCHECK_LE(current_size, last_size); size_t current_total_memory_usage = usage_of_others + current_size; if (increase > max_memory_usage_ - current_total_memory_usage) return false; total_memory_usage_ = current_total_memory_usage + increase; return true; } } // namespace content
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/streams/stream_registry.h" #include "content/browser/streams/stream.h" namespace content { namespace { // The maximum size of memory each StreamRegistry instance is allowed to use // for its Stream instances. const size_t kDefaultMaxMemoryUsage = 1024 * 1024 * 1024U; // 1GiB } StreamRegistry::StreamRegistry() : total_memory_usage_(0), max_memory_usage_(kDefaultMaxMemoryUsage) { } StreamRegistry::~StreamRegistry() { } void StreamRegistry::RegisterStream(scoped_refptr<Stream> stream) { DCHECK(CalledOnValidThread()); DCHECK(stream.get()); DCHECK(!stream->url().is_empty()); streams_[stream->url()] = stream; } scoped_refptr<Stream> StreamRegistry::GetStream(const GURL& url) { DCHECK(CalledOnValidThread()); StreamMap::const_iterator stream = streams_.find(url); if (stream != streams_.end()) return stream->second; return NULL; } bool StreamRegistry::CloneStream(const GURL& url, const GURL& src_url) { DCHECK(CalledOnValidThread()); scoped_refptr<Stream> stream(GetStream(src_url)); if (stream.get()) { streams_[url] = stream; return true; } return false; } void StreamRegistry::UnregisterStream(const GURL& url) { DCHECK(CalledOnValidThread()); StreamMap::iterator iter = streams_.find(url); if (iter == streams_.end()) return; // Only update |total_memory_usage_| if |url| is NOT a Stream clone because // cloned streams do not update |total_memory_usage_|. if (iter->second->url() == url) { size_t buffered_bytes = iter->second->last_total_buffered_bytes(); DCHECK_LE(buffered_bytes, total_memory_usage_); total_memory_usage_ -= buffered_bytes; } streams_.erase(url); } bool StreamRegistry::UpdateMemoryUsage(const GURL& url, size_t current_size, size_t increase) { DCHECK(CalledOnValidThread()); StreamMap::iterator iter = streams_.find(url); // A Stream must be registered with its parent registry to get memory. if (iter == streams_.end()) return false; size_t last_size = iter->second->last_total_buffered_bytes(); DCHECK_LE(last_size, total_memory_usage_); size_t usage_of_others = total_memory_usage_ - last_size; DCHECK_LE(current_size, last_size); size_t current_total_memory_usage = usage_of_others + current_size; if (increase > max_memory_usage_ - current_total_memory_usage) return false; total_memory_usage_ = current_total_memory_usage + increase; return true; } } // namespace content
Fix DCHECK caused by updating total_memory_usage_ for cloned streams.
Fix DCHECK caused by updating total_memory_usage_ for cloned streams. BUG=240603 Review URL: https://chromiumcodereview.appspot.com/23726048 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@224586 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
Just-D/chromium-1,jaruba/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,Fireblend/chromium-crosswalk,M4sse/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,anirudhSK/chromium,Chilledheart/chromium,anirudhSK/chromium,anirudhSK/chromium,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,anirudhSK/chromium,fujunwei/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,patrickm/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,littlstar/chromium.src,jaruba/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,M4sse/chromium.src,ltilve/chromium,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,Fireblend/chromium-crosswalk,anirudhSK/chromium,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,ondra-novak/chromium.src,patrickm/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,dushu1203/chromium.src,Chilledheart/chromium,ondra-novak/chromium.src,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,jaruba/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,Just-D/chromium-1,Chilledheart/chromium,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,Chilledheart/chromium,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,axinging/chromium-crosswalk,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,ltilve/chromium,mogoweb/chromium-crosswalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,littlstar/chromium.src,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,Just-D/chromium-1,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,dednal/chromium.src,M4sse/chromium.src,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,Just-D/chromium-1,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,anirudhSK/chromium,littlstar/chromium.src,ltilve/chromium,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,dednal/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,patrickm/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,Just-D/chromium-1,fujunwei/chromium-crosswalk,dednal/chromium.src,anirudhSK/chromium,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,Jonekee/chromium.src,anirudhSK/chromium,littlstar/chromium.src,ltilve/chromium,anirudhSK/chromium,chuan9/chromium-crosswalk,markYoungH/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,Just-D/chromium-1,jaruba/chromium.src,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,dednal/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,M4sse/chromium.src,anirudhSK/chromium,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,patrickm/chromium.src,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,jaruba/chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,Chilledheart/chromium,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,markYoungH/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,anirudhSK/chromium,dushu1203/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ltilve/chromium,littlstar/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk
b0b6f4f7d1724b832c663bab791e7cc329bcc953
src/reader.cpp
src/reader.cpp
///////////////////////////////////////////////////////////////////////////// // This file is part of EasyRPG. // // EasyRPG 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. // // EasyRPG 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>. ///////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// /// Headers //////////////////////////////////////////////////////////// #include "reader.h" #include <cstdarg> #ifdef _WIN32 #include <windows.h> #else #include <iconv.h> #endif //////////////////////////////////////////////////////////// /// Statics //////////////////////////////////////////////////////////// std::string Reader::error_str; //////////////////////////////////////////////////////////// Reader::Reader(char* filename, std::string encoding) { stream = fopen(filename, "rb"); this->encoding = encoding; this->filename = std::string(filename); } //////////////////////////////////////////////////////////// Reader::Reader(const std::string& filename, std::string encoding) { stream = fopen(filename.c_str(), "rb"); this->encoding = encoding; this->filename = std::string(filename); } //////////////////////////////////////////////////////////// Reader::~Reader() { if (stream != NULL) { fclose(stream); } } //////////////////////////////////////////////////////////// bool Reader::ReadBool() { return (Read32(Reader::CompressedInteger) > 0); } //////////////////////////////////////////////////////////// uint8_t Reader::Read8() { uint8_t val = 0; #ifndef NDEBUG assert(fread(&val, 1, 1, stream) == 1); #else fread(&val, 1, 1, stream); #endif return val; } //////////////////////////////////////////////////////////// int16_t Reader::Read16() { int16_t val = 0; #ifndef NDEBUG assert(fread(&val, 2, 1, stream) == 1); #else fread(&val, 2, 1, stream); #endif #ifdef READER_BIG_ENDIAN uint16_t val2 = (uint16_t)val; SwapByteOrder(val2); val = val2; #endif return val; } //////////////////////////////////////////////////////////// int32_t Reader::Read32(IntegerType type) { int32_t value = 0; unsigned char temp = 0; #ifdef READER_BIG_ENDIAN uint32_t val2 = 0; #endif switch (type) { case Reader::NormalInteger: #ifndef NDEBUG assert(fread(&value, 4, 1, stream) == 1); #else fread(&value, 4, 1, stream); #endif #ifdef READER_BIG_ENDIAN val2 = (uint32_t)value; SwapByteOrder(val2); value = val2; #endif return value; case Reader::CompressedInteger: do { value <<= 7; if (fread(&temp, 1, 1, stream) != 1) // Get byte's value return 0; value |= temp & 0x7F; // Check if it's a BER integer } while (temp & 0x80); return value; default: #ifndef NDEBUG assert(false && "Invalid IntegerType in Read32"); #endif return 0; } } //////////////////////////////////////////////////////////// double Reader::ReadDouble() { double val = 0; #ifndef NDEBUG assert(fread(&val, 8, 1, stream) == 1); #else fread(&val, 8, 1, stream); #endif #ifdef READER_BIG_ENDIAN #error "Need 64-bit byte swap" #endif return val; } //////////////////////////////////////////////////////////// void Reader::ReadBool(std::vector<bool> &buffer, size_t size) { uint8_t val = 0; buffer.clear(); for (unsigned i = 0; i < size; ++i) { #ifndef NDEBUG assert(fread(&val, 1, 1, stream) == 1); #else fread(&val, 1, 1, stream); #endif buffer.push_back(val > 0); } } //////////////////////////////////////////////////////////// void Reader::Read8(std::vector<uint8_t> &buffer, size_t size) { uint8_t val; buffer.clear(); for (unsigned int i = 0; i < size; ++i) { #ifndef NDEBUG assert(fread(&val, 1, 1, stream) == 1); #else fread(&val, 1, 1, stream); #endif buffer.push_back(val); } } //////////////////////////////////////////////////////////// void Reader::Read16(std::vector<int16_t> &buffer, size_t size) { int16_t val; buffer.clear(); size_t items = size / 2; for (unsigned int i = 0; i < items; ++i) { #ifndef NDEBUG assert(fread(&val, 2, 1, stream) == 1); #else fread(&val, 2, 1, stream); #endif #ifdef READER_BIG_ENDIAN uint16_t val2 = (uint16_t)val; SwapByteOrder(val2); val = val2; #endif buffer.push_back(val); } } //////////////////////////////////////////////////////////// void Reader::Read32(std::vector<uint32_t> &buffer, size_t size) { uint32_t val; buffer.clear(); size_t items = size / 4; for (unsigned int i = 0; i < items; ++i) { #ifndef NDEBUG assert(fread(&val, 4, 1, stream) == 1); #else fread(&val, 4, 1, stream); #endif #ifdef READER_BIG_ENDIAN SwapByteOrder(val); #endif buffer.push_back(val); } } //////////////////////////////////////////////////////////// std::string Reader::ReadString(size_t size) { char* chars = new char[size + 1]; chars[size] = '\0'; #ifndef NDEBUG assert(fread(chars, 1, size, stream) == size); #else fread(chars, 1, size, stream); #endif std::string str; str = Encode(std::string(chars)); delete[] chars; return str; } //////////////////////////////////////////////////////////// bool Reader::IsOk() const { return (stream != NULL && !ferror(stream)); } //////////////////////////////////////////////////////////// bool Reader::Eof() const { return feof(stream) != 0; } //////////////////////////////////////////////////////////// void Reader::Seek(size_t pos, SeekMode mode) { switch (mode) { case Reader::FromStart: fseek(stream, pos, SEEK_SET); break; case Reader::FromCurrent: fseek(stream, pos, SEEK_CUR); break; case Reader::FromEnd: fseek(stream, pos, SEEK_END); break; default: #ifndef NDEBUG assert(false && "Invalid SeekMode"); #else ; #endif } } //////////////////////////////////////////////////////////// uint32_t Reader::Tell() { return (uint32_t)ftell(stream); } //////////////////////////////////////////////////////////// bool Reader::Ungetch(uint8_t ch) { return (ungetc(ch, stream) == ch); } //////////////////////////////////////////////////////////// #ifdef _DEBUG void Reader::SkipDebug(const struct Reader::Chunk& chunk_info, const char* srcfile) { #else void Reader::Skip(const struct Reader::Chunk& chunk_info) { #endif #ifdef _DEBUG // Dump the Chunk Data in Debug Mode #ifdef _WIN32 const char* srcfilename = strrchr(srcfile, '\\'); #else const char* srcfilename = strrchr(srcfile, '/'); #endif if (srcfilename == NULL) { srcfilename = srcfile; } else { srcfilename++; } fprintf(stderr, "Skipped Chunk %02X (%d byte) in %s at %X (%s)\n", chunk_info.ID, chunk_info.length, filename.c_str(), Tell(), srcfilename); for (uint32_t i = 0; i < chunk_info.length; ++i) { fprintf(stderr, "%02X ", Reader::Read8()); if ((i+1) % 16 == 0) { fprintf(stderr, "\n"); } } fprintf(stderr, "\n"); #else Seek((size_t)chunk_info.length, FromCurrent); #endif } //////////////////////////////////////////////////////////// void Reader::SetError(const char* fmt, ...) { va_list args; va_start(args, fmt); char str[256]; vsprintf(str, fmt, args); error_str = str; //Output::ErrorStr((std::string)str); va_end(args); } //////////////////////////////////////////////////////////// const std::string& Reader::GetError() { return error_str; } //////////////////////////////////////////////////////////// std::string Reader::Encode(const std::string& str_to_encode) { size_t strsize = str_to_encode.size(); #ifdef _WIN32 wchar_t* widechar = new wchar_t[strsize * 5 + 1]; char* utf8char = new char[strsize * 5 + 1]; // To Utf16 // Default codepage is 0, so we dont need a check here int res = MultiByteToWideChar(atoi(encoding.c_str()), 0, str_to_encode.c_str(), strsize, widechar, strsize * 5 + 1); if (res == 0) { // Invalid codepage delete [] widechar; delete [] utf8char; return str_to_encode; } widechar[res] = '\0'; // Back to Utf8 ... res = WideCharToMultiByte(CP_UTF8, 0, widechar, res, utf8char, strsize * 5 + 1, NULL, NULL); utf8char[res] = '\0'; // Result in str std::string str = std::string(utf8char, res); delete [] widechar; delete [] utf8char; return str; #else iconv_t cd = iconv_open("UTF-8", encoding.c_str()); if (cd == (iconv_t)-1) return str_to_encode; char *src = (char *) str_to_encode.c_str(); size_t src_left = str_to_encode.size(); size_t dst_size = str_to_encode.size() * 5 + 10; char *dst = new char[dst_size]; size_t dst_left = dst_size; char *p = src; char *q = dst; size_t status = iconv(cd, &p, &src_left, &q, &dst_left); iconv_close(cd); if (status == (size_t) -1 || src_left > 0) { delete[] dst; return ""; } *q++ = '\0'; std::string result = std::string(dst); delete[] dst; return result; #endif } //////////////////////////////////////////////////////////// #ifdef READER_BIG_ENDIAN void Reader::SwapByteOrder(uint16_t& us) { us = (us >> 8) | (us << 8); } void Reader::SwapByteOrder(uint32_t& ui) { ui = (ui >> 24) | ((ui<<8) & 0x00FF0000) | ((ui>>8) & 0x0000FF00) | (ui << 24); } #endif
///////////////////////////////////////////////////////////////////////////// // This file is part of EasyRPG. // // EasyRPG 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. // // EasyRPG 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>. ///////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// /// Headers //////////////////////////////////////////////////////////// #include "reader.h" #include <cstdarg> #ifdef _WIN32 #include <windows.h> #else #include <iconv.h> #endif //////////////////////////////////////////////////////////// /// Statics //////////////////////////////////////////////////////////// std::string Reader::error_str; //////////////////////////////////////////////////////////// Reader::Reader(char* filename, std::string encoding) { stream = fopen(filename, "rb"); this->encoding = encoding; this->filename = std::string(filename); } //////////////////////////////////////////////////////////// Reader::Reader(const std::string& filename, std::string encoding) { stream = fopen(filename.c_str(), "rb"); this->encoding = encoding; this->filename = std::string(filename); } //////////////////////////////////////////////////////////// Reader::~Reader() { if (stream != NULL) { fclose(stream); } } //////////////////////////////////////////////////////////// bool Reader::ReadBool() { return (Read32(Reader::CompressedInteger) > 0); } //////////////////////////////////////////////////////////// uint8_t Reader::Read8() { uint8_t val = 0; #ifndef NDEBUG assert(fread(&val, 1, 1, stream) == 1); #else fread(&val, 1, 1, stream); #endif return val; } //////////////////////////////////////////////////////////// int16_t Reader::Read16() { int16_t val = 0; #ifndef NDEBUG assert(fread(&val, 2, 1, stream) == 1); #else fread(&val, 2, 1, stream); #endif #ifdef READER_BIG_ENDIAN uint16_t val2 = (uint16_t)val; SwapByteOrder(val2); val = val2; #endif return val; } //////////////////////////////////////////////////////////// int32_t Reader::Read32(IntegerType type) { int32_t value = 0; unsigned char temp = 0; #ifdef READER_BIG_ENDIAN uint32_t val2 = 0; #endif switch (type) { case Reader::NormalInteger: #ifndef NDEBUG assert(fread(&value, 4, 1, stream) == 1); #else fread(&value, 4, 1, stream); #endif #ifdef READER_BIG_ENDIAN val2 = (uint32_t)value; SwapByteOrder(val2); value = val2; #endif return value; case Reader::CompressedInteger: do { value <<= 7; if (fread(&temp, 1, 1, stream) != 1) // Get byte's value return 0; value |= temp & 0x7F; // Check if it's a BER integer } while (temp & 0x80); return value; default: #ifndef NDEBUG assert(false && "Invalid IntegerType in Read32"); #endif return 0; } } //////////////////////////////////////////////////////////// double Reader::ReadDouble() { double val = 0; #ifndef NDEBUG assert(fread(&val, 8, 1, stream) == 1); #else fread(&val, 8, 1, stream); #endif #ifdef READER_BIG_ENDIAN #error "Need 64-bit byte swap" #endif return val; } //////////////////////////////////////////////////////////// void Reader::ReadBool(std::vector<bool> &buffer, size_t size) { uint8_t val = 0; buffer.clear(); for (unsigned i = 0; i < size; ++i) { #ifndef NDEBUG assert(fread(&val, 1, 1, stream) == 1); #else fread(&val, 1, 1, stream); #endif buffer.push_back(val > 0); } } //////////////////////////////////////////////////////////// void Reader::Read8(std::vector<uint8_t> &buffer, size_t size) { uint8_t val; buffer.clear(); for (unsigned int i = 0; i < size; ++i) { #ifndef NDEBUG assert(fread(&val, 1, 1, stream) == 1); #else fread(&val, 1, 1, stream); #endif buffer.push_back(val); } } //////////////////////////////////////////////////////////// void Reader::Read16(std::vector<int16_t> &buffer, size_t size) { int16_t val; buffer.clear(); size_t items = size / 2; for (unsigned int i = 0; i < items; ++i) { #ifndef NDEBUG assert(fread(&val, 2, 1, stream) == 1); #else fread(&val, 2, 1, stream); #endif #ifdef READER_BIG_ENDIAN uint16_t val2 = (uint16_t)val; SwapByteOrder(val2); val = val2; #endif buffer.push_back(val); } } //////////////////////////////////////////////////////////// void Reader::Read32(std::vector<uint32_t> &buffer, size_t size) { uint32_t val; buffer.clear(); size_t items = size / 4; for (unsigned int i = 0; i < items; ++i) { #ifndef NDEBUG assert(fread(&val, 4, 1, stream) == 1); #else fread(&val, 4, 1, stream); #endif #ifdef READER_BIG_ENDIAN SwapByteOrder(val); #endif buffer.push_back(val); } } //////////////////////////////////////////////////////////// std::string Reader::ReadString(size_t size) { char* chars = new char[size + 1]; chars[size] = '\0'; #ifndef NDEBUG assert(fread(chars, 1, size, stream) == size); #else fread(chars, 1, size, stream); #endif std::string str; str = Encode(std::string(chars)); delete[] chars; return str; } //////////////////////////////////////////////////////////// bool Reader::IsOk() const { return (stream != NULL && !ferror(stream)); } //////////////////////////////////////////////////////////// bool Reader::Eof() const { return feof(stream) != 0; } //////////////////////////////////////////////////////////// void Reader::Seek(size_t pos, SeekMode mode) { switch (mode) { case Reader::FromStart: fseek(stream, pos, SEEK_SET); break; case Reader::FromCurrent: fseek(stream, pos, SEEK_CUR); break; case Reader::FromEnd: fseek(stream, pos, SEEK_END); break; default: #ifndef NDEBUG assert(false && "Invalid SeekMode"); #else ; #endif } } //////////////////////////////////////////////////////////// uint32_t Reader::Tell() { return (uint32_t)ftell(stream); } //////////////////////////////////////////////////////////// bool Reader::Ungetch(uint8_t ch) { return (ungetc(ch, stream) == ch); } //////////////////////////////////////////////////////////// #ifdef _DEBUG void Reader::SkipDebug(const struct Reader::Chunk& chunk_info, const char* srcfile) { #else void Reader::Skip(const struct Reader::Chunk& chunk_info) { #endif #ifdef _DEBUG // Dump the Chunk Data in Debug Mode #ifdef _WIN32 const char* srcfilename = strrchr(srcfile, '\\'); #else const char* srcfilename = strrchr(srcfile, '/'); #endif if (srcfilename == NULL) { srcfilename = srcfile; } else { srcfilename++; } fprintf(stderr, "Skipped Chunk %02X (%d byte) in %s at %X (%s)\n", chunk_info.ID, chunk_info.length, filename.c_str(), Tell(), srcfilename); for (uint32_t i = 0; i < chunk_info.length; ++i) { fprintf(stderr, "%02X ", Reader::Read8()); if ((i+1) % 16 == 0) { fprintf(stderr, "\n"); } } fprintf(stderr, "\n"); #else Seek((size_t)chunk_info.length, FromCurrent); #endif } //////////////////////////////////////////////////////////// void Reader::SetError(const char* fmt, ...) { va_list args; va_start(args, fmt); char str[256]; vsprintf(str, fmt, args); error_str = str; //Output::ErrorStr((std::string)str); va_end(args); } //////////////////////////////////////////////////////////// const std::string& Reader::GetError() { return error_str; } //////////////////////////////////////////////////////////// std::string Reader::Encode(const std::string& str_to_encode) { size_t strsize = str_to_encode.size(); #ifdef _WIN32 wchar_t* widechar = new wchar_t[strsize * 5 + 1]; char* utf8char = new char[strsize * 5 + 1]; // To Utf16 // Default codepage is 0, so we dont need a check here int res = MultiByteToWideChar(atoi(encoding.c_str()), 0, str_to_encode.c_str(), strsize, widechar, strsize * 5 + 1); if (res == 0) { // Invalid codepage delete [] widechar; delete [] utf8char; return str_to_encode; } widechar[res] = '\0'; // Back to Utf8 ... res = WideCharToMultiByte(CP_UTF8, 0, widechar, res, utf8char, strsize * 5 + 1, NULL, NULL); utf8char[res] = '\0'; // Result in str std::string str = std::string(utf8char, res); delete [] widechar; delete [] utf8char; return str; #else iconv_t cd = iconv_open("UTF-8", encoding.c_str()); if (cd == (iconv_t)-1) return str_to_encode; char *src = (char *) str_to_encode.c_str(); size_t src_left = str_to_encode.size(); size_t dst_size = str_to_encode.size() * 5 + 10; char *dst = new char[dst_size]; size_t dst_left = dst_size; char *p = src; char *q = dst; size_t status = iconv(cd, &p, &src_left, &q, &dst_left); iconv_close(cd); if (status == (size_t) -1 || src_left > 0) { delete[] dst; return ""; } *q++ = '\0'; std::string result(dst); delete[] dst; return result; #endif } //////////////////////////////////////////////////////////// #ifdef READER_BIG_ENDIAN void Reader::SwapByteOrder(uint16_t& us) { us = (us >> 8) | (us << 8); } void Reader::SwapByteOrder(uint32_t& ui) { ui = (ui >> 24) | ((ui<<8) & 0x00FF0000) | ((ui>>8) & 0x0000FF00) | (ui << 24); } #endif
Remove some leaks.
Remove some leaks.
C++
mit
glynnc/liblcf,Ghabry/easyrpg-liblcf,carstene1ns/easyrpg-liblcf,EasyRPG/liblcf,EasyRPG/liblcf,Ghabry/easyrpg-liblcf,glynnc/liblcf,Ghabry/easyrpg-liblcf,carstene1ns/easyrpg-liblcf,Zegeri/liblcf,carstene1ns/easyrpg-liblcf,fdelapena/easyrpg-liblcf,fdelapena/easyrpg-liblcf,glynnc/liblcf,fdelapena/easyrpg-liblcf,EasyRPG/liblcf,EasyRPG/liblcf,Zegeri/liblcf,Ghabry/easyrpg-liblcf,glynnc/liblcf,Zegeri/liblcf
41bebecd181863f239cfdc11d4ddb05c53534ab7
ionGUI/CGUIManager.cpp
ionGUI/CGUIManager.cpp
#include <ionConfig.h> #ifdef _ION_CONFIG_USE_GWEN #include "CGUIManager.h" #include "OpenGL3Font.h" Gwen::Font * LoadFont(Gwen::UnicodeString const & File, float const Size) { Gwen::Font * Font = new Gwen::Font(); Font->facename = File; Font->size = Size; return Font; } CGUIManager::CGUIManager() {} void CGUIManager::Init(string const & SkinFile) { if (Initialized) { cerr << "GUIManager being initialized is already initialized" << endl; return; } Gwen::Renderer::Base * pRenderer = new Gwen::Renderer::OpenGL3Font(ion::GL::Context::GetViewportSize()); Gwen::Skin::TexturedBase * skin = new Gwen::Skin::TexturedBase(pRenderer); skin->Init(SkinFile); skin->SetDefaultFont(L"OpenSans.ttf", 12.f); LargeFont = LoadFont(L"OpenSans.ttf", 40.f); MediumFont = LoadFont(L"OpenSans.ttf", 24.f); RegularFont = LoadFont(L"OpenSans.ttf", 12.f); Canvas = new Gwen::Controls::Canvas(skin); Canvas->SetSize(ion::GL::Context::GetViewportSize().X, ion::GL::Context::GetViewportSize().Y); Initialized = true; } void CGUIManager::Draw(f32 const Elapsed, bool const ClearAll) { if (! Initialized) { cerr << "GUIManager being used is uninitialized." << endl; return; } for (auto it = Widgets.begin(); it != Widgets.end(); ++ it) (* it)->Update(Elapsed); if (ClearAll) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); else glClear(GL_DEPTH_BUFFER_BIT); Canvas->RenderCanvas(); } Gwen::Controls::Canvas * CGUIManager::GetCanvas() { return Canvas; } Gwen::Font * CGUIManager::GetLargeFont() { return LargeFont; } Gwen::Font * CGUIManager::GetMediumFont() { return MediumFont; } Gwen::Font * CGUIManager::GetRegularFont() { return RegularFont; } void CGUIManager::AddWidget(CGUIWidget * Widget) { Widgets.push_back(Widget); } void CGUIManager::RemoveWidget(CGUIWidget * Widget) { for (auto it = Widgets.begin(); it != Widgets.end(); ++ it) delete (* it); Widgets.erase(std::remove(Widgets.begin(), Widgets.end(), Widget), Widgets.end()); } void CGUIManager::RemoveAllWidgets() { Widgets.clear(); } #endif
#include <ionConfig.h> #ifdef _ION_CONFIG_USE_GWEN #include "CGUIManager.h" #include "OpenGL3Font.h" Gwen::Font * LoadFont(Gwen::UnicodeString const & File, float const Size) { Gwen::Font * Font = new Gwen::Font(); Font->facename = File; Font->size = Size; return Font; } CGUIManager::CGUIManager() {} void CGUIManager::Init(string const & SkinFile) { if (Initialized) { cerr << "GUIManager being initialized is already initialized" << endl; return; } Gwen::Renderer::Base * pRenderer = new Gwen::Renderer::OpenGL3Font(ion::GL::Context::GetViewportSize()); Gwen::Skin::TexturedBase * skin = new Gwen::Skin::TexturedBase(pRenderer); skin->Init(SkinFile); skin->SetDefaultFont(L"OpenSans.ttf", 12.f); LargeFont = LoadFont(L"OpenSans.ttf", 40.f); MediumFont = LoadFont(L"OpenSans.ttf", 24.f); RegularFont = LoadFont(L"OpenSans.ttf", 12.f); Canvas = new Gwen::Controls::Canvas(skin); Canvas->SetSize(ion::GL::Context::GetViewportSize().X, ion::GL::Context::GetViewportSize().Y); Initialized = true; } void CGUIManager::Draw(f32 const Elapsed, bool const ClearAll) { if (! Initialized) { cerr << "GUIManager being used is uninitialized." << endl; return; } for (auto it = Widgets.begin(); it != Widgets.end(); ++ it) (* it)->Update(Elapsed); if (ClearAll) ion::GL::Context::Clear({ ion::GL::EBuffer::Color, ion::GL::EBuffer::Depth }); else ion::GL::Context::Clear({ ion::GL::EBuffer::Depth }); Canvas->RenderCanvas(); } Gwen::Controls::Canvas * CGUIManager::GetCanvas() { return Canvas; } Gwen::Font * CGUIManager::GetLargeFont() { return LargeFont; } Gwen::Font * CGUIManager::GetMediumFont() { return MediumFont; } Gwen::Font * CGUIManager::GetRegularFont() { return RegularFont; } void CGUIManager::AddWidget(CGUIWidget * Widget) { Widgets.push_back(Widget); } void CGUIManager::RemoveWidget(CGUIWidget * Widget) { for (auto it = Widgets.begin(); it != Widgets.end(); ++ it) delete (* it); Widgets.erase(std::remove(Widgets.begin(), Widgets.end(), Widget), Widgets.end()); } void CGUIManager::RemoveAllWidgets() { Widgets.clear(); } #endif
Update CGUIManager to use ion::GL
Update CGUIManager to use ion::GL
C++
mit
iondune/ionEngine,iondune/ionEngine
5cbdcfb46300296e31a6624fe98d28620711ae36
mtp/mtpz/TrustedApp.cpp
mtp/mtpz/TrustedApp.cpp
/* This file is part of Android File Transfer For Linux. Copyright (C) 2015-2020 Vladimir Menshakov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <mtp/mtpz/TrustedApp.h> #include <mtp/ptp/Session.h> #include <mtp/log.h> #include <mutex> #include <tuple> #ifdef MTPZ_ENABLED # include <openssl/bio.h> # include <openssl/bn.h> # include <openssl/crypto.h> # include <openssl/rsa.h> # include <openssl/rand.h> # include <openssl/sha.h> #endif namespace mtp { std::once_flag crypto_init; TrustedApp::TrustedApp(const SessionPtr & session, const std::string &mtpzDataPath): _session(session), _keys(LoadKeys(mtpzDataPath)) {} TrustedApp::~TrustedApp() { } #ifdef MTPZ_ENABLED struct TrustedApp::Keys { ByteArray skey; //session key BIGNUM *exp, *mod, *pkey; RSA * rsa; ByteArray certificate; Keys(): exp(), mod(), pkey(), rsa(RSA_new()) { } void Update() { if (RSA_set0_key(rsa, mod, exp, pkey)) { debug("created RSA key"); mod = exp = pkey = NULL; } else throw std::runtime_error("failed to create RSA key"); } ~Keys() { if (exp) BN_free(exp); if (mod) BN_free(mod); if (pkey) BN_free(pkey); if (rsa) RSA_free(rsa); } ByteArray HKDF(const u8 * message, size_t messageSize, size_t keySize) { size_t blockSize = SHA_DIGEST_LENGTH; size_t blocks = (keySize + blockSize - 1) / blockSize; ByteArray key(blocks * blockSize); ByteArray ctr(messageSize + 4); const auto ctrPtr = std::copy(message, message + messageSize, ctr.data()); u8 * dst = key.data(); for(size_t i = 0; i < blocks; ++i, dst += blockSize) { ctrPtr[0] = i >> 24; ctrPtr[1] = i >> 16; ctrPtr[2] = i >> 8; ctrPtr[3] = i; SHA1(ctr.data(), ctr.size(), dst); } return key; } std::tuple<ByteArray, ByteArray> GenerateCertificateMessage() { static const size_t messageSize = 156 + certificate.size(); ByteArray challenge(16); RAND_bytes(challenge.data(), challenge.size()); ByteArray message(messageSize); auto dst = message.data(); *dst++ = 0x02; *dst++ = 0x01; *dst++ = 0x01; *dst++ = 0x00; *dst++ = 0x00; *dst++ = certificate.size() >> 8; *dst++ = certificate.size(); dst = std::copy(certificate.begin(), certificate.end(), dst); *dst++ = 0x00; *dst++ = 0x10; dst = std::copy(challenge.begin(), challenge.end(), dst); ByteArray hash(SHA_DIGEST_LENGTH); { ByteArray salt(SHA_DIGEST_LENGTH + 8); SHA1(certificate.data() + 2, dst - certificate.data() - 2, salt.data() + 8); SHA1(salt.data(), salt.size(), hash.data()); } ByteArray key = HKDF(hash.data(), hash.size(), 107); HexDump("key", key); ByteArray signature(RSA_size(rsa)); signature[106] = 1; for(size_t i = 0; i < hash.size(); ++i) signature[i + 107] = hash[i]; for(size_t i = 0; i < 107; ++i) signature[i] ^= key[i]; signature[0] &= 127; signature[127] = 188; HexDump("signature", signature); *dst++ = 1; *dst++ = 0; *dst++ = signature.size(); if (RSA_private_encrypt(signature.size(), signature.data(), dst, rsa, RSA_NO_PADDING) == -1) throw std::runtime_error("RSA_private_encrypt failed"); return std::make_tuple(challenge, message); } static u8 FromHex(char ch) { if (ch >= '0' && ch <= '9') return ch - '0'; if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10; if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10; throw std::runtime_error(std::string("invalid hex character ") + ch); } static ByteArray FromHex(const char *buf, size_t bufsize) { ByteArray data; data.reserve((bufsize + 1) / 2); while(buf[0] && buf[1]) { u8 h = FromHex(*buf++); u8 l = FromHex(*buf++); data.push_back((h << 4) | l); } if (buf[0] != 0 && !isspace(buf[0])) throw std::runtime_error("tailing character"); return data; } }; bool TrustedApp::Probe(const SessionPtr & session) { auto & di = session->GetDeviceInfo(); bool supported = di.Supports(OperationCode::SendWMDRMPDAppRequest) && di.Supports(OperationCode::GetWMDRMPDAppResponse) && di.Supports(OperationCode::EnableTrustedFilesOperations) && di.Supports(OperationCode::DisableTrustedFilesOperations) && di.Supports(OperationCode::EndTrustedAppSession); debug("MTPZ supported: " , supported? "yes": "no"); return supported; } void TrustedApp::Authenticate() { auto & di = _session->GetDeviceInfo(); if (di.Supports(DeviceProperty::SessionInitiatorVersionInfo)) _session->SetDeviceProperty(DeviceProperty::SessionInitiatorVersionInfo, "Android File Transfer for Linux/MTPZClass Driver"); _session->GenericOperation(OperationCode::EndTrustedAppSession); ByteArray challenge, message; std::tie(challenge, message) = _keys->GenerateCertificateMessage(); HexDump("certificate payload", message); _session->GenericOperation(OperationCode::SendWMDRMPDAppRequest, message); } TrustedApp::KeysPtr TrustedApp::LoadKeys(const std::string & path) { BIO * bio = BIO_new_file(path.c_str(), "rt"); if (bio == NULL) { error("could not open .mtpz-data"); return nullptr; } auto keys = std::make_shared<Keys>(); try { char buf[4096]; //public exp BIO_gets(bio, buf, sizeof(buf)); if (BN_hex2bn(&keys->exp, buf) <= 0) throw std::runtime_error("can't read public exponent"); //session key auto r = BIO_gets(bio, buf, sizeof(buf)); if (r <= 0) throw std::runtime_error("BIO_gets: short read"); keys->skey = Keys::FromHex(buf, r); //HexDump("session key", keys->skey); //public mod BIO_gets(bio, buf, sizeof(buf)); if (BN_hex2bn(&keys->mod, buf) <= 0) throw std::runtime_error("can't read public modulus"); //private exponent BIO_gets(bio, buf, sizeof(buf)); if (BN_hex2bn(&keys->pkey, buf) <= 0) throw std::runtime_error("can't read private key"); r = BIO_gets(bio, buf, sizeof(buf)); if (r <= 0) throw std::runtime_error("BIO_gets: short read"); keys->certificate = Keys::FromHex(buf, r); //HexDump("certificate", keys->certificate); } catch(...) { BIO_free(bio); throw; } BIO_free(bio); keys->Update(); return keys; } #else bool TrustedApp::Probe(const SessionPtr & session) { return false; } TrustedApp::KeysPtr TrustedApp::LoadKeys(const std::string & path) { return nullptr; } void TrustedApp::Authenticate() { } #endif }
/* This file is part of Android File Transfer For Linux. Copyright (C) 2015-2020 Vladimir Menshakov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <mtp/mtpz/TrustedApp.h> #include <mtp/ptp/Session.h> #include <mtp/log.h> #include <mutex> #include <tuple> #ifdef MTPZ_ENABLED # include <openssl/bio.h> # include <openssl/bn.h> # include <openssl/crypto.h> # include <openssl/rsa.h> # include <openssl/rand.h> # include <openssl/sha.h> #endif namespace mtp { std::once_flag crypto_init; TrustedApp::TrustedApp(const SessionPtr & session, const std::string &mtpzDataPath): _session(session), _keys(LoadKeys(mtpzDataPath)) {} TrustedApp::~TrustedApp() { } #ifdef MTPZ_ENABLED struct TrustedApp::Keys { ByteArray skey; //session key BIGNUM *exp, *mod, *pkey; RSA * rsa; ByteArray certificate; Keys(): exp(), mod(), pkey(), rsa(RSA_new()) { } void Update() { if (RSA_set0_key(rsa, mod, exp, pkey)) { debug("created RSA key"); mod = exp = pkey = NULL; } else throw std::runtime_error("failed to create RSA key"); } ~Keys() { if (exp) BN_free(exp); if (mod) BN_free(mod); if (pkey) BN_free(pkey); if (rsa) RSA_free(rsa); } ByteArray HKDF(const u8 * message, size_t messageSize, size_t keySize) { size_t blockSize = SHA_DIGEST_LENGTH; size_t blocks = (keySize + blockSize - 1) / blockSize; ByteArray key(blocks * blockSize); ByteArray ctr(messageSize + 4); const auto ctrPtr = std::copy(message, message + messageSize, ctr.data()); u8 * dst = key.data(); for(size_t i = 0; i < blocks; ++i, dst += blockSize) { ctrPtr[0] = i >> 24; ctrPtr[1] = i >> 16; ctrPtr[2] = i >> 8; ctrPtr[3] = i; SHA1(ctr.data(), ctr.size(), dst); } return key; } std::tuple<ByteArray, ByteArray> GenerateCertificateMessage() { static const size_t messageSize = 156 + certificate.size(); ByteArray challenge(16); RAND_bytes(challenge.data(), challenge.size()); ByteArray message(messageSize); auto dst = message.data(); *dst++ = 0x02; *dst++ = 0x01; *dst++ = 0x01; *dst++ = 0x00; *dst++ = 0x00; *dst++ = certificate.size() >> 8; *dst++ = certificate.size(); dst = std::copy(certificate.begin(), certificate.end(), dst); *dst++ = 0x00; *dst++ = 0x10; dst = std::copy(challenge.begin(), challenge.end(), dst); ByteArray hash(SHA_DIGEST_LENGTH); { ByteArray salt(SHA_DIGEST_LENGTH + 8); SHA1(certificate.data() + 2, dst - certificate.data() - 2, salt.data() + 8); SHA1(salt.data(), salt.size(), hash.data()); } ByteArray key = HKDF(hash.data(), hash.size(), 107); HexDump("key", key); ByteArray signature(RSA_size(rsa)); signature[106] = 1; for(size_t i = 0; i < hash.size(); ++i) signature[i + 107] = hash[i]; for(size_t i = 0; i < 107; ++i) signature[i] ^= key[i]; signature[0] &= 127; signature[127] = 188; HexDump("signature", signature); *dst++ = 1; *dst++ = 0; *dst++ = signature.size(); if (RSA_private_encrypt(signature.size(), signature.data(), dst, rsa, RSA_NO_PADDING) == -1) throw std::runtime_error("RSA_private_encrypt failed"); return std::make_tuple(challenge, message); } static u8 FromHex(char ch) { if (ch >= '0' && ch <= '9') return ch - '0'; if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10; if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10; throw std::runtime_error(std::string("invalid hex character ") + ch); } static ByteArray FromHex(const char *buf, size_t bufsize) { ByteArray data; data.reserve((bufsize + 1) / 2); while(buf[0] && buf[1]) { u8 h = FromHex(*buf++); u8 l = FromHex(*buf++); data.push_back((h << 4) | l); } if (buf[0] != 0 && !isspace(buf[0])) throw std::runtime_error("tailing character"); return data; } }; bool TrustedApp::Probe(const SessionPtr & session) { auto & di = session->GetDeviceInfo(); bool supported = di.Supports(OperationCode::SendWMDRMPDAppRequest) && di.Supports(OperationCode::GetWMDRMPDAppResponse) && di.Supports(OperationCode::EnableTrustedFilesOperations) && di.Supports(OperationCode::DisableTrustedFilesOperations) && di.Supports(OperationCode::EndTrustedAppSession); debug("MTPZ supported: " , supported? "yes": "no"); return supported; } void TrustedApp::Authenticate() { if (!_keys) return; auto & di = _session->GetDeviceInfo(); if (di.Supports(DeviceProperty::SessionInitiatorVersionInfo)) _session->SetDeviceProperty(DeviceProperty::SessionInitiatorVersionInfo, "Android File Transfer for Linux/MTPZClass Driver"); _session->GenericOperation(OperationCode::EndTrustedAppSession); ByteArray challenge, message; std::tie(challenge, message) = _keys->GenerateCertificateMessage(); HexDump("certificate payload", message); _session->GenericOperation(OperationCode::SendWMDRMPDAppRequest, message); } TrustedApp::KeysPtr TrustedApp::LoadKeys(const std::string & path) { BIO * bio = BIO_new_file(path.c_str(), "rt"); if (bio == NULL) { error("could not open .mtpz-data"); return nullptr; } auto keys = std::make_shared<Keys>(); try { char buf[4096]; //public exp BIO_gets(bio, buf, sizeof(buf)); if (BN_hex2bn(&keys->exp, buf) <= 0) throw std::runtime_error("can't read public exponent"); //session key auto r = BIO_gets(bio, buf, sizeof(buf)); if (r <= 0) throw std::runtime_error("BIO_gets: short read"); keys->skey = Keys::FromHex(buf, r); //HexDump("session key", keys->skey); //public mod BIO_gets(bio, buf, sizeof(buf)); if (BN_hex2bn(&keys->mod, buf) <= 0) throw std::runtime_error("can't read public modulus"); //private exponent BIO_gets(bio, buf, sizeof(buf)); if (BN_hex2bn(&keys->pkey, buf) <= 0) throw std::runtime_error("can't read private key"); r = BIO_gets(bio, buf, sizeof(buf)); if (r <= 0) throw std::runtime_error("BIO_gets: short read"); keys->certificate = Keys::FromHex(buf, r); //HexDump("certificate", keys->certificate); } catch(...) { BIO_free(bio); throw; } BIO_free(bio); keys->Update(); return keys; } #else bool TrustedApp::Probe(const SessionPtr & session) { return false; } TrustedApp::KeysPtr TrustedApp::LoadKeys(const std::string & path) { return nullptr; } void TrustedApp::Authenticate() { } #endif }
fix crash if no keys present
fix crash if no keys present
C++
lgpl-2.1
whoozle/android-file-transfer-linux,whoozle/android-file-transfer-linux,whoozle/android-file-transfer-linux,whoozle/android-file-transfer-linux
aa8b3ffc5f23611f6f2f33ccbb5551f32cc4a0b8
client_demo/netlicensing_client_demo.cc
client_demo/netlicensing_client_demo.cc
#include <iostream> #include <random> #include <ctime> #include <sstream> #include "netlicensing/netlicensing.h" #include "netlicensing/constants.h" int main(int argc, char* argv[]) { using namespace netlicensing; std::string licensee_number = "IR2Q7A5P3"; if (argc > 1) { licensee_number = argv[1]; } std::mt19937 gen; gen.seed(time(0)); std::stringstream ss; ss << "P" << gen(); std::string productNumber = ss.str(); std::cout << "Hello, this is NetLicensing demo client\n"; std::cout << "Product endpoint " << endpoint<Product>() << std::endl; std::cout << "Product test number " << productNumber << std::endl; try { Context ctx; ctx.set_base_url("https://go.netlicensing.io/core/v2/rest/"); ctx.set_username("demo"); ctx.set_password("demo"); // product section Product p; p.setName("Test name"); p.setNumber(productNumber); std::list<ProductDiscount> discounts; ProductDiscount discount; ProductDiscount discount2; discount.setTotalPrice("20"); discount.setCurrency("EUR"); discount.setAmountFix("10"); discount2.setTotalPrice("25"); discount2.setCurrency("EUR"); discount2.setAmountPercent("10"); discounts.push_back(discount); discounts.push_back(discount2); p.setProductsDiscounts(discounts); Product newp = ProductService::create(ctx, p); std::list<ProductDiscount> newpDiscounts = newp.getDiscounts(); std::cout << "product disounts size: " << newpDiscounts.size() << std::endl; int i = 0; for (ProductDiscount newpDiscount : newpDiscounts) { std::string newpDiscountStr = newpDiscount.toString(); std::cout << "product disount #" << i << ": " << newpDiscountStr << std::endl; i++; } newp.setName("Updated name"); std::list<ProductDiscount> discountsEmpty; newp.setProductsDiscounts(discountsEmpty); std::cin.ignore(); Product newp2 = ProductService::update(ctx, newp.getNumber(), newp); std::list<ProductDiscount> newp2Discounts = newp2.getDiscounts(); std::cout << "product disounts size: " << newp2Discounts.size() << std::endl; std::cin.ignore(); std::list<Product> products = ProductService::list(ctx, ""); std::cout << "before delete products count " << products.size() << std::endl; ProductService::del(ctx, newp2.getNumber(), false); products = ProductService::list(ctx, ""); std::cout << "after delete products count " << products.size() << std::endl; if (!licensee_number.empty()) { std::cout << "start validation for " << licensee_number << std::endl; ValidationResult vres = LicenseeService::validate(ctx, licensee_number); std::cout << "got validation results:\n" << vres.toString() << std::endl; } } catch (const RestException& e) { std::cerr << e.what() << " code " << e.http_code() << std::endl; for (auto det : e.get_details()) { std::cerr << det.to_string() << std::endl; } return 2; } catch (const std::runtime_error& err) { std::cerr << err.what() << std::endl; std::cin.ignore(); return 1; } return 0; }
#include <iostream> #include <random> #include <ctime> #include <sstream> #include <string> #include "netlicensing/netlicensing.h" #include "netlicensing/constants.h" int main(int argc, char* argv[]) { using namespace netlicensing; std::string licensee_number; if (argc > 1) { licensee_number = argv[1]; } std::mt19937 gen; gen.seed(time(0)); std::stringstream ss; std::cout << "Hello, this is NetLicensing demo client\n"; try { Context ctx; ctx.set_base_url("https://go.netlicensing.io/core/v2/rest/"); ctx.set_username("demo"); ctx.set_password("demo"); if (licensee_number.empty()) { std::cout << "Please enter a valid licensee number for validation (choose licensee in demo account): " << std::endl; if (!std::getline(std::cin, licensee_number)) { return -1; } if (!licensee_number.empty()) { std::cout << "start validation for " << licensee_number << std::endl; ValidationResult vres = LicenseeService::validate(ctx, licensee_number); std::cout << "got validation results:\n" << vres.toString() << std::endl; } else { std::cout << "Invalid licensee number for validation." << std::endl; return -1; } } } catch (const RestException& e) { std::cerr << e.what() << " code " << e.http_code() << std::endl; for (auto det : e.get_details()) { std::cerr << det.to_string() << std::endl; } std::cin.ignore(); return 2; } catch (const std::runtime_error& err) { std::cerr << err.what() << std::endl; std::cin.ignore(); return 1; } return 0; }
FIx netlicensing_client_demo
FIx netlicensing_client_demo
C++
apache-2.0
Labs64/NetLicensingClient-cpp,Labs64/NetLicensingClient-cpp
2360428ff826fa27a8104335114668613543a2eb
3RVX/OSD/VolumeOSD.cpp
3RVX/OSD/VolumeOSD.cpp
#include "VolumeOSD.h" #include "..\SoundPlayer.h" #include <string> #include "..\HotkeyInfo.h" #include "..\LanguageTranslator.h" #include "..\MeterWnd\Meters\CallbackMeter.h" #include "..\Monitor.h" #include "..\Skin.h" #include "..\SkinManager.h" #include "..\Slider\VolumeSlider.h" #include "..\MeterWnd\LayeredWnd.h" VolumeOSD::VolumeOSD() : OSD(L"3RVX-VolumeDispatcher"), _mWnd(L"3RVX-VolumeOSD", L"3RVX-VolumeOSD"), _muteWnd(L"3RVX-MuteOSD", L"3RVX-MuteOSD") { LoadSkin(); /* Start the volume controller */ _volumeCtrl = new CoreAudio(Window::Handle()); std::wstring device = _settings->AudioDeviceID(); _volumeCtrl->Init(device); _selectedDesc = _volumeCtrl->DeviceDesc(); /* Set up volume state variables */ _lastVolume = _volumeCtrl->Volume(); _muted = _volumeCtrl->Muted(); if (_settings->SoundEffectsEnabled()) { _sounds = true; } /* Create the slider */ _volumeSlider = new VolumeSlider(*_volumeCtrl); /* Set up context menu */ if (_settings->NotifyIconEnabled()) { LanguageTranslator *translator = _settings->Translator(); _menuSetStr = translator->Translate(_menuSetStr); _menuDevStr = translator->Translate(_menuDevStr); _menuMixerStr = translator->Translate(_menuMixerStr); _menuExitStr = translator->Translate(_menuExitStr); _iconMuteStr = translator->Translate(_iconMuteStr); _menu = CreatePopupMenu(); _deviceMenu = CreatePopupMenu(); InsertMenu(_menu, -1, MF_ENABLED, MENU_SETTINGS, _menuSetStr.c_str()); InsertMenu(_menu, -1, MF_POPUP, UINT(_deviceMenu), _menuDevStr.c_str()); InsertMenu(_menu, -1, MF_ENABLED, MENU_MIXER, _menuMixerStr.c_str()); InsertMenu(_menu, -1, MF_ENABLED, MENU_EXIT, _menuExitStr.c_str()); _menuFlags = TPM_RIGHTBUTTON; if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0) { _menuFlags |= TPM_RIGHTALIGN; } else { _menuFlags |= TPM_LEFTALIGN; } UpdateDeviceMenu(); } UpdateIcon(); float v = _volumeCtrl->Volume(); MeterLevels(v); _volumeSlider->MeterLevels(v); /* TODO: check whether we should show the OSD on startup or not. If so, post * a MSG_VOL_CHNG so that the volume level (or mute) is displayed: */ SendMessage(Window::Handle(), VolumeController::MSG_VOL_CHNG, NULL, (LPARAM) 1); } VolumeOSD::~VolumeOSD() { DestroyMenu(_deviceMenu); DestroyMenu(_menu); delete _icon; delete _volumeSlider; delete _callbackMeter; _volumeCtrl->Dispose(); } void VolumeOSD::UpdateDeviceMenu() { if (_menu == NULL || _deviceMenu == NULL) { return; } /* Remove any devices currently in the menu first */ for (unsigned int i = 0; i < _deviceList.size(); ++i) { RemoveMenu(_deviceMenu, 0, MF_BYPOSITION); } _deviceList.clear(); std::list<VolumeController::DeviceInfo> devices = _volumeCtrl->ListDevices(); std::wstring currentDeviceId = _volumeCtrl->DeviceId(); int menuItem = MENU_DEVICE; for (VolumeController::DeviceInfo device : devices) { unsigned int flags = MF_ENABLED; if (currentDeviceId == device.id) { flags |= MF_CHECKED; } InsertMenu(_deviceMenu, -1, flags, menuItem++, device.name.c_str()); _deviceList.push_back(device); } } void VolumeOSD::LoadSkin() { Skin *skin = SkinManager::Instance()->CurrentSkin(); /* Volume OSD */ /* TODO: should make sure this isn't NULL! */ _mWnd.BackgroundImage(skin->volumeBackground); if (skin->volumeMask != NULL) { _mWnd.EnableGlass(skin->volumeMask); } for (Meter *m : skin->volumeMeters) { _mWnd.AddMeter(m); } /* Add a callback meter with the default volume increment for sounds */ _callbackMeter = new CallbackMeter( skin->DefaultVolumeUnits(), *this); _mWnd.AddMeter(_callbackMeter); /* Default volume increment */ _defaultIncrement = (float) (10000 / skin->DefaultVolumeUnits()) / 10000.0f; CLOG(L"Default volume increment: %f", _defaultIncrement); _mWnd.Update(); /* Mute OSD */ /* TODO: NULL check*/ _muteWnd.BackgroundImage(skin->muteBackground); if (skin->muteMask != NULL) { _muteWnd.EnableGlass(skin->muteMask); } _muteWnd.Update(); /* Now that everything is set up, initialize the meter windows. */ OSD::InitMeterWnd(_mWnd); OSD::InitMeterWnd(_muteWnd); /* Set up notification icon */ if (_settings->NotifyIconEnabled()) { _iconImages = skin->volumeIconset; if (_iconImages.size() > 0) { _icon = new NotifyIcon(Window::Handle(), L"3RVX", _iconImages[0]); } } /* Enable sound effects, if any */ if (_settings->SoundEffectsEnabled()) { if (skin->volumeSound) { _soundPlayer = skin->volumeSound; } } } void VolumeOSD::MeterLevels(float level) { _mWnd.MeterLevels(level); _mWnd.Update(); } void VolumeOSD::MeterChangeCallback(int units) { /* This method is called each time the callback meter changes by at least * 1 volume unit (as defined by the skin's default unit amount). The * callback meter is also used for incrementing/decrementing the volume by * skin units. */ } void VolumeOSD::Hide() { _mWnd.Hide(false); _muteWnd.Hide(false); } void VolumeOSD::HideIcon() { delete _icon; } void VolumeOSD::UpdateIcon() { UpdateIconImage(); UpdateIconTip(); } void VolumeOSD::UpdateIconImage() { if (_icon == NULL) { return; } int icon = 0; if (_volumeCtrl->Muted() == false) { int vUnits = _iconImages.size() - 1; icon = (int) ceil(_volumeCtrl->Volume() * vUnits); } if (icon != _lastIcon) { _icon->UpdateIcon(_iconImages[icon]); _lastIcon = icon; } } void VolumeOSD::UpdateIconTip() { if (_icon == NULL) { return; } if (_volumeCtrl->Muted()) { _icon->UpdateToolTip(_selectedDesc + L": " + _iconMuteStr); } else { float v = _volumeCtrl->Volume(); std::wstring perc = std::to_wstring((int) (v * 100.0f)); std::wstring level = _selectedDesc + L": " + perc + L"%"; _icon->UpdateToolTip(level); } } void VolumeOSD::UnMute() { if (_volumeCtrl->Muted() == true) { _volumeCtrl->Muted(false); } } void VolumeOSD::ProcessHotkeys(HotkeyInfo &hki) { switch (hki.action) { case HotkeyInfo::IncreaseVolume: case HotkeyInfo::DecreaseVolume: UnMute(); ProcessVolumeHotkeys(hki); break; case HotkeyInfo::SetVolume: { HotkeyInfo::VolumeKeyArgTypes type = HotkeyInfo::VolumeArgType(hki); if (type == HotkeyInfo::VolumeKeyArgTypes::NoArgs) { return; } else if (type == HotkeyInfo::VolumeKeyArgTypes::Units) { int numUnits = hki.ArgToInt(0); _volumeCtrl->Volume(numUnits * _defaultIncrement); } else if (type == HotkeyInfo::VolumeKeyArgTypes::Percentage) { double perc = hki.ArgToDouble(0); _volumeCtrl->Volume((float) perc); } } SendMessage(Window::Handle(), VolumeController::MSG_VOL_CHNG, NULL, (LPARAM) 1); break; case HotkeyInfo::Mute: _volumeCtrl->ToggleMute(); SendMessage(Window::Handle(), VolumeController::MSG_VOL_CHNG, NULL, (LPARAM) 1); break; case HotkeyInfo::VolumeSlider: if (_volumeSlider->Visible()) { /* If the slider is already visible, user must want to close it. */ _volumeSlider->Hide(); } else { SendMessage(Window::Handle(), MSG_NOTIFYICON, NULL, WM_LBUTTONUP); } break; } } void VolumeOSD::ProcessVolumeHotkeys(HotkeyInfo &hki) { float currentVol = _volumeCtrl->Volume(); HotkeyInfo::VolumeKeyArgTypes type = HotkeyInfo::VolumeArgType(hki); if (type == HotkeyInfo::VolumeKeyArgTypes::Percentage) { /* Deal with percentage-based amounts */ float amount = ((float) hki.ArgToDouble(0) / 100.0f); if (hki.action == HotkeyInfo::HotkeyActions::DecreaseVolume) { amount = -amount; } _volumeCtrl->Volume(currentVol + amount); } else { /* Unit-based amounts */ int unitIncrement = 1; int currentUnit = _callbackMeter->CalcUnits(); if (currentVol <= 0.000001f) { currentUnit = 0; } if (hki.action == HotkeyInfo::DecreaseVolume) { unitIncrement = -1; } if (type == HotkeyInfo::VolumeKeyArgTypes::Units) { unitIncrement *= hki.ArgToInt(0); } _volumeCtrl->Volume( (float) (currentUnit + unitIncrement) * _defaultIncrement); } /* Tell 3RVX that we changed the volume */ SendMessage(Window::Handle(), VolumeController::MSG_VOL_CHNG, NULL, (LPARAM) 1); } void VolumeOSD::UpdateVolumeState() { float v = _volumeCtrl->Volume(); MeterLevels(v); _volumeSlider->MeterLevels(v); UpdateIcon(); } LRESULT VolumeOSD::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == VolumeController::MSG_VOL_CHNG) { float v = _volumeCtrl->Volume(); bool muteState = _volumeCtrl->Muted(); _volumeSlider->MeterLevels(v); UpdateIcon(); if (wParam > 0) { /* We manually post a MSG_VOL_CHNG when modifying the volume with * hotkeys, so this CoreAudio-generated event can be ignored * by the OSD. */ CLOG(L"Ignoring volume change notification generated by 3RVX"); return DefWindowProc(hWnd, message, wParam, lParam); } CLOG(L"Volume change notification:\nNew level: %f\nPrevious: %f", v, _lastVolume); if (lParam == 0 && (muteState == _muted)) { if (abs(v - _lastVolume) < 0.0001f) { CLOG(L"No change in volume detected; ignoring event."); return DefWindowProc(hWnd, message, wParam, lParam); } } _lastVolume = v; _muted = muteState; if (_volumeSlider->Visible() == false) { if (_volumeCtrl->Muted() || v == 0.0f) { _muteWnd.Show(); _mWnd.Hide(false); } else { MeterLevels(v); _mWnd.Show(); _muteWnd.Hide(false); if (_soundPlayer) { _soundPlayer->Play(); } } HideOthers(Volume); } } else if (message == VolumeController::MSG_VOL_DEVCHNG) { CLOG(L"Volume device change detected."); if (_selectedDevice == L"") { _volumeCtrl->SelectDefaultDevice(); } else { HRESULT hr = _volumeCtrl->SelectDevice(_selectedDevice); if (FAILED(hr)) { _volumeCtrl->SelectDefaultDevice(); } } _selectedDesc = _volumeCtrl->DeviceDesc(); UpdateDeviceMenu(); UpdateVolumeState(); } else if (message == MSG_NOTIFYICON) { if (lParam == WM_LBUTTONUP) { _volumeSlider->MeterLevels(_volumeCtrl->Volume()); _volumeSlider->Show(); } else if (lParam == WM_RBUTTONUP) { POINT p; GetCursorPos(&p); SetForegroundWindow(hWnd); TrackPopupMenuEx(_menu, _menuFlags, p.x, p.y, Window::Handle(), NULL); PostMessage(hWnd, WM_NULL, 0, 0); } } else if (message == WM_COMMAND) { int menuItem = LOWORD(wParam); switch (menuItem) { case MENU_SETTINGS: Settings::LaunchSettingsApp(); break; case MENU_MIXER: { CLOG(L"Menu: Mixer"); HINSTANCE code = ShellExecute(NULL, L"open", L"sndvol", NULL, NULL, SW_SHOWNORMAL); break; } case MENU_EXIT: CLOG(L"Menu: Exit: %d", (int) _masterWnd); SendMessage(_masterWnd, WM_CLOSE, NULL, NULL); break; } /* Device menu items */ if ((menuItem & MENU_DEVICE) > 0) { int device = menuItem & 0x0FFF; VolumeController::DeviceInfo selectedDev = _deviceList[device]; if (selectedDev.id != _volumeCtrl->DeviceId()) { /* A different device has been selected */ CLOG(L"Changing to volume device: %s", selectedDev.name.c_str()); _volumeCtrl->SelectDevice(selectedDev.id); UpdateDeviceMenu(); UpdateVolumeState(); } } } return DefWindowProc(hWnd, message, wParam, lParam); }
#include "VolumeOSD.h" #include "..\SoundPlayer.h" #include <string> #include "..\HotkeyInfo.h" #include "..\LanguageTranslator.h" #include "..\MeterWnd\Meters\CallbackMeter.h" #include "..\Monitor.h" #include "..\Skin.h" #include "..\SkinManager.h" #include "..\Slider\VolumeSlider.h" #include "..\MeterWnd\LayeredWnd.h" VolumeOSD::VolumeOSD() : OSD(L"3RVX-VolumeDispatcher"), _mWnd(L"3RVX-VolumeOSD", L"3RVX-VolumeOSD"), _muteWnd(L"3RVX-MuteOSD", L"3RVX-MuteOSD") { LoadSkin(); /* Start the volume controller */ _volumeCtrl = new CoreAudio(Window::Handle()); std::wstring device = _settings->AudioDeviceID(); _volumeCtrl->Init(device); _selectedDesc = _volumeCtrl->DeviceDesc(); /* Set up volume state variables */ _lastVolume = _volumeCtrl->Volume(); _muted = _volumeCtrl->Muted(); if (_settings->SoundEffectsEnabled()) { _sounds = true; } /* Create the slider */ _volumeSlider = new VolumeSlider(*_volumeCtrl); /* Set up context menu */ if (_settings->NotifyIconEnabled()) { LanguageTranslator *translator = _settings->Translator(); _menuSetStr = translator->Translate(_menuSetStr); _menuDevStr = translator->Translate(_menuDevStr); _menuMixerStr = translator->Translate(_menuMixerStr); _menuExitStr = translator->Translate(_menuExitStr); _iconMuteStr = translator->Translate(_iconMuteStr); _menu = CreatePopupMenu(); _deviceMenu = CreatePopupMenu(); InsertMenu(_menu, -1, MF_ENABLED, MENU_SETTINGS, _menuSetStr.c_str()); InsertMenu(_menu, -1, MF_POPUP, UINT(_deviceMenu), _menuDevStr.c_str()); InsertMenu(_menu, -1, MF_ENABLED, MENU_MIXER, _menuMixerStr.c_str()); InsertMenu(_menu, -1, MF_ENABLED, MENU_EXIT, _menuExitStr.c_str()); _menuFlags = TPM_RIGHTBUTTON; if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0) { _menuFlags |= TPM_RIGHTALIGN; } else { _menuFlags |= TPM_LEFTALIGN; } UpdateDeviceMenu(); } UpdateIcon(); float v = _volumeCtrl->Volume(); MeterLevels(v); _volumeSlider->MeterLevels(v); /* TODO: check whether we should show the OSD on startup or not. If so, post * a MSG_VOL_CHNG so that the volume level (or mute) is displayed: */ SendMessage(Window::Handle(), VolumeController::MSG_VOL_CHNG, NULL, (LPARAM) 1); } VolumeOSD::~VolumeOSD() { DestroyMenu(_deviceMenu); DestroyMenu(_menu); delete _icon; delete _volumeSlider; delete _callbackMeter; _volumeCtrl->Dispose(); } void VolumeOSD::UpdateDeviceMenu() { if (_menu == NULL || _deviceMenu == NULL) { return; } /* Remove any devices currently in the menu first */ for (unsigned int i = 0; i < _deviceList.size(); ++i) { RemoveMenu(_deviceMenu, 0, MF_BYPOSITION); } _deviceList.clear(); std::list<VolumeController::DeviceInfo> devices = _volumeCtrl->ListDevices(); std::wstring currentDeviceId = _volumeCtrl->DeviceId(); int menuItem = MENU_DEVICE; for (VolumeController::DeviceInfo device : devices) { unsigned int flags = MF_ENABLED; if (currentDeviceId == device.id) { flags |= MF_CHECKED; } InsertMenu(_deviceMenu, -1, flags, menuItem++, device.name.c_str()); _deviceList.push_back(device); } } void VolumeOSD::LoadSkin() { Skin *skin = SkinManager::Instance()->CurrentSkin(); /* Volume OSD */ /* TODO: should make sure this isn't NULL! */ _mWnd.BackgroundImage(skin->volumeBackground); if (skin->volumeMask != NULL) { _mWnd.EnableGlass(skin->volumeMask); } for (Meter *m : skin->volumeMeters) { _mWnd.AddMeter(m); } /* Add a callback meter with the default volume increment for sounds */ _callbackMeter = new CallbackMeter( skin->DefaultVolumeUnits(), *this); _mWnd.AddMeter(_callbackMeter); /* Default volume increment */ _defaultIncrement = (float) (10000 / skin->DefaultVolumeUnits()) / 10000.0f; CLOG(L"Default volume increment: %f", _defaultIncrement); _mWnd.Update(); /* Mute OSD */ /* TODO: NULL check*/ _muteWnd.BackgroundImage(skin->muteBackground); if (skin->muteMask != NULL) { _muteWnd.EnableGlass(skin->muteMask); } _muteWnd.Update(); /* Now that everything is set up, initialize the meter windows. */ OSD::InitMeterWnd(_mWnd); OSD::InitMeterWnd(_muteWnd); /* Set up notification icon */ if (_settings->NotifyIconEnabled()) { _iconImages = skin->volumeIconset; if (_iconImages.size() > 0) { _icon = new NotifyIcon(Window::Handle(), L"3RVX", _iconImages[0]); } } /* Enable sound effects, if any */ if (_settings->SoundEffectsEnabled()) { if (skin->volumeSound) { _soundPlayer = skin->volumeSound; } } } void VolumeOSD::MeterLevels(float level) { _mWnd.MeterLevels(level); _mWnd.Update(); } void VolumeOSD::MeterChangeCallback(int units) { /* This method is called each time the callback meter changes by at least * 1 volume unit (as defined by the skin's default unit amount). The * callback meter is also used for incrementing/decrementing the volume by * skin units. */ } void VolumeOSD::Hide() { _mWnd.Hide(false); _muteWnd.Hide(false); } void VolumeOSD::HideIcon() { delete _icon; } void VolumeOSD::UpdateIcon() { UpdateIconImage(); UpdateIconTip(); } void VolumeOSD::UpdateIconImage() { if (_icon == NULL) { return; } int icon = 0; if (_volumeCtrl->Muted() == false) { int vUnits = _iconImages.size() - 1; icon = (int) ceil(_volumeCtrl->Volume() * vUnits); } if (icon != _lastIcon) { _icon->UpdateIcon(_iconImages[icon]); _lastIcon = icon; } } void VolumeOSD::UpdateIconTip() { if (_icon == NULL) { return; } if (_volumeCtrl->Muted()) { _icon->UpdateToolTip(_selectedDesc + L": " + _iconMuteStr); } else { float v = _volumeCtrl->Volume(); std::wstring perc = std::to_wstring((int) (v * 100.0f)); std::wstring level = _selectedDesc + L": " + perc + L"%"; _icon->UpdateToolTip(level); } } void VolumeOSD::UnMute() { if (_volumeCtrl->Muted() == true) { _volumeCtrl->Muted(false); } } void VolumeOSD::ProcessHotkeys(HotkeyInfo &hki) { switch (hki.action) { case HotkeyInfo::IncreaseVolume: case HotkeyInfo::DecreaseVolume: UnMute(); ProcessVolumeHotkeys(hki); break; case HotkeyInfo::SetVolume: { HotkeyInfo::VolumeKeyArgTypes type = HotkeyInfo::VolumeArgType(hki); if (type == HotkeyInfo::VolumeKeyArgTypes::NoArgs) { return; } else if (type == HotkeyInfo::VolumeKeyArgTypes::Units) { int numUnits = hki.ArgToInt(0); _volumeCtrl->Volume(numUnits * _defaultIncrement); } else if (type == HotkeyInfo::VolumeKeyArgTypes::Percentage) { double perc = hki.ArgToDouble(0); _volumeCtrl->Volume((float) perc); } } SendMessage(Window::Handle(), VolumeController::MSG_VOL_CHNG, NULL, (LPARAM) 1); break; case HotkeyInfo::Mute: _volumeCtrl->ToggleMute(); SendMessage(Window::Handle(), VolumeController::MSG_VOL_CHNG, NULL, (LPARAM) 1); break; case HotkeyInfo::VolumeSlider: if (_volumeSlider->Visible()) { /* If the slider is already visible, user must want to close it. */ _volumeSlider->Hide(); } else { SendMessage(Window::Handle(), MSG_NOTIFYICON, NULL, WM_LBUTTONUP); } break; } } void VolumeOSD::ProcessVolumeHotkeys(HotkeyInfo &hki) { float currentVol = _volumeCtrl->Volume(); HotkeyInfo::VolumeKeyArgTypes type = HotkeyInfo::VolumeArgType(hki); if (type == HotkeyInfo::VolumeKeyArgTypes::Percentage) { /* Deal with percentage-based amounts */ float amount = ((float) hki.ArgToDouble(0) / 100.0f); if (hki.action == HotkeyInfo::HotkeyActions::DecreaseVolume) { amount = -amount; } _volumeCtrl->Volume(currentVol + amount); } else { /* Unit-based amounts */ int unitIncrement = 1; int currentUnit = _callbackMeter->CalcUnits(); if (currentVol <= 0.000001f) { currentUnit = 0; } if (hki.action == HotkeyInfo::DecreaseVolume) { unitIncrement = -1; } if (type == HotkeyInfo::VolumeKeyArgTypes::Units) { unitIncrement *= hki.ArgToInt(0); } _volumeCtrl->Volume( (float) (currentUnit + unitIncrement) * _defaultIncrement); } /* Tell 3RVX that we changed the volume */ SendMessage(Window::Handle(), VolumeController::MSG_VOL_CHNG, NULL, (LPARAM) 1); } void VolumeOSD::UpdateVolumeState() { float v = _volumeCtrl->Volume(); MeterLevels(v); _volumeSlider->MeterLevels(v); UpdateIcon(); } LRESULT VolumeOSD::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == VolumeController::MSG_VOL_CHNG) { float v = _volumeCtrl->Volume(); bool muteState = _volumeCtrl->Muted(); _volumeSlider->MeterLevels(v); UpdateIcon(); if (wParam > 0) { /* We manually post a MSG_VOL_CHNG when modifying the volume with * hotkeys, so this CoreAudio-generated event can be ignored * by the OSD. */ CLOG(L"Ignoring volume change notification generated by 3RVX"); return DefWindowProc(hWnd, message, wParam, lParam); } CLOG(L"Volume change notification:\nNew level: %f\nPrevious: %f", v, _lastVolume); if (lParam == 0 && (muteState == _muted)) { if (abs(v - _lastVolume) < 0.0001f) { CLOG(L"No change in volume detected; ignoring event."); return DefWindowProc(hWnd, message, wParam, lParam); } } _lastVolume = v; _muted = muteState; if (_volumeSlider->Visible() == false) { if (_volumeCtrl->Muted() || v == 0.0f) { _muteWnd.Show(); _mWnd.Hide(false); } else { MeterLevels(v); _mWnd.Show(); _muteWnd.Hide(false); if (_soundPlayer) { _soundPlayer->Play(); } } HideOthers(Volume); } } else if (message == VolumeController::MSG_VOL_DEVCHNG) { CLOG(L"Volume device change detected."); if (_selectedDevice == L"") { _volumeCtrl->SelectDefaultDevice(); } else { HRESULT hr = _volumeCtrl->SelectDevice(_selectedDevice); if (FAILED(hr)) { _volumeCtrl->SelectDefaultDevice(); } } _selectedDesc = _volumeCtrl->DeviceDesc(); UpdateDeviceMenu(); UpdateVolumeState(); } else if (message == MSG_NOTIFYICON) { if (lParam == WM_LBUTTONUP) { _volumeSlider->MeterLevels(_volumeCtrl->Volume()); _volumeSlider->Show(); } else if (lParam == WM_RBUTTONUP) { POINT p; GetCursorPos(&p); SetForegroundWindow(hWnd); TrackPopupMenuEx(_menu, _menuFlags, p.x, p.y, Window::Handle(), NULL); PostMessage(hWnd, WM_NULL, 0, 0); } } else if (message == WM_COMMAND) { int menuItem = LOWORD(wParam); switch (menuItem) { case MENU_SETTINGS: Settings::LaunchSettingsApp(); break; case MENU_MIXER: { CLOG(L"Menu: Mixer"); HINSTANCE code = ShellExecute(NULL, L"open", L"sndvol", NULL, NULL, SW_SHOWNORMAL); break; } case MENU_EXIT: CLOG(L"Menu: Exit: %d", (int) _masterWnd); SendMessage(_masterWnd, WM_CLOSE, NULL, NULL); break; } /* Device menu items */ if ((menuItem & MENU_DEVICE) > 0) { int device = menuItem & 0x0FFF; VolumeController::DeviceInfo selectedDev = _deviceList[device]; if (selectedDev.id != _volumeCtrl->DeviceId()) { /* A different device has been selected */ CLOG(L"Changing to volume device: %s", selectedDev.name.c_str()); _volumeCtrl->SelectDevice(selectedDev.id); UpdateDeviceMenu(); UpdateVolumeState(); } } } return DefWindowProc(hWnd, message, wParam, lParam); }
Reformat for 80 char limit
Reformat for 80 char limit
C++
bsd-2-clause
malensek/3RVX,Soulflare3/3RVX,Soulflare3/3RVX,Soulflare3/3RVX,malensek/3RVX,malensek/3RVX
045f70a8de8bb21cc6a3deef44cd2d2af5c16d4b
tests/test_qios.cpp
tests/test_qios.cpp
/* * Copyright (c) 2012 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #ifdef WIN32 # include <process.h> // for getpid #else # include <unistd.h> // for getpid #endif #include <cstdio> #include <gtest/gtest.h> #include <boost/filesystem.hpp> #include <qi/path.hpp> #include <qi/os.hpp> #include <qi/qi.hpp> class QiOSTests: public ::testing::Test { public: QiOSTests() : a_newPath() { } protected: void SetUp() { a_newPath = qi::os::mktmpdir("QiOsTest"); a_newPath.append(a_accent, qi::unicodeFacet()); FILE* fileHandle = qi::os::fopen(a_newPath.string(qi::unicodeFacet()).c_str(), "w"); fclose(fileHandle); // QString pouet = QDir::tempPath() + "/" + QString::fromUtf8(a_accent); // FILE* fileHandle = qi::os::fopen(pouet.toUtf8().data(), "w"); // fclose(fileHandle); } void TearDown() { if(boost::filesystem::exists(a_newPath)) { try { boost::filesystem::remove_all(a_newPath.parent_path()); } catch (std::exception &) { } } } public: boost::filesystem::path a_newPath; static const char a_accent[4]; }; // "é" in utf-8 w. french locale. const char QiOSTests::a_accent[4] = { '/', 0xc3, 0xa9, '\0' } ; TEST_F(QiOSTests, LowLevelAccent) { // Try to retrieve the file. // The name must be in utf-8 to be retrieved on unix. ASSERT_TRUE(boost::filesystem::exists(a_newPath)) << a_newPath.string() << std::endl; } // TODO: us qi::time when it's available :) TEST(QiOs, sleep) { qi::os::sleep(1); } TEST(QiOS, msleep) { qi::os::msleep(1000); } TEST(QiOs, env) { int ret = qi::os::setenv("TITI", "TUTU"); ASSERT_FALSE(ret); EXPECT_EQ("TUTU", qi::os::getenv("TITI")); } TEST(QiOs, getpid) { ASSERT_EQ(getpid(), qi::os::getpid()); } TEST(QiOs, tmp) { std::string temp = qi::os::tmp(); ASSERT_NE(temp, std::string("")); EXPECT_TRUE(boost::filesystem::exists(temp)); EXPECT_TRUE(boost::filesystem::is_directory(temp)); } //check if the folder exists and is writable void test_writable_and_empty(std::string fdir) { std::string tempfile; boost::filesystem::path p(fdir, qi::unicodeFacet()); boost::filesystem::path pp(fdir, qi::unicodeFacet()); EXPECT_TRUE(boost::filesystem::exists(fdir)); EXPECT_TRUE(boost::filesystem::is_directory(fdir)); pp.append("tmpfile", qi::unicodeFacet()); tempfile = pp.string(qi::unicodeFacet()); FILE *f = qi::os::fopen(tempfile.c_str(), "w+"); EXPECT_TRUE((void *)f); fclose(f); EXPECT_TRUE(boost::filesystem::exists(tempfile)); EXPECT_TRUE(boost::filesystem::is_regular_file(tempfile)); boost::filesystem::directory_iterator it(p); EXPECT_EQ(pp, it->path()); it++; EXPECT_EQ(boost::filesystem::directory_iterator(), it); } void clean_dir(std::string fdir) { if(boost::filesystem::exists(fdir)) { //fail is dir is not removable => dir should be removable boost::filesystem::remove_all(fdir); } } TEST(QiOs, tmpdir_noprefix) { std::string temp = qi::os::mktmpdir(); test_writable_and_empty(temp); clean_dir(temp); } TEST(QiOs, tmpdir_tmpdir) { std::string temp1 = qi::os::mktmpdir(); std::string temp2 = qi::os::mktmpdir(); EXPECT_NE(temp1, temp2); clean_dir(temp1); clean_dir(temp2); } TEST(QiOs, tmpdir_parent) { std::string temp = qi::os::mktmpdir("plaf"); boost::filesystem::path ppa(temp, qi::unicodeFacet()); ppa = ppa.parent_path(); boost::filesystem::path ppatmp(qi::os::tmp(), qi::unicodeFacet()); EXPECT_TRUE(boost::filesystem::equivalent(ppa, ppatmp)); clean_dir(temp); } TEST(QiOs, tmpdir_prefix) { std::string temp = qi::os::mktmpdir("plaf"); test_writable_and_empty(temp); boost::filesystem::path pp(temp, qi::unicodeFacet()); std::string tempfname = pp.filename().string(qi::unicodeFacet()); EXPECT_EQ(tempfname[0], 'p'); EXPECT_EQ(tempfname[1], 'l'); EXPECT_EQ(tempfname[2], 'a'); EXPECT_EQ(tempfname[3], 'f'); clean_dir(temp); } TEST(QiOs, tmpdir_prefix_accentuated) { char utf8[] = { 0xC5, 0xAA, 0x6E, 0xC4, 0xAD, 0x63, 0xC5, 0x8D, 0x64, 0x65, 0xCC, 0xBD, 0 }; std::string temp = qi::os::mktmpdir(utf8); test_writable_and_empty(temp); clean_dir(temp); } TEST(QiOs, tmpdir_prefix_zero) { std::string temp = qi::os::mktmpdir(0); test_writable_and_empty(temp); clean_dir(temp); }
/* * Copyright (c) 2012 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #ifdef WIN32 # include <process.h> // for getpid #else # include <unistd.h> // for getpid #endif #include <cstdio> #include <gtest/gtest.h> #include <boost/filesystem.hpp> #include <qi/path.hpp> #include <qi/os.hpp> #include <qi/qi.hpp> class QiOSTests: public ::testing::Test { public: QiOSTests() : a_newPath() { } protected: void SetUp() { a_newPath = qi::os::mktmpdir("QiOsTest"); a_newPath.append(a_accent, qi::unicodeFacet()); FILE* fileHandle = qi::os::fopen(a_newPath.string(qi::unicodeFacet()).c_str(), "w"); fclose(fileHandle); // QString pouet = QDir::tempPath() + "/" + QString::fromUtf8(a_accent); // FILE* fileHandle = qi::os::fopen(pouet.toUtf8().data(), "w"); // fclose(fileHandle); } void TearDown() { if(boost::filesystem::exists(a_newPath)) { try { boost::filesystem::remove_all(a_newPath.parent_path()); } catch (std::exception &) { } } } public: boost::filesystem::path a_newPath; static const char a_accent[4]; }; // "é" in utf-8 w. french locale. const char QiOSTests::a_accent[4] = { '/', 0xc3, 0xa9, '\0' } ; TEST_F(QiOSTests, LowLevelAccent) { // Try to retrieve the file. // The name must be in utf-8 to be retrieved on unix. ASSERT_TRUE(boost::filesystem::exists(a_newPath)) << a_newPath.string() << std::endl; } // TODO: us qi::time when it's available :) TEST(QiOs, sleep) { qi::os::sleep(1); } TEST(QiOS, msleep) { qi::os::msleep(1000); } TEST(QiOs, env) { int ret = qi::os::setenv("TITI", "TUTU"); ASSERT_FALSE(ret); EXPECT_EQ("TUTU", qi::os::getenv("TITI")); } TEST(QiOs, getpid) { ASSERT_EQ(getpid(), qi::os::getpid()); } TEST(QiOs, tmp) { std::string temp = qi::os::tmp(); ASSERT_NE(temp, std::string("")); EXPECT_TRUE(boost::filesystem::exists(temp)); EXPECT_TRUE(boost::filesystem::is_directory(temp)); } //check if the folder exists and is writable void test_writable_and_empty(std::string fdir) { std::string tempfile; boost::filesystem::path p(fdir, qi::unicodeFacet()); boost::filesystem::path pp(fdir, qi::unicodeFacet()); EXPECT_TRUE(boost::filesystem::exists(p)); EXPECT_TRUE(boost::filesystem::is_directory(p)); pp.append("tmpfile", qi::unicodeFacet()); tempfile = pp.string(qi::unicodeFacet()); FILE *f = qi::os::fopen(tempfile.c_str(), "w+"); EXPECT_TRUE((void *)f); fclose(f); EXPECT_TRUE(boost::filesystem::exists(pp)); EXPECT_TRUE(boost::filesystem::is_regular_file(pp)); boost::filesystem::directory_iterator it(p); EXPECT_EQ(pp, it->path()); it++; EXPECT_EQ(boost::filesystem::directory_iterator(), it); } void clean_dir(std::string fdir) { if(boost::filesystem::exists(fdir)) { //fail is dir is not removable => dir should be removable boost::filesystem::remove_all(fdir); } } TEST(QiOs, tmpdir_noprefix) { std::string temp = qi::os::mktmpdir(); test_writable_and_empty(temp); clean_dir(temp); } TEST(QiOs, tmpdir_tmpdir) { std::string temp1 = qi::os::mktmpdir(); std::string temp2 = qi::os::mktmpdir(); EXPECT_NE(temp1, temp2); clean_dir(temp1); clean_dir(temp2); } TEST(QiOs, tmpdir_parent) { std::string temp = qi::os::mktmpdir("plaf"); boost::filesystem::path ppa(temp, qi::unicodeFacet()); ppa = ppa.parent_path(); boost::filesystem::path ppatmp(qi::os::tmp(), qi::unicodeFacet()); EXPECT_TRUE(boost::filesystem::equivalent(ppa, ppatmp)); clean_dir(temp); } TEST(QiOs, tmpdir_prefix) { std::string temp = qi::os::mktmpdir("plaf"); test_writable_and_empty(temp); boost::filesystem::path pp(temp, qi::unicodeFacet()); std::string tempfname = pp.filename().string(qi::unicodeFacet()); EXPECT_EQ(tempfname[0], 'p'); EXPECT_EQ(tempfname[1], 'l'); EXPECT_EQ(tempfname[2], 'a'); EXPECT_EQ(tempfname[3], 'f'); clean_dir(temp); } TEST(QiOs, tmpdir_prefix_accentuated) { char utf8[] = { 0xC5, 0xAA, 0x6E, 0xC4, 0xAD, 0x63, 0xC5, 0x8D, 0x64, 0x65, 0xCC, 0xBD, 0 }; std::string temp = qi::os::mktmpdir(utf8); test_writable_and_empty(temp); clean_dir(temp); } TEST(QiOs, tmpdir_prefix_zero) { std::string temp = qi::os::mktmpdir(0); test_writable_and_empty(temp); clean_dir(temp); }
use locale correct paths
test_qios: use locale correct paths
C++
bsd-3-clause
bsautron/libqi,aldebaran/libqi,vbarbaresi/libqi,aldebaran/libqi,aldebaran/libqi
a6472e5bf26d1b0e445fc95fc4b3293cc740fe02
tests/lexerTest.cpp
tests/lexerTest.cpp
#include <gtest/gtest.h> #include <vector> #include "utils/util.hpp" #include "lexer.hpp" #include "token.hpp" class LexerTest: public ::testing::Test { protected: Lexer lx = Lexer(); const std::vector<Token>& getTokens(std::string code) { return lx.tokenize(code, "<lexer-test>").getTokens(); } }; TEST_F(LexerTest, CommentsSingleLine) { ASSERT_EQ(getTokens("// test\n"), std::vector<Token> {Token(FILE_END, "", defaultTrace)}); ASSERT_EQ(getTokens("// asd 123 . ////**//"), std::vector<Token> {Token(FILE_END, "", defaultTrace)}); ASSERT_EQ(lx.getLineCount(), 1); } TEST_F(LexerTest, CommentsMultiLine) { ASSERT_EQ(getTokens("/*asdad\ndasd\nasd*/"), std::vector<Token> {Token(FILE_END, "", defaultTrace)}); ASSERT_EQ(lx.getLineCount(), 3); } TEST_F(LexerTest, IntegerLiterals) { EXPECT_EQ(getTokens("123")[0], Token(L_INTEGER, "123", defaultTrace)); EXPECT_EQ(getTokens("0xA")[0], Token(L_INTEGER, "10", defaultTrace)); EXPECT_EQ(getTokens("0o10")[0], Token(L_INTEGER, "8", defaultTrace)); EXPECT_EQ(getTokens("0b10")[0], Token(L_INTEGER, "2", defaultTrace)); } TEST_F(LexerTest, Radix) { EXPECT_THROW(getTokens("0j123")[0], Error); EXPECT_THROW(getTokens("0123")[0], Error); EXPECT_THROW(getTokens("0x0123")[0], Error); EXPECT_EQ(getTokens("0")[0], Token(L_INTEGER, "0", defaultTrace)); } TEST_F(LexerTest, FloatLiterals) { EXPECT_EQ(getTokens("12.3")[0], Token(L_FLOAT, "12.3", defaultTrace)); EXPECT_THROW(getTokens("12.")[0], Error); EXPECT_THROW(getTokens("12.123.")[0], Error); EXPECT_THROW(getTokens("0x12.123")[0], Error); } TEST_F(LexerTest, BooleanLiterals) { EXPECT_EQ(getTokens("true")[0], Token(L_BOOLEAN, "true", defaultTrace)); EXPECT_EQ(getTokens("false")[0], Token(L_BOOLEAN, "false", defaultTrace)); } TEST_F(LexerTest, StringLiterals) { EXPECT_EQ(getTokens("\"qwerty123\"")[0], Token(L_STRING, "qwerty123", defaultTrace)); EXPECT_THROW(getTokens("\"qwerty123")[0], Error); } TEST_F(LexerTest, EscapeSequences) { EXPECT_THROW(getTokens("\"cool string here\" \\n "), Error); EXPECT_EQ(getTokens("\" \\n \"")[0], Token(L_STRING, " \n ", defaultTrace)); // FIXME // EXPECT_EQ(getTokens("\" \\x0A \"")[0], Token(L_STRING, " \n ", defaultTrace)); // EXPECT_EQ(getTokens("\" \\075 \"")[0], Token(L_STRING, " = ", defaultTrace)); EXPECT_EQ(getTokens("\" \\\\ \"")[0], Token(L_STRING, " \\ ", defaultTrace)); EXPECT_EQ(getTokens("\" \\\" \"")[0], Token(L_STRING, " \" ", defaultTrace)); } TEST_F(LexerTest, Constructs) { EXPECT_EQ(getTokens(";")[0], Token(C_SEMI, ";", defaultTrace)); EXPECT_EQ(getTokens("]")[0], Token(C_SQPAREN_RIGHT, "]", defaultTrace)); } TEST_F(LexerTest, FatArrow) { ASSERT_EQ(getTokens("=>")[0], Token(K_FAT_ARROW, "=>", defaultTrace)); } TEST_F(LexerTest, Operators) { EXPECT_EQ(getTokens("!=")[0], Token(OPERATOR, 1, defaultTrace)); EXPECT_EQ(getTokens("1 + 1")[1], Token(OPERATOR, 31, defaultTrace)); EXPECT_EQ(getTokens("+ 1")[0], Token(OPERATOR, 25, defaultTrace)); EXPECT_EQ(getTokens("++1")[0], Token(OPERATOR, 23, defaultTrace)); EXPECT_EQ(getTokens("1++ + 2")[1], Token(OPERATOR, 20, defaultTrace)); EXPECT_EQ(lx[2], Token(OPERATOR, 31, defaultTrace)); EXPECT_EQ(getTokens("1++ + ++2")[3], Token(OPERATOR, 23, defaultTrace)); EXPECT_EQ(lx[2], Token(OPERATOR, 31, defaultTrace)); } TEST_F(LexerTest, Keywords) { EXPECT_EQ(getTokens("define")[0], Token(K_DEFINE, "define", defaultTrace)); EXPECT_EQ(getTokens("function")[0], Token(K_FUNCTION, "function", defaultTrace)); EXPECT_EQ(getTokens("protected")[0], Token(K_PROTECT, "protected", defaultTrace)); } TEST_F(LexerTest, Expression) { getTokens("(-12 + -3) / 1.5 >> 1"); EXPECT_EQ(lx[0], Token(C_PAREN_LEFT, "(", defaultTrace)); EXPECT_EQ(lx[1], Token(OPERATOR, 24, defaultTrace)); EXPECT_EQ(lx[2], Token(L_INTEGER, "12", defaultTrace)); EXPECT_EQ(lx[5], Token(L_INTEGER, "3", defaultTrace)); EXPECT_EQ(lx[6], Token(C_PAREN_RIGHT, ")", defaultTrace)); EXPECT_EQ(lx[8], Token(L_FLOAT, "1.5", defaultTrace)); EXPECT_EQ(lx[10], Token(L_INTEGER, "1", defaultTrace)); }
#include <gtest/gtest.h> #include <vector> #include "utils/util.hpp" #include "lexer.hpp" #include "token.hpp" class LexerTest: public ::testing::Test { protected: Lexer lx = Lexer(); const std::vector<Token>& getTokens(std::string code) { return lx.tokenize(code, "<lexer-test>").getTokens(); } }; TEST_F(LexerTest, CommentsSingleLine) { ASSERT_EQ(getTokens("// test\n"), std::vector<Token> {Token(FILE_END, "", defaultTrace)}); ASSERT_EQ(getTokens("// asd 123 . ////**//"), std::vector<Token> {Token(FILE_END, "", defaultTrace)}); ASSERT_EQ(lx.getLineCount(), 1); } TEST_F(LexerTest, CommentsMultiLine) { ASSERT_EQ(getTokens("/*asdad\ndasd\nasd*/"), std::vector<Token> {Token(FILE_END, "", defaultTrace)}); ASSERT_EQ(lx.getLineCount(), 3); } TEST_F(LexerTest, IntegerLiterals) { EXPECT_EQ(getTokens("123")[0], Token(L_INTEGER, "123", defaultTrace)); EXPECT_EQ(getTokens("0xA")[0], Token(L_INTEGER, "10", defaultTrace)); EXPECT_EQ(getTokens("0o10")[0], Token(L_INTEGER, "8", defaultTrace)); EXPECT_EQ(getTokens("0b10")[0], Token(L_INTEGER, "2", defaultTrace)); } TEST_F(LexerTest, Radix) { EXPECT_THROW(getTokens("0j123")[0], Error); EXPECT_THROW(getTokens("0123")[0], Error); EXPECT_THROW(getTokens("0x0123")[0], Error); EXPECT_EQ(getTokens("0")[0], Token(L_INTEGER, "0", defaultTrace)); } TEST_F(LexerTest, FloatLiterals) { EXPECT_EQ(getTokens("12.3")[0], Token(L_FLOAT, "12.3", defaultTrace)); EXPECT_THROW(getTokens("12.")[0], Error); EXPECT_THROW(getTokens("12.123.")[0], Error); EXPECT_THROW(getTokens("0x12.123")[0], Error); } TEST_F(LexerTest, BooleanLiterals) { EXPECT_EQ(getTokens("true")[0], Token(L_BOOLEAN, "true", defaultTrace)); EXPECT_EQ(getTokens("false")[0], Token(L_BOOLEAN, "false", defaultTrace)); } TEST_F(LexerTest, StringLiterals) { EXPECT_EQ(getTokens("\"qwerty123\"")[0], Token(L_STRING, "qwerty123", defaultTrace)); EXPECT_THROW(getTokens("\"qwerty123")[0], Error); } TEST_F(LexerTest, EscapeSequences) { EXPECT_THROW(getTokens("\"cool string here\" \\n "), Error); EXPECT_EQ(getTokens("\" \\n \"")[0], Token(L_STRING, " \n ", defaultTrace)); // TODO // EXPECT_EQ(getTokens("\" \\x0A \"")[0], Token(L_STRING, " \n ", defaultTrace)); // EXPECT_EQ(getTokens("\" \\075 \"")[0], Token(L_STRING, " = ", defaultTrace)); EXPECT_EQ(getTokens("\" \\\\ \"")[0], Token(L_STRING, " \\ ", defaultTrace)); EXPECT_EQ(getTokens("\" \\\" \"")[0], Token(L_STRING, " \" ", defaultTrace)); } TEST_F(LexerTest, Constructs) { EXPECT_EQ(getTokens(";")[0], Token(C_SEMI, ";", defaultTrace)); EXPECT_EQ(getTokens("]")[0], Token(C_SQPAREN_RIGHT, "]", defaultTrace)); } TEST_F(LexerTest, FatArrow) { ASSERT_EQ(getTokens("=>")[0], Token(K_FAT_ARROW, "=>", defaultTrace)); } TEST_F(LexerTest, Operators) { EXPECT_EQ(getTokens("!=")[0], Token(OPERATOR, 1, defaultTrace)); EXPECT_EQ(getTokens("1 + 1")[1], Token(OPERATOR, 31, defaultTrace)); EXPECT_EQ(getTokens("+ 1")[0], Token(OPERATOR, 25, defaultTrace)); EXPECT_EQ(getTokens("++1")[0], Token(OPERATOR, 23, defaultTrace)); EXPECT_EQ(getTokens("1++ + 2")[1], Token(OPERATOR, 20, defaultTrace)); EXPECT_EQ(lx[2], Token(OPERATOR, 31, defaultTrace)); EXPECT_EQ(getTokens("1++ + ++2")[3], Token(OPERATOR, 23, defaultTrace)); EXPECT_EQ(lx[2], Token(OPERATOR, 31, defaultTrace)); } TEST_F(LexerTest, Keywords) { EXPECT_EQ(getTokens("define")[0], Token(K_DEFINE, "define", defaultTrace)); EXPECT_EQ(getTokens("function")[0], Token(K_FUNCTION, "function", defaultTrace)); EXPECT_EQ(getTokens("protected")[0], Token(K_PROTECT, "protected", defaultTrace)); } TEST_F(LexerTest, Expression) { getTokens("(-12 + -3) / 1.5 >> 1"); EXPECT_EQ(lx[0], Token(C_PAREN_LEFT, "(", defaultTrace)); EXPECT_EQ(lx[1], Token(OPERATOR, 24, defaultTrace)); EXPECT_EQ(lx[2], Token(L_INTEGER, "12", defaultTrace)); EXPECT_EQ(lx[5], Token(L_INTEGER, "3", defaultTrace)); EXPECT_EQ(lx[6], Token(C_PAREN_RIGHT, ")", defaultTrace)); EXPECT_EQ(lx[8], Token(L_FLOAT, "1.5", defaultTrace)); EXPECT_EQ(lx[10], Token(L_INTEGER, "1", defaultTrace)); }
Change fixme to todo
Change fixme to todo
C++
mit
slak44/Xylene,slak44/test-lang
a629af4d1e28d1be9d0715dc463eb76e6fcbe144
extensions/CuteHMI.2/include/cutehmi/CuteHMI.hpp
extensions/CuteHMI.2/include/cutehmi/CuteHMI.hpp
#ifndef H_MODULES_CUTEHMI__1_INCLUDE_CUTEHMI_CUTEHMI_HPP #define H_MODULES_CUTEHMI__1_INCLUDE_CUTEHMI_CUTEHMI_HPP #include "internal/common.hpp" #include "PopupBridge.hpp" #include "NotificationManager.hpp" #include <QObject> namespace cutehmi { /** * %CuteHMI singleton. This is a cornerstone object, which acts as a bridge * between various parts of the framework. It exposes essential properties to * frontend applications, plugins and QML components. * * To retrieve singleton use Instance() function. Frontend applications (tools) * may need to call Destroy() function to satisfy destruction order * requirements. */ class CUTEHMI_API CuteHMI: public QObject { Q_OBJECT public: Q_PROPERTY(PopupBridge * popupBridge READ popupBridge CONSTANT) ///< %Popup bridge. This property is never @p nullptr, unless CuteHMI singleton is destroyed. Q_PROPERTY(NotificationManager * notificationManager READ notificationManager CONSTANT) ///< %Notification manager. This property is never @p nullptr, unless CuteHMI singleton is destroyed. /** * Get instance. Gets a reference to the instance of the singleton class. * Calling this function for the first time will also result in registering * some types with qRegisterMetaType() function. Types that are registered: * - cutehmi::ErrorInfo * - cutehmi::Prompt::Button * - const cutehmi::ProjectNode * * . * * @return a reference to the instance of the singleton class. * * @warning Typically Destroy() function should be used to satisfy the requirement * that QApplication has to be first created and last destroyed QObject. * * @warning if Destroy() function is not used, then destructor will be * called on static de-initialization. Beware of using singleton instance in * destructor of some other static object. If that's unavoidable, assure that * singletons or any static objects are constructed in the reverse order they are * going to be destructed. * * @internal utils::Singleton is not being used to prevent inlining of template * function and incorporating static instance into other translation units. */ static CuteHMI & Instance(); /** * Destroy instance. This function is provided to satisfy the requirement that * QApplication has to be first created and last destroyed QObject. * Once this function is called singleton becomes unusable. * * @note Only frontend applications, which instantiate QApplication should take care about * this function. */ static void Destroy(); /** * Get popup bridge. * @return popup bridge. */ PopupBridge * popupBridge() const; /** * Get notification manager. * @return notification manager. */ NotificationManager * notificationManager() const; protected: /** * Default constructor. */ CuteHMI(); /** * Get instance pointer. * @return instance pointer. * * @note This is provided as a workaround (id="cutehmi_1-2"). */ static std::unique_ptr<CuteHMI> & InstancePtr(); private: struct Members { std::unique_ptr<PopupBridge> popupBridge; std::unique_ptr<NotificationManager> notificationManager; }; MPtr<Members> m; }; } #endif //(c)MP: Copyright © 2018, Michal Policht. All rights reserved. //(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef H_MODULES_CUTEHMI__1_INCLUDE_CUTEHMI_CUTEHMI_HPP #define H_MODULES_CUTEHMI__1_INCLUDE_CUTEHMI_CUTEHMI_HPP #include "internal/common.hpp" #include "PopupBridge.hpp" #include "NotificationManager.hpp" #include <QObject> namespace cutehmi { /** * %CuteHMI singleton. This is a cornerstone object, which acts as a bridge * between various parts of the framework. It exposes essential properties to * frontend applications, plugins and QML components. * * To retrieve singleton use Instance() function. Frontend applications (tools) * may need to call Destroy() function to satisfy destruction order * requirements. */ class CUTEHMI_API CuteHMI: public QObject { Q_OBJECT public: Q_PROPERTY(PopupBridge * popupBridge READ popupBridge CONSTANT) ///< %Popup bridge. This property is never @p nullptr, unless CuteHMI singleton is destroyed. Q_PROPERTY(NotificationManager * notificationManager READ notificationManager CONSTANT) ///< %Notification manager. This property is never @p nullptr, unless CuteHMI singleton is destroyed. /** * Get instance. Gets a reference to the instance of the singleton class. * Calling this function for the first time will also result in registering * some types with qRegisterMetaType() function. Types that are registered: * - cutehmi::ErrorInfo * - cutehmi::Prompt::Button * . * * @return a reference to the instance of the singleton class. * * @warning Typically Destroy() function should be used to satisfy the requirement * that QApplication has to be first created and last destroyed QObject. * * @warning if Destroy() function is not used, then destructor will be * called on static de-initialization. Beware of using singleton instance in * destructor of some other static object. If that's unavoidable, assure that * singletons or any static objects are constructed in the reverse order they are * going to be destructed. * * @internal utils::Singleton is not being used to prevent inlining of template * function and incorporating static instance into other translation units. */ static CuteHMI & Instance(); /** * Destroy instance. This function is provided to satisfy the requirement that * QApplication has to be first created and last destroyed QObject. * Once this function is called singleton becomes unusable. * * @note Only frontend applications, which instantiate QApplication should take care about * this function. */ static void Destroy(); /** * Get popup bridge. * @return popup bridge. */ PopupBridge * popupBridge() const; /** * Get notification manager. * @return notification manager. */ NotificationManager * notificationManager() const; protected: /** * Default constructor. */ CuteHMI(); /** * Get instance pointer. * @return instance pointer. * * @note This is provided as a workaround (id="cutehmi_1-2"). */ static std::unique_ptr<CuteHMI> & InstancePtr(); private: struct Members { std::unique_ptr<PopupBridge> popupBridge; std::unique_ptr<NotificationManager> notificationManager; }; MPtr<Members> m; }; } #endif //(c)MP: Copyright © 2018, Michal Policht. All rights reserved. //(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
Update documentation.
Update documentation.
C++
mit
michpolicht/CuteHMI,michpolicht/CuteHMI,michpolicht/CuteHMI,michpolicht/CuteHMI,michpolicht/CuteHMI
84840c2d10dc26b40813389d5937d38246707736
host/cv/main_2.cpp
host/cv/main_2.cpp
/** * OpenCV (OCV) - Video capture on BBB * * GOAL: * This program takes continuous images from the host camera and detect a circular * object of specific color. The color and other configuration are provided as * input argument to the program. * * INPUT: * The program takes two arguments: * - The video device node (0/1) * - The object color (blue/red) * * OUTPUT: * On each frame captured by the program, three files are exported into the * host filesystem (apache directory specifically): * - A colored image with a green circular around the circular object * - A binarized image of the colored image (previous bullet) * - A text file containing information about the object captured * In addition to storing images, at each frame iteration, the program executes a shell script * to communicate information about the frame with the ATMEGA328. * * HOST REQUIREMENTS: * The following packages are required to be installed on the host: * - Apache2 server * - OpenSSH server **/ #include <fstream> #include <iostream> #include <cstring> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <string> #include <vector> #include <math.h> #include <stdlib.h> #include <cstdlib> #include <sstream> #include <stdio.h> #define PI 3.14159265 using namespace cv; using namespace std; // Keep track of video camera frame number long frameNumber = 0; // Assign unique ID for each direction. // The ID must be in sync with the GUI direction values // (Please refer to the documentation for more information about the GUI code) int direction = 0; const int FORWARD = 1; const int REVERSE = 2; const int RIGHT = 3; const int LEFT = 4; const int ROTATE = 5; const int STOP = 6; /** * Get the distance between the object and the camera * Please refer to the documentation report for more information * about the calculations * @return Distance in cm **/ double getDistance(double realDimention, double digitalDimention) { double FOCAL_LENGTH = 339.079; // in pixels int ERROR_MARGIN = 0; //pixels lost due to selection of circular shape return realDimention * FOCAL_LENGTH / (digitalDimention + ERROR_MARGIN); } /** * Detect the edge point of the object. This information allows the * conclusion of the object digial radius * @param imageDest Current video frame * @param def Default point value in case no object was found * @return arbitrary point on the object edge **/ Point edgePoint(Mat imageDest, Point def) { int thresh = 100; // Canny Algorithm for object edge detection Canny(imageDest, imageDest, thresh /*threshold1*/, thresh*2 /*threshold2*/, 3/*apertureSize*/); // Prepare data structure to store the edge points vector<vector<Point> > contours; vector<Vec4i> hierarchy; // Perform the countour finder findContours(imageDest, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); // If no object foud, return the provided default value if(contours.size() == 0) { return def; } // Return a point from the countour return contours[0][0]; } /** * Predefined set of colors that can be detected by the program * The colors supported by the current program are blue and red * @param specs Data strucutre to hold the HSV channel color information * based on the color specified * @param color Color of the object (blue/red) **/ void get_color_specs(vector<vector<int> > &specs, string color){ if (!color.compare("blue")) { specs[0][0] = 100; specs[0][1] = 115; specs[0][2] = 50; specs[1][0] = 130; specs[1][1] = 255; specs[1][2] = 255; } else if (!color.compare("red")) { specs[0][0] = 0; specs[0][1] = 197; specs[0][2] = 109; specs[1][0] = 182; specs[1][1] = 255; specs[1][2] = 255; } else { specs[0][0] = 255; specs[0][1] = 255; specs[0][2] = 255; specs[1][0] = 255; specs[1][1] = 255; specs[1][2] = 255; } } void control(int left, int right) { stringstream ss; ss << "/root/mr_robot/tools/control/write " << left << "," << right << "#" << endl; cout << left << "," << right << "#" << endl; system(ss.str().c_str()); } /** * Drive the car based on the angle and distance * Decisions are mainly taken based on experiments * @param angle Car angel * @param distance Distance of the car from the camera * @param diameter Digital diameter of the circular object * @return Direction code **/ void drive(double angle, double distance, double diameter) { int full_speed = 255; int rotation_speed = 145; int turn_speed = 40; int stopping_distance = 45; int stop_angle = 4; // If no object found: rotate if(diameter == 0 && direction != ROTATE) { cout << endl << "rotating "; control(rotation_speed, -rotation_speed); direction = ROTATE; // If object is within stopping_distance and visible: stop } else if(distance <= stopping_distance && diameter > 0 && direction != STOP) { cout << endl << "stopping "; control(0, 0); direction = STOP; // If object more than stop_angle degrees to right and farther than stopping distance: turn right } else if (angle > stop_angle && distance >= stopping_distance && direction != RIGHT){ cout << endl << "turning right "; control(turn_speed, -turn_speed); direction = RIGHT; // If object more than stop_angle degrees to left and farther than stopping distance: turn left } else if (angle < -stop_angle && distance >= stopping_distance && direction != LEFT) { cout << endl << "turning left "; control (-turn_speed, turn_speed); direction = LEFT; // If ball is past stopping distance and within stop_angles: forward } else if (distance > stopping_distance && angle < stop_angle && angle > -stop_angle && direction != FORWARD) { cout << endl << "going forward "; control(full_speed, full_speed); direction = FORWARD; } } /** * Start the OpenCV program **/ int main( int argc, char** argv ) { // Capture video number is: /dev/video(0/1) int cap_num = atoi(argv[1]); // Color blue/red string color = argv[2]; // Start camera VideoCapture cap; if(!cap.open(cap_num)) return 1; // Configure the camera for fast capture and good resolution cap.set(CV_CAP_PROP_FRAME_WIDTH, 432); cap.set(CV_CAP_PROP_FRAME_HEIGHT,240); cap.set(CV_CAP_PROP_FPS , 30); // Keep taking pictures while(1) { // Store the frame in a matrix Mat imageSrc; cap >> imageSrc; // Fetch the color information vector<vector<int> > color_specs(2, vector<int>(3)); get_color_specs(color_specs, color); // HSV low-high values int lowH = color_specs[0][0]; int highH = color_specs[1][0]; int lowS = color_specs[0][1]; int highS = color_specs[1][1]; int lowV = color_specs[0][2]; int highV = color_specs[1][2]; // Destination image Mat imageDest; // Convert BGR to HSV cvtColor(imageSrc, imageDest, COLOR_BGR2HSV); // Get colors in specified range inRange(imageDest, Scalar(lowH, lowS, lowV), Scalar(highH, highS, highV), imageDest); // Morphological opening erode(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); dilate(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); // Morphological closing dilate(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); erode(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); // Create moment Moments mmts = moments(imageDest); // Calculate center x and y (Centroids) double x_object = mmts.m10 / mmts.m00; double y_object = mmts.m01 / mmts.m00; // Center of image cv::Size size = imageSrc.size(); double x_center = size.width/2.0f; double y_center = size.height/2.0f; // Contour Mat tmpDest = imageDest.clone(); Point point = edgePoint(tmpDest, Point(x_center, y_center)); // Calculate digital diameter in cm double diameter = norm(Point(x_object, y_object)- point)*2; double realDiameter = 6.5; // Calculate the real distance double distance = getDistance(realDiameter, diameter); // Get rotation angle int digitalDiff = x_object - x_center; double realDiff = digitalDiff * (realDiameter / diameter); double rotation_angle = atan(realDiff / distance) * 180 / PI; // If no object found, then diameter is set to zero if(isnan((double)x_object) && isnan((double)y_object)) { diameter = 0.0;; } // Log the calculated information cout << endl; printf("\t%-10s%4.2f\n", "angle:", rotation_angle); printf("\t%-10s%4.2f\n", "distance:", distance); printf("\t%-10s%4.2f\n", "diameter:", diameter); // Draw circle at x and y Mat tmpSource = imageSrc.clone(); circle(tmpSource, Point(x_object,y_object), 3, Scalar(229, 240, 76), 2); circle(tmpSource, Point(x_object,y_object), diameter/2, Scalar(44, 252, 14), 3); // Center circle(tmpSource, Point(x_center,y_center), 2, Scalar(255, 255, 255), 2); // Get direction code drive(rotation_angle, distance, diameter); // Write images and text into the file system/ // Director /var/www/html correspond to the path for // Apache2 server. All files placed in this directory will be // accessible on all users in the network over host IP and port 80 imwrite("/var/www/html/mr_robot/out.jpg", tmpSource); imwrite("/var/www/html/mr_robot/bw.jpg", imageDest); ofstream myfile; myfile.open ("/var/www/html/mr_robot/info.txt"); myfile << "Distance from camera: " << distance << " cm\n"; myfile << "Rotation angle: " << rotation_angle << "\n"; myfile << "Digital diameter: " << diameter << " px\n"; myfile << "Frame number: " << ++frameNumber << "\n"; string dir_message = "Direction: "; switch (direction) { case FORWARD: myfile << dir_message << "Forward" << endl; break; case REVERSE: myfile << dir_message << "Reversing" << endl; break; case RIGHT: myfile << dir_message << "Right" << endl; break; case LEFT: myfile << dir_message << "Left" << endl; break; case ROTATE: myfile << dir_message << "Rotating" << endl; break; case STOP: myfile << dir_message << "Stop" << endl; break; } myfile << "DIR_CODE: " << direction << "\n"; myfile.close(); } return 0; }
/** * OpenCV (OCV) - Video capture on BBB * * GOAL: * This program takes continuous images from the host camera and detect a circular * object of specific color. The color and other configuration are provided as * input argument to the program. * * INPUT: * The program takes two arguments: * - The video device node (0/1) * - The object color (blue/red) * * OUTPUT: * On each frame captured by the program, three files are exported into the * host filesystem (apache directory specifically): * - A colored image with a green circular around the circular object * - A binarized image of the colored image (previous bullet) * - A text file containing information about the object captured * In addition to storing images, at each frame iteration, the program executes a shell script * to communicate information about the frame with the ATMEGA328. * * HOST REQUIREMENTS: * The following packages are required to be installed on the host: * - Apache2 server * - OpenSSH server **/ #include <fstream> #include <iostream> #include <cstring> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <string> #include <vector> #include <math.h> #include <stdlib.h> #include <cstdlib> #include <sstream> #include <stdio.h> #include <ctime> #include <unistd.h> #define PI 3.14159265 using namespace cv; using namespace std; // Keep track of video camera frame number long frameNumber = 0; // Assign unique ID for each direction. // The ID must be in sync with the GUI direction values // (Please refer to the documentation for more information about the GUI code) int direction = 0; clock_t start_time; const int FORWARD = 1; const int REVERSE = 2; const int RIGHT = 3; const int LEFT = 4; const int ROTATE = 5; const int PAUSE = 6; const int STOP = 7; /** * Get the distance between the object and the camera * Please refer to the documentation report for more information * about the calculations * @return Distance in cm **/ double getDistance(double realDimention, double digitalDimention) { double FOCAL_LENGTH = 339.079; // in pixels int ERROR_MARGIN = 0; //pixels lost due to selection of circular shape return realDimention * FOCAL_LENGTH / (digitalDimention + ERROR_MARGIN); } /** * Detect the edge point of the object. This information allows the * conclusion of the object digial radius * @param imageDest Current video frame * @param def Default point value in case no object was found * @return arbitrary point on the object edge **/ Point edgePoint(Mat imageDest, Point def) { int thresh = 100; // Canny Algorithm for object edge detection Canny(imageDest, imageDest, thresh /*threshold1*/, thresh*2 /*threshold2*/, 3/*apertureSize*/); // Prepare data structure to store the edge points vector<vector<Point> > contours; vector<Vec4i> hierarchy; // Perform the countour finder findContours(imageDest, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); // If no object foud, return the provided default value if(contours.size() == 0) { return def; } // Return a point from the countour return contours[0][0]; } /** * Predefined set of colors that can be detected by the program * The colors supported by the current program are blue and red * @param specs Data strucutre to hold the HSV channel color information * based on the color specified * @param color Color of the object (blue/red) **/ void get_color_specs(vector<vector<int> > &specs, string color){ if (!color.compare("blue")) { specs[0][0] = 100; specs[0][1] = 115; specs[0][2] = 50; specs[1][0] = 130; specs[1][1] = 255; specs[1][2] = 255; } else if (!color.compare("red")) { specs[0][0] = 0; specs[0][1] = 197; specs[0][2] = 109; specs[1][0] = 182; specs[1][1] = 255; specs[1][2] = 255; } else { specs[0][0] = 255; specs[0][1] = 255; specs[0][2] = 255; specs[1][0] = 255; specs[1][1] = 255; specs[1][2] = 255; } } void drive(int left, int right) { stringstream ss; ss << "/root/mr_robot/tools/control/write " << left << "," << right << "#" << endl; cout << left << "," << right << "#" << endl; system(ss.str().c_str()); } /** * Drive the car based on the angle and distance * Decisions are mainly taken based on experiments * @param angle Car angel * @param distance Distance of the car from the camera * @param diameter Digital diameter of the circular object * @param loop_count Necessary to keep from writing to Atmega328p faster than it can read messages * @return Direction code **/ void find_ball(double angle, double distance, double diameter, int &loop_count) { int full_speed = 255; int rotation_speed = 140; int turn_speed = 40; int pausing_distance = 45; int target_angle = 4; if (loop_count > 1) { // If no object found: rotate if(diameter == 0 && direction != ROTATE) { cout << endl << "rotating "; drive(rotation_speed, -rotation_speed); direction = ROTATE; loop_count = 0; start_time = clock(); // If object is within pausing_distance and visible: pause } else if(distance <= pausing_distance && diameter > 0 && direction != PAUSE) { cout << endl << "pausing "; drive(0, 0); direction = PAUSE; loop_count = 0; cout << "\n**** BALL FOUND ****\n" << endl; // If object more than target_angle degrees to right and farther than pausing distance: turn right } else if (angle > target_angle && distance >= pausing_distance && direction != RIGHT){ cout << endl << "turning right "; drive(turn_speed, -turn_speed); direction = RIGHT; loop_count = 0; // If object more than target_angle degrees to left and farther than pausing distance: turn left } else if (angle < -target_angle && distance >= pausing_distance && direction != LEFT) { cout << endl << "turning left "; drive(-turn_speed, turn_speed); direction = LEFT; loop_count = 0; // If ball is past pausing distance and within target_angle: forward } else if (distance > pausing_distance && angle < target_angle && angle > -target_angle && direction != FORWARD) { cout << endl << "going forward "; drive(full_speed, full_speed); direction = FORWARD; loop_count = 0; // If ball rotates ~360 degrees and doesn't see ball: stop } else if (direction == ROTATE) { clock_t rotation_duration = (clock() - start_time) / (double)(CLOCKS_PER_SEC); cout << "\trot time: " << rotation_duration << " s" << endl; if (rotation_duration > 12) { drive(0, 0); cout << "\n**** BALL NOT FOUND ****\n" << endl; direction = STOP; } } } loop_count++; } /** * Start the OpenCV program **/ int main( int argc, char** argv ) { // Capture video number is: /dev/video(0/1) int cap_num = atoi(argv[1]); // Color blue/red string color = argv[2]; // Start camera VideoCapture cap; if(!cap.open(cap_num)) return 1; // Configure the camera for fast capture and good resolution cap.set(CV_CAP_PROP_FRAME_WIDTH, 432); cap.set(CV_CAP_PROP_FRAME_HEIGHT,240); cap.set(CV_CAP_PROP_FPS , 30); // loop_count is used to make sure that the find_ball function has looped at least twice // before sending a message to the Atmega328p. This was created in response to a bug found // when writing too fast to the Atmega328p. The direction variable would be modified however // the write message wouldn't be interpreted. This causes the car to get stuck in a // certain direction. Initialized to 2 so that the car begins moving immediately int loop_count = 2; // Keep taking pictures while(1) { // Store the frame in a matrix Mat imageSrc; cap >> imageSrc; // Fetch the color information vector<vector<int> > color_specs(2, vector<int>(3)); get_color_specs(color_specs, color); // HSV low-high values int lowH = color_specs[0][0]; int highH = color_specs[1][0]; int lowS = color_specs[0][1]; int highS = color_specs[1][1]; int lowV = color_specs[0][2]; int highV = color_specs[1][2]; // Destination image Mat imageDest; // Convert BGR to HSV cvtColor(imageSrc, imageDest, COLOR_BGR2HSV); // Get colors in specified range inRange(imageDest, Scalar(lowH, lowS, lowV), Scalar(highH, highS, highV), imageDest); // Morphological opening erode(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); dilate(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); // Morphological closing dilate(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); erode(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); // Create moment Moments mmts = moments(imageDest); // Calculate center x and y (Centroids) double x_object = mmts.m10 / mmts.m00; double y_object = mmts.m01 / mmts.m00; // Center of image cv::Size size = imageSrc.size(); double x_center = size.width/2.0f; double y_center = size.height/2.0f; // Contour Mat tmpDest = imageDest.clone(); Point point = edgePoint(tmpDest, Point(x_center, y_center)); // Calculate digital diameter in cm double diameter = norm(Point(x_object, y_object)- point)*2; double realDiameter = 6.5; // Calculate the real distance double distance = getDistance(realDiameter, diameter); // Get rotation angle int digitalDiff = x_object - x_center; double realDiff = digitalDiff * (realDiameter / diameter); double rotation_angle = atan(realDiff / distance) * 180 / PI; // If no object found, then diameter is set to zero if(isnan((double)x_object) && isnan((double)y_object)) { diameter = 0.0;; } // Log the calculated information cout << endl; printf("\t%-10s%4.2f\n", "angle:", rotation_angle); printf("\t%-10s%4.2f\n", "distance:", distance); printf("\t%-10s%4.2f\n", "diameter:", diameter); // Draw circle at x and y Mat tmpSource = imageSrc.clone(); circle(tmpSource, Point(x_object,y_object), 3, Scalar(229, 240, 76), 2); circle(tmpSource, Point(x_object,y_object), diameter/2, Scalar(44, 252, 14), 3); // Center circle(tmpSource, Point(x_center,y_center), 2, Scalar(255, 255, 255), 2); // Logic to navigate to ball find_ball(rotation_angle, distance, diameter, loop_count); // Write images and text into the file system/ // Director /var/www/html correspond to the path for // Apache2 server. All files placed in this directory will be // accessible on all users in the network over host IP and port 80 imwrite("/var/www/html/mr_robot/out.jpg", tmpSource); imwrite("/var/www/html/mr_robot/bw.jpg", imageDest); ofstream myfile; myfile.open ("/var/www/html/mr_robot/info.txt"); myfile << "Distance from camera: " << distance << " cm\n"; myfile << "Rotation angle: " << rotation_angle << "\n"; myfile << "Digital diameter: " << diameter << " px\n"; myfile << "Frame number: " << ++frameNumber << "\n"; string dir_message = "Direction: "; switch (direction) { case FORWARD: myfile << dir_message << "Forward" << endl; break; case REVERSE: myfile << dir_message << "Reversing" << endl; break; case RIGHT: myfile << dir_message << "Right" << endl; break; case LEFT: myfile << dir_message << "Left" << endl; break; case ROTATE: myfile << dir_message << "Rotating" << endl; break; case PAUSE: myfile << dir_message << "Pause" << endl; break; case STOP: myfile << dir_message << "Stop" << endl; break; } myfile << "DIR_CODE: " << direction << "\n"; myfile.close(); if (direction == STOP) { return 0; } } return 0; }
Make car stop if he rotates 360 degrees and doesn't find ball
Make car stop if he rotates 360 degrees and doesn't find ball
C++
mit
EliHar/mr_robot,EliHar/mr_robot,EliHar/mr_robot,EliHar/mr_robot,EliHar/mr_robot,EliHar/mr_robot,EliHar/mr_robot
2d4b789c09a1b20f652c2ff13ab60501cb9d0f09
modules/control/controller/controller_agent.cc
modules/control/controller/controller_agent.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/control/controller/controller_agent.h" #include <utility> #include "modules/common/log.h" #include "modules/common/time/time.h" #include "modules/control/common/control_gflags.h" #include "modules/control/controller/lat_controller.h" #include "modules/control/controller/lon_controller.h" #include "modules/control/controller/mpc_controller.h" namespace apollo { namespace control { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::time::Clock; void ControllerAgent::RegisterControllers(const ControlConf *control_conf) { AINFO << "Only support MPC controller or Lat + Lon controllers as of now"; if (control_conf->active_controllers().size() == 1 && control_conf->active_controllers(0) == ControlConf::MPC_CONTROLLER) { controller_factory_.Register( ControlConf::MPC_CONTROLLER, []() -> Controller * { return new MPCController(); }); } else { controller_factory_.Register( ControlConf::LAT_CONTROLLER, []() -> Controller * { return new LatController(); }); controller_factory_.Register( ControlConf::LON_CONTROLLER, []() -> Controller * { return new LonController(); }); } } Status ControllerAgent::InitializeConf(const ControlConf *control_conf) { if (!control_conf) { AERROR << "control_conf is null"; return Status(ErrorCode::CONTROL_INIT_ERROR, "Failed to load config"); } control_conf_ = control_conf; for (auto controller_type : control_conf_->active_controllers()) { auto controller = controller_factory_.CreateObject( static_cast<ControlConf::ControllerType>(controller_type)); if (controller) { controller_list_.emplace_back(std::move(controller)); } else { AERROR << "Controller: " << controller_type << "is not supported"; return Status(ErrorCode::CONTROL_INIT_ERROR, "Invalid controller type:" + controller_type); } } return Status::OK(); } Status ControllerAgent::Init(const ControlConf *control_conf) { RegisterControllers(control_conf); CHECK(InitializeConf(control_conf).ok()) << "Fail to initialize config."; for (auto &controller : controller_list_) { if (controller == NULL || !controller->Init(control_conf_).ok()) { if (controller != NULL) { AERROR << "Controller <" << controller->Name() << "> init failed!"; return Status(ErrorCode::CONTROL_INIT_ERROR, "Failed to init Controller:" + controller->Name()); } else { return Status(ErrorCode::CONTROL_INIT_ERROR, "Failed to init Controller"); } } AINFO << "Controller <" << controller->Name() << "> init done!"; } return Status::OK(); } Status ControllerAgent::ComputeControlCommand( const localization::LocalizationEstimate *localization, const canbus::Chassis *chassis, const planning::ADCTrajectory *trajectory, control::ControlCommand *cmd) { for (auto &controller : controller_list_) { ADEBUG << "controller:" << controller->Name() << " processing ..."; double start_timestamp = Clock::NowInSeconds(); controller->ComputeControlCommand(localization, chassis, trajectory, cmd); double end_timestamp = Clock::NowInSeconds(); const double time_diff_ms = (end_timestamp - start_timestamp) * 1000; ADEBUG << "controller: " << controller->Name() << " calculation time is: " << time_diff_ms << " ms."; cmd->mutable_latency_stats()->add_controller_time_ms(time_diff_ms); } return Status::OK(); } Status ControllerAgent::Reset() { for (auto &controller : controller_list_) { ADEBUG << "controller:" << controller->Name() << " reset..."; controller->Reset(); } return Status::OK(); } } // namespace control } // namespace apollo
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/control/controller/controller_agent.h" #include <utility> #include "modules/common/log.h" #include "modules/common/time/time.h" #include "modules/control/common/control_gflags.h" #include "modules/control/controller/lat_controller.h" #include "modules/control/controller/lon_controller.h" #include "modules/control/controller/mpc_controller.h" namespace apollo { namespace control { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::time::Clock; void ControllerAgent::RegisterControllers(const ControlConf *control_conf) { AINFO << "Only support MPC controller or Lat + Lon controllers as of now"; for (auto active_controller : control_conf->active_controllers()) { switch (active_controller) { case ControlConf::MPC_CONTROLLER: controller_factory_.Register( ControlConf::MPC_CONTROLLER, []() -> Controller * { return new MPCController(); }); break; case ControlConf::LAT_CONTROLLER: controller_factory_.Register( ControlConf::LAT_CONTROLLER, []() -> Controller * { return new LatController(); }); break; case ControlConf::LON_CONTROLLER: controller_factory_.Register( ControlConf::LON_CONTROLLER, []() -> Controller * { return new LonController(); }); break; default: AERROR << "Unknown active controller type:" << active_controller; } } } Status ControllerAgent::InitializeConf(const ControlConf *control_conf) { if (!control_conf) { AERROR << "control_conf is null"; return Status(ErrorCode::CONTROL_INIT_ERROR, "Failed to load config"); } control_conf_ = control_conf; for (auto controller_type : control_conf_->active_controllers()) { auto controller = controller_factory_.CreateObject( static_cast<ControlConf::ControllerType>(controller_type)); if (controller) { controller_list_.emplace_back(std::move(controller)); } else { AERROR << "Controller: " << controller_type << "is not supported"; return Status(ErrorCode::CONTROL_INIT_ERROR, "Invalid controller type:" + controller_type); } } return Status::OK(); } Status ControllerAgent::Init(const ControlConf *control_conf) { RegisterControllers(control_conf); CHECK(InitializeConf(control_conf).ok()) << "Fail to initialize config."; for (auto &controller : controller_list_) { if (controller == NULL || !controller->Init(control_conf_).ok()) { if (controller != NULL) { AERROR << "Controller <" << controller->Name() << "> init failed!"; return Status(ErrorCode::CONTROL_INIT_ERROR, "Failed to init Controller:" + controller->Name()); } else { return Status(ErrorCode::CONTROL_INIT_ERROR, "Failed to init Controller"); } } AINFO << "Controller <" << controller->Name() << "> init done!"; } return Status::OK(); } Status ControllerAgent::ComputeControlCommand( const localization::LocalizationEstimate *localization, const canbus::Chassis *chassis, const planning::ADCTrajectory *trajectory, control::ControlCommand *cmd) { for (auto &controller : controller_list_) { ADEBUG << "controller:" << controller->Name() << " processing ..."; double start_timestamp = Clock::NowInSeconds(); controller->ComputeControlCommand(localization, chassis, trajectory, cmd); double end_timestamp = Clock::NowInSeconds(); const double time_diff_ms = (end_timestamp - start_timestamp) * 1000; ADEBUG << "controller: " << controller->Name() << " calculation time is: " << time_diff_ms << " ms."; cmd->mutable_latency_stats()->add_controller_time_ms(time_diff_ms); } return Status::OK(); } Status ControllerAgent::Reset() { for (auto &controller : controller_list_) { ADEBUG << "controller:" << controller->Name() << " reset..."; controller->Reset(); } return Status::OK(); } } // namespace control } // namespace apollo
refactor controller creation process.
control: refactor controller creation process.
C++
apache-2.0
startcode/apollo,startcode/apollo,startcode/apollo,startcode/apollo,startcode/apollo,startcode/apollo
f114a9bb4ea1169ce9ad59938403aabca105fdee
tests/skia_test.cpp
tests/skia_test.cpp
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "CrashHandler.h" #include "OverwriteLine.h" #include "Resources.h" #include "SkAtomics.h" #include "SkCommonFlags.h" #include "SkGraphics.h" #include "SkOSFile.h" #include "SkPathOpsDebug.h" #include "SkTArray.h" #include "SkTaskGroup.h" #include "SkTemplates.h" #include "SkTime.h" #include "Test.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrContextFactory.h" #endif using namespace skiatest; using namespace sk_gpu_test; DEFINE_bool2(extendedTest, x, false, "run extended tests for pathOps."); #if DEBUG_COIN DEFINE_bool2(coinTest, c, false, "detect unused coincidence algorithms."); #endif // need to explicitly declare this, or we get some weird infinite loop llist template TestRegistry* TestRegistry::gHead; void (*gVerboseFinalize)() = nullptr; // The threads report back to this object when they are done. class Status { public: explicit Status(int total) : fDone(0), fTestCount(0), fFailCount(0), fTotal(total) {} // Threadsafe. void endTest(const char* testName, bool success, SkMSec elapsed, int testCount) { const int done = 1 + sk_atomic_inc(&fDone); for (int i = 0; i < testCount; ++i) { sk_atomic_inc(&fTestCount); } if (!success) { SkDebugf("\n---- %s FAILED", testName); } SkString prefix(kSkOverwriteLine); SkString time; if (FLAGS_verbose) { prefix.printf("\n"); time.printf("%5dms ", elapsed); } SkDebugf("%s[%3d/%3d] %s%s", prefix.c_str(), done, fTotal, time.c_str(), testName); } void reportFailure() { sk_atomic_inc(&fFailCount); } int32_t testCount() { return fTestCount; } int32_t failCount() { return fFailCount; } private: int32_t fDone; // atomic int32_t fTestCount; // atomic int32_t fFailCount; // atomic const int fTotal; }; class SkTestRunnable { public: SkTestRunnable(const Test& test, Status* status, GrContextFactory* grContextFactory = nullptr) : fTest(test), fStatus(status), fGrContextFactory(grContextFactory) {} void operator()() { struct TestReporter : public skiatest::Reporter { public: TestReporter() : fStats(nullptr), fError(false), fTestCount(0) {} void bumpTestCount() override { ++fTestCount; } bool allowExtendedTest() const override { return FLAGS_extendedTest; } bool verbose() const override { return FLAGS_veryVerbose; } void reportFailed(const skiatest::Failure& failure) override { SkDebugf("\nFAILED: %s", failure.toString().c_str()); fError = true; } void* stats() { return fStats; } void* fStats; bool fError; int fTestCount; } reporter; const Timer timer; fTest.proc(&reporter, fGrContextFactory); SkMSec elapsed = timer.elapsedMsInt(); if (reporter.fError) { fStatus->reportFailure(); } fStatus->endTest(fTest.name, !reporter.fError, elapsed, reporter.fTestCount); } private: Test fTest; Status* fStatus; GrContextFactory* fGrContextFactory; }; static bool should_run(const char* testName, bool isGPUTest) { if (SkCommandLineFlags::ShouldSkip(FLAGS_match, testName)) { return false; } if (!FLAGS_cpu && !isGPUTest) { return false; } if (!FLAGS_gpu && isGPUTest) { return false; } return true; } int test_main(); int test_main() { SetupCrashHandler(); SkAutoGraphics ag; { SkString header("Skia UnitTests:"); if (!FLAGS_match.isEmpty()) { header.appendf(" --match"); for (int index = 0; index < FLAGS_match.count(); ++index) { header.appendf(" %s", FLAGS_match[index]); } } SkString tmpDir = skiatest::GetTmpDir(); if (!tmpDir.isEmpty()) { header.appendf(" --tmpDir %s", tmpDir.c_str()); } SkString resourcePath = GetResourcePath(); if (!resourcePath.isEmpty()) { header.appendf(" --resourcePath %s", resourcePath.c_str()); } #ifdef SK_DEBUG header.append(" SK_DEBUG"); #else header.append(" SK_RELEASE"); #endif if (FLAGS_veryVerbose) { header.appendf("\n"); } SkDebugf("%s", header.c_str()); } // Count tests first. int total = 0; int toRun = 0; for (const TestRegistry* iter = TestRegistry::Head(); iter; iter = iter->next()) { const Test& test = iter->factory(); if (should_run(test.name, test.needsGpu)) { toRun++; } total++; } // Now run them. int skipCount = 0; SkTaskGroup::Enabler enabled(FLAGS_threads); SkTaskGroup cpuTests; SkTArray<const Test*> gpuTests; Status status(toRun); for (const TestRegistry* iter = TestRegistry::Head(); iter; iter = iter->next()) { const Test& test = iter->factory(); if (!should_run(test.name, test.needsGpu)) { ++skipCount; } else if (test.needsGpu) { gpuTests.push_back(&test); } else { cpuTests.add(SkTestRunnable(test, &status)); } } GrContextFactory* grContextFactoryPtr = nullptr; #if SK_SUPPORT_GPU // Give GPU tests a context factory if that makes sense on this machine. GrContextFactory grContextFactory; grContextFactoryPtr = &grContextFactory; #endif // Run GPU tests on this thread. for (int i = 0; i < gpuTests.count(); i++) { SkTestRunnable(*gpuTests[i], &status, grContextFactoryPtr)(); } // Block until threaded tests finish. cpuTests.wait(); if (FLAGS_verbose) { SkDebugf( "\nFinished %d tests, %d failures, %d skipped. " "(%d internal tests)", toRun, status.failCount(), skipCount, status.testCount()); if (gVerboseFinalize) { (*gVerboseFinalize)(); } } SkDebugf("\n"); #if DEBUG_COIN if (FLAGS_coinTest) { SkPathOpsDebug::DumpCoinDict(); } #endif return (status.failCount() == 0) ? 0 : 1; } #if !defined(SK_BUILD_FOR_IOS) int main(int argc, char** argv) { SkCommandLineFlags::Parse(argc, argv); return test_main(); } #endif
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "CrashHandler.h" #include "OverwriteLine.h" #include "Resources.h" #include "SkAtomics.h" #include "SkCommonFlags.h" #include "SkGraphics.h" #include "SkOSFile.h" #include "SkPathOpsDebug.h" #include "SkTArray.h" #include "SkTaskGroup.h" #include "SkTemplates.h" #include "SkTime.h" #include "Test.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrContextFactory.h" #endif using namespace skiatest; using namespace sk_gpu_test; DEFINE_bool2(extendedTest, x, false, "run extended tests for pathOps."); #if DEBUG_COIN DEFINE_bool2(coinTest, c, false, "detect unused coincidence algorithms."); #endif // need to explicitly declare this, or we get some weird infinite loop llist template TestRegistry* TestRegistry::gHead; void (*gVerboseFinalize)() = nullptr; // The threads report back to this object when they are done. class Status { public: explicit Status(int total) : fDone(0), fTestCount(0), fFailCount(0), fTotal(total) {} // Threadsafe. void endTest(const char* testName, bool success, SkMSec elapsed, int testCount) { const int done = 1 + sk_atomic_inc(&fDone); for (int i = 0; i < testCount; ++i) { sk_atomic_inc(&fTestCount); } if (!success) { SkDebugf("\n---- %s FAILED", testName); } SkString prefix(kSkOverwriteLine); SkString time; if (FLAGS_verbose) { prefix.printf("\n"); time.printf("%5dms ", elapsed); } SkDebugf("%s[%3d/%3d] %s%s", prefix.c_str(), done, fTotal, time.c_str(), testName); } void reportFailure() { sk_atomic_inc(&fFailCount); } int32_t testCount() { return fTestCount; } int32_t failCount() { return fFailCount; } private: int32_t fDone; // atomic int32_t fTestCount; // atomic int32_t fFailCount; // atomic const int fTotal; }; class SkTestRunnable { public: SkTestRunnable(const Test& test, Status* status, GrContextFactory* grContextFactory = nullptr) : fTest(test), fStatus(status), fGrContextFactory(grContextFactory) {} void operator()() { struct TestReporter : public skiatest::Reporter { public: TestReporter() : fStats(nullptr), fError(false), fTestCount(0) {} void bumpTestCount() override { ++fTestCount; } bool allowExtendedTest() const override { return FLAGS_extendedTest; } bool verbose() const override { return FLAGS_veryVerbose; } void reportFailed(const skiatest::Failure& failure) override { SkDebugf("\nFAILED: %s", failure.toString().c_str()); fError = true; } void* stats() const override { return fStats; } void* fStats; bool fError; int fTestCount; } reporter; const Timer timer; fTest.proc(&reporter, fGrContextFactory); SkMSec elapsed = timer.elapsedMsInt(); if (reporter.fError) { fStatus->reportFailure(); } fStatus->endTest(fTest.name, !reporter.fError, elapsed, reporter.fTestCount); } private: Test fTest; Status* fStatus; GrContextFactory* fGrContextFactory; }; static bool should_run(const char* testName, bool isGPUTest) { if (SkCommandLineFlags::ShouldSkip(FLAGS_match, testName)) { return false; } if (!FLAGS_cpu && !isGPUTest) { return false; } if (!FLAGS_gpu && isGPUTest) { return false; } return true; } int test_main(); int test_main() { SetupCrashHandler(); SkAutoGraphics ag; { SkString header("Skia UnitTests:"); if (!FLAGS_match.isEmpty()) { header.appendf(" --match"); for (int index = 0; index < FLAGS_match.count(); ++index) { header.appendf(" %s", FLAGS_match[index]); } } SkString tmpDir = skiatest::GetTmpDir(); if (!tmpDir.isEmpty()) { header.appendf(" --tmpDir %s", tmpDir.c_str()); } SkString resourcePath = GetResourcePath(); if (!resourcePath.isEmpty()) { header.appendf(" --resourcePath %s", resourcePath.c_str()); } #ifdef SK_DEBUG header.append(" SK_DEBUG"); #else header.append(" SK_RELEASE"); #endif if (FLAGS_veryVerbose) { header.appendf("\n"); } SkDebugf("%s", header.c_str()); } // Count tests first. int total = 0; int toRun = 0; for (const TestRegistry* iter = TestRegistry::Head(); iter; iter = iter->next()) { const Test& test = iter->factory(); if (should_run(test.name, test.needsGpu)) { toRun++; } total++; } // Now run them. int skipCount = 0; SkTaskGroup::Enabler enabled(FLAGS_threads); SkTaskGroup cpuTests; SkTArray<const Test*> gpuTests; Status status(toRun); for (const TestRegistry* iter = TestRegistry::Head(); iter; iter = iter->next()) { const Test& test = iter->factory(); if (!should_run(test.name, test.needsGpu)) { ++skipCount; } else if (test.needsGpu) { gpuTests.push_back(&test); } else { cpuTests.add(SkTestRunnable(test, &status)); } } GrContextFactory* grContextFactoryPtr = nullptr; #if SK_SUPPORT_GPU // Give GPU tests a context factory if that makes sense on this machine. GrContextFactory grContextFactory; grContextFactoryPtr = &grContextFactory; #endif // Run GPU tests on this thread. for (int i = 0; i < gpuTests.count(); i++) { SkTestRunnable(*gpuTests[i], &status, grContextFactoryPtr)(); } // Block until threaded tests finish. cpuTests.wait(); if (FLAGS_verbose) { SkDebugf( "\nFinished %d tests, %d failures, %d skipped. " "(%d internal tests)", toRun, status.failCount(), skipCount, status.testCount()); if (gVerboseFinalize) { (*gVerboseFinalize)(); } } SkDebugf("\n"); #if DEBUG_COIN if (FLAGS_coinTest) { SkPathOpsDebug::DumpCoinDict(); } #endif return (status.failCount() == 0) ? 0 : 1; } #if !defined(SK_BUILD_FOR_IOS) int main(int argc, char** argv) { SkCommandLineFlags::Parse(argc, argv); return test_main(); } #endif
fix mac all build
fix mac all build [email protected] GOLD_TRYBOT_URL= https://gold.skia.org/search?issue=2394943002 Review-Url: https://codereview.chromium.org/2394943002
C++
bsd-3-clause
google/skia,rubenvb/skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,google/skia,google/skia,google/skia,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,rubenvb/skia,google/skia,HalCanary/skia-hc,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,rubenvb/skia,HalCanary/skia-hc,HalCanary/skia-hc,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,google/skia,HalCanary/skia-hc,google/skia,aosp-mirror/platform_external_skia,rubenvb/skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,Hikari-no-Tenshi/android_external_skia,google/skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,google/skia,rubenvb/skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,HalCanary/skia-hc,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia
4f3704c713f0dfaa2507c8faa5dc0b58e8fdc15f
src/alert.cpp
src/alert.cpp
// // Alert system // #include <algorithm> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/foreach.hpp> #include <map> #include "alert.h" #include "key.h" #include "net.h" #include "sync.h" #include "ui_interface.h" using namespace std; map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; static const char* pszMainKey = "04a60aab3d24106d0076d7e18d01a8233973783ba83bc50c33e6a80eb118cb1f3491acb244c320c4b42106cc88274a39bb6bdd072d27d06a6370984adac1c14b3a"; static const char* pszTestKey = "0405f43221bab8286fa392a8e37dec3b6090f980b468e6d0ff3a3f886df05895dc0c677cf6a6ec4ec35f0bbdfc2ad9ed0a9752803639e239dbfb24116cfb26ffda"; void CUnsignedAlert::SetNull() { nVersion = 1; nRelayUntil = 0; nExpiration = 0; nID = 0; nCancel = 0; setCancel.clear(); nMinVer = 0; nMaxVer = 0; setSubVer.clear(); nPriority = 0; strComment.clear(); strStatusBar.clear(); strReserved.clear(); } std::string CUnsignedAlert::ToString() const { std::string strSetCancel; BOOST_FOREACH(int n, setCancel) strSetCancel += strprintf("%d ", n); std::string strSetSubVer; BOOST_FOREACH(std::string str, setSubVer) strSetSubVer += "\"" + str + "\" "; return strprintf( "CAlert(\n" " nVersion = %d\n" " nRelayUntil = %"PRI64d"\n" " nExpiration = %"PRI64d"\n" " nID = %d\n" " nCancel = %d\n" " setCancel = %s\n" " nMinVer = %d\n" " nMaxVer = %d\n" " setSubVer = %s\n" " nPriority = %d\n" " strComment = \"%s\"\n" " strStatusBar = \"%s\"\n" ")\n", nVersion, nRelayUntil, nExpiration, nID, nCancel, strSetCancel.c_str(), nMinVer, nMaxVer, strSetSubVer.c_str(), nPriority, strComment.c_str(), strStatusBar.c_str()); } void CUnsignedAlert::print() const { printf("%s", ToString().c_str()); } void CAlert::SetNull() { CUnsignedAlert::SetNull(); vchMsg.clear(); vchSig.clear(); } bool CAlert::IsNull() const { return (nExpiration == 0); } uint256 CAlert::GetHash() const { return Hash(this->vchMsg.begin(), this->vchMsg.end()); } bool CAlert::IsInEffect() const { return (GetAdjustedTime() < nExpiration); } bool CAlert::Cancels(const CAlert& alert) const { if (!IsInEffect()) return false; // this was a no-op before 31403 return (alert.nID <= nCancel || setCancel.count(alert.nID)); } bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const { // TODO: rework for client-version-embedded-in-strSubVer ? return (IsInEffect() && nMinVer <= nVersion && nVersion <= nMaxVer && (setSubVer.empty() || setSubVer.count(strSubVerIn))); } bool CAlert::AppliesToMe() const { return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>())); } bool CAlert::RelayTo(CNode* pnode) const { if (!IsInEffect()) return false; // returns true if wasn't already contained in the set if (pnode->setKnown.insert(GetHash()).second) { if (AppliesTo(pnode->nVersion, pnode->strSubVer) || AppliesToMe() || GetAdjustedTime() < nRelayUntil) { pnode->PushMessage("alert", *this); return true; } } return false; } bool CAlert::CheckSignature() const { CPubKey key(ParseHex(fTestNet ? pszTestKey : pszMainKey)); if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert(bool fThread) { if (!CheckSignature()) return false; if (!IsInEffect()) return false; // alert.nID=max is reserved for if the alert key is // compromised. It must have a pre-defined message, // must never expire, must apply to all versions, // and must cancel all previous // alerts or it will be ignored (so an attacker can't // send an "everything is OK, don't panic" version that // cannot be overridden): int maxInt = std::numeric_limits<int>::max(); if (nID == maxInt) { if (!( nExpiration == maxInt && nCancel == (maxInt-1) && nMinVer == 0 && nMaxVer == maxInt && setSubVer.empty() && nPriority == maxInt && strStatusBar == "URGENT: Alert key compromised, upgrade required" )) return false; } { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI and -alertnotify if it applies to me if(AppliesToMe()) { uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); std::string strCmd = GetArg("-alertnotify", ""); if (!strCmd.empty()) { // Alert text should be plain ascii coming from a trusted source, but to // be safe we first strip anything not in safeChars, then add single quotes around // the whole string before passing it to the shell: std::string singleQuote("'"); std::string safeStatus = SanitizeString(strStatusBar); safeStatus = singleQuote+safeStatus+singleQuote; boost::replace_all(strCmd, "%s", safeStatus); if (fThread) boost::thread t(runCommand, strCmd); // thread runs free else runCommand(strCmd); } } } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; }
// // Alert system // #include <algorithm> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/foreach.hpp> #include <map> #include "alert.h" #include "key.h" #include "net.h" #include "sync.h" #include "ui_interface.h" using namespace std; map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; static const char* pszMainKey = "040284710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9"; static const char* pszTestKey = "04322390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a"; void CUnsignedAlert::SetNull() { nVersion = 1; nRelayUntil = 0; nExpiration = 0; nID = 0; nCancel = 0; setCancel.clear(); nMinVer = 0; nMaxVer = 0; setSubVer.clear(); nPriority = 0; strComment.clear(); strStatusBar.clear(); strReserved.clear(); } std::string CUnsignedAlert::ToString() const { std::string strSetCancel; BOOST_FOREACH(int n, setCancel) strSetCancel += strprintf("%d ", n); std::string strSetSubVer; BOOST_FOREACH(std::string str, setSubVer) strSetSubVer += "\"" + str + "\" "; return strprintf( "CAlert(\n" " nVersion = %d\n" " nRelayUntil = %"PRI64d"\n" " nExpiration = %"PRI64d"\n" " nID = %d\n" " nCancel = %d\n" " setCancel = %s\n" " nMinVer = %d\n" " nMaxVer = %d\n" " setSubVer = %s\n" " nPriority = %d\n" " strComment = \"%s\"\n" " strStatusBar = \"%s\"\n" ")\n", nVersion, nRelayUntil, nExpiration, nID, nCancel, strSetCancel.c_str(), nMinVer, nMaxVer, strSetSubVer.c_str(), nPriority, strComment.c_str(), strStatusBar.c_str()); } void CUnsignedAlert::print() const { printf("%s", ToString().c_str()); } void CAlert::SetNull() { CUnsignedAlert::SetNull(); vchMsg.clear(); vchSig.clear(); } bool CAlert::IsNull() const { return (nExpiration == 0); } uint256 CAlert::GetHash() const { return Hash(this->vchMsg.begin(), this->vchMsg.end()); } bool CAlert::IsInEffect() const { return (GetAdjustedTime() < nExpiration); } bool CAlert::Cancels(const CAlert& alert) const { if (!IsInEffect()) return false; // this was a no-op before 31403 return (alert.nID <= nCancel || setCancel.count(alert.nID)); } bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const { // TODO: rework for client-version-embedded-in-strSubVer ? return (IsInEffect() && nMinVer <= nVersion && nVersion <= nMaxVer && (setSubVer.empty() || setSubVer.count(strSubVerIn))); } bool CAlert::AppliesToMe() const { return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>())); } bool CAlert::RelayTo(CNode* pnode) const { if (!IsInEffect()) return false; // returns true if wasn't already contained in the set if (pnode->setKnown.insert(GetHash()).second) { if (AppliesTo(pnode->nVersion, pnode->strSubVer) || AppliesToMe() || GetAdjustedTime() < nRelayUntil) { pnode->PushMessage("alert", *this); return true; } } return false; } bool CAlert::CheckSignature() const { CPubKey key(ParseHex(fTestNet ? pszTestKey : pszMainKey)); if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert(bool fThread) { if (!CheckSignature()) return false; if (!IsInEffect()) return false; // alert.nID=max is reserved for if the alert key is // compromised. It must have a pre-defined message, // must never expire, must apply to all versions, // and must cancel all previous // alerts or it will be ignored (so an attacker can't // send an "everything is OK, don't panic" version that // cannot be overridden): int maxInt = std::numeric_limits<int>::max(); if (nID == maxInt) { if (!( nExpiration == maxInt && nCancel == (maxInt-1) && nMinVer == 0 && nMaxVer == maxInt && setSubVer.empty() && nPriority == maxInt && strStatusBar == "URGENT: Alert key compromised, upgrade required" )) return false; } { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI and -alertnotify if it applies to me if(AppliesToMe()) { uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); std::string strCmd = GetArg("-alertnotify", ""); if (!strCmd.empty()) { // Alert text should be plain ascii coming from a trusted source, but to // be safe we first strip anything not in safeChars, then add single quotes around // the whole string before passing it to the shell: std::string singleQuote("'"); std::string safeStatus = SanitizeString(strStatusBar); safeStatus = singleQuote+safeStatus+singleQuote; boost::replace_all(strCmd, "%s", safeStatus); if (fThread) boost::thread t(runCommand, strCmd); // thread runs free else runCommand(strCmd); } } } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; }
Revert alert keys
Revert alert keys
C++
mit
worldcoinproject/worldcoin-v0.8,coinkeeper/2015-06-22_19-19_worldcoin,WorldcoinGlobal/WorldcoinLegacy,qreatora/worldcoin-v0.8,WorldcoinGlobal/WorldcoinLegacy,worldcoinproject/worldcoin-v0.8,worldcoinproject/worldcoin-v0.8,qreatora/worldcoin-v0.8,coinkeeper/2015-06-22_19-19_worldcoin,WorldcoinGlobal/WorldcoinLegacy,qreatora/worldcoin-v0.8,qreatora/worldcoin-v0.8,WorldcoinGlobal/WorldcoinLegacy,Bluejudy/worldcoin,worldcoinproject/worldcoin-v0.8,Bluejudy/worldcoin,coinkeeper/2015-06-22_19-19_worldcoin,worldcoinproject/worldcoin-v0.8,Bluejudy/worldcoin,Bluejudy/worldcoin,qreatora/worldcoin-v0.8,coinkeeper/2015-06-22_19-19_worldcoin,Bluejudy/worldcoin,coinkeeper/2015-06-22_19-19_worldcoin,WorldcoinGlobal/WorldcoinLegacy
fcb6a6ed3cefe078c918f7b8ec79714a08a34c76
amgcl/io/mm.hpp
amgcl/io/mm.hpp
#ifndef AMGCL_IO_MM_HPP #define AMGCL_IO_MM_HPP /* The MIT License Copyright (c) 2012-2017 Denis Demidov <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file amgcl/io/mm.hpp * \author Denis Demidov <[email protected]> * \brief Readers for Matrix Market sparse matrices and dense vectors. */ #include <vector> #include <string> #include <fstream> #include <sstream> #include <numeric> #include <boost/type_traits.hpp> #include <boost/tuple/tuple.hpp> #include <amgcl/util.hpp> #include <amgcl/backend/interface.hpp> #include <amgcl/value_type/interface.hpp> #include <amgcl/detail/sort_row.hpp> namespace amgcl { namespace io { /// Matrix market reader. class mm_reader { public: /// Open the file by name mm_reader(const std::string &fname) : f(fname.c_str()) { precondition(f, "Failed to open file \"" + fname + "\""); // Read banner. std::string line; precondition(std::getline(f, line), format_error()); std::istringstream is(line); std::string banner, mtx, coord, dtype, storage; precondition( is >> banner >> mtx >> coord >> dtype >> storage, format_error()); precondition(banner == "%%MatrixMarket", format_error("no banner")); precondition(mtx == "matrix", format_error("not a matrix")); if (storage == "general") { _symmetric = false; } else if (storage == "symmetric") { _symmetric = true; } else { precondition(false, "unsupported storage type"); } if (coord == "coordinate") { _sparse = true; } else if (coord == "array") { _sparse = false; } else { precondition(false, format_error("unsupported coordinate type")); } if (dtype == "real") { _complex = false; _integer = false; } else if (dtype == "complex") { _complex = true; _integer = false; } else if (dtype == "integer") { _complex = false; _integer = true; } else { precondition(false, format_error("unsupported data type")); } // Skip comments. std::streampos pos; do { pos = f.tellg(); precondition(std::getline(f, line), format_error("unexpected eof")); } while (line[0] == '%'); // Get back to the first non-comment line. f.seekg(pos); } /// Matrix in the file is symmetric. bool is_symmetric() const { return _symmetric; } /// Matrix in the file is sparse. bool is_sparse() const { return _sparse; } /// Matrix in the file is complex-valued. bool is_complex() const { return _complex; } /// Matrix in the file is integer-valued. bool is_integer() const { return _integer; } /// Read sparse matrix from the file. template <typename Idx, typename Val> boost::tuple<size_t, size_t> operator()( std::vector<Idx> &ptr, std::vector<Idx> &col, std::vector<Val> &val ) { precondition(_sparse, format_error("not a sparse matrix")); precondition(boost::is_complex<Val>::value == _complex, _complex ? "attempt to read complex values into real vector" : "attempt to read real values into complex vector" ); precondition(boost::is_integral<Val>::value == _integer, _integer ? "attempt to read integer values into real vector" : "attempt to read real values into integer vector" ); // Read sizes size_t n, m, nnz; std::string line; std::istringstream is; { precondition(std::getline(f, line), format_error("unexpected eof")); is.clear(); is.str(line); precondition(is >> n >> m >> nnz, format_error()); } std::vector<Idx> _row; _row.reserve(nnz); std::vector<Idx> _col; _col.reserve(nnz); std::vector<Val> _val; _val.reserve(nnz); for(size_t k = 0; k < nnz; ++k) { precondition(std::getline(f, line), format_error("unexpected eof")); is.clear(); is.str(line); Idx i, j; Val v; precondition(is >> i >> j, format_error()); v = read_value<Val>(is); _row.push_back(i-1); _col.push_back(j-1); _val.push_back(v); } precondition(_val.size() == nnz, format_error("inconsistent data")); ptr.resize(n+1); std::fill(ptr.begin(), ptr.end(), 0); for(size_t k = 0; k < nnz; ++k) { Idx i = _row[k]; Idx j = _col[k]; ++ptr[i+1]; if (_symmetric && j != i) ++ptr[j+1]; } std::partial_sum(ptr.begin(), ptr.end(), ptr.begin()); col.resize(ptr.back()); val.resize(ptr.back()); for(size_t k = 0; k < nnz; ++k) { Idx i = _row[k]; Idx j = _col[k]; Val v = _val[k]; Idx head = ptr[i]++; col[head] = j; val[head] = v; if (_symmetric && j != i) { Idx head = ptr[j]++; col[head] = i; val[head] = v; } } std::rotate(ptr.begin(), ptr.end() - 1, ptr.end()); ptr.front() = 0; #pragma omp parallel for for(ptrdiff_t i = 0; i < static_cast<ptrdiff_t>(n); ++i) { Idx beg = ptr[i]; Idx end = ptr[i+1]; amgcl::detail::sort_row(&col[0] + beg, &val[0] + beg, end - beg); } return boost::make_tuple(n, m); } /// Read dense array from the file. template <typename Val> boost::tuple<size_t, size_t> operator()(std::vector<Val> &val) { precondition(!_sparse, format_error("not a dense array")); precondition(boost::is_complex<Val>::value == _complex, _complex ? "attempt to read complex values into real vector" : "attempt to read real values into complex vector" ); precondition(boost::is_integral<Val>::value == _integer, _integer ? "attempt to read integer values into real vector" : "attempt to read real values into integer vector" ); // Read sizes size_t n, m; std::string line; std::istringstream is; { precondition(std::getline(f, line), format_error("unexpected eof")); is.clear(); is.str(line); precondition(is >> n >> m, format_error()); } val.resize(n * m); for(size_t j = 0; j < m; ++j) { for(size_t i = 0; i < n; ++i) { precondition(std::getline(f, line), format_error("unexpected eof")); is.clear(); is.str(line); val[i * m + j] = read_value<Val>(is); } } return boost::make_tuple(n, m); } private: std::ifstream f; bool _sparse; bool _symmetric; bool _complex; bool _integer; std::string format_error(const std::string &msg = "") const { std::string err_string = "MatrixMarket format error"; if (!msg.empty()) err_string += " (" + msg + ")"; return err_string; } template <typename T> typename boost::enable_if<typename boost::is_complex<T>::type, T>::type read_value(std::istream &s) { typename math::scalar_of<T>::type x,y; precondition(s >> x >> y, format_error()); return T(x,y); } template <typename T> typename boost::disable_if<typename boost::is_complex<T>::type, T>::type read_value(std::istream &s) { T x; precondition(s >> x, format_error()); return x; } }; namespace detail { template <typename Val> typename boost::enable_if<typename boost::is_complex<Val>::type, std::ostream&>::type write_value(std::ostream &s, Val v) { return s << std::real(v) << " " << std::imag(v); } template <typename Val> typename boost::disable_if<typename boost::is_complex<Val>::type, std::ostream&>::type write_value(std::ostream &s, Val v) { return s << v; } } // namespace detail /// Write dense array in Matrix Market format. template <typename Val> void mm_write( const std::string &fname, const Val *data, size_t rows, size_t cols = 1 ) { std::ofstream f(fname.c_str()); precondition(f, "Failed to open file \"" + fname + "\" for writing"); // Banner f << "%%MatrixMarket matrix array "; if (boost::is_complex<Val>::value) { f << "complex "; } else if(boost::is_integral<Val>::value) { f << "integer "; } else { f << "real "; } f << "general\n"; // Sizes f << rows << " " << cols << "\n"; // Data for(size_t j = 0; j < cols; ++j) { for(size_t i = 0; i < rows; ++i) { detail::write_value(f, data[i * cols + j]) << "\n"; } } } /// Write sparse matrix in Matrix Market format. template <class Matrix> void mm_write(const std::string &fname, const Matrix &A) { typedef typename backend::value_type<Matrix>::type Val; typedef typename backend::row_iterator<Matrix>::type row_iterator; const size_t rows = backend::rows(A); const size_t cols = backend::cols(A); const size_t nnz = backend::nonzeros(A); std::ofstream f(fname.c_str()); precondition(f, "Failed to open file \"" + fname + "\" for writing"); // Banner f << "%%MatrixMarket matrix coordinate "; if (boost::is_complex<Val>::value) { f << "complex "; } else if(boost::is_integral<Val>::value) { f << "integer "; } else { f << "real "; } f << "general\n"; // Sizes f << rows << " " << cols << " " << nnz << "\n"; // Data for(size_t i = 0; i < rows; ++i) { for(row_iterator a = backend::row_begin(A, i); a; ++a) { f << i << " " << a.col() << " "; detail::write_value(f, a.value()) << "\n"; } } } } // namespace io } // namespace amgcl #endif
#ifndef AMGCL_IO_MM_HPP #define AMGCL_IO_MM_HPP /* The MIT License Copyright (c) 2012-2017 Denis Demidov <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file amgcl/io/mm.hpp * \author Denis Demidov <[email protected]> * \brief Readers for Matrix Market sparse matrices and dense vectors. */ #include <vector> #include <string> #include <fstream> #include <sstream> #include <numeric> #include <boost/type_traits.hpp> #include <boost/tuple/tuple.hpp> #include <amgcl/util.hpp> #include <amgcl/backend/interface.hpp> #include <amgcl/value_type/interface.hpp> #include <amgcl/detail/sort_row.hpp> namespace amgcl { namespace io { /// Matrix market reader. class mm_reader { public: /// Open the file by name mm_reader(const std::string &fname) : f(fname.c_str()) { precondition(f, "Failed to open file \"" + fname + "\""); // Read banner. std::string line; precondition(std::getline(f, line), format_error()); std::istringstream is(line); std::string banner, mtx, coord, dtype, storage; precondition( is >> banner >> mtx >> coord >> dtype >> storage, format_error()); precondition(banner == "%%MatrixMarket", format_error("no banner")); precondition(mtx == "matrix", format_error("not a matrix")); if (storage == "general") { _symmetric = false; } else if (storage == "symmetric") { _symmetric = true; } else { precondition(false, "unsupported storage type"); } if (coord == "coordinate") { _sparse = true; } else if (coord == "array") { _sparse = false; } else { precondition(false, format_error("unsupported coordinate type")); } if (dtype == "real") { _complex = false; _integer = false; } else if (dtype == "complex") { _complex = true; _integer = false; } else if (dtype == "integer") { _complex = false; _integer = true; } else { precondition(false, format_error("unsupported data type")); } // Skip comments. std::streampos pos; do { pos = f.tellg(); precondition(std::getline(f, line), format_error("unexpected eof")); } while (line[0] == '%'); // Get back to the first non-comment line. f.seekg(pos); } /// Matrix in the file is symmetric. bool is_symmetric() const { return _symmetric; } /// Matrix in the file is sparse. bool is_sparse() const { return _sparse; } /// Matrix in the file is complex-valued. bool is_complex() const { return _complex; } /// Matrix in the file is integer-valued. bool is_integer() const { return _integer; } /// Read sparse matrix from the file. template <typename Idx, typename Val> boost::tuple<size_t, size_t> operator()( std::vector<Idx> &ptr, std::vector<Idx> &col, std::vector<Val> &val ) { precondition(_sparse, format_error("not a sparse matrix")); precondition(boost::is_complex<Val>::value == _complex, _complex ? "attempt to read complex values into real vector" : "attempt to read real values into complex vector" ); precondition(boost::is_integral<Val>::value == _integer, _integer ? "attempt to read integer values into real vector" : "attempt to read real values into integer vector" ); // Read sizes size_t n, m, nnz; std::string line; std::istringstream is; { precondition(std::getline(f, line), format_error("unexpected eof")); is.clear(); is.str(line); precondition(is >> n >> m >> nnz, format_error()); } std::vector<Idx> _row; _row.reserve(nnz); std::vector<Idx> _col; _col.reserve(nnz); std::vector<Val> _val; _val.reserve(nnz); for(size_t k = 0; k < nnz; ++k) { precondition(std::getline(f, line), format_error("unexpected eof")); is.clear(); is.str(line); Idx i, j; Val v; precondition(is >> i >> j, format_error()); v = read_value<Val>(is); _row.push_back(i-1); _col.push_back(j-1); _val.push_back(v); } precondition(_val.size() == nnz, format_error("inconsistent data")); ptr.resize(n+1); std::fill(ptr.begin(), ptr.end(), 0); for(size_t k = 0; k < nnz; ++k) { Idx i = _row[k]; Idx j = _col[k]; ++ptr[i+1]; if (_symmetric && j != i) ++ptr[j+1]; } std::partial_sum(ptr.begin(), ptr.end(), ptr.begin()); col.resize(ptr.back()); val.resize(ptr.back()); for(size_t k = 0; k < nnz; ++k) { Idx i = _row[k]; Idx j = _col[k]; Val v = _val[k]; Idx head = ptr[i]++; col[head] = j; val[head] = v; if (_symmetric && j != i) { Idx head = ptr[j]++; col[head] = i; val[head] = v; } } std::rotate(ptr.begin(), ptr.end() - 1, ptr.end()); ptr.front() = 0; #pragma omp parallel for for(ptrdiff_t i = 0; i < static_cast<ptrdiff_t>(n); ++i) { Idx beg = ptr[i]; Idx end = ptr[i+1]; amgcl::detail::sort_row(&col[0] + beg, &val[0] + beg, end - beg); } return boost::make_tuple(n, m); } /// Read dense array from the file. template <typename Val> boost::tuple<size_t, size_t> operator()(std::vector<Val> &val) { precondition(!_sparse, format_error("not a dense array")); precondition(boost::is_complex<Val>::value == _complex, _complex ? "attempt to read complex values into real vector" : "attempt to read real values into complex vector" ); precondition(boost::is_integral<Val>::value == _integer, _integer ? "attempt to read integer values into real vector" : "attempt to read real values into integer vector" ); // Read sizes size_t n, m; std::string line; std::istringstream is; { precondition(std::getline(f, line), format_error("unexpected eof")); is.clear(); is.str(line); precondition(is >> n >> m, format_error()); } val.resize(n * m); for(size_t j = 0; j < m; ++j) { for(size_t i = 0; i < n; ++i) { precondition(std::getline(f, line), format_error("unexpected eof")); is.clear(); is.str(line); val[i * m + j] = read_value<Val>(is); } } return boost::make_tuple(n, m); } private: std::ifstream f; bool _sparse; bool _symmetric; bool _complex; bool _integer; std::string format_error(const std::string &msg = "") const { std::string err_string = "MatrixMarket format error"; if (!msg.empty()) err_string += " (" + msg + ")"; return err_string; } template <typename T> typename boost::enable_if<typename boost::is_complex<T>::type, T>::type read_value(std::istream &s) { typename math::scalar_of<T>::type x,y; precondition(s >> x >> y, format_error()); return T(x,y); } template <typename T> typename boost::disable_if<typename boost::is_complex<T>::type, T>::type read_value(std::istream &s) { T x; precondition(s >> x, format_error()); return x; } }; namespace detail { template <typename Val> typename boost::enable_if<typename boost::is_complex<Val>::type, std::ostream&>::type write_value(std::ostream &s, Val v) { return s << std::real(v) << " " << std::imag(v); } template <typename Val> typename boost::disable_if<typename boost::is_complex<Val>::type, std::ostream&>::type write_value(std::ostream &s, Val v) { return s << v; } } // namespace detail /// Write dense array in Matrix Market format. template <typename Val> void mm_write( const std::string &fname, const Val *data, size_t rows, size_t cols = 1 ) { std::ofstream f(fname.c_str()); precondition(f, "Failed to open file \"" + fname + "\" for writing"); // Banner f << "%%MatrixMarket matrix array "; if (boost::is_complex<Val>::value) { f << "complex "; } else if(boost::is_integral<Val>::value) { f << "integer "; } else { f << "real "; } f << "general\n"; // Sizes f << rows << " " << cols << "\n"; // Data for(size_t j = 0; j < cols; ++j) { for(size_t i = 0; i < rows; ++i) { detail::write_value(f, data[i * cols + j]) << "\n"; } } } /// Write sparse matrix in Matrix Market format. template <class Matrix> void mm_write(const std::string &fname, const Matrix &A) { typedef typename backend::value_type<Matrix>::type Val; typedef typename backend::row_iterator<Matrix>::type row_iterator; const size_t rows = backend::rows(A); const size_t cols = backend::cols(A); const size_t nnz = backend::nonzeros(A); std::ofstream f(fname.c_str()); precondition(f, "Failed to open file \"" + fname + "\" for writing"); // Banner f << "%%MatrixMarket matrix coordinate "; if (boost::is_complex<Val>::value) { f << "complex "; } else if(boost::is_integral<Val>::value) { f << "integer "; } else { f << "real "; } f << "general\n"; // Sizes f << rows << " " << cols << " " << nnz << "\n"; // Data for(size_t i = 0; i < rows; ++i) { for(row_iterator a = backend::row_begin(A, i); a; ++a) { f << i + 1 << " " << a.col() + 1 << " "; detail::write_value(f, a.value()) << "\n"; } } } } // namespace io } // namespace amgcl #endif
Fix MatrixMarket writer
Fix MatrixMarket writer
C++
mit
ddemidov/amgcl,ddemidov/amgcl,ddemidov/amgcl,ddemidov/amgcl
bf41b184cc8ccd661b97c63754b9a9f57a820fe7
src/scanner.cc
src/scanner.cc
/* This file is part of the Findd project from University of Poitiers (FR). Copyright (C) 2012 Florian Mhun <[email protected]> Sara Ressam <[email protected]> Bastien Nouhant <[email protected]> Jérôme Cornet <[email protected]> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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 "scanner.h" #include <boost/filesystem.hpp> #include <unistd.h> #include <stdio.h> #include <dirent.h> #include <string.h> #include <sys/stat.h> #include <stdlib.h> #include "file.h" #include "global.h" #include "filesystem.h" #include <iostream> namespace findd { Scanner::Scanner () : _total_bytes_scanned(0) {} Scanner::~Scanner () {} void Scanner::scan (const std::string &directory, const bool recursive) { using namespace std; using namespace filesystem; string dir = trim_path(directory); if (is_already_scanned(dir)) return; std::list<string> dirs_to_scan; dirs_to_scan.push_back(directory); do { dir = dirs_to_scan.front(); dirs_to_scan.pop_front(); _scanned_directories.push_back(dir); DIR *dp; struct dirent *entry; struct stat statbuf; if ((dp = opendir(dir.c_str())) == NULL) { string error = "can not open "; error += dir; throw std::logic_error(error); } // Read dir content while((entry = readdir(dp)) != NULL) { string path = dir_concat(dir, string(entry->d_name)); lstat(path.c_str(), &statbuf); if (S_ISDIR(statbuf.st_mode)) { if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0) continue; dirs_to_scan.push_back(path); } else { _files.push_back(File(path, statbuf.st_size)); _total_bytes_scanned += _files.front().size(); } } closedir(dp); } while (dirs_to_scan.size() != 0 && recursive); } void Scanner::reset () const { // TODO : reset the scanned directories and scanned files } const std::vector<std::string> &Scanner::scanned_directories () const { return _scanned_directories; } file_list Scanner::files () const { return _files; } bool Scanner::is_already_scanned (const std::string &dir) { for (size_t i = 0; i < _scanned_directories.size(); i++) { if (_scanned_directories[i] == dir) return true; } return false; } long Scanner::total_bytes_scanned () const { return _total_bytes_scanned; } }
/* This file is part of the Findd project from University of Poitiers (FR). Copyright (C) 2012 Florian Mhun <[email protected]> Sara Ressam <[email protected]> Bastien Nouhant <[email protected]> Jérôme Cornet <[email protected]> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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 "scanner.h" #include <boost/filesystem.hpp> #include <unistd.h> #include <stdio.h> #include <dirent.h> #include <string.h> #include <sys/stat.h> #include <stdlib.h> #include "file.h" #include "global.h" #include "filesystem.h" #include <iostream> namespace findd { Scanner::Scanner () : _total_bytes_scanned(0) {} Scanner::~Scanner () {} void Scanner::scan (const std::string &directory, const bool recursive) { using namespace std; using namespace filesystem; string dir = trim_path(directory); if (is_already_scanned(dir)) return; std::list<string> dirs_to_scan; dirs_to_scan.push_back(directory); do { dir = dirs_to_scan.front(); dirs_to_scan.pop_front(); _scanned_directories.push_back(dir); DIR *dp; struct dirent *entry; struct stat statbuf; if ((dp = opendir(dir.c_str())) == NULL) { string error = "can not open "; error += dir; throw std::logic_error(error); } // Read dir content while((entry = readdir(dp)) != NULL) { string path = dir_concat(dir, string(entry->d_name)); lstat(path.c_str(), &statbuf); if (S_ISDIR(statbuf.st_mode)) { if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0) continue; dirs_to_scan.push_back(path); } else { _files.push_back(File(path, statbuf.st_size)); _total_bytes_scanned += _files.back().size(); } } closedir(dp); } while (dirs_to_scan.size() != 0 && recursive); } void Scanner::reset () const { // TODO : reset the scanned directories and scanned files } const std::vector<std::string> &Scanner::scanned_directories () const { return _scanned_directories; } file_list Scanner::files () const { return _files; } bool Scanner::is_already_scanned (const std::string &dir) { for (size_t i = 0; i < _scanned_directories.size(); i++) { if (_scanned_directories[i] == dir) return true; } return false; } long Scanner::total_bytes_scanned () const { return _total_bytes_scanned; } }
fix : total bytes scanned was incremented with the same file size for each iteration
fix : total bytes scanned was incremented with the same file size for each iteration
C++
bsd-3-clause
floomoon/findd,fmhun/findd,fmhun/findd,fmhun/findd,floomoon/findd,fmhun/findd,floomoon/findd,floomoon/findd
cd5a372cd18fe71cfa8428be59e355d82f34000d
passes/pmgen/test_pmgen.cc
passes/pmgen/test_pmgen.cc
/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN // for peepopt_pm bool did_something; #include "passes/pmgen/test_pmgen_pm.h" #include "passes/pmgen/ice40_dsp_pm.h" #include "passes/pmgen/peepopt_pm.h" void reduce_chain(test_pmgen_pm &pm) { auto &st = pm.st_reduce; auto &ud = pm.ud_reduce; if (ud.longest_chain.empty()) return; log("Found chain of length %d (%s):\n", GetSize(ud.longest_chain), log_id(st.first->type)); SigSpec A; SigSpec Y = ud.longest_chain.front().first->getPort(ID(Y)); auto last_cell = ud.longest_chain.back().first; for (auto it : ud.longest_chain) { auto cell = it.first; if (cell == last_cell) { A.append(cell->getPort(ID(A))); A.append(cell->getPort(ID(B))); } else { A.append(cell->getPort(it.second == ID(A) ? ID(B) : ID(A))); } log(" %s\n", log_id(cell)); pm.autoremove(cell); } Cell *c; if (last_cell->type == ID($_AND_)) c = pm.module->addReduceAnd(NEW_ID, A, Y); else if (last_cell->type == ID($_OR_)) c = pm.module->addReduceOr(NEW_ID, A, Y); else if (last_cell->type == ID($_XOR_)) c = pm.module->addReduceXor(NEW_ID, A, Y); else log_abort(); log(" -> %s (%s)\n", log_id(c), log_id(c->type)); } void reduce_tree(test_pmgen_pm &pm) { auto &st = pm.st_reduce; auto &ud = pm.ud_reduce; if (ud.longest_chain.empty()) return; SigSpec A = ud.leaves; SigSpec Y = st.first->getPort(ID(Y)); pm.autoremove(st.first); log("Found %s tree with %d leaves for %s (%s).\n", log_id(st.first->type), GetSize(A), log_signal(Y), log_id(st.first)); Cell *c; if (st.first->type == ID($_AND_)) c = pm.module->addReduceAnd(NEW_ID, A, Y); else if (st.first->type == ID($_OR_)) c = pm.module->addReduceOr(NEW_ID, A, Y); else if (st.first->type == ID($_XOR_)) c = pm.module->addReduceXor(NEW_ID, A, Y); else log_abort(); log(" -> %s (%s)\n", log_id(c), log_id(c->type)); } #define GENERATE_PATTERN(pmclass, pattern) \ generate_pattern<pmclass>([](pmclass &pm, std::function<void()> f){ return pm.run_ ## pattern(f); }, #pmclass, #pattern, design) void pmtest_addports(Module *module) { pool<SigBit> driven_bits, used_bits; SigMap sigmap(module); int icnt = 0, ocnt = 0; for (auto cell : module->cells()) for (auto conn : cell->connections()) { if (cell->input(conn.first)) for (auto bit : sigmap(conn.second)) used_bits.insert(bit); if (cell->output(conn.first)) for (auto bit : sigmap(conn.second)) driven_bits.insert(bit); } for (auto wire : vector<Wire*>(module->wires())) { SigSpec ibits, obits; for (auto bit : sigmap(wire)) { if (!used_bits.count(bit)) obits.append(bit); if (!driven_bits.count(bit)) ibits.append(bit); } if (!ibits.empty()) { Wire *w = module->addWire(stringf("\\i%d", icnt++), GetSize(ibits)); w->port_input = true; module->connect(ibits, w); } if (!obits.empty()) { Wire *w = module->addWire(stringf("\\o%d", ocnt++), GetSize(obits)); w->port_output = true; module->connect(w, obits); } } module->fixup_ports(); } template <class pm> void generate_pattern(std::function<void(pm&,std::function<void()>)> run, const char *pmclass, const char *pattern, Design *design) { log("Generating \"%s\" patterns for pattern matcher \"%s\".\n", pattern, pmclass); int modcnt = 0; int maxsubcnt = 4; while (modcnt < 100) { int submodcnt = 0, itercnt = 0, cellcnt = 0; Module *mod = design->addModule(NEW_ID); while (modcnt < 100 && submodcnt < maxsubcnt && itercnt++ < 1000) { pm matcher(mod, mod->cells()); matcher.rng(1); matcher.rngseed += modcnt; matcher.rng(1); matcher.rngseed += submodcnt; matcher.rng(1); matcher.rngseed += itercnt; matcher.rng(1); matcher.rngseed += cellcnt; matcher.rng(1); if (GetSize(mod->cells()) != cellcnt) { bool found_match = false; run(matcher, [&](){ found_match = true; }); if (found_match) { Module *m = design->addModule(stringf("\\pmtest_%s_%s_%05d", pmclass, pattern, modcnt++)); mod->cloneInto(m); pmtest_addports(m); submodcnt++; } cellcnt = GetSize(mod->cells()); } matcher.generate_mode = true; run(matcher, [](){}); } design->remove(mod); maxsubcnt *= 2; } } struct TestPmgenPass : public Pass { TestPmgenPass() : Pass("test_pmgen", "test pass for pmgen") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" test_pmgen -reduce_chain [options] [selection]\n"); log("\n"); log("Demo for recursive pmgen patterns. Map chains of AND/OR/XOR to $reduce_*.\n"); log("\n"); log("\n"); log(" test_pmgen -reduce_tree [options] [selection]\n"); log("\n"); log("Demo for recursive pmgen patterns. Map trees of AND/OR/XOR to $reduce_*.\n"); log("\n"); log("\n"); log(" test_pmgen -generate [options] <pattern_name>\n"); log("\n"); log("Create modules that match the specified pattern.\n"); log("\n"); } void execute_reduce_chain(std::vector<std::string> args, RTLIL::Design *design) { log_header(design, "Executing TEST_PMGEN pass (-reduce_chain).\n"); size_t argidx; for (argidx = 2; argidx < args.size(); argidx++) { // if (args[argidx] == "-singleton") { // singleton_mode = true; // continue; // } break; } extra_args(args, argidx, design); for (auto module : design->selected_modules()) while (test_pmgen_pm(module, module->selected_cells()).run_reduce(reduce_chain)) {} } void execute_reduce_tree(std::vector<std::string> args, RTLIL::Design *design) { log_header(design, "Executing TEST_PMGEN pass (-reduce_tree).\n"); size_t argidx; for (argidx = 2; argidx < args.size(); argidx++) { // if (args[argidx] == "-singleton") { // singleton_mode = true; // continue; // } break; } extra_args(args, argidx, design); for (auto module : design->selected_modules()) test_pmgen_pm(module, module->selected_cells()).run_reduce(reduce_tree); } void execute_generate(std::vector<std::string> args, RTLIL::Design *design) { log_header(design, "Executing TEST_PMGEN pass (-generate).\n"); size_t argidx; for (argidx = 2; argidx < args.size(); argidx++) { // if (args[argidx] == "-singleton") { // singleton_mode = true; // continue; // } break; } if (argidx+1 != args.size()) log_cmd_error("Expected exactly one pattern.\n"); string pattern = args[argidx]; if (pattern == "reduce") return GENERATE_PATTERN(test_pmgen_pm, reduce); if (pattern == "ice40_dsp") return GENERATE_PATTERN(ice40_dsp_pm, ice40_dsp); if (pattern == "peepopt-muldiv") return GENERATE_PATTERN(peepopt_pm, muldiv); if (pattern == "peepopt-shiftmul") return GENERATE_PATTERN(peepopt_pm, shiftmul); log_cmd_error("Unkown pattern: %s\n", pattern.c_str()); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { if (GetSize(args) > 1) { if (args[1] == "-reduce_chain") return execute_reduce_chain(args, design); if (args[1] == "-reduce_tree") return execute_reduce_tree(args, design); if (args[1] == "-generate") return execute_generate(args, design); } log_cmd_error("Missing or unsupported mode parameter.\n"); } } TestPmgenPass; PRIVATE_NAMESPACE_END
/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN // for peepopt_pm bool did_something; #include "passes/pmgen/test_pmgen_pm.h" #include "passes/pmgen/ice40_dsp_pm.h" #include "passes/pmgen/peepopt_pm.h" void reduce_chain(test_pmgen_pm &pm) { auto &st = pm.st_reduce; auto &ud = pm.ud_reduce; if (ud.longest_chain.empty()) return; log("Found chain of length %d (%s):\n", GetSize(ud.longest_chain), log_id(st.first->type)); SigSpec A; SigSpec Y = ud.longest_chain.front().first->getPort(ID(Y)); auto last_cell = ud.longest_chain.back().first; for (auto it : ud.longest_chain) { auto cell = it.first; if (cell == last_cell) { A.append(cell->getPort(ID(A))); A.append(cell->getPort(ID(B))); } else { A.append(cell->getPort(it.second == ID(A) ? ID(B) : ID(A))); } log(" %s\n", log_id(cell)); pm.autoremove(cell); } Cell *c; if (last_cell->type == ID($_AND_)) c = pm.module->addReduceAnd(NEW_ID, A, Y); else if (last_cell->type == ID($_OR_)) c = pm.module->addReduceOr(NEW_ID, A, Y); else if (last_cell->type == ID($_XOR_)) c = pm.module->addReduceXor(NEW_ID, A, Y); else log_abort(); log(" -> %s (%s)\n", log_id(c), log_id(c->type)); } void reduce_tree(test_pmgen_pm &pm) { auto &st = pm.st_reduce; auto &ud = pm.ud_reduce; if (ud.longest_chain.empty()) return; SigSpec A = ud.leaves; SigSpec Y = st.first->getPort(ID(Y)); pm.autoremove(st.first); log("Found %s tree with %d leaves for %s (%s).\n", log_id(st.first->type), GetSize(A), log_signal(Y), log_id(st.first)); Cell *c; if (st.first->type == ID($_AND_)) c = pm.module->addReduceAnd(NEW_ID, A, Y); else if (st.first->type == ID($_OR_)) c = pm.module->addReduceOr(NEW_ID, A, Y); else if (st.first->type == ID($_XOR_)) c = pm.module->addReduceXor(NEW_ID, A, Y); else log_abort(); log(" -> %s (%s)\n", log_id(c), log_id(c->type)); } #define GENERATE_PATTERN(pmclass, pattern) \ generate_pattern<pmclass>([](pmclass &pm, std::function<void()> f){ return pm.run_ ## pattern(f); }, #pmclass, #pattern, design) void pmtest_addports(Module *module) { pool<SigBit> driven_bits, used_bits; SigMap sigmap(module); int icnt = 0, ocnt = 0; for (auto cell : module->cells()) for (auto conn : cell->connections()) { if (cell->input(conn.first)) for (auto bit : sigmap(conn.second)) used_bits.insert(bit); if (cell->output(conn.first)) for (auto bit : sigmap(conn.second)) driven_bits.insert(bit); } for (auto wire : vector<Wire*>(module->wires())) { SigSpec ibits, obits; for (auto bit : sigmap(wire)) { if (!used_bits.count(bit)) obits.append(bit); if (!driven_bits.count(bit)) ibits.append(bit); } if (!ibits.empty()) { Wire *w = module->addWire(stringf("\\i%d", icnt++), GetSize(ibits)); w->port_input = true; module->connect(ibits, w); } if (!obits.empty()) { Wire *w = module->addWire(stringf("\\o%d", ocnt++), GetSize(obits)); w->port_output = true; module->connect(w, obits); } } module->fixup_ports(); } template <class pm> void generate_pattern(std::function<void(pm&,std::function<void()>)> run, const char *pmclass, const char *pattern, Design *design) { log("Generating \"%s\" patterns for pattern matcher \"%s\".\n", pattern, pmclass); int modcnt = 0; int maxsubcnt = 4; while (modcnt < 100) { int submodcnt = 0, itercnt = 0, cellcnt = 0; Module *mod = design->addModule(NEW_ID); while (modcnt < 100 && submodcnt < maxsubcnt && itercnt++ < 1000) { pm matcher(mod, mod->cells()); matcher.rng(1); matcher.rngseed += modcnt; matcher.rng(1); matcher.rngseed += submodcnt; matcher.rng(1); matcher.rngseed += itercnt; matcher.rng(1); matcher.rngseed += cellcnt; matcher.rng(1); if (GetSize(mod->cells()) != cellcnt) { bool found_match = false; run(matcher, [&](){ found_match = true; }); if (found_match) { Module *m = design->addModule(stringf("\\pmtest_%s_%s_%05d", pmclass, pattern, modcnt++)); mod->cloneInto(m); pmtest_addports(m); submodcnt++; } cellcnt = GetSize(mod->cells()); } matcher.generate_mode = true; run(matcher, [](){}); } design->remove(mod); maxsubcnt *= 2; } } struct TestPmgenPass : public Pass { TestPmgenPass() : Pass("test_pmgen", "test pass for pmgen") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" test_pmgen -reduce_chain [options] [selection]\n"); log("\n"); log("Demo for recursive pmgen patterns. Map chains of AND/OR/XOR to $reduce_*.\n"); log("\n"); log("\n"); log(" test_pmgen -reduce_tree [options] [selection]\n"); log("\n"); log("Demo for recursive pmgen patterns. Map trees of AND/OR/XOR to $reduce_*.\n"); log("\n"); log("\n"); log(" test_pmgen -generate [options] <pattern_name>\n"); log("\n"); log("Create modules that match the specified pattern.\n"); log("\n"); } void execute_reduce_chain(std::vector<std::string> args, RTLIL::Design *design) { log_header(design, "Executing TEST_PMGEN pass (-reduce_chain).\n"); size_t argidx; for (argidx = 2; argidx < args.size(); argidx++) { // if (args[argidx] == "-singleton") { // singleton_mode = true; // continue; // } break; } extra_args(args, argidx, design); for (auto module : design->selected_modules()) while (test_pmgen_pm(module, module->selected_cells()).run_reduce(reduce_chain)) {} } void execute_reduce_tree(std::vector<std::string> args, RTLIL::Design *design) { log_header(design, "Executing TEST_PMGEN pass (-reduce_tree).\n"); size_t argidx; for (argidx = 2; argidx < args.size(); argidx++) { // if (args[argidx] == "-singleton") { // singleton_mode = true; // continue; // } break; } extra_args(args, argidx, design); for (auto module : design->selected_modules()) test_pmgen_pm(module, module->selected_cells()).run_reduce(reduce_tree); } void execute_generate(std::vector<std::string> args, RTLIL::Design *design) { log_header(design, "Executing TEST_PMGEN pass (-generate).\n"); size_t argidx; for (argidx = 2; argidx < args.size(); argidx++) { // if (args[argidx] == "-singleton") { // singleton_mode = true; // continue; // } break; } if (argidx+1 != args.size()) log_cmd_error("Expected exactly one pattern.\n"); string pattern = args[argidx]; if (pattern == "reduce") return GENERATE_PATTERN(test_pmgen_pm, reduce); if (pattern == "ice40_dsp") return GENERATE_PATTERN(ice40_dsp_pm, ice40_dsp); if (pattern == "peepopt-muldiv") return GENERATE_PATTERN(peepopt_pm, muldiv); if (pattern == "peepopt-shiftmul") return GENERATE_PATTERN(peepopt_pm, shiftmul); log_cmd_error("Unkown pattern: %s\n", pattern.c_str()); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { if (GetSize(args) > 1) { if (args[1] == "-reduce_chain") return execute_reduce_chain(args, design); if (args[1] == "-reduce_tree") return execute_reduce_tree(args, design); if (args[1] == "-generate") return execute_generate(args, design); } help(); log_cmd_error("Missing or unsupported mode parameter.\n"); } } TestPmgenPass; PRIVATE_NAMESPACE_END
Add help() call
Add help() call
C++
isc
antmicro/yosys,cliffordwolf/yosys,antmicro/yosys,cliffordwolf/yosys,cliffordwolf/yosys,SymbiFlow/yosys,cliffordwolf/yosys,YosysHQ/yosys,cliffordwolf/yosys,cliffordwolf/yosys,SymbiFlow/yosys,SymbiFlow/yosys,SymbiFlow/yosys,antmicro/yosys,YosysHQ/yosys,YosysHQ/yosys,YosysHQ/yosys,cliffordwolf/yosys,SymbiFlow/yosys,YosysHQ/yosys,cliffordwolf/yosys,YosysHQ/yosys,antmicro/yosys,SymbiFlow/yosys,YosysHQ/yosys,antmicro/yosys,SymbiFlow/yosys,antmicro/yosys,antmicro/yosys,cliffordwolf/yosys,YosysHQ/yosys,antmicro/yosys,SymbiFlow/yosys