text
stringlengths
54
60.6k
<commit_before>/* * * MIT License * * Copyright (c) 2016-2018 The Cats Project * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #ifndef CATS_CORECAT_UTIL_FUNCTION_HPP #define CATS_CORECAT_UTIL_FUNCTION_HPP #include <functional> #include <tuple> #include <type_traits> #include <utility> #include "Sequence.hpp" namespace Cats { namespace Corecat { inline namespace Util { namespace Impl { template <class T> struct IsReferenceWrapper : std::false_type {}; template <class T> struct IsReferenceWrapper<std::reference_wrapper<T>> : std::true_type {}; #define INVOKE_IMPL_EXPR std::forward<F>(f)(std::forward<Arg>(arg)...) template <typename F, typename... Arg> auto invokeImpl(F&& f, Arg&&... arg) noexcept(noexcept(INVOKE_IMPL_EXPR)) -> decltype(INVOKE_IMPL_EXPR) { return INVOKE_IMPL_EXPR; } #undef INVOKE_IMPL_EXPR #define INVOKE_IMPL_MEMBER_FUNCTION(cond, expr) \ template <typename F, typename C, typename T, typename = typename std::enable_if<std::is_function<F>::value && (cond)>::type, typename... Arg> \ auto invokeImpl(F C::* f, T&& t, Arg&&... arg) noexcept(noexcept(expr)) -> decltype(expr) { return expr; } INVOKE_IMPL_MEMBER_FUNCTION( (std::is_base_of<C, typename std::decay<T>::type>::value), (std::forward<T>(t).*f)(std::forward<Arg>(arg)...)); INVOKE_IMPL_MEMBER_FUNCTION( (IsReferenceWrapper<typename std::decay<T>::type>::value), (t.get().*f)(std::forward<Arg>(arg)...)); INVOKE_IMPL_MEMBER_FUNCTION( (!std::is_base_of<C, typename std::decay<T>::type>::value && !IsReferenceWrapper<typename std::decay<T>::type>::value), ((*std::forward<T>(t)).*f)(std::forward<Arg>(arg)...)); #undef INVOKE_IMPL_MEMBER_FUNCTION #define INVOKE_IMPL_MEMBER_OBJECT(cond, expr) \ template <typename F, typename C, typename T, typename = typename std::enable_if<!std::is_function<F>::value && (cond)>::type> \ auto invokeImpl(F C::* f, T&& t) noexcept(noexcept(expr)) -> decltype(expr) { return expr; } INVOKE_IMPL_MEMBER_OBJECT( (std::is_base_of<C, typename std::decay<T>::type>::value), std::forward<T>(t).*f); INVOKE_IMPL_MEMBER_OBJECT( (IsReferenceWrapper<typename std::decay<T>::type>::value), t.get().*f); INVOKE_IMPL_MEMBER_OBJECT( (!std::is_base_of<C, typename std::decay<T>::type>::value && !IsReferenceWrapper<typename std::decay<T>::type>::value), (*std::forward<T>(t)).*f); #undef INVOKE_IMPL_MEMBER_OBJECT } #define INVOKE_EXPR Impl::invokeImpl(std::forward<F>(f), std::forward<Arg>(arg)...) template <typename F, typename... Arg> auto invoke(F&& f, Arg&&... arg) noexcept(noexcept(INVOKE_EXPR)) -> decltype(INVOKE_EXPR) { return INVOKE_EXPR; } #undef INVOKE_EXPR namespace Impl { template <typename, typename, typename...> struct InvokeResultImpl {}; template <typename F, typename... Arg> struct InvokeResultImpl<decltype(void(invoke(std::declval<F>(), std::declval<Arg>()...))), F, Arg...> { using Type = decltype(invoke(std::declval<F>(), std::declval<Arg>()...)); }; } template <typename F, typename... Arg> using InvokeResult = Impl::InvokeResultImpl<F, Arg...>; namespace Impl { #define APPLY_IMPL_EXPR invoke(std::forward<F>(f), std::get<I>(std::forward<T>(t))...) template <typename F, typename T, std::size_t... I> auto applyImpl(F&& f, T&& t, Sequence<std::size_t, I...>) noexcept(noexcept(APPLY_IMPL_EXPR)) -> decltype(APPLY_IMPL_EXPR) { return APPLY_IMPL_EXPR; } #undef APPLY_IMPL_EXPR } #define APPLY_EXPR \ Impl::applyImpl(std::forward<F>(f), std::forward<T>(t), \ IndexSequence<std::size_t, 0, std::tuple_size<typename std::remove_reference<T>::type>::value>()) template <typename F, typename T> auto apply(F&& f, T&& t) noexcept(noexcept(APPLY_EXPR)) -> decltype(APPLY_EXPR) { return APPLY_EXPR; } #undef APPLY_EXPR } } } #endif <commit_msg>Update Function<commit_after>/* * * MIT License * * Copyright (c) 2016-2018 The Cats Project * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #ifndef CATS_CORECAT_UTIL_FUNCTION_HPP #define CATS_CORECAT_UTIL_FUNCTION_HPP #include <functional> #include <tuple> #include <type_traits> #include <utility> #include "Sequence.hpp" namespace Cats { namespace Corecat { inline namespace Util { namespace Impl { template <class T> struct IsReferenceWrapper : std::false_type {}; template <class T> struct IsReferenceWrapper<std::reference_wrapper<T>> : std::true_type {}; #define INVOKE_IMPL_EXPR std::forward<F>(f)(std::forward<Arg>(arg)...) template <typename F, typename... Arg> constexpr auto invokeImpl(F&& f, Arg&&... arg) noexcept(noexcept(INVOKE_IMPL_EXPR)) -> decltype(INVOKE_IMPL_EXPR) { return INVOKE_IMPL_EXPR; } #undef INVOKE_IMPL_EXPR #define INVOKE_IMPL_MEMBER_FUNCTION(cond, expr) \ template <typename F, typename C, typename T, typename = typename std::enable_if<std::is_function<F>::value && (cond)>::type, typename... Arg> \ constexpr auto invokeImpl(F C::* f, T&& t, Arg&&... arg) noexcept(noexcept(expr)) -> decltype(expr) { return expr; } INVOKE_IMPL_MEMBER_FUNCTION( (std::is_base_of<C, typename std::decay<T>::type>::value), (std::forward<T>(t).*f)(std::forward<Arg>(arg)...)); INVOKE_IMPL_MEMBER_FUNCTION( (IsReferenceWrapper<typename std::decay<T>::type>::value), (t.get().*f)(std::forward<Arg>(arg)...)); INVOKE_IMPL_MEMBER_FUNCTION( (!std::is_base_of<C, typename std::decay<T>::type>::value && !IsReferenceWrapper<typename std::decay<T>::type>::value), ((*std::forward<T>(t)).*f)(std::forward<Arg>(arg)...)); #undef INVOKE_IMPL_MEMBER_FUNCTION #define INVOKE_IMPL_MEMBER_OBJECT(cond, expr) \ template <typename F, typename C, typename T, typename = typename std::enable_if<!std::is_function<F>::value && (cond)>::type> \ constexpr auto invokeImpl(F C::* f, T&& t) noexcept(noexcept(expr)) -> decltype(expr) { return expr; } INVOKE_IMPL_MEMBER_OBJECT( (std::is_base_of<C, typename std::decay<T>::type>::value), std::forward<T>(t).*f); INVOKE_IMPL_MEMBER_OBJECT( (IsReferenceWrapper<typename std::decay<T>::type>::value), t.get().*f); INVOKE_IMPL_MEMBER_OBJECT( (!std::is_base_of<C, typename std::decay<T>::type>::value && !IsReferenceWrapper<typename std::decay<T>::type>::value), (*std::forward<T>(t)).*f); #undef INVOKE_IMPL_MEMBER_OBJECT } #define INVOKE_EXPR Impl::invokeImpl(std::forward<F>(f), std::forward<Arg>(arg)...) template <typename F, typename... Arg> constexpr auto invoke(F&& f, Arg&&... arg) noexcept(noexcept(INVOKE_EXPR)) -> decltype(INVOKE_EXPR) { return INVOKE_EXPR; } #undef INVOKE_EXPR namespace Impl { template <typename, typename, typename...> struct InvokeResultImpl {}; template <typename F, typename... Arg> struct InvokeResultImpl<decltype(void(invoke(std::declval<F>(), std::declval<Arg>()...))), F, Arg...> { using Type = decltype(invoke(std::declval<F>(), std::declval<Arg>()...)); }; } template <typename F, typename... Arg> using InvokeResult = Impl::InvokeResultImpl<F, Arg...>; namespace Impl { #define APPLY_IMPL_EXPR invoke(std::forward<F>(f), std::get<I>(std::forward<T>(t))...) template <typename F, typename T, std::size_t... I> constexpr auto applyImpl(F&& f, T&& t, Sequence<std::size_t, I...>) noexcept(noexcept(APPLY_IMPL_EXPR)) -> decltype(APPLY_IMPL_EXPR) { return APPLY_IMPL_EXPR; } #undef APPLY_IMPL_EXPR } #define APPLY_EXPR \ Impl::applyImpl(std::forward<F>(f), std::forward<T>(t), \ IndexSequence<std::size_t, 0, std::tuple_size<typename std::remove_reference<T>::type>::value>()) template <typename F, typename T> constexpr auto apply(F&& f, T&& t) noexcept(noexcept(APPLY_EXPR)) -> decltype(APPLY_EXPR) { return APPLY_EXPR; } #undef APPLY_EXPR } } } #endif <|endoftext|>
<commit_before>// Copyright (C) 2013 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/Config.hpp> #include <Nazara/Core/Error.hpp> #include <Nazara/Core/File.hpp> #include <Nazara/Core/InputStream.hpp> #include <Nazara/Core/MemoryStream.hpp> #include <Nazara/Core/Debug.hpp> template<typename Type, typename Parameters> bool NzResourceLoader<Type, Parameters>::IsExtensionSupported(const NzString& extension) { for (auto loader = Type::s_loaders.begin(); loader != Type::s_loaders.end(); ++loader) { ExtensionGetter isExtensionSupported = std::get<0>(*loader); if (isExtensionSupported && isExtensionSupported(extension)) return true; } return false; } template<typename Type, typename Parameters> bool NzResourceLoader<Type, Parameters>::LoadFromFile(Type* resource, const NzString& filePath, const Parameters& parameters) { #if NAZARA_CORE_SAFE if (!parameters.IsValid()) { NazaraError("Invalid parameters"); return false; } #endif NzString path = NzFile::NormalizePath(filePath); NzString ext = path.SubstrFrom('.', -1, true); if (ext.IsEmpty()) { NazaraError("Failed to get file extension"); return false; } NzFile file(path); // Ouvert seulement en cas de besoin bool found = false; for (auto loader = Type::s_loaders.begin(); loader != Type::s_loaders.end(); ++loader) { ExtensionGetter isExtensionSupported = std::get<0>(*loader); if (!isExtensionSupported || !isExtensionSupported(ext)) continue; StreamChecker checkFunc = std::get<1>(*loader); StreamLoader streamLoader = std::get<2>(*loader); FileLoader fileLoader = std::get<3>(*loader); if (checkFunc && !file.IsOpen()) { if (!file.Open(NzFile::ReadOnly)) { NazaraError("Failed to load file: unable to open file"); return false; } } if (fileLoader) { if (checkFunc) { file.SetCursorPos(0); if (!checkFunc(file, parameters)) continue; } found = true; if (fileLoader(resource, filePath, parameters)) return true; } else { file.SetCursorPos(0); if (!checkFunc(file, parameters)) continue; file.SetCursorPos(0); found = true; if (streamLoader(resource, file, parameters)) return true; } NazaraWarning("Loader failed"); } if (found) NazaraError("Failed to load file: all loaders failed"); else NazaraError("Failed to load file: no loader found"); return false; } template<typename Type, typename Parameters> bool NzResourceLoader<Type, Parameters>::LoadFromMemory(Type* resource, const void* data, unsigned int size, const Parameters& parameters) { NzMemoryStream stream(data, size); return LoadFromStream(resource, stream, parameters); } template<typename Type, typename Parameters> bool NzResourceLoader<Type, Parameters>::LoadFromStream(Type* resource, NzInputStream& stream, const Parameters& parameters) { #if NAZARA_CORE_SAFE if (!parameters.IsValid()) { NazaraError("Invalid parameters"); return false; } if (stream.GetSize() == 0 || stream.GetCursorPos() >= stream.GetSize()) { NazaraError("No data to load"); return false; } #endif nzUInt64 streamPos = stream.GetCursorPos(); bool found = false; for (auto loader = Type::s_loaders.begin(); loader != Type::s_loaders.end(); ++loader) { StreamChecker checkFunc = std::get<1>(*loader); StreamLoader streamLoader = std::get<2>(*loader); stream.SetCursorPos(streamPos); // Le loader supporte-t-il les données ? if (!checkFunc(stream, parameters)) continue; // On repositionne le stream à son ancienne position stream.SetCursorPos(streamPos); // Chargement de la ressource found = true; if (streamLoader(resource, stream, parameters)) return true; NazaraWarning("Loader failed"); } if (found) NazaraError("Failed to load file: all loaders failed"); else NazaraError("Failed to load file: no loader found"); return false; } template<typename Type, typename Parameters> void NzResourceLoader<Type, Parameters>::RegisterLoader(ExtensionGetter extensionGetter, StreamChecker checkFunc, StreamLoader streamLoader, FileLoader fileLoader) { #if NAZARA_CORE_SAFE if (streamLoader) { if (!checkFunc) { NazaraError("StreamLoader present without StreamChecker"); return; } } else if (!fileLoader) { NazaraError("Neither FileLoader nor StreamLoader were present"); return; } #endif Type::s_loaders.push_front(std::make_tuple(extensionGetter, checkFunc, streamLoader, fileLoader)); } template<typename Type, typename Parameters> void NzResourceLoader<Type, Parameters>::UnregisterLoader(ExtensionGetter extensionGetter, StreamChecker checkFunc, StreamLoader streamLoader, FileLoader fileLoader) { Type::s_loaders.remove(std::make_tuple(extensionGetter, checkFunc, streamLoader, fileLoader)); } #include <Nazara/Core/DebugOff.hpp> <commit_msg>Improved error message<commit_after>// Copyright (C) 2013 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/Config.hpp> #include <Nazara/Core/Error.hpp> #include <Nazara/Core/File.hpp> #include <Nazara/Core/InputStream.hpp> #include <Nazara/Core/MemoryStream.hpp> #include <Nazara/Core/Debug.hpp> template<typename Type, typename Parameters> bool NzResourceLoader<Type, Parameters>::IsExtensionSupported(const NzString& extension) { for (auto loader = Type::s_loaders.begin(); loader != Type::s_loaders.end(); ++loader) { ExtensionGetter isExtensionSupported = std::get<0>(*loader); if (isExtensionSupported && isExtensionSupported(extension)) return true; } return false; } template<typename Type, typename Parameters> bool NzResourceLoader<Type, Parameters>::LoadFromFile(Type* resource, const NzString& filePath, const Parameters& parameters) { #if NAZARA_CORE_SAFE if (!parameters.IsValid()) { NazaraError("Invalid parameters"); return false; } #endif NzString path = NzFile::NormalizePath(filePath); NzString ext = path.SubstrFrom('.', -1, true); if (ext.IsEmpty()) { NazaraError("Failed to get file extension from \"" + filePath + '"'); return false; } NzFile file(path); // Ouvert seulement en cas de besoin bool found = false; for (auto loader = Type::s_loaders.begin(); loader != Type::s_loaders.end(); ++loader) { ExtensionGetter isExtensionSupported = std::get<0>(*loader); if (!isExtensionSupported || !isExtensionSupported(ext)) continue; StreamChecker checkFunc = std::get<1>(*loader); StreamLoader streamLoader = std::get<2>(*loader); FileLoader fileLoader = std::get<3>(*loader); if (checkFunc && !file.IsOpen()) { if (!file.Open(NzFile::ReadOnly)) { NazaraError("Failed to load file: unable to open \"" + filePath + '"'); return false; } } if (fileLoader) { if (checkFunc) { file.SetCursorPos(0); if (!checkFunc(file, parameters)) continue; } found = true; if (fileLoader(resource, filePath, parameters)) return true; } else { file.SetCursorPos(0); if (!checkFunc(file, parameters)) continue; file.SetCursorPos(0); found = true; if (streamLoader(resource, file, parameters)) return true; } NazaraWarning("Loader failed"); } if (found) NazaraError("Failed to load file: all loaders failed"); else NazaraError("Failed to load file: no loader found"); return false; } template<typename Type, typename Parameters> bool NzResourceLoader<Type, Parameters>::LoadFromMemory(Type* resource, const void* data, unsigned int size, const Parameters& parameters) { NzMemoryStream stream(data, size); return LoadFromStream(resource, stream, parameters); } template<typename Type, typename Parameters> bool NzResourceLoader<Type, Parameters>::LoadFromStream(Type* resource, NzInputStream& stream, const Parameters& parameters) { #if NAZARA_CORE_SAFE if (!parameters.IsValid()) { NazaraError("Invalid parameters"); return false; } if (stream.GetSize() == 0 || stream.GetCursorPos() >= stream.GetSize()) { NazaraError("No data to load"); return false; } #endif nzUInt64 streamPos = stream.GetCursorPos(); bool found = false; for (auto loader = Type::s_loaders.begin(); loader != Type::s_loaders.end(); ++loader) { StreamChecker checkFunc = std::get<1>(*loader); StreamLoader streamLoader = std::get<2>(*loader); stream.SetCursorPos(streamPos); // Le loader supporte-t-il les données ? if (!checkFunc(stream, parameters)) continue; // On repositionne le stream à son ancienne position stream.SetCursorPos(streamPos); // Chargement de la ressource found = true; if (streamLoader(resource, stream, parameters)) return true; NazaraWarning("Loader failed"); } if (found) NazaraError("Failed to load file: all loaders failed"); else NazaraError("Failed to load file: no loader found"); return false; } template<typename Type, typename Parameters> void NzResourceLoader<Type, Parameters>::RegisterLoader(ExtensionGetter extensionGetter, StreamChecker checkFunc, StreamLoader streamLoader, FileLoader fileLoader) { #if NAZARA_CORE_SAFE if (streamLoader) { if (!checkFunc) { NazaraError("StreamLoader present without StreamChecker"); return; } } else if (!fileLoader) { NazaraError("Neither FileLoader nor StreamLoader were present"); return; } #endif Type::s_loaders.push_front(std::make_tuple(extensionGetter, checkFunc, streamLoader, fileLoader)); } template<typename Type, typename Parameters> void NzResourceLoader<Type, Parameters>::UnregisterLoader(ExtensionGetter extensionGetter, StreamChecker checkFunc, StreamLoader streamLoader, FileLoader fileLoader) { Type::s_loaders.remove(std::make_tuple(extensionGetter, checkFunc, streamLoader, fileLoader)); } #include <Nazara/Core/DebugOff.hpp> <|endoftext|>
<commit_before>#include "core/global.h" #include "EventSender.h" EventSender::EventSender() : m_log("eventsender", "Event Sender"), m_socket(io_service, udp::v4()), m_enabled(false) { } void EventSender::init(const std::string& target) { std::string str_ip = target; if(str_ip == "") { m_enabled = false; m_log.debug() << "Not enabled." << std::endl; return; } m_log.debug() << "Resolving target..." << std::endl; std::string str_port = str_ip.substr(str_ip.find(':', 0) + 1, std::string::npos); str_ip = str_ip.substr(0, str_ip.find(':', 0)); udp::resolver resolver(io_service); udp::resolver::query query(str_ip, str_port); udp::resolver::iterator it = resolver.resolve(query); m_target = *it; m_enabled = true; m_log.debug() << "Initialized." << std::endl; } void EventSender::send(const DatagramHandle dg) { if(!m_enabled) { m_log.trace() << "Disabled; discarding event..." << std::endl; return; } m_log.trace() << "Sending event..." << std::endl; m_socket.send_to(boost::asio::buffer(dg->get_data(), dg->size()), m_target); } EventSender g_eventsender; // And now the convenience class: LoggedEvent::LoggedEvent() : LoggedEvent("unset", "unset") { } LoggedEvent::LoggedEvent(const std::string &type) : LoggedEvent(type, "unset") { } LoggedEvent::LoggedEvent(const std::string &type, const std::string &sender) { add("type", type); add("sender", sender); } void LoggedEvent::add(const std::string &key, const std::string &value) { if(m_keys.find(key) == m_keys.end()) { m_keys[key] = m_kv.size(); m_kv.push_back(std::make_pair(key, value)); } else { m_kv[m_keys[key]] = std::make_pair(key, value); } } static inline void pack_string(DatagramPtr dg, const std::string &str) { size_t size = str.size(); if(size < 32) { // Small enough for fixstr: dg->add_uint8(0xa0 + size); } else { // Use a str16. // We don't have to worry about str32, nothing that big will fit in a // single UDP packet anyway. dg->add_uint8(0xda); dg->add_uint8(size>>8 & 0xFF); dg->add_uint8(size & 0xFF); } dg->add_data(str); } DatagramHandle LoggedEvent::make_datagram() const { DatagramPtr dg = Datagram::create(); // First, append the size of our map: size_t size = m_kv.size(); if(size < 16) { // Small enough for fixmap: dg->add_uint8(0x80 + size); } else { // Use a map16. // We don't have to worry about map32, nothing that big will fit in a // single UDP packet anyway. dg->add_uint8(0xde); dg->add_uint8(size>>8 & 0xFF); dg->add_uint8(size & 0xFF); } for(auto &it : m_kv) { pack_string(dg, it.first); pack_string(dg, it.second); } return dg; } <commit_msg>emergency bugfix: Fix build on draft C++11 compilers.<commit_after>#include "core/global.h" #include "EventSender.h" EventSender::EventSender() : m_log("eventsender", "Event Sender"), m_socket(io_service, udp::v4()), m_enabled(false) { } void EventSender::init(const std::string& target) { std::string str_ip = target; if(str_ip == "") { m_enabled = false; m_log.debug() << "Not enabled." << std::endl; return; } m_log.debug() << "Resolving target..." << std::endl; std::string str_port = str_ip.substr(str_ip.find(':', 0) + 1, std::string::npos); str_ip = str_ip.substr(0, str_ip.find(':', 0)); udp::resolver resolver(io_service); udp::resolver::query query(str_ip, str_port); udp::resolver::iterator it = resolver.resolve(query); m_target = *it; m_enabled = true; m_log.debug() << "Initialized." << std::endl; } void EventSender::send(const DatagramHandle dg) { if(!m_enabled) { m_log.trace() << "Disabled; discarding event..." << std::endl; return; } m_log.trace() << "Sending event..." << std::endl; m_socket.send_to(boost::asio::buffer(dg->get_data(), dg->size()), m_target); } EventSender g_eventsender; // And now the convenience class: LoggedEvent::LoggedEvent() { add("type", "unset"); add("sender", "unset"); } LoggedEvent::LoggedEvent(const std::string &type) { add("type", type); add("sender", "unset"); } LoggedEvent::LoggedEvent(const std::string &type, const std::string &sender) { add("type", type); add("sender", sender); } void LoggedEvent::add(const std::string &key, const std::string &value) { if(m_keys.find(key) == m_keys.end()) { m_keys[key] = m_kv.size(); m_kv.push_back(std::make_pair(key, value)); } else { m_kv[m_keys[key]] = std::make_pair(key, value); } } static inline void pack_string(DatagramPtr dg, const std::string &str) { size_t size = str.size(); if(size < 32) { // Small enough for fixstr: dg->add_uint8(0xa0 + size); } else { // Use a str16. // We don't have to worry about str32, nothing that big will fit in a // single UDP packet anyway. dg->add_uint8(0xda); dg->add_uint8(size>>8 & 0xFF); dg->add_uint8(size & 0xFF); } dg->add_data(str); } DatagramHandle LoggedEvent::make_datagram() const { DatagramPtr dg = Datagram::create(); // First, append the size of our map: size_t size = m_kv.size(); if(size < 16) { // Small enough for fixmap: dg->add_uint8(0x80 + size); } else { // Use a map16. // We don't have to worry about map32, nothing that big will fit in a // single UDP packet anyway. dg->add_uint8(0xde); dg->add_uint8(size>>8 & 0xFF); dg->add_uint8(size & 0xFF); } for(auto &it : m_kv) { pack_string(dg, it.first); pack_string(dg, it.second); } return dg; } <|endoftext|>
<commit_before>#include <cctype> #include <sstream> #include <string> #include <vector> #include <boost/filesystem.hpp> #include "NameCompare.hh" #include "parseString.hh" namespace { std::vector<std::string> nameIndex(std::string const &name) { std::vector<std::string> index; if (name.size() == 0) return index; std::ostringstream buf; bool prevIsDigit = std::isdigit(name[0]); for (std::string::const_iterator iter = name.begin(); iter != name.end(); ++iter) { bool curIsDigit = std::isdigit(*iter); if (curIsDigit && prevIsDigit) buf << *iter; else { index.push_back(buf.str()); buf.str(""); buf << *iter; } prevIsDigit = curIsDigit; } // Leftover index.push_back(buf.str()); return index; } } namespace alpinocorpus { bool NameCompare::operator()(std::string const &s1, std::string const &s2) const { std::vector<std::string> const &i1 = nameIndex(s1); std::vector<std::string> const &i2 = nameIndex(s2); for (size_t i = 0; i < i1.size() && i < i2.size(); ++i) { // Both digits? Sort on digits! if (std::isdigit(i1[i][0]) && std::isdigit(i2[i][0])) { long long int d1 = util::parseString<long long int>(i1[i]); long long int d2 = util::parseString<long long int>(i2[i]); if (d1 != d2) return d1 < d2; } else if (i1[i] != i2[i]) return i1[i] < i2[i]; } // The pairs are equal... return false; } bool PathCompare::operator()(boost::filesystem::path const &p1, boost::filesystem::path const &p2) const { return d_nameCompare(p1.string(), p2.string()); } } <commit_msg>Fix a bug in NameCompare.<commit_after>#include <cctype> #include <sstream> #include <string> #include <vector> #include <boost/filesystem.hpp> #include "NameCompare.hh" #include "parseString.hh" namespace { std::vector<std::string> nameIndex(std::string const &name) { std::vector<std::string> index; if (name.size() == 0) return index; std::ostringstream buf; bool prevIsDigit = std::isdigit(name[0]); for (std::string::const_iterator iter = name.begin(); iter != name.end(); ++iter) { bool curIsDigit = std::isdigit(*iter); if (curIsDigit && prevIsDigit) buf << *iter; else { index.push_back(buf.str()); buf.str(""); buf << *iter; } prevIsDigit = curIsDigit; } // Leftover index.push_back(buf.str()); return index; } } namespace alpinocorpus { bool NameCompare::operator()(std::string const &s1, std::string const &s2) const { std::vector<std::string> const &i1 = nameIndex(s1); std::vector<std::string> const &i2 = nameIndex(s2); for (size_t i = 0; i < i1.size() && i < i2.size(); ++i) { // Both digits? Sort on digits! if (std::isdigit(i1[i][0]) && std::isdigit(i2[i][0])) { long long int d1 = util::parseString<long long int>(i1[i]); long long int d2 = util::parseString<long long int>(i2[i]); if (d1 != d2) return d1 < d2; } else if (i1[i] != i2[i]) return i1[i] < i2[i]; } if (i1.size() != i2.size()) return i1.size() < i2.size(); // The pairs are equal... return false; } bool PathCompare::operator()(boost::filesystem::path const &p1, boost::filesystem::path const &p2) const { return d_nameCompare(p1.string(), p2.string()); } } <|endoftext|>
<commit_before>/* * OCILIB - C Driver for Oracle (C Wrapper for Oracle OCI) * * Website: http://www.ocilib.net * * Copyright (c) 2007-2020 Vincent ROGIER <vince.rogier@ocilib.net> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "ocilibcpp/types.hpp" namespace ocilib { inline Exception::Exception() noexcept : _what(nullptr), _pStatement(nullptr), _pConnnection(nullptr), _row(0), _type(static_cast<ExceptionType::Type>(0)), _errLib(0), _errOracle(0) { } inline Exception::Exception(OCI_Error *err) noexcept : _what(nullptr), _pStatement(OCI_ErrorGetStatement(err)), _pConnnection(OCI_ErrorGetConnection(err)), _row(OCI_ErrorGetRow(err)), _type(static_cast<ExceptionType::Type>(OCI_ErrorGetType(err))), _errLib(OCI_ErrorGetInternalCode(err)), _errOracle(OCI_ErrorGetOCICode(err)) { SetWhat(OCI_ErrorGetString(err)); } inline Exception::Exception(const Exception& other) noexcept : Exception(nullptr) { SetWhat(other._what); } inline Exception::~Exception() noexcept { delete [] _what; } inline Exception& Exception::operator = (const Exception& other) noexcept { if (this != &other) { _what = ostrdup(other._what); } return *this; } inline void Exception::SetWhat(const otext* value) noexcept { if (!value) { return; } const size_t len = ostrlen(value); _what = new (std::nothrow) otext[len + 1]; if (_what) { memcpy(_what, value, (len + 1) * (sizeof(otext))); } } inline const char * Exception::what() const noexcept { return _what; } inline ostring Exception::GetMessage() const { const otext* str = what(); return str ? str : ostring{}; } inline Exception::ExceptionType Exception::GetType() const { return _type; } inline int Exception::GetOracleErrorCode() const { return _errOracle; } inline int Exception::GetInternalErrorCode() const { return _errLib; } inline Statement Exception::GetStatement() const { return Statement(_pStatement, nullptr); } inline Connection Exception::GetConnection() const { return Connection(_pConnnection, nullptr); } inline unsigned int Exception::GetRow() const { return _row; } } <commit_msg>- Fixed Exception copy constructor that only copied the error message since the refactoring made in v4.7.0 - Make sure to free previous value when setting exception error message<commit_after>/* * OCILIB - C Driver for Oracle (C Wrapper for Oracle OCI) * * Website: http://www.ocilib.net * * Copyright (c) 2007-2020 Vincent ROGIER <vince.rogier@ocilib.net> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "ocilibcpp/types.hpp" namespace ocilib { inline Exception::Exception() noexcept : _what(nullptr), _pStatement(nullptr), _pConnnection(nullptr), _row(0), _type(static_cast<ExceptionType::Type>(0)), _errLib(0), _errOracle(0) { } inline Exception::Exception(OCI_Error *err) noexcept : _what(nullptr), _pStatement(OCI_ErrorGetStatement(err)), _pConnnection(OCI_ErrorGetConnection(err)), _row(OCI_ErrorGetRow(err)), _type(static_cast<ExceptionType::Type>(OCI_ErrorGetType(err))), _errLib(OCI_ErrorGetInternalCode(err)), _errOracle(OCI_ErrorGetOCICode(err)) { SetWhat(OCI_ErrorGetString(err)); } inline Exception::Exception(const Exception& other) noexcept : Exception() { *this = other; } inline Exception::~Exception() noexcept { delete [] _what; } inline Exception& Exception::operator = (const Exception& other) noexcept { if (this != &other) { _pStatement = other._pStatement; _pConnnection = other._pConnnection; _row = other._row; _type = other._type; _errLib = other._errLib; _errOracle = other._errOracle; SetWhat(other._what); } return *this; } inline void Exception::SetWhat(const otext* value) noexcept { if (_what) { delete[] _what; _what = nullptr; } if (!value) { return; } const size_t len = ostrlen(value); _what = new (std::nothrow) otext[len + 1]; if (_what) { memcpy(_what, value, (len + 1) * (sizeof(otext))); } } inline const char * Exception::what() const noexcept { return _what; } inline ostring Exception::GetMessage() const { const otext* str = what(); return str ? str : ostring{}; } inline Exception::ExceptionType Exception::GetType() const { return _type; } inline int Exception::GetOracleErrorCode() const { return _errOracle; } inline int Exception::GetInternalErrorCode() const { return _errLib; } inline Statement Exception::GetStatement() const { return Statement(_pStatement, nullptr); } inline Connection Exception::GetConnection() const { return Connection(_pConnnection, nullptr); } inline unsigned int Exception::GetRow() const { return _row; } } <|endoftext|>
<commit_before>// // utils/log/Trivial.cc // librefract // // Created by Thomas Jandecka on 16/02/2018 // Copyright (c) 2018 Apiary Inc. All rights reserved. // #include "Trivial.h" #ifdef LOGGING static_assert(false, "LOGGING..."); #include <ofstream> #endif using namespace drafter; using namespace utils; using namespace log; namespace { bool enough_severity(severity s) { switch (s) { case debug: #ifdef DEBUG return true; #else return false; #endif default: return true; } } } // namespace trivial_log& trivial_log::instance() { static trivial_log instance_; return instance_; } const char* log::severity_to_str(severity s) { switch (s) { case debug: return "DEBUG"; case info: return "INFO "; case warning: return "WARN "; case error: return "ERROR"; default: return ""; } } trivial_entry::trivial_entry(trivial_log& log, severity svrty, size_t line, const char* file) : log_(log), severity_(svrty), log_lock_(log_.mtx()) { if (enough_severity(severity_)) if (auto* out = log_.out()) { *out << '[' << severity_to_str(svrty) << "]"; *out << '[' << std::this_thread::get_id() << "]"; *out << '[' << file << ':' << line << "] "; } } trivial_entry::~trivial_entry() { if (enough_severity(severity_)) if (auto* out = log_.out()) { *out << '\n'; // TODO @tjanc@ could throw } } std::mutex& trivial_log::mtx() const { return write_mtx_; } std::ostream* trivial_log::out() { return out_; } void trivial_log::enable() { std::lock_guard<std::mutex> lock(write_mtx_); #ifdef LOGGING static std::ofstream log_file_{ "drafter.log" }; out_ = &log_file_; #endif } <commit_msg>(fix) removed debugging assert<commit_after>// // utils/log/Trivial.cc // librefract // // Created by Thomas Jandecka on 16/02/2018 // Copyright (c) 2018 Apiary Inc. All rights reserved. // #include "Trivial.h" #ifdef LOGGING #include <fstream> #endif using namespace drafter; using namespace utils; using namespace log; namespace { bool enough_severity(severity s) { switch (s) { case debug: #ifdef DEBUG return true; #else return false; #endif default: return true; } } } // namespace trivial_log& trivial_log::instance() { static trivial_log instance_; return instance_; } const char* log::severity_to_str(severity s) { switch (s) { case debug: return "DEBUG"; case info: return "INFO "; case warning: return "WARN "; case error: return "ERROR"; default: return ""; } } trivial_entry::trivial_entry(trivial_log& log, severity svrty, size_t line, const char* file) : log_(log), severity_(svrty), log_lock_(log_.mtx()) { if (enough_severity(severity_)) if (auto* out = log_.out()) { *out << '[' << severity_to_str(svrty) << "]"; *out << '[' << std::this_thread::get_id() << "]"; *out << '[' << file << ':' << line << "] "; } } trivial_entry::~trivial_entry() { if (enough_severity(severity_)) if (auto* out = log_.out()) { *out << '\n'; // TODO @tjanc@ could throw } } std::mutex& trivial_log::mtx() const { return write_mtx_; } std::ostream* trivial_log::out() { return out_; } void trivial_log::enable() { std::lock_guard<std::mutex> lock(write_mtx_); #ifdef LOGGING static std::ofstream log_file_{ "drafter.log" }; out_ = &log_file_; #endif } <|endoftext|>
<commit_before>#ifndef __MAPNIK_VECTOR_TILE_UTIL_H__ #define __MAPNIK_VECTOR_TILE_UTIL_H__ #include "vector_tile.pb.h" #include <mapnik/vertex.hpp> #include <mapnik/box2d.hpp> #include <mapnik/geometry.hpp> #include <stdexcept> #include <string> #ifdef CONV_CLIPPER #include "clipper.hpp" #endif namespace mapnik { namespace vector { #ifdef CONV_CLIPPER bool is_solid_clipper(mapnik::vector::tile const& tile, std::string & key) { ClipperLib::Clipper clipper; for (int i = 0; i < tile.layers_size(); i++) { mapnik::vector::tile_layer const& layer = tile.layers(i); unsigned extent = layer.extent(); unsigned side = extent - 1; double extent_area = side * side; ClipperLib::Polygon clip_box; clip_box.push_back(ClipperLib::IntPoint(0, 0)); clip_box.push_back(ClipperLib::IntPoint(side, 0)); clip_box.push_back(ClipperLib::IntPoint(side, side)); clip_box.push_back(ClipperLib::IntPoint(0, side)); clip_box.push_back(ClipperLib::IntPoint(0, 0)); for (int j = 0; j < layer.features_size(); j++) { mapnik::vector::tile_feature const& feature = layer.features(j); int cmd = -1; const int cmd_bits = 3; unsigned length = 0; int32_t x = 0, y = 0; int32_t start_x = 0, start_y = 0; ClipperLib::Polygons geometry; ClipperLib::Polygon polygon; for (int k = 0; k < feature.geometry_size();) { if (!length) { unsigned cmd_length = feature.geometry(k++); cmd = cmd_length & ((1 << cmd_bits) - 1); length = cmd_length >> cmd_bits; } if (length > 0) { length--; if (cmd == mapnik::SEG_MOVETO || cmd == mapnik::SEG_LINETO) { int32_t dx = feature.geometry(k++); int32_t dy = feature.geometry(k++); x += ((dx >> 1) ^ (-(dx & 1))); y += ((dy >> 1) ^ (-(dy & 1))); // We can abort early if this feature has a vertex that is // inside the bbox. if ((x > 0 && x < static_cast<int>(side)) && (y > 0 && y < static_cast<int>(side))) { return false; } if (cmd == mapnik::SEG_MOVETO) { start_x = x; start_y = y; geometry.push_back(polygon); polygon.clear(); } polygon.push_back(ClipperLib::IntPoint(x, y)); } else if (cmd == (mapnik::SEG_CLOSE & ((1 << cmd_bits) - 1))) { polygon.push_back(ClipperLib::IntPoint(start_x, start_y)); geometry.push_back(polygon); polygon.clear(); } else { std::stringstream msg; msg << "Unknown command type (is_solid_clipper): " << cmd; throw std::runtime_error(msg.str()); } } } ClipperLib::Polygons solution; clipper.Clear(); clipper.AddPolygons(geometry, ClipperLib::ptSubject); clipper.AddPolygon(clip_box, ClipperLib::ptClip); clipper.Execute(ClipperLib::ctIntersection, solution, ClipperLib::pftNonZero, ClipperLib::pftNonZero); // If there are more than one result polygons, it can't be covered by // a single feature. Similarly, if there's no result, this geometry // is completely outside the bounding box. if (solution.size() != 1) { return false; } // Once we have only one clipped result polygon, we can compare the // areas and return early if they don't match. double area = ClipperLib::Area(solution.front()); if (area != extent_area) { return false; } if (i == 0) { key = layer.name(); } else if (i > 0) { key += std::string("-") + layer.name(); } } } // It's either empty or doesn't have features that have vertices that are // not on the border of the bbox. return true; } #endif bool is_solid_extent(mapnik::vector::tile const& tile, std::string & key) { for (int i = 0; i < tile.layers_size(); i++) { mapnik::vector::tile_layer const& layer = tile.layers(i); unsigned extent = layer.extent(); unsigned side = extent - 1; double extent_area = side * side; for (int j = 0; j < layer.features_size(); j++) { mapnik::vector::tile_feature const& feature = layer.features(j); int cmd = -1; const int cmd_bits = 3; unsigned length = 0; bool first = true; mapnik::box2d<double> box; int32_t x = 0, y = 0; for (int k = 0; k < feature.geometry_size();) { if (!length) { unsigned cmd_length = feature.geometry(k++); cmd = cmd_length & ((1 << cmd_bits) - 1); length = cmd_length >> cmd_bits; } if (length > 0) { length--; if (cmd == mapnik::SEG_MOVETO || cmd == mapnik::SEG_LINETO) { int32_t dx = feature.geometry(k++); int32_t dy = feature.geometry(k++); x += ((dx >> 1) ^ (-(dx & 1))); y += ((dy >> 1) ^ (-(dy & 1))); // We can abort early if this feature has a vertex that is // inside the bbox. if ((x > 0 && x < static_cast<int>(side)) && (y > 0 && y < static_cast<int>(side))) { return false; } if (first) { box.init(x,y,x,y); first = false; } else { box.expand_to_include(x,y); } } else if (cmd == (mapnik::SEG_CLOSE & ((1 << cmd_bits) - 1))) { // pass } else { std::stringstream msg; msg << "Unknown command type (is_solid_extent): " << cmd; throw std::runtime_error(msg.str()); } } } // Once we have only one clipped result polygon, we can compare the // areas and return early if they don't match. double geom_area = box.width() * box.height(); if (geom_area < (extent_area - 32) ) { return false; } if (i == 0) { key = layer.name(); } else if (i > 0) { key += std::string("-") + layer.name(); } } } // It's either empty or doesn't have features that have vertices that are // not on the border of the bbox. return true; } }} // end ns #endif // __MAPNIK_VECTOR_TILE_UTIL_H__ <commit_msg>test for line intersections in isSolid check - refs #41<commit_after>#ifndef __MAPNIK_VECTOR_TILE_UTIL_H__ #define __MAPNIK_VECTOR_TILE_UTIL_H__ #include "vector_tile.pb.h" #include <mapnik/vertex.hpp> #include <mapnik/box2d.hpp> #include <mapnik/geometry.hpp> #include <stdexcept> #include <string> #ifdef CONV_CLIPPER #include "clipper.hpp" #endif namespace mapnik { namespace vector { #ifdef CONV_CLIPPER bool is_solid_clipper(mapnik::vector::tile const& tile, std::string & key) { ClipperLib::Clipper clipper; for (int i = 0; i < tile.layers_size(); i++) { mapnik::vector::tile_layer const& layer = tile.layers(i); unsigned extent = layer.extent(); unsigned side = extent - 1; double extent_area = side * side; ClipperLib::Polygon clip_box; clip_box.push_back(ClipperLib::IntPoint(0, 0)); clip_box.push_back(ClipperLib::IntPoint(side, 0)); clip_box.push_back(ClipperLib::IntPoint(side, side)); clip_box.push_back(ClipperLib::IntPoint(0, side)); clip_box.push_back(ClipperLib::IntPoint(0, 0)); for (int j = 0; j < layer.features_size(); j++) { mapnik::vector::tile_feature const& feature = layer.features(j); int cmd = -1; const int cmd_bits = 3; unsigned length = 0; int32_t x = 0, y = 0; int32_t start_x = 0, start_y = 0; ClipperLib::Polygons geometry; ClipperLib::Polygon polygon; for (int k = 0; k < feature.geometry_size();) { if (!length) { unsigned cmd_length = feature.geometry(k++); cmd = cmd_length & ((1 << cmd_bits) - 1); length = cmd_length >> cmd_bits; } if (length > 0) { length--; if (cmd == mapnik::SEG_MOVETO || cmd == mapnik::SEG_LINETO) { int32_t dx = feature.geometry(k++); int32_t dy = feature.geometry(k++); x += ((dx >> 1) ^ (-(dx & 1))); y += ((dy >> 1) ^ (-(dy & 1))); // We can abort early if this feature has a vertex that is // inside the bbox. if ((x > 0 && x < static_cast<int>(side)) && (y > 0 && y < static_cast<int>(side))) { return false; } if (cmd == mapnik::SEG_MOVETO) { start_x = x; start_y = y; geometry.push_back(polygon); polygon.clear(); } polygon.push_back(ClipperLib::IntPoint(x, y)); } else if (cmd == (mapnik::SEG_CLOSE & ((1 << cmd_bits) - 1))) { polygon.push_back(ClipperLib::IntPoint(start_x, start_y)); geometry.push_back(polygon); polygon.clear(); } else { std::stringstream msg; msg << "Unknown command type (is_solid_clipper): " << cmd; throw std::runtime_error(msg.str()); } } } ClipperLib::Polygons solution; clipper.Clear(); clipper.AddPolygons(geometry, ClipperLib::ptSubject); clipper.AddPolygon(clip_box, ClipperLib::ptClip); clipper.Execute(ClipperLib::ctIntersection, solution, ClipperLib::pftNonZero, ClipperLib::pftNonZero); // If there are more than one result polygons, it can't be covered by // a single feature. Similarly, if there's no result, this geometry // is completely outside the bounding box. if (solution.size() != 1) { return false; } // Once we have only one clipped result polygon, we can compare the // areas and return early if they don't match. double area = ClipperLib::Area(solution.front()); if (area != extent_area) { return false; } if (i == 0) { key = layer.name(); } else if (i > 0) { key += std::string("-") + layer.name(); } } } // It's either empty or doesn't have features that have vertices that are // not on the border of the bbox. return true; } #endif // ported from http://stackoverflow.com/a/1968345/2333354 bool line_intersects(int p0_x, int p0_y, int p1_x, int p1_y, int p2_x, int p2_y, int p3_x, int p3_y) { float s1_x = p1_x - p0_x; float s1_y = p1_y - p0_y; float s2_x = p3_x - p2_x; float s2_y = p3_y - p2_y; float a = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)); float b = (-s2_x * s1_y + s1_x * s2_y); if (b == 0 ) return false; float s = a / b; if (s > 1 || s < 1) return false; float c = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)); float d = (-s2_x * s1_y + s1_x * s2_y); if (d == 0 ) return false; float t = c / d; if (t > 1 || t < 1) return false; if (s >= 0 && s <= 1 && t >= 0 && t <= 1) return true; return false; } bool line_intersects_box(int p0_x, int p0_y, int p1_x, int p1_y, mapnik::box2d<int> box) { // possible early return for degenerate line if (p0_x == p1_x && p0_y == p1_y) return false; // check intersections with 4 sides of box /* 0,1 ------ 2,1 | | | | 0,3 ------ 2,3 */ // bottom side: 0,3,2,3 if (line_intersects(p0_x,p0_y,p1_x,p1_y, box[0],box[3],box[2],box[3])) { return true; } // right side: 2,3,2,1 else if (line_intersects(p0_x,p0_y,p1_x,p1_y, box[2],box[3],box[2],box[1])) { return true; } // top side: 0,1,2,1 else if (line_intersects(p0_x,p0_y,p1_x,p1_y, box[0],box[1],box[2],box[1])) { return true; } // left side: 0,1,0,3 else if (line_intersects(p0_x,p0_y,p1_x,p1_y, box[0],box[1],box[0],box[3])) { return true; } return false; } bool is_solid_extent(mapnik::vector::tile const& tile, std::string & key) { for (int i = 0; i < tile.layers_size(); i++) { mapnik::vector::tile_layer const& layer = tile.layers(i); unsigned extent = layer.extent(); unsigned side = extent - 1; // TODO: need to account for buffer here // NOTE: insetting box by 2 pixels is needed to account for // rounding issues (at least on right and bottom) mapnik::box2d<int> container(2, 2, extent-2, extent-2); double extent_area = side * side; for (int j = 0; j < layer.features_size(); j++) { mapnik::vector::tile_feature const& feature = layer.features(j); int cmd = -1; const int cmd_bits = 3; unsigned length = 0; bool first = true; mapnik::box2d<int> box; int32_t x1 = 0; int32_t y1 = 0; int32_t x0 = 0; int32_t y0 = 0; for (int k = 0; k < feature.geometry_size();) { if (!length) { unsigned cmd_length = feature.geometry(k++); cmd = cmd_length & ((1 << cmd_bits) - 1); length = cmd_length >> cmd_bits; } if (length > 0) { length--; if (cmd == mapnik::SEG_MOVETO || cmd == mapnik::SEG_LINETO) { int32_t dx = feature.geometry(k++); int32_t dy = feature.geometry(k++); dx = ((dx >> 1) ^ (-(dx & 1))); dy = ((dy >> 1) ^ (-(dy & 1))); x1 += dx; y1 += dy; if ((x1 > 0 && x1 < static_cast<int>(side)) && (y1 > 0 && y1 < static_cast<int>(side))) { // We can abort early if this feature has a vertex that is // inside the bbox. return false; } else if (!first && line_intersects_box(x0,y0,x1,y1,container)) { // or if the last line segment intersects with the expected bounding rectangle return false; } x0 = x1; y0 = y1; if (first) { box.init(x1,y1,x1,y1); first = false; } else { box.expand_to_include(x1,y1); } } else if (cmd == (mapnik::SEG_CLOSE & ((1 << cmd_bits) - 1))) { // pass } else { std::stringstream msg; msg << "Unknown command type (is_solid_extent): " << cmd; throw std::runtime_error(msg.str()); } } } // Once we have only one clipped result polygon, we can compare the // areas and return early if they don't match. int geom_area = box.width() * box.height(); if (geom_area < (extent_area - 32) ) { return false; } if (i == 0) { key = layer.name(); } else if (i > 0) { key += std::string("-") + layer.name(); } } } // It's either empty or doesn't have features that have vertices that are // not on the border of the bbox. return true; } }} // end ns #endif // __MAPNIK_VECTOR_TILE_UTIL_H__ <|endoftext|>
<commit_before>#include "txbuilder.h" #include "../amount.h" #include "../main.h" #include "../policy/policy.h" #include "../random.h" #include "../script/script.h" #include "../txmempool.h" #include "../uint256.h" #include "../util.h" #include <boost/format.hpp> #include <algorithm> #include <random> #include <stdexcept> #include <string> #include <assert.h> #include <stddef.h> InputSigner::InputSigner() : InputSigner(COutPoint()) { } InputSigner::InputSigner(const COutPoint& output, uint32_t seq) : output(output), sequence(seq) { } InputSigner::~InputSigner() { } TxBuilder::TxBuilder(CWallet& wallet) noexcept : wallet(wallet) { } TxBuilder::~TxBuilder() { } CWalletTx TxBuilder::Build(const std::vector<CRecipient>& recipients, CAmount& fee) { if (recipients.empty()) { throw std::invalid_argument(_("No recipients")); } // calculate total value to spend CAmount spend = 0; unsigned recipientsToSubtractFee = 0; for (size_t i = 0; i < recipients.size(); i++) { auto& recipient = recipients[i]; if (!MoneyRange(recipient.nAmount)) { throw std::invalid_argument(boost::str(boost::format(_("Recipient %1% has invalid amount")) % i)); } spend += recipient.nAmount; if (recipient.fSubtractFeeFromAmount) { recipientsToSubtractFee++; } } CWalletTx result; CMutableTransaction tx; result.fTimeReceivedIsTxTime = true; result.BindWallet(&wallet); // Discourage fee sniping. // // For a large miner the value of the transactions in the best block and // the mempool can exceed the cost of deliberately attempting to mine two // blocks to orphan the current best block. By setting nLockTime such that // only the next block can include the transaction, we discourage this // practice as the height restricted and limited blocksize gives miners // considering fee sniping fewer options for pulling off this attack. // // A simple way to think about this is from the wallet's point of view we // always want the blockchain to move forward. By setting nLockTime this // way we're basically making the statement that we only want this // transaction to appear in the next block; we don't want to potentially // encourage reorgs by allowing transactions to appear at lower heights // than the next block in forks of the best chain. // // Of course, the subsidy is high enough, and transaction volume low // enough, that fee sniping isn't a problem yet, but by implementing a fix // now we ensure code won't be written that makes assumptions about // nLockTime that preclude a fix later. tx.nLockTime = chainActive.Height(); // Secondly occasionally randomly pick a nLockTime even further back, so // that transactions that are delayed after signing for whatever reason, // e.g. high-latency mix networks and some CoinJoin implementations, have // better privacy. if (GetRandInt(10) == 0) { tx.nLockTime = std::max(0, static_cast<int>(tx.nLockTime) - GetRandInt(100)); } assert(tx.nLockTime <= static_cast<unsigned>(chainActive.Height())); assert(tx.nLockTime < LOCKTIME_THRESHOLD); // Start with no fee and loop until there is enough fee; for (fee = payTxFee.GetFeePerK();;) { // In case of not enough fee, reset mint seed counter CAmount required = spend; tx.vin.clear(); tx.vout.clear(); tx.wit.SetNull(); result.fFromMe = true; result.changes.clear(); // If no any recipients to subtract fee then the sender need to pay by themself. if (!recipientsToSubtractFee) { required += fee; } // fill outputs bool remainderSubtracted = false; for (size_t i = 0; i < recipients.size(); i++) { auto& recipient = recipients[i]; CTxOut vout(recipient.nAmount, recipient.scriptPubKey); if (recipient.fSubtractFeeFromAmount) { // Subtract fee equally from each selected recipient. vout.nValue -= fee / recipientsToSubtractFee; if (!remainderSubtracted) { // First receiver pays the remainder not divisible by output count. vout.nValue -= fee % recipientsToSubtractFee; remainderSubtracted = true; } } if (vout.IsDust(minRelayTxFee)) { std::string err; if (recipient.fSubtractFeeFromAmount && fee > 0) { if (vout.nValue < 0) { err = boost::str(boost::format(_("Amount for recipient %1% is too small to pay the fee")) % i); } else { err = boost::str(boost::format(_("Amount for recipient %1% is too small to send after the fee has been deducted")) % i); } } else { err = boost::str(boost::format(_("Amount for recipient %1% is too small")) % i); } throw std::invalid_argument(err); } tx.vout.push_back(vout); } // get inputs std::vector<std::unique_ptr<InputSigner>> signers; CAmount total = GetInputs(signers, required); // add changes CAmount change = total - required; if (change > 0) { // get changes outputs std::vector<CTxOut> changes; fee += GetChanges(changes, change); // shuffle changes to provide some privacy std::vector<std::pair<std::reference_wrapper<CTxOut>, bool>> outputs; outputs.reserve(tx.vout.size() + changes.size()); for (auto& output : tx.vout) { outputs.push_back(std::make_pair(std::ref(output), false)); } for (auto& output : changes) { outputs.push_back(std::make_pair(std::ref(output), true)); } std::shuffle(outputs.begin(), outputs.end(), std::random_device()); // replace outputs with shuffled one std::vector<CTxOut> shuffled; shuffled.reserve(outputs.size()); for (size_t i = 0; i < outputs.size(); i++) { auto& output = outputs[i]; shuffled.push_back(output.first); if (output.second) { result.changes.insert(static_cast<uint32_t>(i)); } } tx.vout = std::move(shuffled); } // fill inputs for (auto& signer : signers) { tx.vin.emplace_back(signer->output, CScript(), signer->sequence); } // now every fields is populated then we can sign transaction uint256 sig = tx.GetHash(); for (size_t i = 0; i < tx.vin.size(); i++) { tx.vin[i].scriptSig = signers[i]->Sign(tx, sig); } // check fee static_cast<CTransaction&>(result) = CTransaction(tx); if (GetTransactionWeight(result) >= MAX_STANDARD_TX_WEIGHT) { throw std::runtime_error(_("Transaction too large")); } // check fee unsigned size = GetVirtualTransactionSize(result); CAmount feeNeeded = CWallet::GetMinimumFee(size, nTxConfirmTarget, mempool); feeNeeded = AdjustFee(feeNeeded, size); // If we made it here and we aren't even able to meet the relay fee on the next pass, give up // because we must be at the maximum allowed fee. if (feeNeeded < minRelayTxFee.GetFee(size)) { throw std::runtime_error(_("Transaction too large for fee policy")); } if (fee >= feeNeeded) { break; } fee = feeNeeded; } if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) { // Lastly, ensure this tx will pass the mempool's chain limits LockPoints lp; CTxMemPoolEntry entry(tx, 0, 0, 0, 0, false, 0, false, 0, lp); CTxMemPool::setEntries setAncestors; size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT); size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000; size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT); size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000; std::string errString; if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) { throw std::runtime_error(_("Transaction has too long of a mempool chain")); } } return result; } CAmount TxBuilder::AdjustFee(CAmount needed, unsigned txSize) { return needed; } <commit_msg>Revert to previous method of count reset should fee be too low in Sigma<commit_after>#include "txbuilder.h" #include "../amount.h" #include "../main.h" #include "../policy/policy.h" #include "../random.h" #include "../script/script.h" #include "../txmempool.h" #include "../uint256.h" #include "../util.h" #include <boost/format.hpp> #include <algorithm> #include <random> #include <stdexcept> #include <string> #include <assert.h> #include <stddef.h> InputSigner::InputSigner() : InputSigner(COutPoint()) { } InputSigner::InputSigner(const COutPoint& output, uint32_t seq) : output(output), sequence(seq) { } InputSigner::~InputSigner() { } TxBuilder::TxBuilder(CWallet& wallet) noexcept : wallet(wallet) { } TxBuilder::~TxBuilder() { } CWalletTx TxBuilder::Build(const std::vector<CRecipient>& recipients, CAmount& fee) { if (recipients.empty()) { throw std::invalid_argument(_("No recipients")); } // calculate total value to spend CAmount spend = 0; unsigned recipientsToSubtractFee = 0; for (size_t i = 0; i < recipients.size(); i++) { auto& recipient = recipients[i]; if (!MoneyRange(recipient.nAmount)) { throw std::invalid_argument(boost::str(boost::format(_("Recipient %1% has invalid amount")) % i)); } spend += recipient.nAmount; if (recipient.fSubtractFeeFromAmount) { recipientsToSubtractFee++; } } CWalletTx result; CMutableTransaction tx; result.fTimeReceivedIsTxTime = true; result.BindWallet(&wallet); // Discourage fee sniping. // // For a large miner the value of the transactions in the best block and // the mempool can exceed the cost of deliberately attempting to mine two // blocks to orphan the current best block. By setting nLockTime such that // only the next block can include the transaction, we discourage this // practice as the height restricted and limited blocksize gives miners // considering fee sniping fewer options for pulling off this attack. // // A simple way to think about this is from the wallet's point of view we // always want the blockchain to move forward. By setting nLockTime this // way we're basically making the statement that we only want this // transaction to appear in the next block; we don't want to potentially // encourage reorgs by allowing transactions to appear at lower heights // than the next block in forks of the best chain. // // Of course, the subsidy is high enough, and transaction volume low // enough, that fee sniping isn't a problem yet, but by implementing a fix // now we ensure code won't be written that makes assumptions about // nLockTime that preclude a fix later. tx.nLockTime = chainActive.Height(); // Secondly occasionally randomly pick a nLockTime even further back, so // that transactions that are delayed after signing for whatever reason, // e.g. high-latency mix networks and some CoinJoin implementations, have // better privacy. if (GetRandInt(10) == 0) { tx.nLockTime = std::max(0, static_cast<int>(tx.nLockTime) - GetRandInt(100)); } assert(tx.nLockTime <= static_cast<unsigned>(chainActive.Height())); assert(tx.nLockTime < LOCKTIME_THRESHOLD); // Start with no fee and loop until there is enough fee; uint32_t nCountLastUsed = zwalletMain->GetCount(); for (fee = payTxFee.GetFeePerK();;) { // In case of not enough fee, reset mint seed counter zwalletMain->SetCount(nCountLastUsed); CAmount required = spend; tx.vin.clear(); tx.vout.clear(); tx.wit.SetNull(); result.fFromMe = true; result.changes.clear(); // If no any recipients to subtract fee then the sender need to pay by themself. if (!recipientsToSubtractFee) { required += fee; } // fill outputs bool remainderSubtracted = false; for (size_t i = 0; i < recipients.size(); i++) { auto& recipient = recipients[i]; CTxOut vout(recipient.nAmount, recipient.scriptPubKey); if (recipient.fSubtractFeeFromAmount) { // Subtract fee equally from each selected recipient. vout.nValue -= fee / recipientsToSubtractFee; if (!remainderSubtracted) { // First receiver pays the remainder not divisible by output count. vout.nValue -= fee % recipientsToSubtractFee; remainderSubtracted = true; } } if (vout.IsDust(minRelayTxFee)) { std::string err; if (recipient.fSubtractFeeFromAmount && fee > 0) { if (vout.nValue < 0) { err = boost::str(boost::format(_("Amount for recipient %1% is too small to pay the fee")) % i); } else { err = boost::str(boost::format(_("Amount for recipient %1% is too small to send after the fee has been deducted")) % i); } } else { err = boost::str(boost::format(_("Amount for recipient %1% is too small")) % i); } throw std::invalid_argument(err); } tx.vout.push_back(vout); } // get inputs std::vector<std::unique_ptr<InputSigner>> signers; CAmount total = GetInputs(signers, required); // add changes CAmount change = total - required; if (change > 0) { // get changes outputs std::vector<CTxOut> changes; fee += GetChanges(changes, change); // shuffle changes to provide some privacy std::vector<std::pair<std::reference_wrapper<CTxOut>, bool>> outputs; outputs.reserve(tx.vout.size() + changes.size()); for (auto& output : tx.vout) { outputs.push_back(std::make_pair(std::ref(output), false)); } for (auto& output : changes) { outputs.push_back(std::make_pair(std::ref(output), true)); } std::shuffle(outputs.begin(), outputs.end(), std::random_device()); // replace outputs with shuffled one std::vector<CTxOut> shuffled; shuffled.reserve(outputs.size()); for (size_t i = 0; i < outputs.size(); i++) { auto& output = outputs[i]; shuffled.push_back(output.first); if (output.second) { result.changes.insert(static_cast<uint32_t>(i)); } } tx.vout = std::move(shuffled); } // fill inputs for (auto& signer : signers) { tx.vin.emplace_back(signer->output, CScript(), signer->sequence); } // now every fields is populated then we can sign transaction uint256 sig = tx.GetHash(); for (size_t i = 0; i < tx.vin.size(); i++) { tx.vin[i].scriptSig = signers[i]->Sign(tx, sig); } // check fee static_cast<CTransaction&>(result) = CTransaction(tx); if (GetTransactionWeight(result) >= MAX_STANDARD_TX_WEIGHT) { throw std::runtime_error(_("Transaction too large")); } // check fee unsigned size = GetVirtualTransactionSize(result); CAmount feeNeeded = CWallet::GetMinimumFee(size, nTxConfirmTarget, mempool); feeNeeded = AdjustFee(feeNeeded, size); // If we made it here and we aren't even able to meet the relay fee on the next pass, give up // because we must be at the maximum allowed fee. if (feeNeeded < minRelayTxFee.GetFee(size)) { throw std::runtime_error(_("Transaction too large for fee policy")); } if (fee >= feeNeeded) { break; } fee = feeNeeded; } if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) { // Lastly, ensure this tx will pass the mempool's chain limits LockPoints lp; CTxMemPoolEntry entry(tx, 0, 0, 0, 0, false, 0, false, 0, lp); CTxMemPool::setEntries setAncestors; size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT); size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000; size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT); size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000; std::string errString; if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) { throw std::runtime_error(_("Transaction has too long of a mempool chain")); } } return result; } CAmount TxBuilder::AdjustFee(CAmount needed, unsigned txSize) { return needed; } <|endoftext|>
<commit_before>#include <websocketpp/config/asio_no_tls.hpp> #include <websocketpp/server.hpp> #include <websocketpp/common/thread.hpp> #include "logger.hpp" #include "protocol.hpp" #include "parser.hpp" #include "util.hpp" #include "server.hpp" using websocketpp::connection_hdl; using websocketpp::lib::placeholders::_1; using websocketpp::lib::placeholders::_2; using websocketpp::lib::bind; using websocketpp::lib::thread; using websocketpp::lib::mutex; using websocketpp::lib::unique_lock; using websocketpp::lib::condition_variable; namespace WAMPP { typedef websocketpp::server<websocketpp::config::asio> WSServer; enum action_type { OPEN, CLOSE, MESSAGE }; struct action { action(action_type t, connection_hdl h) : type(t), hdl(h) {} action(action_type t, connection_hdl h, WSServer::message_ptr m) : type(t), hdl(h), msg(m) {} action_type type; connection_hdl hdl; WSServer::message_ptr msg; }; typedef std::set<connection_hdl,std::owner_less<connection_hdl>> SessionSet; class ServerImpl: public Server { public: ServerImpl(const string& ident); ~ServerImpl(); void run(uint16_t port); void addRPC(string uri, RemoteProc *rpc); bool on_validate(connection_hdl hdl); void on_open(connection_hdl hdl); void on_close(connection_hdl hdl); void on_message(connection_hdl hdl, WSServer::message_ptr msg); void actions_loop(); private: WSServer m_server; shared_ptr<thread> m_actions_thread; SessionSet m_sessions; std::queue<action> m_actions; std::map<string,RemoteProc*> m_rpcs; std::map<string,SessionSet*> m_topics; // Concurrent read/write access to the Server internal lists // is protected by a set of mutexes defined below. // The same pattern is used whenever a member requests access // to one of them. // 1. A lock is acquired at the block level by instantiating a // std::unique_lock: // { // unique_lock<mutex> lock(m_action_lock); // (This call blocks until the mutex is available) // 2. The required operations are performed // ... // 3. The mutex is unlocked when the lock goes out of scope // } mutex m_action_lock; mutex m_session_lock; mutex m_rpc_lock; mutex m_topics_lock; condition_variable m_action_cond; void send(connection_hdl hdl, Message* msg); const string m_ident; }; Server* Server::create(const std::string& ident) { return new ServerImpl(ident); } ServerImpl::ServerImpl(const string& ident): m_ident(ident) { // Initialize Asio Transport m_server.init_asio(); // Register handler callbacks m_server.set_validate_handler(bind(&ServerImpl::on_validate,this,::_1)); m_server.set_open_handler(bind(&ServerImpl::on_open,this,::_1)); m_server.set_close_handler(bind(&ServerImpl::on_close,this,::_1)); m_server.set_message_handler(bind(&ServerImpl::on_message,this,::_1,::_2)); // Start a thread to run the processing loop m_actions_thread.reset(new thread(bind(&ServerImpl::actions_loop,this))); } ServerImpl::~ServerImpl() { // Terminate the actions thread m_actions_thread->join(); } // Run the asio loop (called from main thread) void ServerImpl::run(uint16_t port) { // listen on specified port m_server.listen(port); // Start the server accept loop m_server.start_accept(); // Start the ASIO io_service run loop try { m_server.run(); } catch (const std::exception & e) { LOGGER_WRITE(Logger::DEBUG,e.what()); } catch (websocketpp::lib::error_code e) { LOGGER_WRITE(Logger::DEBUG,e.message()); } catch (...) { LOGGER_WRITE(Logger::DEBUG,"other exception"); } } bool ServerImpl::on_validate(connection_hdl hdl) { bool result = false; WSServer::connection_ptr con = m_server.get_con_from_hdl(hdl); const std::vector<std::string> & subp_requests = con->get_requested_subprotocols(); std::vector<std::string>::const_iterator it; LOGGER_WRITE(Logger::DEBUG,"Requested protocols:"); for (it = subp_requests.begin(); it != subp_requests.end(); ++it) { std::string subprotocol = std::string(*it); LOGGER_WRITE(Logger::DEBUG,subprotocol); if (subprotocol == "wamp") { con->select_subprotocol("wamp"); LOGGER_WRITE(Logger::DEBUG,"Selecting WAMP subprotocol"); result = true; } } return result; } void ServerImpl::on_open(connection_hdl hdl) { unique_lock<mutex> lock(m_action_lock); LOGGER_WRITE(Logger::DEBUG,"on_open"); m_actions.push(action(OPEN,hdl)); lock.unlock(); m_action_cond.notify_one(); } void ServerImpl::on_close(connection_hdl hdl) { unique_lock<mutex> lock(m_action_lock); LOGGER_WRITE(Logger::DEBUG,"on_close"); m_actions.push(action(CLOSE,hdl)); lock.unlock(); m_action_cond.notify_one(); } void ServerImpl::on_message(connection_hdl hdl, WSServer::message_ptr msg) { // queue message up for sending by processing thread unique_lock<mutex> lock(m_action_lock); LOGGER_WRITE(Logger::DEBUG,"on_message"); m_actions.push(action(MESSAGE,hdl,msg)); lock.unlock(); m_action_cond.notify_one(); } void ServerImpl::actions_loop() { while(1) { unique_lock<mutex> lock(m_action_lock); while(m_actions.empty()) { m_action_cond.wait(lock); } action a = m_actions.front(); m_actions.pop(); lock.unlock(); if (a.type == OPEN) { string sessionId = genRandomId(16); Welcome welcome(sessionId,WAMPP_PROTOCOL_VERSION,m_ident); unique_lock<mutex> lock(m_session_lock); m_sessions.insert(a.hdl); send(a.hdl,&welcome); } else if (a.type == CLOSE) { unique_lock<mutex> lock(m_session_lock); m_sessions.erase(a.hdl); } else if (a.type == MESSAGE) { unique_lock<mutex> lock(m_session_lock); Message* wamp_msg = parseMessage(a.msg->get_payload()); if (wamp_msg) { switch (wamp_msg->getType()) { case WELCOME: case CALLRESULT: case CALLERROR: case EVENT: { LOGGER_WRITE(Logger::ERROR,"Ignoring Server to Client message"); delete wamp_msg; break; } case CALL: { string callID = ((Call *)wamp_msg)->callID(); string procURI = ((Call *)wamp_msg)->procURI(); unique_lock<mutex> lock(m_rpc_lock); std::map<string,RemoteProc*>::iterator it = m_rpcs.find(procURI); if(it != m_rpcs.end()) { // Call RPC JSON::NodePtr result; if (it->second->invoke(callID, ((Call *)wamp_msg)->args(), result)) { CallResult response(callID,result); send(a.hdl,&response); } else { CallError error(callID, "wampp:call-error", "The remote procedure call failed (see error details)", result); send(a.hdl,&error); } } else { JSON::NodePtr errorDetails(new JSON::Node(procURI)); CallError error(callID, "wampp:no-such-method", "No such method", errorDetails); send(a.hdl,&error); } break; } case SUBSCRIBE: { string topicURI = ((Subscribe *)wamp_msg)->topicURI(); unique_lock<mutex> lock(m_topics_lock); std::map<string,SessionSet*>::iterator it = m_topics.find(topicURI); SessionSet* subscribers; if (it == m_topics.end()) { SessionSet* subscribers = new SessionSet(); m_topics.insert(std::make_pair(topicURI,subscribers)); } else { subscribers = it->second; } subscribers->insert(a.hdl); break; } case UNSUBSCRIBE: { string topicURI = ((UnSubscribe *)wamp_msg)->topicURI(); unique_lock<mutex> lock(m_topics_lock); std::map<string,SessionSet*>::iterator it = m_topics.find(topicURI); if (it != m_topics.end()) { SessionSet* subscribers = it->second; subscribers->erase(a.hdl); if (subscribers->empty()) { m_topics.erase(it); delete(subscribers); } } } default: break; } delete wamp_msg; } } else { // undefined. } } } void ServerImpl::send(connection_hdl hdl, Message* msg) { std::ostringstream oss; msg->serialize(oss); m_server.send(hdl,oss.str(),websocketpp::frame::opcode::text); } void ServerImpl::addRPC(string uri, RemoteProc* rpc) { unique_lock<mutex> lock(m_rpc_lock); m_rpcs.insert(std::make_pair(uri,rpc)); } } // namespace WAMPP <commit_msg>server: Thread-safe subscriptions and stupid bug<commit_after>#include <websocketpp/config/asio_no_tls.hpp> #include <websocketpp/server.hpp> #include <websocketpp/common/thread.hpp> #include "logger.hpp" #include "protocol.hpp" #include "parser.hpp" #include "util.hpp" #include "server.hpp" using websocketpp::connection_hdl; using websocketpp::lib::placeholders::_1; using websocketpp::lib::placeholders::_2; using websocketpp::lib::bind; using websocketpp::lib::thread; using websocketpp::lib::mutex; using websocketpp::lib::unique_lock; using websocketpp::lib::condition_variable; namespace WAMPP { typedef websocketpp::server<websocketpp::config::asio> WSServer; enum action_type { OPEN, CLOSE, MESSAGE }; struct action { action(action_type t, connection_hdl h) : type(t), hdl(h) {} action(action_type t, connection_hdl h, WSServer::message_ptr m) : type(t), hdl(h), msg(m) {} action_type type; connection_hdl hdl; WSServer::message_ptr msg; }; typedef std::set<connection_hdl,std::owner_less<connection_hdl>> ConnList; struct SessionSet { mutex m_lock; ConnList m_cnxs; }; class ServerImpl: public Server { public: ServerImpl(const string& ident); ~ServerImpl(); void run(uint16_t port); void addRPC(string uri, RemoteProc *rpc); bool on_validate(connection_hdl hdl); void on_open(connection_hdl hdl); void on_close(connection_hdl hdl); void on_message(connection_hdl hdl, WSServer::message_ptr msg); void actions_loop(); private: WSServer m_server; shared_ptr<thread> m_actions_thread; SessionSet m_sessions; std::queue<action> m_actions; std::map<string,RemoteProc*> m_rpcs; std::map<string,SessionSet*> m_topics; // Concurrent read/write access to the Server internal lists // is protected by a set of mutexes defined below. // The same pattern is used whenever a member requests access // to one of them. // 1. A lock is acquired at the block level by instantiating a // std::unique_lock: // { // unique_lock<mutex> lock(m_action_lock); // (This call blocks until the mutex is available) // 2. The required operations are performed // ... // 3. The mutex is unlocked when the lock goes out of scope // } mutex m_action_lock; mutex m_rpc_lock; mutex m_topics_lock; condition_variable m_action_cond; void send(connection_hdl hdl, Message* msg); const string m_ident; }; Server* Server::create(const std::string& ident) { return new ServerImpl(ident); } ServerImpl::ServerImpl(const string& ident): m_ident(ident) { // Initialize Asio Transport m_server.init_asio(); // Register handler callbacks m_server.set_validate_handler(bind(&ServerImpl::on_validate,this,::_1)); m_server.set_open_handler(bind(&ServerImpl::on_open,this,::_1)); m_server.set_close_handler(bind(&ServerImpl::on_close,this,::_1)); m_server.set_message_handler(bind(&ServerImpl::on_message,this,::_1,::_2)); // Start a thread to run the processing loop m_actions_thread.reset(new thread(bind(&ServerImpl::actions_loop,this))); } ServerImpl::~ServerImpl() { // Terminate the actions thread m_actions_thread->join(); } // Run the asio loop (called from main thread) void ServerImpl::run(uint16_t port) { // listen on specified port m_server.listen(port); // Start the server accept loop m_server.start_accept(); // Start the ASIO io_service run loop try { m_server.run(); } catch (const std::exception & e) { LOGGER_WRITE(Logger::DEBUG,e.what()); } catch (websocketpp::lib::error_code e) { LOGGER_WRITE(Logger::DEBUG,e.message()); } catch (...) { LOGGER_WRITE(Logger::DEBUG,"other exception"); } } bool ServerImpl::on_validate(connection_hdl hdl) { bool result = false; WSServer::connection_ptr con = m_server.get_con_from_hdl(hdl); const std::vector<std::string> & subp_requests = con->get_requested_subprotocols(); std::vector<std::string>::const_iterator it; LOGGER_WRITE(Logger::DEBUG,"Requested protocols:"); for (it = subp_requests.begin(); it != subp_requests.end(); ++it) { std::string subprotocol = std::string(*it); LOGGER_WRITE(Logger::DEBUG,subprotocol); if (subprotocol == "wamp") { con->select_subprotocol("wamp"); LOGGER_WRITE(Logger::DEBUG,"Selecting WAMP subprotocol"); result = true; } } return result; } void ServerImpl::on_open(connection_hdl hdl) { unique_lock<mutex> lock(m_action_lock); LOGGER_WRITE(Logger::DEBUG,"on_open"); m_actions.push(action(OPEN,hdl)); lock.unlock(); m_action_cond.notify_one(); } void ServerImpl::on_close(connection_hdl hdl) { unique_lock<mutex> lock(m_action_lock); LOGGER_WRITE(Logger::DEBUG,"on_close"); m_actions.push(action(CLOSE,hdl)); lock.unlock(); m_action_cond.notify_one(); } void ServerImpl::on_message(connection_hdl hdl, WSServer::message_ptr msg) { // queue message up for sending by processing thread unique_lock<mutex> lock(m_action_lock); LOGGER_WRITE(Logger::DEBUG,"on_message"); m_actions.push(action(MESSAGE,hdl,msg)); lock.unlock(); m_action_cond.notify_one(); } void ServerImpl::actions_loop() { while(1) { unique_lock<mutex> lock(m_action_lock); while(m_actions.empty()) { m_action_cond.wait(lock); } action a = m_actions.front(); m_actions.pop(); lock.unlock(); if (a.type == OPEN) { string sessionId = genRandomId(16); Welcome welcome(sessionId,WAMPP_PROTOCOL_VERSION,m_ident); unique_lock<mutex> sesslock(m_sessions.m_lock); m_sessions.m_cnxs.insert(a.hdl); send(a.hdl,&welcome); } else if (a.type == CLOSE) { unique_lock<mutex> sesslock(m_sessions.m_lock); m_sessions.m_cnxs.erase(a.hdl); } else if (a.type == MESSAGE) { unique_lock<mutex> sesslock(m_sessions.m_lock); Message* wamp_msg = parseMessage(a.msg->get_payload()); if (wamp_msg) { switch (wamp_msg->getType()) { case WELCOME: case CALLRESULT: case CALLERROR: case EVENT: { LOGGER_WRITE(Logger::ERROR,"Ignoring Server to Client message"); delete wamp_msg; break; } case CALL: { string callID = ((Call *)wamp_msg)->callID(); string procURI = ((Call *)wamp_msg)->procURI(); unique_lock<mutex> rpclock(m_rpc_lock); std::map<string,RemoteProc*>::iterator it = m_rpcs.find(procURI); if(it != m_rpcs.end()) { // Call RPC JSON::NodePtr result; if (it->second->invoke(callID, ((Call *)wamp_msg)->args(), result)) { CallResult response(callID,result); send(a.hdl,&response); } else { CallError error(callID, "wampp:call-error", "The remote procedure call failed (see error details)", result); send(a.hdl,&error); } } else { JSON::NodePtr errorDetails(new JSON::Node(procURI)); CallError error(callID, "wampp:no-such-method", "No such method", errorDetails); send(a.hdl,&error); } break; } case SUBSCRIBE: { string topicURI = ((Subscribe *)wamp_msg)->topicURI(); unique_lock<mutex> topicslock(m_topics_lock); std::map<string,SessionSet*>::iterator it = m_topics.find(topicURI); SessionSet* subscribers; if (it == m_topics.end()) { subscribers = new SessionSet(); m_topics.insert(std::make_pair(topicURI,subscribers)); } else { subscribers = it->second; } unique_lock<mutex> subslock(subscribers->m_lock); subscribers->m_cnxs.insert(a.hdl); break; } case UNSUBSCRIBE: { string topicURI = ((UnSubscribe *)wamp_msg)->topicURI(); unique_lock<mutex> lock(m_topics_lock); std::map<string,SessionSet*>::iterator it = m_topics.find(topicURI); if (it != m_topics.end()) { SessionSet* subscribers = it->second; unique_lock<mutex> subslock(subscribers->m_lock); subscribers->m_cnxs.erase(a.hdl); if (subscribers->m_cnxs.empty()) { m_topics.erase(it); delete(subscribers); } } } default: break; } delete wamp_msg; } } else { // undefined. } } } void ServerImpl::send(connection_hdl hdl, Message* msg) { std::ostringstream oss; msg->serialize(oss); m_server.send(hdl,oss.str(),websocketpp::frame::opcode::text); } void ServerImpl::addRPC(string uri, RemoteProc* rpc) { unique_lock<mutex> lock(m_rpc_lock); m_rpcs.insert(std::make_pair(uri,rpc)); } } // namespace WAMPP <|endoftext|>
<commit_before>/* Copyright (c) 2010, The Mineserver Project 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 The Mineserver Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 <cstdlib> #include <cstdio> #include <iostream> #include "../logger.h" #include "../constants.h" #include "../tools.h" #include "../map.h" #include "../config.h" #include "mersenne.h" // libnoise #ifdef DEBIAN #include <libnoise/noise.h> #else #include <noise/noise.h> #endif #include "cavegen.h" void CaveGen::init(int seed) { // Set up us the Perlin-noise module. caveNoise1.SetSeed (seed); caveNoise1.SetFrequency (1.5/20); //caveNoise.SetLacunarity (0.5); caveNoise1.SetOctaveCount (2); caveNoise1.SetNoiseQuality (noise::QUALITY_STD); // Set up us the Perlin-noise module. caveNoise2.SetSeed (seed+2); caveNoise2.SetFrequency (1.5/20); //caveNoise.SetLacunarity (0.5); caveNoise2.SetOctaveCount (2); caveNoise2.SetNoiseQuality (noise::QUALITY_STD); caveScale = 0.9; addCaves = Conf::get()->bValue("add_caves"); caveDensity = Conf::get()->iValue("cave_density"); caveSize = Conf::get()->iValue("cave_size"); addCaveLava = Conf::get()->bValue("cave_lava"); addCaveWater = Conf::get()->bValue("cave_water"); addOre = Conf::get()->bValue("cave_ore"); seaLevel = Conf::get()->iValue("sea_level"); } void CaveGen::AddCaves(uint8 &block, double x, double y, double z) { if(addCaves) { x *= caveScale; z *= caveScale; caveN2 = caveNoise2.GetValue(x,y,z); if(caveN2 > 0.45 && block != BLOCK_WATER && block != BLOCK_STATIONARY_WATER) { // Add bottomlava if(y < 10.0) { block = BLOCK_STATIONARY_LAVA; return; } block = BLOCK_AIR; return; } if(y < 60) { caveN1 = caveNoise1.GetValue(x,y,z); if(caveN1 > 0.56) { if(y < 32.0 && caveN1 > 0.67) { if(y < 16.0 && caveN1 > 0.79) { block = BLOCK_DIAMOND_ORE; return; } block = BLOCK_GOLD_ORE; return; } block = BLOCK_IRON_ORE; } return; } } } <commit_msg>cave_lava and cave_ore settings actually do something now<commit_after>/* Copyright (c) 2010, The Mineserver Project 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 The Mineserver Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 <cstdlib> #include <cstdio> #include <iostream> #include "../logger.h" #include "../constants.h" #include "../tools.h" #include "../map.h" #include "../config.h" #include "mersenne.h" // libnoise #ifdef DEBIAN #include <libnoise/noise.h> #else #include <noise/noise.h> #endif #include "cavegen.h" void CaveGen::init(int seed) { // Set up us the Perlin-noise module. caveNoise1.SetSeed (seed); caveNoise1.SetFrequency (1.5/20); //caveNoise.SetLacunarity (0.5); caveNoise1.SetOctaveCount (2); caveNoise1.SetNoiseQuality (noise::QUALITY_STD); // Set up us the Perlin-noise module. caveNoise2.SetSeed (seed+2); caveNoise2.SetFrequency (1.5/20); //caveNoise.SetLacunarity (0.5); caveNoise2.SetOctaveCount (2); caveNoise2.SetNoiseQuality (noise::QUALITY_STD); caveScale = 0.9; addCaves = Conf::get()->bValue("add_caves"); caveDensity = Conf::get()->iValue("cave_density"); caveSize = Conf::get()->iValue("cave_size"); addCaveLava = Conf::get()->bValue("cave_lava"); addCaveWater = Conf::get()->bValue("cave_water"); addOre = Conf::get()->bValue("cave_ore"); seaLevel = Conf::get()->iValue("sea_level"); } void CaveGen::AddCaves(uint8 &block, double x, double y, double z) { if(addCaves) { x *= caveScale; z *= caveScale; caveN2 = caveNoise2.GetValue(x,y,z); if(caveN2 > 0.45 && block != BLOCK_WATER && block != BLOCK_STATIONARY_WATER) { // Add bottomlava if(y < 10.0 && addCaveLava) { block = BLOCK_STATIONARY_LAVA; return; } block = BLOCK_AIR; return; } if(y < 60 && addOre) { caveN1 = caveNoise1.GetValue(x,y,z); if(caveN1 > 0.56) { if(y < 32.0 && caveN1 > 0.67) { if(y < 16.0 && caveN1 > 0.79) { block = BLOCK_DIAMOND_ORE; return; } block = BLOCK_GOLD_ORE; return; } block = BLOCK_IRON_ORE; } return; } } } <|endoftext|>
<commit_before>#include <x0/http/HttpCore.h> #include <x0/http/HttpCore.h> #include <x0/DateTime.h> #include <x0/Settings.h> #include <x0/Scope.h> #include <x0/Logger.h> #include <sys/resource.h> #include <sys/time.h> namespace x0 { inline bool _contains(const std::map<int, std::map<std::string, std::function<bool(const SettingsValue&, Scope&)>>>& map, const std::string& cvar) { for (auto pi = map.begin(), pe = map.end(); pi != pe; ++pi) for (auto ci = pi->second.begin(), ce = pi->second.end(); ci != ce; ++ci) if (ci->first == cvar) return true; return false; } inline bool _contains(const std::vector<std::string>& list, const std::string& var) { for (auto i = list.begin(), e = list.end(); i != e; ++i) if (*i == var) return true; return false; } HttpCore::HttpCore(HttpServer& server) : HttpPlugin(server, "core"), max_fds(std::bind(&HttpCore::getrlimit, this, RLIMIT_CORE), std::bind(&HttpCore::setrlimit, this, RLIMIT_NOFILE, std::placeholders::_1)) { // register cvars declareCVar("Log", HttpContext::server, &HttpCore::setup_logging); declareCVar("Resources", HttpContext::server, &HttpCore::setup_resources); declareCVar("Plugins", HttpContext::server, &HttpCore::setup_modules); declareCVar("ErrorDocuments", HttpContext::server, &HttpCore::setup_error_documents); declareCVar("FileInfo", HttpContext::server, &HttpCore::setup_fileinfo); declareCVar("Hosts", HttpContext::server, &HttpCore::setup_hosts); declareCVar("Advertise", HttpContext::server, &HttpCore::setup_advertise); } HttpCore::~HttpCore() { } static inline const char *rc2str(int resource) { switch (resource) { case RLIMIT_CORE: return "core"; case RLIMIT_AS: return "address-space"; case RLIMIT_NOFILE: return "filedes"; default: return "unknown"; } } long long HttpCore::getrlimit(int resource) { struct rlimit rlim; if (::getrlimit(resource, &rlim) == -1) { server().log(Severity::warn, "Failed to retrieve current resource limit on %s (%d).", rc2str(resource), resource); return 0; } return rlim.rlim_cur; } long long HttpCore::setrlimit(int resource, long long value) { struct rlimit rlim; if (::getrlimit(resource, &rlim) == -1) { server().log(Severity::warn, "Failed to retrieve current resource limit on %s.", rc2str(resource), resource); return 0; } long long last = rlim.rlim_cur; // patch against human readable form long long hlast = last, hvalue = value; switch (resource) { case RLIMIT_AS: case RLIMIT_CORE: hlast /= 1024 / 1024; value *= 1024 * 1024; break; default: break; } rlim.rlim_cur = value; rlim.rlim_max = value; if (::setrlimit(resource, &rlim) == -1) { server().log(Severity::warn, "Failed to set resource limit on %s from %lld to %lld.", rc2str(resource), hlast, hvalue); return 0; } debug(1, "Set resource limit on %s from %lld to %lld.", rc2str(resource), hlast, hvalue); return value; } bool HttpCore::setup_logging(const SettingsValue& cvar, Scope& s) { std::string logmode(cvar["Mode"].as<std::string>()); auto nowfn = std::bind(&DateTime::htlog_str, &server().now_); if (logmode == "file") server().logger_.reset(new FileLogger<decltype(nowfn)>(cvar["FileName"].as<std::string>(), nowfn)); else if (logmode == "null") server().logger_.reset(new NullLogger()); else if (logmode == "stderr") server().logger_.reset(new FileLogger<decltype(nowfn)>("/dev/stderr", nowfn)); else //! \todo add syslog logger server().logger_.reset(new NullLogger()); server().logger_->level(Severity(cvar["Level"].as<std::string>())); cvar["Colorize"].load(server().colored_log_); return true; } bool HttpCore::setup_modules(const SettingsValue& cvar, Scope& s) { std::vector<std::string> list; cvar["Load"].load(list); for (auto i = list.begin(), e = list.end(); i != e; ++i) server().loadPlugin(*i); return true; } bool HttpCore::setup_resources(const SettingsValue& cvar, Scope& s) { cvar["MaxConnections"].load(server().max_connections); cvar["MaxKeepAliveIdle"].load(server().max_keep_alive_idle); cvar["MaxReadIdle"].load(server().max_read_idle); cvar["MaxWriteIdle"].load(server().max_write_idle); cvar["TCP_CORK"].load(server().tcp_cork); cvar["TCP_NODELAY"].load(server().tcp_nodelay); long long value = 0; if (cvar["MaxFiles"].load(value)) setrlimit(RLIMIT_NOFILE, value); if (cvar["MaxAddressSpace"].load(value)) setrlimit(RLIMIT_AS, value); if (cvar["MaxCoreFileSize"].load(value)) setrlimit(RLIMIT_CORE, value); return true; } bool HttpCore::setup_hosts(const SettingsValue& cvar, Scope& s) { std::vector<std::string> hostids = cvar.keys<std::string>(); for (auto i = hostids.begin(), e = hostids.end(); i != e; ++i) { std::string hostid = *i; auto host_cvars = cvar[hostid].keys<std::string>(); // handle all vhost-directives for (auto pi = server().cvars_host_.begin(), pe = server().cvars_host_.end(); pi != pe; ++pi) { for (auto ci = pi->second.begin(), ce = pi->second.end(); ci != ce; ++ci) { if (cvar[hostid].contains(ci->first)) { //debug(1, "CVAR_HOST(%s): %s", hostid.c_str(), ci->first.c_str()); ci->second(cvar[hostid][ci->first], server().host(hostid)); } } } // handle all path scopes for (auto vi = host_cvars.begin(), ve = host_cvars.end(); vi != ve; ++vi) { std::string path = *vi; if (path[0] == '/') { std::vector<std::string> keys = cvar[hostid][path].keys<std::string>(); for (auto pi = server().cvars_path_.begin(), pe = server().cvars_path_.end(); pi != pe; ++pi) for (auto ci = pi->second.begin(), ce = pi->second.end(); ci != ce; ++ci) if (_contains(keys, ci->first)) ;//! \todo ci->second(cvar[hostid][path], vhost(hostid).location(path)); for (auto ki = keys.begin(), ke = keys.end(); ki != ke; ++ki) if (!_contains(server().cvars_path_, *ki)) server().log(Severity::error, "Unknown location-context variable: '%s'", ki->c_str()); } } } return true; } bool HttpCore::setup_fileinfo(const SettingsValue& cvar, Scope& s) { std::string value; if (cvar["MimeType"]["MimeFile"].load(value)) server().fileinfo.load_mimetypes(value); if (cvar["MimeType"]["DefaultType"].load(value)) server().fileinfo.default_mimetype(value); bool flag = false; if (cvar["ETag"]["ConsiderMtime"].load(flag)) server().fileinfo.etag_consider_mtime(flag); if (cvar["ETag"]["ConsiderSize"].load(flag)) server().fileinfo.etag_consider_size(flag); if (cvar["ETag"]["ConsiderInode"].load(flag)) server().fileinfo.etag_consider_inode(flag); return true; } // ErrorDocuments = array of [pair<code, path>] bool HttpCore::setup_error_documents(const SettingsValue& cvar, Scope& s) { return true; //! \todo } // Advertise = BOOLEAN bool HttpCore::setup_advertise(const SettingsValue& cvar, Scope& s) { return cvar.load(server().advertise); } } // namespace x0 <commit_msg>fixes cvar evaluation priorities<commit_after>#include <x0/http/HttpCore.h> #include <x0/http/HttpCore.h> #include <x0/DateTime.h> #include <x0/Settings.h> #include <x0/Scope.h> #include <x0/Logger.h> #include <sys/resource.h> #include <sys/time.h> namespace x0 { inline bool _contains(const std::map<int, std::map<std::string, std::function<bool(const SettingsValue&, Scope&)>>>& map, const std::string& cvar) { for (auto pi = map.begin(), pe = map.end(); pi != pe; ++pi) for (auto ci = pi->second.begin(), ce = pi->second.end(); ci != ce; ++ci) if (ci->first == cvar) return true; return false; } inline bool _contains(const std::vector<std::string>& list, const std::string& var) { for (auto i = list.begin(), e = list.end(); i != e; ++i) if (*i == var) return true; return false; } HttpCore::HttpCore(HttpServer& server) : HttpPlugin(server, "core"), max_fds(std::bind(&HttpCore::getrlimit, this, RLIMIT_CORE), std::bind(&HttpCore::setrlimit, this, RLIMIT_NOFILE, std::placeholders::_1)) { // register cvars declareCVar("Log", HttpContext::server, &HttpCore::setup_logging, -7); declareCVar("Resources", HttpContext::server, &HttpCore::setup_resources, -6); declareCVar("Plugins", HttpContext::server, &HttpCore::setup_modules, -5); declareCVar("ErrorDocuments", HttpContext::server, &HttpCore::setup_error_documents, -4); declareCVar("FileInfo", HttpContext::server, &HttpCore::setup_fileinfo, -4); declareCVar("Hosts", HttpContext::server, &HttpCore::setup_hosts, -3); declareCVar("Advertise", HttpContext::server, &HttpCore::setup_advertise, -2); } HttpCore::~HttpCore() { } static inline const char *rc2str(int resource) { switch (resource) { case RLIMIT_CORE: return "core"; case RLIMIT_AS: return "address-space"; case RLIMIT_NOFILE: return "filedes"; default: return "unknown"; } } long long HttpCore::getrlimit(int resource) { struct rlimit rlim; if (::getrlimit(resource, &rlim) == -1) { server().log(Severity::warn, "Failed to retrieve current resource limit on %s (%d).", rc2str(resource), resource); return 0; } return rlim.rlim_cur; } long long HttpCore::setrlimit(int resource, long long value) { struct rlimit rlim; if (::getrlimit(resource, &rlim) == -1) { server().log(Severity::warn, "Failed to retrieve current resource limit on %s.", rc2str(resource), resource); return 0; } long long last = rlim.rlim_cur; // patch against human readable form long long hlast = last, hvalue = value; switch (resource) { case RLIMIT_AS: case RLIMIT_CORE: hlast /= 1024 / 1024; value *= 1024 * 1024; break; default: break; } rlim.rlim_cur = value; rlim.rlim_max = value; if (::setrlimit(resource, &rlim) == -1) { server().log(Severity::warn, "Failed to set resource limit on %s from %lld to %lld.", rc2str(resource), hlast, hvalue); return 0; } debug(1, "Set resource limit on %s from %lld to %lld.", rc2str(resource), hlast, hvalue); return value; } bool HttpCore::setup_logging(const SettingsValue& cvar, Scope& s) { std::string logmode(cvar["Mode"].as<std::string>()); auto nowfn = std::bind(&DateTime::htlog_str, &server().now_); if (logmode == "file") server().logger_.reset(new FileLogger<decltype(nowfn)>(cvar["FileName"].as<std::string>(), nowfn)); else if (logmode == "null") server().logger_.reset(new NullLogger()); else if (logmode == "stderr") server().logger_.reset(new FileLogger<decltype(nowfn)>("/dev/stderr", nowfn)); else //! \todo add syslog logger server().logger_.reset(new NullLogger()); server().logger_->level(Severity(cvar["Level"].as<std::string>())); cvar["Colorize"].load(server().colored_log_); return true; } bool HttpCore::setup_modules(const SettingsValue& cvar, Scope& s) { std::vector<std::string> list; cvar["Load"].load(list); for (auto i = list.begin(), e = list.end(); i != e; ++i) server().loadPlugin(*i); return true; } bool HttpCore::setup_resources(const SettingsValue& cvar, Scope& s) { cvar["MaxConnections"].load(server().max_connections); cvar["MaxKeepAliveIdle"].load(server().max_keep_alive_idle); cvar["MaxReadIdle"].load(server().max_read_idle); cvar["MaxWriteIdle"].load(server().max_write_idle); cvar["TCP_CORK"].load(server().tcp_cork); cvar["TCP_NODELAY"].load(server().tcp_nodelay); long long value = 0; if (cvar["MaxFiles"].load(value)) setrlimit(RLIMIT_NOFILE, value); if (cvar["MaxAddressSpace"].load(value)) setrlimit(RLIMIT_AS, value); if (cvar["MaxCoreFileSize"].load(value)) setrlimit(RLIMIT_CORE, value); return true; } bool HttpCore::setup_hosts(const SettingsValue& cvar, Scope& s) { std::vector<std::string> hostids = cvar.keys<std::string>(); for (auto i = hostids.begin(), e = hostids.end(); i != e; ++i) { std::string hostid = *i; auto host_cvars = cvar[hostid].keys<std::string>(); // handle all vhost-directives for (auto pi = server().cvars_host_.begin(), pe = server().cvars_host_.end(); pi != pe; ++pi) { for (auto ci = pi->second.begin(), ce = pi->second.end(); ci != ce; ++ci) { if (cvar[hostid].contains(ci->first)) { //debug(1, "CVAR_HOST(%s): %s", hostid.c_str(), ci->first.c_str()); ci->second(cvar[hostid][ci->first], server().host(hostid)); } } } // handle all path scopes for (auto vi = host_cvars.begin(), ve = host_cvars.end(); vi != ve; ++vi) { std::string path = *vi; if (path[0] == '/') { std::vector<std::string> keys = cvar[hostid][path].keys<std::string>(); for (auto pi = server().cvars_path_.begin(), pe = server().cvars_path_.end(); pi != pe; ++pi) for (auto ci = pi->second.begin(), ce = pi->second.end(); ci != ce; ++ci) if (_contains(keys, ci->first)) ;//! \todo ci->second(cvar[hostid][path], vhost(hostid).location(path)); for (auto ki = keys.begin(), ke = keys.end(); ki != ke; ++ki) if (!_contains(server().cvars_path_, *ki)) server().log(Severity::error, "Unknown location-context variable: '%s'", ki->c_str()); } } } return true; } bool HttpCore::setup_fileinfo(const SettingsValue& cvar, Scope& s) { std::string value; if (cvar["MimeType"]["MimeFile"].load(value)) server().fileinfo.load_mimetypes(value); if (cvar["MimeType"]["DefaultType"].load(value)) server().fileinfo.default_mimetype(value); bool flag = false; if (cvar["ETag"]["ConsiderMtime"].load(flag)) server().fileinfo.etag_consider_mtime(flag); if (cvar["ETag"]["ConsiderSize"].load(flag)) server().fileinfo.etag_consider_size(flag); if (cvar["ETag"]["ConsiderInode"].load(flag)) server().fileinfo.etag_consider_inode(flag); return true; } // ErrorDocuments = array of [pair<code, path>] bool HttpCore::setup_error_documents(const SettingsValue& cvar, Scope& s) { return true; //! \todo } // Advertise = BOOLEAN bool HttpCore::setup_advertise(const SettingsValue& cvar, Scope& s) { return cvar.load(server().advertise); } } // namespace x0 <|endoftext|>
<commit_before>/** * Copyright 2008 Matthew Graham * 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 <testpp/test.h> #include "default_output.h" #include <memory> #include <algorithm> #include <ctime> testpp_c::testpp_c() : m_result( NULL ) {} void testpp_c::set_result( testpp_result_c &result ) { m_result = &result; } void testpp_c::not_implemented() { m_result->set_test_not_implemented(); } void testpp_c::not_implemented( short year, short month, short day ) { if ( is_before( year, month, day ) ) { m_result->set_test_not_implemented(); } m_result->fail( "not implemented" ); } void testpp_c::ignore_until( short year, short month, short day ) { if ( is_before( year, month, day ) ) { m_result->set_ignore_failures(); } } bool testpp_c::is_before( short year, short month, short day ) { tm t = { 0 }; t.tm_year = year - 1900; t.tm_mon = month - 1; t.tm_mday = day; t.tm_isdst = -1; time_t then( mktime( &t ) ); time_t now( time( NULL ) ); return ( now < then ); } void testpp_c::fail( const std::string &msg, const char *filename, int line ) { m_result->fail( msg, filename, line ); } testpp_set_c::~testpp_set_c() { std::list< testpp_type_i * >::iterator it; for ( it=m_tests.begin(); it!=m_tests.end(); ++it ) { delete *it; } m_tests.clear(); m_files.clear(); m_suites.clear(); } void testpp_set_c::run_test( testpp_c & test, testpp_result_c &result ) { test.set_result( result ); try { test.setup(); test.test(); test.teardown(); } catch (...) { std::cerr << "catch...\n"; } } void testpp_set_c::run( testpp_output_i &out ) { std::list< testpp_type_i * >::const_iterator it; int passed( 0 ); int failed( 0 ); int ignored( 0 ); int not_implemented( 0 ); for ( it=m_tests.begin(); it!=m_tests.end(); ++it ) { testpp_type_i &type( **it ); out.begin( type.id() ); std::auto_ptr< testpp_c > test( type.create_test() ); testpp_result_c result; run_test( *test, result ); if ( result.failure() ) { ++failed; } else if ( result.ignore_failures() ) { ++ignored; } else if ( result.test_not_implemented() ) { ++not_implemented; } else { ++passed; } out.complete( type.id(), result ); } out.summarize( passed, failed, ignored, not_implemented ); } void testpp_set_c::run( testpp_output_i &out, const std::string &test_name ) { std::list< testpp_type_i * >::iterator it; int passed( 0 ); int failed( 0 ); int ignored( 0 ); int not_implemented( 0 ); for ( it=m_tests.begin(); it!=m_tests.end(); ++it ) { if ( ! (*it)->id().in_suite( test_name ) ) { continue; } out.begin( (*it)->id() ); std::auto_ptr< testpp_c > test( (*it)->create_test() ); testpp_result_c result; run_test( *test, result ); if ( result.failure() ) { ++failed; } else if ( result.ignore_failures() ) { ++ignored; } else if ( result.test_not_implemented() ) { ++not_implemented; } else { ++passed; } out.complete( (*it)->id(), result ); } out.summarize( passed, failed, ignored, not_implemented ); } testpp_set_c & testpp_tests() { static testpp_set_c static_set; return static_set; } <commit_msg>fixed a bug so the not_implemented() function doesn't fail if before the given date.<commit_after>/** * Copyright 2008 Matthew Graham * 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 <testpp/test.h> #include "default_output.h" #include <memory> #include <algorithm> #include <ctime> testpp_c::testpp_c() : m_result( NULL ) {} void testpp_c::set_result( testpp_result_c &result ) { m_result = &result; } void testpp_c::not_implemented() { m_result->set_test_not_implemented(); } void testpp_c::not_implemented( short year, short month, short day ) { if ( is_before( year, month, day ) ) { m_result->set_test_not_implemented(); } else { m_result->fail( "not implemented" ); } } void testpp_c::ignore_until( short year, short month, short day ) { if ( is_before( year, month, day ) ) { m_result->set_ignore_failures(); } } bool testpp_c::is_before( short year, short month, short day ) { tm t = { 0 }; t.tm_year = year - 1900; t.tm_mon = month - 1; t.tm_mday = day; t.tm_isdst = -1; time_t then( mktime( &t ) ); time_t now( time( NULL ) ); return ( now < then ); } void testpp_c::fail( const std::string &msg, const char *filename, int line ) { m_result->fail( msg, filename, line ); } testpp_set_c::~testpp_set_c() { std::list< testpp_type_i * >::iterator it; for ( it=m_tests.begin(); it!=m_tests.end(); ++it ) { delete *it; } m_tests.clear(); m_files.clear(); m_suites.clear(); } void testpp_set_c::run_test( testpp_c & test, testpp_result_c &result ) { test.set_result( result ); try { test.setup(); test.test(); test.teardown(); } catch (...) { std::cerr << "catch...\n"; } } void testpp_set_c::run( testpp_output_i &out ) { std::list< testpp_type_i * >::const_iterator it; int passed( 0 ); int failed( 0 ); int ignored( 0 ); int not_implemented( 0 ); for ( it=m_tests.begin(); it!=m_tests.end(); ++it ) { testpp_type_i &type( **it ); out.begin( type.id() ); std::auto_ptr< testpp_c > test( type.create_test() ); testpp_result_c result; run_test( *test, result ); if ( result.failure() ) { ++failed; } else if ( result.ignore_failures() ) { ++ignored; } else if ( result.test_not_implemented() ) { ++not_implemented; } else { ++passed; } out.complete( type.id(), result ); } out.summarize( passed, failed, ignored, not_implemented ); } void testpp_set_c::run( testpp_output_i &out, const std::string &test_name ) { std::list< testpp_type_i * >::iterator it; int passed( 0 ); int failed( 0 ); int ignored( 0 ); int not_implemented( 0 ); for ( it=m_tests.begin(); it!=m_tests.end(); ++it ) { if ( ! (*it)->id().in_suite( test_name ) ) { continue; } out.begin( (*it)->id() ); std::auto_ptr< testpp_c > test( (*it)->create_test() ); testpp_result_c result; run_test( *test, result ); if ( result.failure() ) { ++failed; } else if ( result.ignore_failures() ) { ++ignored; } else if ( result.test_not_implemented() ) { ++not_implemented; } else { ++passed; } out.complete( (*it)->id(), result ); } out.summarize( passed, failed, ignored, not_implemented ); } testpp_set_c & testpp_tests() { static testpp_set_c static_set; return static_set; } <|endoftext|>
<commit_before>#include <keymap.h> #include <logger.h> #include <vector> #include <iostream> #include <config.h> namespace newsbeuter { struct op_desc { operation op; char * opstr; char * default_key; char * help_text; unsigned short flags; }; static op_desc opdescs[] = { { OP_OPEN, "open", "enter", _("Open feed/article"), KM_NEWSBEUTER }, { OP_QUIT, "quit", "q", _("Return to previous dialog/Quit"), KM_BOTH }, { OP_RELOAD, "reload", "r", _("Reload currently selected feed"), KM_NEWSBEUTER }, { OP_RELOADALL, "reload-all", "R", _("Reload all feeds"), KM_NEWSBEUTER }, { OP_MARKFEEDREAD, "mark-feed-read", "A", _("Mark feed read"), KM_NEWSBEUTER }, { OP_MARKALLFEEDSREAD, "mark-all-feeds-read", "C", _("Mark all feeds read"), KM_NEWSBEUTER }, { OP_SAVE, "save", "s", _("Save article"), KM_NEWSBEUTER }, { OP_NEXTUNREAD, "next-unread", "n", _("Go to next unread article"), KM_NEWSBEUTER }, { OP_OPENINBROWSER, "open-in-browser", "o", _("Open article in browser"), KM_NEWSBEUTER }, { OP_HELP, "help", "h", _("Open help dialog"), KM_BOTH }, { OP_TOGGLESOURCEVIEW, "toggle-source-view", "^u", _("Toggle source view"), KM_NEWSBEUTER }, { OP_TOGGLEITEMREAD, "toggle-article-read", "N", _("Toggle read status for article"), KM_NEWSBEUTER }, { OP_TOGGLESHOWREAD, "toggle-show-read-feeds", "l", _("Toggle show read feeds"), KM_NEWSBEUTER }, { OP_SHOWURLS, "show-urls", "u", _("Show URLs in current article"), KM_NEWSBEUTER }, { OP_CLEARTAG, "clear-tag", "^t", _("Clear current tag"), KM_NEWSBEUTER }, { OP_SETTAG, "set-tag", "t", _("Select tag"), KM_NEWSBEUTER }, { OP_SEARCH, "open-search", "/", _("Open search dialog"), KM_NEWSBEUTER }, { OP_ENQUEUE, "enqueue", "e", _("Add download to queue"), KM_NEWSBEUTER }, { OP_PB_DOWNLOAD, "pb-download", "d", _("Download file"), KM_PODBEUTER }, { OP_PB_CANCEL, "pb-cancel", "c", _("Cancel download"), KM_PODBEUTER }, { OP_PB_DELETE, "pb-delete", "D", _("Mark download as deleted"), KM_PODBEUTER }, { OP_PB_PURGE, "pb-purge", "P", _("Purge finished and deleted downloads from queue"), KM_PODBEUTER }, { OP_PB_TOGGLE_DLALL, "pb-toggle-download-all", "a", _("Toggle automatic download on/off"), KM_PODBEUTER }, { OP_PB_PLAY, "pb-play", "p", _("Start player with currently selected download"), KM_PODBEUTER }, { OP_PB_MOREDL, "pb-increase-max-dls", "+", _("Increase the number of concurrent downloads"), KM_PODBEUTER }, { OP_PB_LESSDL, "pb-decreate-max-dls", "-", _("Decrease the number of concurrent downloads"), KM_PODBEUTER }, { OP_REDRAW, "redraw", "^l", _("Redraw screen"), KM_BOTH }, { OP_NIL, NULL, NULL, NULL, 0 } }; keymap::keymap() { for (int i=0;opdescs[i].help_text;++i) { keymap_[opdescs[i].default_key] = opdescs[i].op; } } void keymap::get_keymap_descriptions(std::vector<std::pair<std::string,std::string> >& descs, unsigned short flags) { for (std::map<std::string,operation>::iterator it=keymap_.begin();it!=keymap_.end();++it) { operation op = it->second; if (op != OP_NIL) { std::string helptext; bool add = false; for (int i=0;opdescs[i].help_text;++i) { if (opdescs[i].op == op && opdescs[i].flags & flags) { helptext = gettext(opdescs[i].help_text); add = true; } } if (add) { descs.push_back(std::pair<std::string,std::string>(it->first, helptext)); } } } } keymap::~keymap() { } void keymap::set_key(operation op, const std::string& key) { GetLogger().log(LOG_DEBUG,"keymap::set_key(%d,%s) called", op, key.c_str()); keymap_[key] = op; } void keymap::unset_key(const std::string& key) { GetLogger().log(LOG_DEBUG,"keymap::unset_key(%s) called", key.c_str()); keymap_[key] = OP_NIL; } operation keymap::get_opcode(const std::string& opstr) { for (int i=0;opdescs[i].opstr;++i) { if (opstr == opdescs[i].opstr) { return opdescs[i].op; } } return OP_NIL; } char keymap::get_key(const std::string& keycode) { if (strncmp(keycode.c_str(),"CHAR(",5)==0) { unsigned int x; char c; sscanf(keycode.c_str(),"CHAR(%u)",&x); if (x >= 32 && x <= 126) { c = static_cast<char>(x); return c; } } return 0; } operation keymap::get_operation(const std::string& keycode) { std::string key; if (keycode.length() > 0) { if (keycode == "ENTER") { key = "enter"; } else if (keycode == "ESC") { key = "esc"; } else if (keycode[0] == 'F') { key = keycode; key[0] = 'f'; } else if (strncmp(keycode.c_str(),"CHAR(",5)==0) { unsigned int x; char c; sscanf(keycode.c_str(),"CHAR(%u)",&x); // std::cerr << x << std::endl; if (32 == x) { key.append("space"); } else if (x > 32 && x <= 126) { c = static_cast<char>(x); key.append(1,c); } else if (x<=26) { key.append("^"); key.append(1,static_cast<char>(0x60 + x)); } else { // TODO: handle special keys } } } else { key = "NIL"; } return keymap_[key]; } action_handler_status keymap::handle_action(const std::string& action, const std::vector<std::string>& params) { GetLogger().log(LOG_DEBUG,"keymap::handle_action(%s, ...) called",action.c_str()); if (action == "bind-key") { if (params.size() < 2) { return AHS_TOO_FEW_PARAMS; } else { set_key(get_opcode(params[1]), params[0]); // keymap_[params[0]] = get_opcode(params[1]); return AHS_OK; } } else if (action == "unbind-key") { if (params.size() < 1) { return AHS_TOO_FEW_PARAMS; } else { unset_key(params[0]); return AHS_OK; } } else return AHS_INVALID_PARAMS; } std::string keymap::getkey(operation op) { for (std::map<std::string,operation>::iterator it=keymap_.begin(); it!=keymap_.end(); ++it) { if (it->second == op) return it->first; } return "<none>"; } } <commit_msg>Andreas Krennmair: found wrong key that slipped in due to the refactoring efforts previously.<commit_after>#include <keymap.h> #include <logger.h> #include <vector> #include <iostream> #include <config.h> namespace newsbeuter { struct op_desc { operation op; char * opstr; char * default_key; char * help_text; unsigned short flags; }; static op_desc opdescs[] = { { OP_OPEN, "open", "enter", _("Open feed/article"), KM_NEWSBEUTER }, { OP_QUIT, "quit", "q", _("Return to previous dialog/Quit"), KM_BOTH }, { OP_RELOAD, "reload", "r", _("Reload currently selected feed"), KM_NEWSBEUTER }, { OP_RELOADALL, "reload-all", "R", _("Reload all feeds"), KM_NEWSBEUTER }, { OP_MARKFEEDREAD, "mark-feed-read", "A", _("Mark feed read"), KM_NEWSBEUTER }, { OP_MARKALLFEEDSREAD, "mark-all-feeds-read", "C", _("Mark all feeds read"), KM_NEWSBEUTER }, { OP_SAVE, "save", "s", _("Save article"), KM_NEWSBEUTER }, { OP_NEXTUNREAD, "next-unread", "n", _("Go to next unread article"), KM_NEWSBEUTER }, { OP_OPENINBROWSER, "open-in-browser", "o", _("Open article in browser"), KM_NEWSBEUTER }, { OP_HELP, "help", "?", _("Open help dialog"), KM_BOTH }, { OP_TOGGLESOURCEVIEW, "toggle-source-view", "^u", _("Toggle source view"), KM_NEWSBEUTER }, { OP_TOGGLEITEMREAD, "toggle-article-read", "N", _("Toggle read status for article"), KM_NEWSBEUTER }, { OP_TOGGLESHOWREAD, "toggle-show-read-feeds", "l", _("Toggle show read feeds"), KM_NEWSBEUTER }, { OP_SHOWURLS, "show-urls", "u", _("Show URLs in current article"), KM_NEWSBEUTER }, { OP_CLEARTAG, "clear-tag", "^t", _("Clear current tag"), KM_NEWSBEUTER }, { OP_SETTAG, "set-tag", "t", _("Select tag"), KM_NEWSBEUTER }, { OP_SEARCH, "open-search", "/", _("Open search dialog"), KM_NEWSBEUTER }, { OP_ENQUEUE, "enqueue", "e", _("Add download to queue"), KM_NEWSBEUTER }, { OP_PB_DOWNLOAD, "pb-download", "d", _("Download file"), KM_PODBEUTER }, { OP_PB_CANCEL, "pb-cancel", "c", _("Cancel download"), KM_PODBEUTER }, { OP_PB_DELETE, "pb-delete", "D", _("Mark download as deleted"), KM_PODBEUTER }, { OP_PB_PURGE, "pb-purge", "P", _("Purge finished and deleted downloads from queue"), KM_PODBEUTER }, { OP_PB_TOGGLE_DLALL, "pb-toggle-download-all", "a", _("Toggle automatic download on/off"), KM_PODBEUTER }, { OP_PB_PLAY, "pb-play", "p", _("Start player with currently selected download"), KM_PODBEUTER }, { OP_PB_MOREDL, "pb-increase-max-dls", "+", _("Increase the number of concurrent downloads"), KM_PODBEUTER }, { OP_PB_LESSDL, "pb-decreate-max-dls", "-", _("Decrease the number of concurrent downloads"), KM_PODBEUTER }, { OP_REDRAW, "redraw", "^l", _("Redraw screen"), KM_BOTH }, { OP_NIL, NULL, NULL, NULL, 0 } }; keymap::keymap() { for (int i=0;opdescs[i].help_text;++i) { keymap_[opdescs[i].default_key] = opdescs[i].op; } } void keymap::get_keymap_descriptions(std::vector<std::pair<std::string,std::string> >& descs, unsigned short flags) { for (std::map<std::string,operation>::iterator it=keymap_.begin();it!=keymap_.end();++it) { operation op = it->second; if (op != OP_NIL) { std::string helptext; bool add = false; for (int i=0;opdescs[i].help_text;++i) { if (opdescs[i].op == op && opdescs[i].flags & flags) { helptext = gettext(opdescs[i].help_text); add = true; } } if (add) { descs.push_back(std::pair<std::string,std::string>(it->first, helptext)); } } } } keymap::~keymap() { } void keymap::set_key(operation op, const std::string& key) { GetLogger().log(LOG_DEBUG,"keymap::set_key(%d,%s) called", op, key.c_str()); keymap_[key] = op; } void keymap::unset_key(const std::string& key) { GetLogger().log(LOG_DEBUG,"keymap::unset_key(%s) called", key.c_str()); keymap_[key] = OP_NIL; } operation keymap::get_opcode(const std::string& opstr) { for (int i=0;opdescs[i].opstr;++i) { if (opstr == opdescs[i].opstr) { return opdescs[i].op; } } return OP_NIL; } char keymap::get_key(const std::string& keycode) { if (strncmp(keycode.c_str(),"CHAR(",5)==0) { unsigned int x; char c; sscanf(keycode.c_str(),"CHAR(%u)",&x); if (x >= 32 && x <= 126) { c = static_cast<char>(x); return c; } } return 0; } operation keymap::get_operation(const std::string& keycode) { std::string key; if (keycode.length() > 0) { if (keycode == "ENTER") { key = "enter"; } else if (keycode == "ESC") { key = "esc"; } else if (keycode[0] == 'F') { key = keycode; key[0] = 'f'; } else if (strncmp(keycode.c_str(),"CHAR(",5)==0) { unsigned int x; char c; sscanf(keycode.c_str(),"CHAR(%u)",&x); // std::cerr << x << std::endl; if (32 == x) { key.append("space"); } else if (x > 32 && x <= 126) { c = static_cast<char>(x); key.append(1,c); } else if (x<=26) { key.append("^"); key.append(1,static_cast<char>(0x60 + x)); } else { // TODO: handle special keys } } } else { key = "NIL"; } return keymap_[key]; } action_handler_status keymap::handle_action(const std::string& action, const std::vector<std::string>& params) { GetLogger().log(LOG_DEBUG,"keymap::handle_action(%s, ...) called",action.c_str()); if (action == "bind-key") { if (params.size() < 2) { return AHS_TOO_FEW_PARAMS; } else { set_key(get_opcode(params[1]), params[0]); // keymap_[params[0]] = get_opcode(params[1]); return AHS_OK; } } else if (action == "unbind-key") { if (params.size() < 1) { return AHS_TOO_FEW_PARAMS; } else { unset_key(params[0]); return AHS_OK; } } else return AHS_INVALID_PARAMS; } std::string keymap::getkey(operation op) { for (std::map<std::string,operation>::iterator it=keymap_.begin(); it!=keymap_.end(); ++it) { if (it->second == op) return it->first; } return "<none>"; } } <|endoftext|>
<commit_before>#include "locale.h" #include "language.h" #include <KConfigGroup> #include <KSharedConfig> #include <QDebug> namespace Kubuntu { typedef QList<Language *> LanguagePtrList; class LocalePrivate { public: LocalePrivate(); void init(LanguagePtrList _languages, QString _country); LanguagePtrList languages; QString country; QString encoding; QString variant; }; LocalePrivate::LocalePrivate() : encoding(QLatin1String("UTF-8")) { } void LocalePrivate::init(LanguagePtrList _languages, QString _country) { languages = _languages; country = _country; const QString mainLanguage = _languages.at(0)->languageCode(); qDebug() << mainLanguage; if (mainLanguage.contains(QChar('@'))) { QStringList components = mainLanguage.split(QChar('@')); variant = components.at(1); } } Locale::Locale() : d_ptr(new LocalePrivate) { Q_D(Locale); KSharedConfigPtr config = KSharedConfig::openConfig("kdeglobals", KConfig::CascadeConfig); KConfigGroup settings = KConfigGroup(config, "Locale"); LanguagePtrList languages; QString languageSetting = settings.readEntry("Language", QString::fromLatin1("en_US")); if (languageSetting.contains(QChar(':'))) { QStringList languageCodes = languageSetting.split(QChar(':')); foreach (const QString &languageCode, languageCodes) languages.append(new Language(languageCode)); } else { languages.append(new Language(languageSetting)); } QString country = settings.readEntry("Country", QString::fromLatin1("C")); d->init(languages, country); } Locale::~Locale() { } QString Locale::systemLocaleString() const { Q_D(const Locale); QString locale = d->languages.at(0)->systemLanguageCode(); if (!d->country.isEmpty()) locale.append(QString("_%1").arg(d->country.toUpper())); if (!d->encoding.isEmpty()) locale.append(QString(".%1").arg(d->encoding)); else // Encoding must not ever not be set as otherwise ISO nonsense comes up. locale.append(QLatin1String(".UTF-8")); if (!d->variant.isEmpty()) locale.append(QString("@%1").arg(d->variant)); return locale; } QList<QString> Locale::systemLanguages() const { Q_D(const Locale); QStringList list; foreach (Language *language, d->languages) { if (list.isEmpty() || list.last() != language->systemLanguageCode()) list.append(language->systemLanguageCode()); } if (list.isEmpty() || list.last() != QLatin1String("en")) list.append("en"); return list; } QString Locale::systemLanguagesString() const { return QStringList(systemLanguages()).join(QChar(':')); } } // namespace Kubuntu <commit_msg>cleanup Language instances in locale<commit_after>#include "locale.h" #include "language.h" #include <KConfigGroup> #include <KSharedConfig> #include <QDebug> namespace Kubuntu { typedef QList<Language *> LanguagePtrList; class LocalePrivate { public: LocalePrivate(); ~LocalePrivate(); void init(LanguagePtrList _languages, QString _country); LanguagePtrList languages; QString country; QString encoding; QString variant; }; LocalePrivate::LocalePrivate() : encoding(QLatin1String("UTF-8")) { } LocalePrivate::~LocalePrivate() { qDeleteAll(languages); } void LocalePrivate::init(LanguagePtrList _languages, QString _country) { languages = _languages; country = _country; const QString mainLanguage = _languages.at(0)->languageCode(); qDebug() << mainLanguage; if (mainLanguage.contains(QChar('@'))) { QStringList components = mainLanguage.split(QChar('@')); variant = components.at(1); } } Locale::Locale() : d_ptr(new LocalePrivate) { Q_D(Locale); KSharedConfigPtr config = KSharedConfig::openConfig("kdeglobals", KConfig::CascadeConfig); KConfigGroup settings = KConfigGroup(config, "Locale"); LanguagePtrList languages; QString languageSetting = settings.readEntry("Language", QString::fromLatin1("en_US")); if (languageSetting.contains(QChar(':'))) { QStringList languageCodes = languageSetting.split(QChar(':')); foreach (const QString &languageCode, languageCodes) languages.append(new Language(languageCode)); } else { languages.append(new Language(languageSetting)); } QString country = settings.readEntry("Country", QString::fromLatin1("C")); d->init(languages, country); } Locale::~Locale() { } QString Locale::systemLocaleString() const { Q_D(const Locale); QString locale = d->languages.at(0)->systemLanguageCode(); if (!d->country.isEmpty()) locale.append(QString("_%1").arg(d->country.toUpper())); if (!d->encoding.isEmpty()) locale.append(QString(".%1").arg(d->encoding)); else // Encoding must not ever not be set as otherwise ISO nonsense comes up. locale.append(QLatin1String(".UTF-8")); if (!d->variant.isEmpty()) locale.append(QString("@%1").arg(d->variant)); return locale; } QList<QString> Locale::systemLanguages() const { Q_D(const Locale); QStringList list; foreach (Language *language, d->languages) { if (list.isEmpty() || list.last() != language->systemLanguageCode()) list.append(language->systemLanguageCode()); } if (list.isEmpty() || list.last() != QLatin1String("en")) list.append("en"); return list; } QString Locale::systemLanguagesString() const { return QStringList(systemLanguages()).join(QChar(':')); } } // namespace Kubuntu <|endoftext|>
<commit_before>#include "logger.h" namespace Akumuli { Formatter::Formatter(std::stringstream& str) : str_(str) { } Logger::Logger() { } } // namespace <commit_msg>This must be a part of the previous commit<commit_after>#include "logger.h" namespace Akumuli { Formatter::Formatter(std::stringstream& str) : str_(str) { } Logger::Logger() { } } // namespace <|endoftext|>
<commit_before>// 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 <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <algorithm> #include <limits> #include "base/file_util.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_POSIX) #include <sys/mman.h> #include <unistd.h> #endif using std::nothrow; using std::numeric_limits; namespace { // This function acts as a compiler optimization barrier. We use it to // prevent the compiler from making an expression a compile-time constant. // We also use it so that the compiler doesn't discard certain return values // as something we don't need (see the comment with calloc below). template <typename Type> Type HideValueFromCompiler(volatile Type value) { #if defined(__GNUC__) // In a GCC compatible compiler (GCC or Clang), make this compiler barrier // more robust than merely using "volatile". __asm__ volatile ("" : "+r" (value)); #endif // __GNUC__ return value; } // - NO_TCMALLOC (should be defined if we compile with linux_use_tcmalloc=0) // - ADDRESS_SANITIZER because it has its own memory allocator // - IOS does not use tcmalloc // - OS_MACOSX does not use tcmalloc #if !defined(NO_TCMALLOC) && !defined(ADDRESS_SANITIZER) && \ !defined(OS_IOS) && !defined(OS_MACOSX) #define TCMALLOC_TEST(function) function #else #define TCMALLOC_TEST(function) DISABLED_##function #endif // TODO(jln): switch to std::numeric_limits<int>::max() when we switch to // C++11. const size_t kTooBigAllocSize = INT_MAX; // Detect runtime TCMalloc bypasses. bool IsTcMallocBypassed() { #if defined(OS_LINUX) || defined(OS_CHROMEOS) // This should detect a TCMalloc bypass from Valgrind. char* g_slice = getenv("G_SLICE"); if (g_slice && !strcmp(g_slice, "always-malloc")) return true; #elif defined(OS_WIN) // This should detect a TCMalloc bypass from setting // the CHROME_ALLOCATOR environment variable. char* allocator = getenv("CHROME_ALLOCATOR"); if (allocator && strcmp(allocator, "tcmalloc")) return true; #endif return false; } bool CallocDiesOnOOM() { // The sanitizers' calloc dies on OOM instead of returning NULL. // The wrapper function in base/process_util_linux.cc that is used when we // compile without TCMalloc will just die on OOM instead of returning NULL. #if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \ defined(THREAD_SANITIZER) || (defined(OS_LINUX) && defined(NO_TCMALLOC)) return true; #else return false; #endif } // Fake test that allow to know the state of TCMalloc by looking at bots. TEST(SecurityTest, TCMALLOC_TEST(IsTCMallocDynamicallyBypassed)) { printf("Malloc is dynamically bypassed: %s\n", IsTcMallocBypassed() ? "yes." : "no."); } // The MemoryAllocationRestrictions* tests test that we can not allocate a // memory range that cannot be indexed via an int. This is used to mitigate // vulnerabilities in libraries that use int instead of size_t. See // crbug.com/169327. TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsMalloc)) { if (!IsTcMallocBypassed()) { scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>( HideValueFromCompiler(malloc(kTooBigAllocSize)))); ASSERT_TRUE(!ptr); } } TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsCalloc)) { if (!IsTcMallocBypassed()) { scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>( HideValueFromCompiler(calloc(kTooBigAllocSize, 1)))); ASSERT_TRUE(!ptr); } } TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsRealloc)) { if (!IsTcMallocBypassed()) { char* orig_ptr = static_cast<char*>(malloc(1)); ASSERT_TRUE(orig_ptr); scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>( HideValueFromCompiler(realloc(orig_ptr, kTooBigAllocSize)))); ASSERT_TRUE(!ptr); // If realloc() did not succeed, we need to free orig_ptr. free(orig_ptr); } } typedef struct { char large_array[kTooBigAllocSize]; } VeryLargeStruct; TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsNew)) { if (!IsTcMallocBypassed()) { scoped_ptr<VeryLargeStruct> ptr( HideValueFromCompiler(new (nothrow) VeryLargeStruct)); ASSERT_TRUE(!ptr); } } TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsNewArray)) { if (!IsTcMallocBypassed()) { scoped_ptr<char[]> ptr( HideValueFromCompiler(new (nothrow) char[kTooBigAllocSize])); ASSERT_TRUE(!ptr); } } // The tests bellow check for overflows in new[] and calloc(). #if defined(OS_IOS) || defined(OS_WIN) #define DISABLE_ON_IOS_AND_WIN(function) DISABLED_##function #else #define DISABLE_ON_IOS_AND_WIN(function) function #endif // There are platforms where these tests are known to fail. We would like to // be able to easily check the status on the bots, but marking tests as // FAILS_ is too clunky. void OverflowTestsSoftExpectTrue(bool overflow_detected) { if (!overflow_detected) { #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_MACOSX) // Sadly, on Linux, Android, and OSX we don't have a good story yet. Don't // fail the test, but report. printf("Platform has overflow: %s\n", !overflow_detected ? "yes." : "no."); #else // Otherwise, fail the test. (Note: EXPECT are ok in subfunctions, ASSERT // aren't). EXPECT_TRUE(overflow_detected); #endif } } // Test array[TooBig][X] and array[X][TooBig] allocations for int overflows. // IOS doesn't honor nothrow, so disable the test there. // Crashes on Windows Dbg builds, disable there as well. TEST(SecurityTest, DISABLE_ON_IOS_AND_WIN(NewOverflow)) { const size_t kArraySize = 4096; // We want something "dynamic" here, so that the compiler doesn't // immediately reject crazy arrays. const size_t kDynamicArraySize = HideValueFromCompiler(kArraySize); // numeric_limits are still not constexpr until we switch to C++11, so we // use an ugly cast. const size_t kMaxSizeT = ~static_cast<size_t>(0); ASSERT_EQ(numeric_limits<size_t>::max(), kMaxSizeT); const size_t kArraySize2 = kMaxSizeT / kArraySize + 10; const size_t kDynamicArraySize2 = HideValueFromCompiler(kArraySize2); { scoped_ptr<char[][kArraySize]> array_pointer(new (nothrow) char[kDynamicArraySize2][kArraySize]); OverflowTestsSoftExpectTrue(!array_pointer); } // On windows, the compiler prevents static array sizes of more than // 0x7fffffff (error C2148). #if !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS) { scoped_ptr<char[][kArraySize2]> array_pointer(new (nothrow) char[kDynamicArraySize][kArraySize2]); OverflowTestsSoftExpectTrue(!array_pointer); } #endif // !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS) } // Call calloc(), eventually free the memory and return whether or not // calloc() did succeed. bool CallocReturnsNull(size_t nmemb, size_t size) { scoped_ptr<char, base::FreeDeleter> array_pointer( static_cast<char*>(calloc(nmemb, size))); // We need the call to HideValueFromCompiler(): we have seen LLVM // optimize away the call to calloc() entirely and assume // the pointer to not be NULL. return HideValueFromCompiler(array_pointer.get()) == NULL; } // Test if calloc() can overflow. // Fails on Mac under ASAN. http://crbug.com/304125 #if defined(OS_MACOSX) && defined(ADDRESS_SANITIZER) #define MAYBE_CallocOverflow DISABLED_CallocOverflow #else #define MAYBE_CallocOverflow CallocOverflow #endif TEST(SecurityTest, MAYBE_CallocOverflow) { const size_t kArraySize = 4096; const size_t kMaxSizeT = numeric_limits<size_t>::max(); const size_t kArraySize2 = kMaxSizeT / kArraySize + 10; if (!CallocDiesOnOOM()) { EXPECT_TRUE(CallocReturnsNull(kArraySize, kArraySize2)); EXPECT_TRUE(CallocReturnsNull(kArraySize2, kArraySize)); } else { // It's also ok for calloc to just terminate the process. #if defined(GTEST_HAS_DEATH_TEST) EXPECT_DEATH(CallocReturnsNull(kArraySize, kArraySize2), ""); EXPECT_DEATH(CallocReturnsNull(kArraySize2, kArraySize), ""); #endif // GTEST_HAS_DEATH_TEST } } #if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__) // Useful for debugging. void PrintProcSelfMaps() { int fd = open("/proc/self/maps", O_RDONLY); file_util::ScopedFD fd_closer(&fd); ASSERT_GE(fd, 0); char buffer[1<<13]; int ret; ret = read(fd, buffer, sizeof(buffer) - 1); ASSERT_GT(ret, 0); buffer[ret - 1] = 0; fprintf(stdout, "%s\n", buffer); } // Check if ptr1 and ptr2 are separated by less than size chars. bool ArePointersToSameArea(void* ptr1, void* ptr2, size_t size) { ptrdiff_t ptr_diff = reinterpret_cast<char*>(std::max(ptr1, ptr2)) - reinterpret_cast<char*>(std::min(ptr1, ptr2)); return static_cast<size_t>(ptr_diff) <= size; } // Check if TCMalloc uses an underlying random memory allocator. TEST(SecurityTest, TCMALLOC_TEST(RandomMemoryAllocations)) { if (IsTcMallocBypassed()) return; size_t kPageSize = 4096; // We support x86_64 only. // Check that malloc() returns an address that is neither the kernel's // un-hinted mmap area, nor the current brk() area. The first malloc() may // not be at a random address because TCMalloc will first exhaust any memory // that it has allocated early on, before starting the sophisticated // allocators. void* default_mmap_heap_address = mmap(0, kPageSize, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); ASSERT_NE(default_mmap_heap_address, static_cast<void*>(MAP_FAILED)); ASSERT_EQ(munmap(default_mmap_heap_address, kPageSize), 0); void* brk_heap_address = sbrk(0); ASSERT_NE(brk_heap_address, reinterpret_cast<void*>(-1)); ASSERT_TRUE(brk_heap_address != NULL); // 1 MB should get us past what TCMalloc pre-allocated before initializing // the sophisticated allocators. size_t kAllocSize = 1<<20; scoped_ptr<char, base::FreeDeleter> ptr( static_cast<char*>(malloc(kAllocSize))); ASSERT_TRUE(ptr != NULL); // If two pointers are separated by less than 512MB, they are considered // to be in the same area. // Our random pointer could be anywhere within 0x3fffffffffff (46bits), // and we are checking that it's not withing 1GB (30 bits) from two // addresses (brk and mmap heap). We have roughly one chance out of // 2^15 to flake. const size_t kAreaRadius = 1<<29; bool in_default_mmap_heap = ArePointersToSameArea( ptr.get(), default_mmap_heap_address, kAreaRadius); EXPECT_FALSE(in_default_mmap_heap); bool in_default_brk_heap = ArePointersToSameArea( ptr.get(), brk_heap_address, kAreaRadius); EXPECT_FALSE(in_default_brk_heap); // In the implementation, we always mask our random addresses with // kRandomMask, so we use it as an additional detection mechanism. const uintptr_t kRandomMask = 0x3fffffffffffULL; bool impossible_random_address = reinterpret_cast<uintptr_t>(ptr.get()) & ~kRandomMask; EXPECT_FALSE(impossible_random_address); } #endif // (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__) } // namespace <commit_msg>Revert 226984 "Disable CallocOverflow under Mac/ASAN"<commit_after>// 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 <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <algorithm> #include <limits> #include "base/file_util.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_POSIX) #include <sys/mman.h> #include <unistd.h> #endif using std::nothrow; using std::numeric_limits; namespace { // This function acts as a compiler optimization barrier. We use it to // prevent the compiler from making an expression a compile-time constant. // We also use it so that the compiler doesn't discard certain return values // as something we don't need (see the comment with calloc below). template <typename Type> Type HideValueFromCompiler(volatile Type value) { #if defined(__GNUC__) // In a GCC compatible compiler (GCC or Clang), make this compiler barrier // more robust than merely using "volatile". __asm__ volatile ("" : "+r" (value)); #endif // __GNUC__ return value; } // - NO_TCMALLOC (should be defined if we compile with linux_use_tcmalloc=0) // - ADDRESS_SANITIZER because it has its own memory allocator // - IOS does not use tcmalloc // - OS_MACOSX does not use tcmalloc #if !defined(NO_TCMALLOC) && !defined(ADDRESS_SANITIZER) && \ !defined(OS_IOS) && !defined(OS_MACOSX) #define TCMALLOC_TEST(function) function #else #define TCMALLOC_TEST(function) DISABLED_##function #endif // TODO(jln): switch to std::numeric_limits<int>::max() when we switch to // C++11. const size_t kTooBigAllocSize = INT_MAX; // Detect runtime TCMalloc bypasses. bool IsTcMallocBypassed() { #if defined(OS_LINUX) || defined(OS_CHROMEOS) // This should detect a TCMalloc bypass from Valgrind. char* g_slice = getenv("G_SLICE"); if (g_slice && !strcmp(g_slice, "always-malloc")) return true; #elif defined(OS_WIN) // This should detect a TCMalloc bypass from setting // the CHROME_ALLOCATOR environment variable. char* allocator = getenv("CHROME_ALLOCATOR"); if (allocator && strcmp(allocator, "tcmalloc")) return true; #endif return false; } bool CallocDiesOnOOM() { // The sanitizers' calloc dies on OOM instead of returning NULL. // The wrapper function in base/process_util_linux.cc that is used when we // compile without TCMalloc will just die on OOM instead of returning NULL. #if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \ defined(THREAD_SANITIZER) || (defined(OS_LINUX) && defined(NO_TCMALLOC)) return true; #else return false; #endif } // Fake test that allow to know the state of TCMalloc by looking at bots. TEST(SecurityTest, TCMALLOC_TEST(IsTCMallocDynamicallyBypassed)) { printf("Malloc is dynamically bypassed: %s\n", IsTcMallocBypassed() ? "yes." : "no."); } // The MemoryAllocationRestrictions* tests test that we can not allocate a // memory range that cannot be indexed via an int. This is used to mitigate // vulnerabilities in libraries that use int instead of size_t. See // crbug.com/169327. TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsMalloc)) { if (!IsTcMallocBypassed()) { scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>( HideValueFromCompiler(malloc(kTooBigAllocSize)))); ASSERT_TRUE(!ptr); } } TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsCalloc)) { if (!IsTcMallocBypassed()) { scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>( HideValueFromCompiler(calloc(kTooBigAllocSize, 1)))); ASSERT_TRUE(!ptr); } } TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsRealloc)) { if (!IsTcMallocBypassed()) { char* orig_ptr = static_cast<char*>(malloc(1)); ASSERT_TRUE(orig_ptr); scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>( HideValueFromCompiler(realloc(orig_ptr, kTooBigAllocSize)))); ASSERT_TRUE(!ptr); // If realloc() did not succeed, we need to free orig_ptr. free(orig_ptr); } } typedef struct { char large_array[kTooBigAllocSize]; } VeryLargeStruct; TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsNew)) { if (!IsTcMallocBypassed()) { scoped_ptr<VeryLargeStruct> ptr( HideValueFromCompiler(new (nothrow) VeryLargeStruct)); ASSERT_TRUE(!ptr); } } TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsNewArray)) { if (!IsTcMallocBypassed()) { scoped_ptr<char[]> ptr( HideValueFromCompiler(new (nothrow) char[kTooBigAllocSize])); ASSERT_TRUE(!ptr); } } // The tests bellow check for overflows in new[] and calloc(). #if defined(OS_IOS) || defined(OS_WIN) #define DISABLE_ON_IOS_AND_WIN(function) DISABLED_##function #else #define DISABLE_ON_IOS_AND_WIN(function) function #endif // There are platforms where these tests are known to fail. We would like to // be able to easily check the status on the bots, but marking tests as // FAILS_ is too clunky. void OverflowTestsSoftExpectTrue(bool overflow_detected) { if (!overflow_detected) { #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_MACOSX) // Sadly, on Linux, Android, and OSX we don't have a good story yet. Don't // fail the test, but report. printf("Platform has overflow: %s\n", !overflow_detected ? "yes." : "no."); #else // Otherwise, fail the test. (Note: EXPECT are ok in subfunctions, ASSERT // aren't). EXPECT_TRUE(overflow_detected); #endif } } // Test array[TooBig][X] and array[X][TooBig] allocations for int overflows. // IOS doesn't honor nothrow, so disable the test there. // Crashes on Windows Dbg builds, disable there as well. TEST(SecurityTest, DISABLE_ON_IOS_AND_WIN(NewOverflow)) { const size_t kArraySize = 4096; // We want something "dynamic" here, so that the compiler doesn't // immediately reject crazy arrays. const size_t kDynamicArraySize = HideValueFromCompiler(kArraySize); // numeric_limits are still not constexpr until we switch to C++11, so we // use an ugly cast. const size_t kMaxSizeT = ~static_cast<size_t>(0); ASSERT_EQ(numeric_limits<size_t>::max(), kMaxSizeT); const size_t kArraySize2 = kMaxSizeT / kArraySize + 10; const size_t kDynamicArraySize2 = HideValueFromCompiler(kArraySize2); { scoped_ptr<char[][kArraySize]> array_pointer(new (nothrow) char[kDynamicArraySize2][kArraySize]); OverflowTestsSoftExpectTrue(!array_pointer); } // On windows, the compiler prevents static array sizes of more than // 0x7fffffff (error C2148). #if !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS) { scoped_ptr<char[][kArraySize2]> array_pointer(new (nothrow) char[kDynamicArraySize][kArraySize2]); OverflowTestsSoftExpectTrue(!array_pointer); } #endif // !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS) } // Call calloc(), eventually free the memory and return whether or not // calloc() did succeed. bool CallocReturnsNull(size_t nmemb, size_t size) { scoped_ptr<char, base::FreeDeleter> array_pointer( static_cast<char*>(calloc(nmemb, size))); // We need the call to HideValueFromCompiler(): we have seen LLVM // optimize away the call to calloc() entirely and assume // the pointer to not be NULL. return HideValueFromCompiler(array_pointer.get()) == NULL; } // Test if calloc() can overflow. TEST(SecurityTest, CallocOverflow) { const size_t kArraySize = 4096; const size_t kMaxSizeT = numeric_limits<size_t>::max(); const size_t kArraySize2 = kMaxSizeT / kArraySize + 10; if (!CallocDiesOnOOM()) { EXPECT_TRUE(CallocReturnsNull(kArraySize, kArraySize2)); EXPECT_TRUE(CallocReturnsNull(kArraySize2, kArraySize)); } else { // It's also ok for calloc to just terminate the process. #if defined(GTEST_HAS_DEATH_TEST) EXPECT_DEATH(CallocReturnsNull(kArraySize, kArraySize2), ""); EXPECT_DEATH(CallocReturnsNull(kArraySize2, kArraySize), ""); #endif // GTEST_HAS_DEATH_TEST } } #if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__) // Useful for debugging. void PrintProcSelfMaps() { int fd = open("/proc/self/maps", O_RDONLY); file_util::ScopedFD fd_closer(&fd); ASSERT_GE(fd, 0); char buffer[1<<13]; int ret; ret = read(fd, buffer, sizeof(buffer) - 1); ASSERT_GT(ret, 0); buffer[ret - 1] = 0; fprintf(stdout, "%s\n", buffer); } // Check if ptr1 and ptr2 are separated by less than size chars. bool ArePointersToSameArea(void* ptr1, void* ptr2, size_t size) { ptrdiff_t ptr_diff = reinterpret_cast<char*>(std::max(ptr1, ptr2)) - reinterpret_cast<char*>(std::min(ptr1, ptr2)); return static_cast<size_t>(ptr_diff) <= size; } // Check if TCMalloc uses an underlying random memory allocator. TEST(SecurityTest, TCMALLOC_TEST(RandomMemoryAllocations)) { if (IsTcMallocBypassed()) return; size_t kPageSize = 4096; // We support x86_64 only. // Check that malloc() returns an address that is neither the kernel's // un-hinted mmap area, nor the current brk() area. The first malloc() may // not be at a random address because TCMalloc will first exhaust any memory // that it has allocated early on, before starting the sophisticated // allocators. void* default_mmap_heap_address = mmap(0, kPageSize, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); ASSERT_NE(default_mmap_heap_address, static_cast<void*>(MAP_FAILED)); ASSERT_EQ(munmap(default_mmap_heap_address, kPageSize), 0); void* brk_heap_address = sbrk(0); ASSERT_NE(brk_heap_address, reinterpret_cast<void*>(-1)); ASSERT_TRUE(brk_heap_address != NULL); // 1 MB should get us past what TCMalloc pre-allocated before initializing // the sophisticated allocators. size_t kAllocSize = 1<<20; scoped_ptr<char, base::FreeDeleter> ptr( static_cast<char*>(malloc(kAllocSize))); ASSERT_TRUE(ptr != NULL); // If two pointers are separated by less than 512MB, they are considered // to be in the same area. // Our random pointer could be anywhere within 0x3fffffffffff (46bits), // and we are checking that it's not withing 1GB (30 bits) from two // addresses (brk and mmap heap). We have roughly one chance out of // 2^15 to flake. const size_t kAreaRadius = 1<<29; bool in_default_mmap_heap = ArePointersToSameArea( ptr.get(), default_mmap_heap_address, kAreaRadius); EXPECT_FALSE(in_default_mmap_heap); bool in_default_brk_heap = ArePointersToSameArea( ptr.get(), brk_heap_address, kAreaRadius); EXPECT_FALSE(in_default_brk_heap); // In the implementation, we always mask our random addresses with // kRandomMask, so we use it as an additional detection mechanism. const uintptr_t kRandomMask = 0x3fffffffffffULL; bool impossible_random_address = reinterpret_cast<uintptr_t>(ptr.get()) & ~kRandomMask; EXPECT_FALSE(impossible_random_address); } #endif // (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__) } // namespace <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "MatchedValueBC.h" registerMooseObject("MooseApp", MatchedValueBC); registerMooseObject("MooseApp", ADMatchedValueBC); template <bool is_ad> InputParameters MatchedValueBCTempl<is_ad>::validParams() { InputParameters params = GenericNodalBC<is_ad>::validParams(); params.addRequiredCoupledVar("v", "The variable whose value we are to match."); params.addParam<Real>("u_coeff", 1.0, " A coefficient for primary variable u"); params.addParam<Real>("v_coeff", 1.0, " A coefficient for coupled variable v"); params.addClassDescription("Implements a NodalBC which equates two different Variables' values " "on a specified boundary."); return params; } template <bool is_ad> MatchedValueBCTempl<is_ad>::MatchedValueBCTempl(const InputParameters & parameters) : GenericNodalBC<is_ad>(parameters), _v(this->template coupledGenericValue<is_ad>("v")), _v_num(coupled("v")), _u_coeff(this->template getParam<Real>("u_coeff")), _v_coeff(this->template getParam<Real>("v_coeff")) { } template <> GenericReal<true> MatchedValueBCTempl<true>::computeQpResidual() { return _u_coeff * _u - _v_coeff * _v[_qp]; } template <> GenericReal<false> MatchedValueBCTempl<false>::computeQpResidual() { return _u_coeff * _u[_qp] - _v_coeff * _v[_qp]; } template <> Real MatchedValueBCTempl<false>::computeQpOffDiagJacobian(unsigned int jvar) { if (jvar == _v_num) return -_v_coeff; else return 0.; } template <> Real MatchedValueBCTempl<true>::computeQpOffDiagJacobian(unsigned int /*jvar*/) { return 0.; } template class MatchedValueBCTempl<false>; template class MatchedValueBCTempl<true>; <commit_msg>Update framework/src/bcs/MatchedValueBC.C<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "MatchedValueBC.h" registerMooseObject("MooseApp", MatchedValueBC); registerMooseObject("MooseApp", ADMatchedValueBC); template <bool is_ad> InputParameters MatchedValueBCTempl<is_ad>::validParams() { InputParameters params = GenericNodalBC<is_ad>::validParams(); params.addRequiredCoupledVar("v", "The variable whose value we are to match."); params.addParam<Real>("u_coeff", 1.0, " A coefficient for primary variable u"); params.addParam<Real>("v_coeff", 1.0, " A coefficient for coupled variable v"); params.addClassDescription("Implements a NodalBC which equates two different Variables' values " "on a specified boundary."); return params; } template <bool is_ad> MatchedValueBCTempl<is_ad>::MatchedValueBCTempl(const InputParameters & parameters) : GenericNodalBC<is_ad>(parameters), _v(this->template coupledGenericValue<is_ad>("v")), _v_num(coupled("v")), _u_coeff(this->template getParam<Real>("u_coeff")), _v_coeff(this->template getParam<Real>("v_coeff")) { } template <> GenericReal<true> MatchedValueBCTempl<true>::computeQpResidual() { return _u_coeff * _u - _v_coeff * _v[_qp]; } template <> GenericReal<false> MatchedValueBCTempl<false>::computeQpResidual() { return _u_coeff * _u[_qp] - _v_coeff * _v[_qp]; } template <bool is_ad> Real MatchedValueBCTempl<is_ad>::computeQpOffDiagJacobian(unsigned int jvar) { // For the AD version, we do not need this implementation since AD will // automatically compute derivatives. In other words, this function will // never be called for the AD version. But we can not eliminate this function // for the AD because C++ does not support an optional function declaration based // on a template parameter. if (jvar == _v_num) return -_v_coeff; else return 0.; } template class MatchedValueBCTempl<false>; template class MatchedValueBCTempl<true>; <|endoftext|>
<commit_before>#include "p0run/interpreter.hpp" #include "p0run/string.hpp" #include "p0run/table.hpp" #include "p0compile/compiler.hpp" #include "p0compile/compiler_error.hpp" #include <boost/test/unit_test.hpp> using namespace p0::run; namespace { bool expect_no_error(p0::compiler_error const &error) { std::cerr << error.what() << '\n'; BOOST_CHECK(nullptr == "no error expected"); return true; } template <class CheckResult> void run_valid_source( std::string const &source, std::vector<value> const &arguments, CheckResult const &check_result) { p0::source_range const source_range( source.data(), source.data() + source.size()); p0::compiler compiler(source_range, expect_no_error); auto const program = compiler.compile(); p0::run::interpreter interpreter(program, nullptr); auto const &main_function = program.functions().front(); auto const result = interpreter.call(main_function, arguments); check_result(result, program); } bool test_invalid_source(std::string const &correct_head, std::string const &illformed_tail) { auto const full_source = correct_head + illformed_tail; auto const error_position = correct_head.size(); bool found_expected_error = false; auto const check_compiler_error = [&full_source, error_position, &found_expected_error] (p0::compiler_error const &error) -> bool { auto const found_error_position = error.position().begin(); found_expected_error = (full_source.data() + error_position == found_error_position); return true; }; p0::source_range const source_range( full_source.data(), full_source.data() + full_source.size()); p0::compiler compiler(source_range, check_compiler_error); compiler.compile(); //TODO make compile() throw return found_expected_error; } } BOOST_AUTO_TEST_CASE(empty_function_compile_test) { std::string const source = ""; std::vector<p0::run::value> const arguments; run_valid_source(source, arguments, [](p0::run::value const &result, p0::intermediate::unit const &program) { auto const &main_function = program.functions().front(); BOOST_CHECK(result == value(main_function)); }); } BOOST_AUTO_TEST_CASE(return_integer_compile_test) { std::string const source = "return 123"; std::vector<value> const arguments; run_valid_source(source, arguments, [](value const &result, p0::intermediate::unit const & /*program*/) { BOOST_CHECK(result == value(static_cast<integer>(123))); }); } BOOST_AUTO_TEST_CASE(return_null_compile_test) { std::string const source = "return null"; std::vector<value> const arguments; run_valid_source(source, arguments, [](value const &result, p0::intermediate::unit const & /*program*/) { BOOST_CHECK(is_null(result)); }); } BOOST_AUTO_TEST_CASE(return_string_compile_test) { std::string const source = "return \"hello, world!\""; std::vector<value> const arguments; run_valid_source(source, arguments, [](value const &result, p0::intermediate::unit const & /*program*/) { BOOST_REQUIRE(result.type == value_type::object); BOOST_REQUIRE(dynamic_cast<string const *>(result.obj)); BOOST_CHECK(dynamic_cast<string const &>(*result.obj).content() == "hello, world!"); }); } BOOST_AUTO_TEST_CASE(return_empty_table_compile_test) { std::string const source = "return []"; std::vector<value> const arguments; run_valid_source(source, arguments, [](value const &result, p0::intermediate::unit const & /*program*/) { BOOST_REQUIRE(result.type == value_type::object); BOOST_REQUIRE(dynamic_cast<table const *>(result.obj)); }); } BOOST_AUTO_TEST_CASE(return_trivial_table_compile_test) { std::string const source = "var t = [] t[123] = 456 return t"; std::vector<value> const arguments; run_valid_source(source, arguments, [](value const &result, p0::intermediate::unit const & /*program*/) { BOOST_REQUIRE(result.type == value_type::object); BOOST_REQUIRE(dynamic_cast<table const *>(result.obj)); auto const element = dynamic_cast<table const &>(*result.obj).get_element( value(static_cast<integer>(123))); BOOST_REQUIRE(element); BOOST_CHECK(*element == value(static_cast<integer>(456))); }); } BOOST_AUTO_TEST_CASE(misplaced_break_continue_test) { BOOST_CHECK(test_invalid_source("", "break")); BOOST_CHECK(test_invalid_source("", "continue")); BOOST_CHECK(test_invalid_source("{", "break}")); BOOST_CHECK(test_invalid_source("{", "continue}")); // BOOST_CHECK(test_invalid_source("while true { function () {", "break} }")); } <commit_msg>test break on function scope<commit_after>#include "p0run/interpreter.hpp" #include "p0run/string.hpp" #include "p0run/table.hpp" #include "p0compile/compiler.hpp" #include "p0compile/compiler_error.hpp" #include <boost/test/unit_test.hpp> using namespace p0::run; namespace { bool expect_no_error(p0::compiler_error const &error) { std::cerr << error.what() << '\n'; BOOST_CHECK(nullptr == "no error expected"); return true; } template <class CheckResult> void run_valid_source( std::string const &source, std::vector<value> const &arguments, CheckResult const &check_result) { p0::source_range const source_range( source.data(), source.data() + source.size()); p0::compiler compiler(source_range, expect_no_error); auto const program = compiler.compile(); p0::run::interpreter interpreter(program, nullptr); auto const &main_function = program.functions().front(); auto const result = interpreter.call(main_function, arguments); check_result(result, program); } bool test_invalid_source(std::string const &correct_head, std::string const &illformed_tail) { auto const full_source = correct_head + illformed_tail; auto const error_position = correct_head.size(); bool found_expected_error = false; auto const check_compiler_error = [&full_source, error_position, &found_expected_error] (p0::compiler_error const &error) -> bool { auto const found_error_position = error.position().begin() - full_source.data(); found_expected_error = (error_position == found_error_position); return true; }; p0::source_range const source_range( full_source.data(), full_source.data() + full_source.size()); p0::compiler compiler(source_range, check_compiler_error); compiler.compile(); //TODO make compile() throw return found_expected_error; } } BOOST_AUTO_TEST_CASE(empty_function_compile_test) { std::string const source = ""; std::vector<p0::run::value> const arguments; run_valid_source(source, arguments, [](p0::run::value const &result, p0::intermediate::unit const &program) { auto const &main_function = program.functions().front(); BOOST_CHECK(result == value(main_function)); }); } BOOST_AUTO_TEST_CASE(return_integer_compile_test) { std::string const source = "return 123"; std::vector<value> const arguments; run_valid_source(source, arguments, [](value const &result, p0::intermediate::unit const & /*program*/) { BOOST_CHECK(result == value(static_cast<integer>(123))); }); } BOOST_AUTO_TEST_CASE(return_null_compile_test) { std::string const source = "return null"; std::vector<value> const arguments; run_valid_source(source, arguments, [](value const &result, p0::intermediate::unit const & /*program*/) { BOOST_CHECK(is_null(result)); }); } BOOST_AUTO_TEST_CASE(return_string_compile_test) { std::string const source = "return \"hello, world!\""; std::vector<value> const arguments; run_valid_source(source, arguments, [](value const &result, p0::intermediate::unit const & /*program*/) { BOOST_REQUIRE(result.type == value_type::object); BOOST_REQUIRE(dynamic_cast<string const *>(result.obj)); BOOST_CHECK(dynamic_cast<string const &>(*result.obj).content() == "hello, world!"); }); } BOOST_AUTO_TEST_CASE(return_empty_table_compile_test) { std::string const source = "return []"; std::vector<value> const arguments; run_valid_source(source, arguments, [](value const &result, p0::intermediate::unit const & /*program*/) { BOOST_REQUIRE(result.type == value_type::object); BOOST_REQUIRE(dynamic_cast<table const *>(result.obj)); }); } BOOST_AUTO_TEST_CASE(return_trivial_table_compile_test) { std::string const source = "var t = [] t[123] = 456 return t"; std::vector<value> const arguments; run_valid_source(source, arguments, [](value const &result, p0::intermediate::unit const & /*program*/) { BOOST_REQUIRE(result.type == value_type::object); BOOST_REQUIRE(dynamic_cast<table const *>(result.obj)); auto const element = dynamic_cast<table const &>(*result.obj).get_element( value(static_cast<integer>(123))); BOOST_REQUIRE(element); BOOST_CHECK(*element == value(static_cast<integer>(456))); }); } BOOST_AUTO_TEST_CASE(misplaced_break_continue_test) { //not allowed in outermost scope BOOST_CHECK(test_invalid_source("", "break")); BOOST_CHECK(test_invalid_source("", "continue")); //not allowed in a non-loop scope BOOST_CHECK(test_invalid_source("{", "break}")); BOOST_CHECK(test_invalid_source("{", "continue}")); //not allowed in the top-level scope of a function BOOST_CHECK(test_invalid_source("function () {", "break}")); //you cannot break out of a function BOOST_CHECK(test_invalid_source("while 1 { function () {", "break} }")); } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS * * * * 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. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFA_COMPONENT_MISC_COMPARESTATE_INL #define SOFA_COMPONENT_MISC_COMPARESTATE_INL #include <SofaValidation/CompareState.h> #include <sofa/core/visual/VisualParams.h> #include <sofa/simulation/common/MechanicalVisitor.h> #include <sofa/simulation/common/UpdateMappingVisitor.h> #include <sofa/core/ObjectFactory.h> #include <sofa/simulation/common/xml/XML.h> #include <sofa/helper/system/FileRepository.h> #include <sofa/helper/system/SetDirectory.h> #include <sstream> #include <algorithm> namespace sofa { namespace component { namespace misc { namespace { /*anonymous namespace for utility functions*/ /* look for potential CompareStateFile formatted likewise %0_%1_%2_mstate.txt.gz with - %0 the current scene name - %1 the current comparestate counter value - %2 the name of the mstate which will undergo comparizons. */ std::string lookForValidCompareStateFile( const std::string& sceneName, const std::string& mstateName, const int counterCompareState, const std::string& extension, const std::string defaultName ="default") { using namespace sofa::helper::system; std::ostringstream ofilename; ofilename << sceneName << "_" << counterCompareState << "_" << mstateName << "_mstate" << extension ; std::string result; std::string testFilename = ofilename.str(); std::ostringstream errorlog; if( DataRepository.findFile(testFilename,"",&errorlog ) ) { result = ofilename.str(); return result; } // from here we look for a closest match in terms of mstateName. std::string parentDir = SetDirectory::GetParentDir(testFilename.c_str()); std::string fileName = SetDirectory::GetFileName(testFilename.c_str()); const int& numDefault = sofa::simulation::xml::numDefault; for( int i = 0; i<numDefault; ++i) { std::ostringstream oss; oss << sceneName << "_" << counterCompareState << "_" << defaultName << i << "_mstate" << extension ; std::string testFile = oss.str(); if(DataRepository.findFile(testFile,"",&errorlog)) { result = testFile; break; } } return result; } } int CompareStateClass = core::RegisterObject("Compare State vectors from a reference frame to the associated Mechanical State") .add< CompareState >(); CompareState::CompareState(): ReadState() { totalError_X=0.0; totalError_V=0.0; dofError_X=0.0; dofError_V=0.0; } //-------------------------------- handleEvent------------------------------------------- void CompareState::handleEvent(sofa::core::objectmodel::Event* event) { if (/* simulation::AnimateBeginEvent* ev = */ dynamic_cast<simulation::AnimateBeginEvent*>(event)) { processCompareState(); } if (/* simulation::AnimateEndEvent* ev = */ dynamic_cast<simulation::AnimateEndEvent*>(event)) { } } //-------------------------------- processCompareState------------------------------------ void CompareState::processCompareState() { double time = getContext()->getTime() + f_shift.getValue(); time += getContext()->getDt() * 0.001; //lastTime = time+0.00001; std::vector<std::string> validLines; if (!nextValidLines.empty() && last_time == getContext()->getTime()) validLines.swap(nextValidLines); else { last_time = getContext()->getTime(); if (!this->readNext(time, validLines)) return; } for (std::vector<std::string>::iterator it=validLines.begin(); it!=validLines.end(); ++it) { std::istringstream str(*it); std::string cmd; str >> cmd; double currentError=0; if (cmd.compare("X=") == 0) { last_X = *it; currentError = mmodel->compareVec(core::VecId::position(), str); totalError_X +=currentError; double dsize = (double)this->mmodel->getSize(); if (dsize != 0.0) dofError_X +=currentError/dsize; } else if (cmd.compare("V=") == 0) { last_V = *it; currentError = mmodel->compareVec(core::VecId::velocity(), str); totalError_V +=currentError; double dsize = (double)this->mmodel->getSize(); if (dsize != 0.0) dofError_V += currentError/dsize; } } sout << "totalError_X = " << totalError_X << ", totalError_V = " << totalError_V << sendl; } //-------------------------------- processCompareState------------------------------------ void CompareState::draw(const core::visual::VisualParams* vparams) { double time = getContext()->getTime() + f_shift.getValue(); time += getContext()->getDt() * 0.001; //lastTime = time+0.00001; if (nextValidLines.empty() && last_time != getContext()->getTime()) { last_time = getContext()->getTime(); if (!this->readNext(time, nextValidLines)) nextValidLines.clear(); else { for (std::vector<std::string>::iterator it=nextValidLines.begin(); it!=nextValidLines.end(); ++it) { std::istringstream str(*it); std::string cmd; str >> cmd; if (cmd.compare("X=") == 0) { last_X = *it; } else if (cmd.compare("V=") == 0) { last_V = *it; } } } } if (mmodel && !last_X.empty()) { core::VecCoordId refX(core::VecCoordId::V_FIRST_DYNAMIC_INDEX); mmodel->vAvail(vparams, refX); mmodel->vAlloc(vparams, refX); std::istringstream str(last_X); std::string cmd; str >> cmd; mmodel->readVec(refX, str); const core::objectmodel::BaseData* dataX = mmodel->baseRead(core::VecCoordId::position()); const core::objectmodel::BaseData* dataRefX = mmodel->baseRead(refX); if (dataX && dataRefX) { const sofa::defaulttype::AbstractTypeInfo* infoX = dataX->getValueTypeInfo(); const sofa::defaulttype::AbstractTypeInfo* infoRefX = dataRefX->getValueTypeInfo(); const void* valueX = dataX->getValueVoidPtr(); const void* valueRefX = dataRefX->getValueVoidPtr(); if (valueX && infoX && infoX->ValidInfo() && valueRefX && infoRefX && infoRefX->ValidInfo()) { int ncX = infoX->size(); int ncRefX = infoRefX->size(); int sizeX = infoX->size(valueX); int sizeRefX = infoRefX->size(valueRefX); if (ncX > 1 && ncRefX > 1) { int nc = std::min(3,std::min(ncX,ncRefX)); int nbp = std::min(sizeX/ncX, sizeRefX/ncRefX); std::vector< Vector3 > points; points.resize(nbp*2); for(int p=0; p<nbp; ++p) { Vector3& pX = points[2*p+0]; Vector3& pRefX = points[2*p+1]; for (int c=0; c<nc; ++c) pX[c] = infoX->getScalarValue(valueX, p*ncX+c); for (int c=0; c<nc; ++c) pRefX[c] = infoRefX->getScalarValue(valueRefX, p*ncRefX+c); } vparams->drawTool()->drawLines(points, 1, Vec<4,float>(1.0f,0.0f,0.5f,1.0f)); } } } mmodel->vFree(vparams, refX); } } CompareStateCreator::CompareStateCreator(const core::ExecParams* params) : Visitor(params) , sceneName("") #ifdef SOFA_HAVE_ZLIB , extension(".txt.gz") #else , extension(".txt") #endif , createInMapping(false) , init(true) , counterCompareState(0) { } CompareStateCreator::CompareStateCreator(const std::string &n, const core::ExecParams* params, bool i, int c) : Visitor(params) , sceneName(n) #ifdef SOFA_HAVE_ZLIB , extension(".txt.gz") #else , extension(".txt") #endif , createInMapping(false) , init(i) , counterCompareState(c) { } //Create a Compare State component each time a mechanical state is found simulation::Visitor::Result CompareStateCreator::processNodeTopDown( simulation::Node* gnode) { using namespace sofa::defaulttype; sofa::core::behavior::BaseMechanicalState * mstate = gnode->mechanicalState; if (!mstate) return simulation::Visitor::RESULT_CONTINUE; core::behavior::OdeSolver *isSimulated; mstate->getContext()->get(isSimulated); if (!isSimulated) return simulation::Visitor::RESULT_CONTINUE; //We have a mechanical state addCompareState(mstate, gnode); return simulation::Visitor::RESULT_CONTINUE; } void CompareStateCreator::addCompareState(sofa::core::behavior::BaseMechanicalState *ms, simulation::Node* gnode) { sofa::core::objectmodel::BaseContext* context = gnode->getContext(); sofa::core::BaseMapping *mapping; context->get(mapping); if (createInMapping || mapping== NULL) { sofa::component::misc::CompareState::SPtr rs; context->get(rs, core::objectmodel::BaseContext::Local); if ( rs == NULL ) { rs = sofa::core::objectmodel::New<sofa::component::misc::CompareState>(); gnode->addObject(rs); } // compatibility: std::string validFilename = lookForValidCompareStateFile(sceneName, ms->getName(), counterCompareState, extension); if(validFilename.empty()) { // look for a file which closest match the shortName of this mechanicalState. validFilename = lookForValidCompareStateFile(sceneName, ms->getName(), counterCompareState, extension, ms->getClass()->shortName); } rs->f_filename.setValue(validFilename); rs->f_listening.setValue(false); //Deactivated only called by extern functions if (init) rs->init(); ++counterCompareState; } } //Create a Compare State component each time a mechanical state is found simulation::Visitor::Result CompareStateResult::processNodeTopDown( simulation::Node* gnode) { sofa::component::misc::CompareState *cv; gnode->get(cv); if (!cv) return simulation::Visitor::RESULT_CONTINUE; //We have a mechanical state error += cv->getTotalError(); errorByDof += cv->getErrorByDof(); numCompareState++; return simulation::Visitor::RESULT_CONTINUE; } } // namespace misc } // namespace component } // namespace sofa #endif <commit_msg>FIX: SofaValidation compilation<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS * * * * 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. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFA_COMPONENT_MISC_COMPARESTATE_INL #define SOFA_COMPONENT_MISC_COMPARESTATE_INL #include <SofaValidation/CompareState.h> #include <sofa/core/visual/VisualParams.h> #include <sofa/simulation/common/MechanicalVisitor.h> #include <sofa/simulation/common/UpdateMappingVisitor.h> #include <sofa/core/ObjectFactory.h> #include <sofa/simulation/common/xml/XML.h> #include <sofa/helper/system/FileRepository.h> #include <sofa/helper/system/SetDirectory.h> #include <sstream> #include <algorithm> using namespace sofa::defaulttype; namespace sofa { namespace component { namespace misc { namespace { /*anonymous namespace for utility functions*/ /* look for potential CompareStateFile formatted likewise %0_%1_%2_mstate.txt.gz with - %0 the current scene name - %1 the current comparestate counter value - %2 the name of the mstate which will undergo comparizons. */ std::string lookForValidCompareStateFile( const std::string& sceneName, const std::string& mstateName, const int counterCompareState, const std::string& extension, const std::string defaultName ="default") { using namespace sofa::helper::system; std::ostringstream ofilename; ofilename << sceneName << "_" << counterCompareState << "_" << mstateName << "_mstate" << extension ; std::string result; std::string testFilename = ofilename.str(); std::ostringstream errorlog; if( DataRepository.findFile(testFilename,"",&errorlog ) ) { result = ofilename.str(); return result; } // from here we look for a closest match in terms of mstateName. std::string parentDir = SetDirectory::GetParentDir(testFilename.c_str()); std::string fileName = SetDirectory::GetFileName(testFilename.c_str()); const int& numDefault = sofa::simulation::xml::numDefault; for( int i = 0; i<numDefault; ++i) { std::ostringstream oss; oss << sceneName << "_" << counterCompareState << "_" << defaultName << i << "_mstate" << extension ; std::string testFile = oss.str(); if(DataRepository.findFile(testFile,"",&errorlog)) { result = testFile; break; } } return result; } } int CompareStateClass = core::RegisterObject("Compare State vectors from a reference frame to the associated Mechanical State") .add< CompareState >(); CompareState::CompareState(): ReadState() { totalError_X=0.0; totalError_V=0.0; dofError_X=0.0; dofError_V=0.0; } //-------------------------------- handleEvent------------------------------------------- void CompareState::handleEvent(sofa::core::objectmodel::Event* event) { if (/* simulation::AnimateBeginEvent* ev = */ dynamic_cast<simulation::AnimateBeginEvent*>(event)) { processCompareState(); } if (/* simulation::AnimateEndEvent* ev = */ dynamic_cast<simulation::AnimateEndEvent*>(event)) { } } //-------------------------------- processCompareState------------------------------------ void CompareState::processCompareState() { double time = getContext()->getTime() + f_shift.getValue(); time += getContext()->getDt() * 0.001; //lastTime = time+0.00001; std::vector<std::string> validLines; if (!nextValidLines.empty() && last_time == getContext()->getTime()) validLines.swap(nextValidLines); else { last_time = getContext()->getTime(); if (!this->readNext(time, validLines)) return; } for (std::vector<std::string>::iterator it=validLines.begin(); it!=validLines.end(); ++it) { std::istringstream str(*it); std::string cmd; str >> cmd; double currentError=0; if (cmd.compare("X=") == 0) { last_X = *it; currentError = mmodel->compareVec(core::VecId::position(), str); totalError_X +=currentError; double dsize = (double)this->mmodel->getSize(); if (dsize != 0.0) dofError_X +=currentError/dsize; } else if (cmd.compare("V=") == 0) { last_V = *it; currentError = mmodel->compareVec(core::VecId::velocity(), str); totalError_V +=currentError; double dsize = (double)this->mmodel->getSize(); if (dsize != 0.0) dofError_V += currentError/dsize; } } sout << "totalError_X = " << totalError_X << ", totalError_V = " << totalError_V << sendl; } //-------------------------------- processCompareState------------------------------------ void CompareState::draw(const core::visual::VisualParams* vparams) { double time = getContext()->getTime() + f_shift.getValue(); time += getContext()->getDt() * 0.001; //lastTime = time+0.00001; if (nextValidLines.empty() && last_time != getContext()->getTime()) { last_time = getContext()->getTime(); if (!this->readNext(time, nextValidLines)) nextValidLines.clear(); else { for (std::vector<std::string>::iterator it=nextValidLines.begin(); it!=nextValidLines.end(); ++it) { std::istringstream str(*it); std::string cmd; str >> cmd; if (cmd.compare("X=") == 0) { last_X = *it; } else if (cmd.compare("V=") == 0) { last_V = *it; } } } } if (mmodel && !last_X.empty()) { core::VecCoordId refX(core::VecCoordId::V_FIRST_DYNAMIC_INDEX); mmodel->vAvail(vparams, refX); mmodel->vAlloc(vparams, refX); std::istringstream str(last_X); std::string cmd; str >> cmd; mmodel->readVec(refX, str); const core::objectmodel::BaseData* dataX = mmodel->baseRead(core::VecCoordId::position()); const core::objectmodel::BaseData* dataRefX = mmodel->baseRead(refX); if (dataX && dataRefX) { const sofa::defaulttype::AbstractTypeInfo* infoX = dataX->getValueTypeInfo(); const sofa::defaulttype::AbstractTypeInfo* infoRefX = dataRefX->getValueTypeInfo(); const void* valueX = dataX->getValueVoidPtr(); const void* valueRefX = dataRefX->getValueVoidPtr(); if (valueX && infoX && infoX->ValidInfo() && valueRefX && infoRefX && infoRefX->ValidInfo()) { int ncX = infoX->size(); int ncRefX = infoRefX->size(); int sizeX = infoX->size(valueX); int sizeRefX = infoRefX->size(valueRefX); if (ncX > 1 && ncRefX > 1) { int nc = std::min(3,std::min(ncX,ncRefX)); int nbp = std::min(sizeX/ncX, sizeRefX/ncRefX); std::vector< Vector3 > points; points.resize(nbp*2); for(int p=0; p<nbp; ++p) { Vector3& pX = points[2*p+0]; Vector3& pRefX = points[2*p+1]; for (int c=0; c<nc; ++c) pX[c] = infoX->getScalarValue(valueX, p*ncX+c); for (int c=0; c<nc; ++c) pRefX[c] = infoRefX->getScalarValue(valueRefX, p*ncRefX+c); } vparams->drawTool()->drawLines(points, 1, Vec<4,float>(1.0f,0.0f,0.5f,1.0f)); } } } mmodel->vFree(vparams, refX); } } CompareStateCreator::CompareStateCreator(const core::ExecParams* params) : Visitor(params) , sceneName("") #ifdef SOFA_HAVE_ZLIB , extension(".txt.gz") #else , extension(".txt") #endif , createInMapping(false) , init(true) , counterCompareState(0) { } CompareStateCreator::CompareStateCreator(const std::string &n, const core::ExecParams* params, bool i, int c) : Visitor(params) , sceneName(n) #ifdef SOFA_HAVE_ZLIB , extension(".txt.gz") #else , extension(".txt") #endif , createInMapping(false) , init(i) , counterCompareState(c) { } //Create a Compare State component each time a mechanical state is found simulation::Visitor::Result CompareStateCreator::processNodeTopDown( simulation::Node* gnode) { using namespace sofa::defaulttype; sofa::core::behavior::BaseMechanicalState * mstate = gnode->mechanicalState; if (!mstate) return simulation::Visitor::RESULT_CONTINUE; core::behavior::OdeSolver *isSimulated; mstate->getContext()->get(isSimulated); if (!isSimulated) return simulation::Visitor::RESULT_CONTINUE; //We have a mechanical state addCompareState(mstate, gnode); return simulation::Visitor::RESULT_CONTINUE; } void CompareStateCreator::addCompareState(sofa::core::behavior::BaseMechanicalState *ms, simulation::Node* gnode) { sofa::core::objectmodel::BaseContext* context = gnode->getContext(); sofa::core::BaseMapping *mapping; context->get(mapping); if (createInMapping || mapping== NULL) { sofa::component::misc::CompareState::SPtr rs; context->get(rs, core::objectmodel::BaseContext::Local); if ( rs == NULL ) { rs = sofa::core::objectmodel::New<sofa::component::misc::CompareState>(); gnode->addObject(rs); } // compatibility: std::string validFilename = lookForValidCompareStateFile(sceneName, ms->getName(), counterCompareState, extension); if(validFilename.empty()) { // look for a file which closest match the shortName of this mechanicalState. validFilename = lookForValidCompareStateFile(sceneName, ms->getName(), counterCompareState, extension, ms->getClass()->shortName); } rs->f_filename.setValue(validFilename); rs->f_listening.setValue(false); //Deactivated only called by extern functions if (init) rs->init(); ++counterCompareState; } } //Create a Compare State component each time a mechanical state is found simulation::Visitor::Result CompareStateResult::processNodeTopDown( simulation::Node* gnode) { sofa::component::misc::CompareState *cv; gnode->get(cv); if (!cv) return simulation::Visitor::RESULT_CONTINUE; //We have a mechanical state error += cv->getTotalError(); errorByDof += cv->getErrorByDof(); numCompareState++; return simulation::Visitor::RESULT_CONTINUE; } } // namespace misc } // namespace component } // namespace sofa #endif <|endoftext|>
<commit_before> /****************************************************************************\ * Copyright (C) 2016 Scandy * * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR * PURPOSE. * \****************************************************************************/ /** * \file basic_usage_file_read.cpp * \brief Shows how to create a ScandyCore instance and read a Royale rrf file. * This basic_usage example shows to create a ScandyCore isntance and read a * Royale file. It then starts the visualizer and runs until closed * by the user. */ // include scandycore so we can make 3D magic happen #include <scandy/core/IScandyCore.h> #include <thread> using namespace scandy::core; using namespace std; using namespace std::chrono_literals; int main(int argc, char *argv[]) { scandy::core::Status status; // Create the ScandyCore instance with a Visualizer window of 400x400 auto core = IScandyCore::factoryCreate(400,400); if(!core) { throw std::runtime_error("ERROR creating ScandyCore"); } // Add some callbacks. core->onScannerStart = []() { std::cout << "Starting file playback";}; core->onScannerStop = []() { std::cout << "File playback stopped."; }; // get the view window auto viz = core->getVisualizer(); if(!viz) { throw std::runtime_error("ERROR creating ScandyCore"); } // Read in a Royale rrf file from the command line status = core->initializeScanner(ScannerType::FILE, argv[1]); if(status != Status::SUCCESS) { throw std::runtime_error("ERROR could not read test file"); } // Start SLAM to process the depth data in the rrf file. status = core->startPreview(); // The visualizer window must run in the main thread. Create a background // thread to kill the visualizer thread after the entire file has been processed. std::thread slam_thread([core, viz]() { auto status = core->startScanning(); if(status != Status::SUCCESS) { throw std::runtime_error("ERROR starting scanner"); } std::this_thread::sleep_for(5s); status = core->stopScanning(); if(status != Status::SUCCESS) { throw std::runtime_error("ERROR stopping scanner"); } viz->stop(); viz->join(); }); // Start the visualizer. viz->start(); // Release the slam_thread. slam_thread.join(); return 0; } <commit_msg>changed to return Status code and print error rather than throw exception<commit_after> /****************************************************************************\ * Copyright (C) 2016 Scandy * * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR * PURPOSE. * \****************************************************************************/ /** * \file basic_usage_file_read.cpp * \brief Shows how to create a ScandyCore instance and read a Royale rrf file. * This basic_usage example shows to create a ScandyCore isntance and read a * Royale file. It then starts the visualizer and runs until closed * by the user. */ // include scandycore so we can make 3D magic happen #include <scandy/core/IScandyCore.h> #include <thread> using namespace scandy::core; using namespace std; using namespace std::chrono_literals; int main(int argc, char *argv[]) { scandy::core::Status status; // Create the ScandyCore instance with a Visualizer window of 400x400 auto core = IScandyCore::factoryCreate(400,400); if(!core) { std::cerr << "ERROR creating ScandyCore" << std::endl; return (int) scandy::core::Status::EXCEPTION_IN_HANDLER;; } // Add some callbacks. core->onScannerStart = []() { std::cout << "Starting file playback";}; core->onScannerStop = []() { std::cout << "File playback stopped."; }; // get the view window auto viz = core->getVisualizer(); if(!viz) { std::cerr << "ERROR getting ScandyCore Visualizer" << std::endl; return (int) scandy::core::Status::NO_VISUALIZER_FOUND; } // Read in a Royale rrf file from the command line char *file_path = argv[1]; if( file_path == nullptr ){ std::cerr << "ERROR you must provide a path to the file" << std::endl; return (int) scandy::core::Status::FILE_NOT_FOUND;; } status = core->initializeScanner(ScannerType::FILE, file_path); if(status != Status::SUCCESS) { std::cerr << "ERROR could not read test files" << std::endl; return (int) status; } // Start SLAM to process the depth data in the rrf file. status = core->startPreview(); // The visualizer window must run in the main thread. Create a background // thread to kill the visualizer thread after the entire file has been processed. std::thread slam_thread([core, viz]() { auto status = core->startScanning(); if(status != Status::SUCCESS) { std::cerr << "ERROR starting scanner" << std::endl; return (int) status; } std::this_thread::sleep_for(5s); status = core->stopScanning(); if(status != Status::SUCCESS) { std::cerr << "ERROR stopping scanner" << std::endl; return (int) status; } viz->stop(); viz->join(); }); // Start the visualizer. viz->start(); // Release the slam_thread. slam_thread.join(); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2011 Matthias Fuchs * * 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 "stromx/runtime/DataContainer.h" #include "stromx/runtime/DataProvider.h" #include "stromx/runtime/Id2DataPair.h" #include "stromx/runtime/NumericParameter.h" #include "stromx/runtime/OperatorException.h" #include "stromx/runtime/Primitive.h" #include "stromx/runtime/Queue.h" #include "stromx/runtime/Try.h" namespace stromx { namespace runtime { const std::string Queue::TYPE("Queue"); const std::string Queue::PACKAGE(STROMX_RUNTIME_PACKAGE_NAME); const Version Queue::VERSION(0, 1, 0); Queue::Queue() : OperatorKernel(TYPE, PACKAGE, VERSION, setupInputs(), setupOutputs(), setupParameters()), m_size(1) { } void Queue::setParameter(unsigned int id, const Data& value) { try { switch(id) { case SIZE: if(m_size == 0) throw WrongParameterValue(parameter(SIZE), *this); m_size = data_cast<UInt32>(value); break; default: throw WrongParameterId(id, *this); } } catch(std::bad_cast&) { throw WrongParameterValue(parameter(id), *this); } } const DataRef Queue::getParameter(const unsigned int id) const { switch(id) { case SIZE: return m_size; default: throw WrongParameterId(id, *this); } } void Queue::deactivate() { m_deque.clear(); } void Queue::execute(DataProvider& provider) { // if the queue is not full if(m_deque.size() < m_size) { Id2DataPair inputDataMapper(INPUT); if(! m_deque.empty()) { // there is some data in the queue // try to get data from the input provider.receiveInputData(Try(inputDataMapper)); } else { // there is no data in the queue // wait here forever provider.receiveInputData(inputDataMapper); } // if there was data push it on the queue if(! inputDataMapper.data().empty()) m_deque.push_back(inputDataMapper.data()); } // if the queue is not empty if(! m_deque.empty()) { Id2DataPair outputDataMapper(OUTPUT, m_deque.front()); if(m_deque.size() < m_size) { // there is some space left // try to push data to the output provider.sendOutputData(Try(outputDataMapper)); } else { // there is no space left // wait here forever provider.sendOutputData(outputDataMapper); } // if this was successful delete the data from the queue if(outputDataMapper.data().empty()) m_deque.pop_front(); } } const std::vector<const runtime::Description*> Queue::setupInputs() { std::vector<const Description*> inputs; Description* input = new Description(INPUT, Variant::DATA); input->setTitle("Input"); inputs.push_back(input); return inputs; } const std::vector<const Description*> Queue::setupOutputs() { std::vector<const Description*> outputs; Description* output = new Description(OUTPUT, Variant::DATA); output->setTitle("Output"); outputs.push_back(output); return outputs; } const std::vector<const Parameter*> Queue::setupParameters() { std::vector<const runtime::Parameter*> parameters; NumericParameter<UInt32>* size = new NumericParameter<UInt32>(SIZE); size->setTitle("Size"); size->setMin(UInt32(1)); size->setAccessMode(runtime::Parameter::INITIALIZED_WRITE); parameters.push_back(size); return parameters; } } } <commit_msg>Set operator thread of queue operator<commit_after>/* * Copyright 2011 Matthias Fuchs * * 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 "stromx/runtime/DataContainer.h" #include "stromx/runtime/DataProvider.h" #include "stromx/runtime/Id2DataPair.h" #include "stromx/runtime/NumericParameter.h" #include "stromx/runtime/OperatorException.h" #include "stromx/runtime/Primitive.h" #include "stromx/runtime/Queue.h" #include "stromx/runtime/Try.h" namespace { const static unsigned int INPUT_THREAD = 0; const static unsigned int OUTPUT_THREAD = 1; } namespace stromx { namespace runtime { const std::string Queue::TYPE("Queue"); const std::string Queue::PACKAGE(STROMX_RUNTIME_PACKAGE_NAME); const Version Queue::VERSION(0, 1, 0); Queue::Queue() : OperatorKernel(TYPE, PACKAGE, VERSION, setupInputs(), setupOutputs(), setupParameters()), m_size(1) { } void Queue::setParameter(unsigned int id, const Data& value) { try { switch(id) { case SIZE: if(m_size == 0) throw WrongParameterValue(parameter(SIZE), *this); m_size = data_cast<UInt32>(value); break; default: throw WrongParameterId(id, *this); } } catch(std::bad_cast&) { throw WrongParameterValue(parameter(id), *this); } } const DataRef Queue::getParameter(const unsigned int id) const { switch(id) { case SIZE: return m_size; default: throw WrongParameterId(id, *this); } } void Queue::deactivate() { m_deque.clear(); } void Queue::execute(DataProvider& provider) { // if the queue is not full if(m_deque.size() < m_size) { Id2DataPair inputDataMapper(INPUT); if(! m_deque.empty()) { // there is some data in the queue // try to get data from the input provider.receiveInputData(Try(inputDataMapper)); } else { // there is no data in the queue // wait here forever provider.receiveInputData(inputDataMapper); } // if there was data push it on the queue if(! inputDataMapper.data().empty()) m_deque.push_back(inputDataMapper.data()); } // if the queue is not empty if(! m_deque.empty()) { Id2DataPair outputDataMapper(OUTPUT, m_deque.front()); if(m_deque.size() < m_size) { // there is some space left // try to push data to the output provider.sendOutputData(Try(outputDataMapper)); } else { // there is no space left // wait here forever provider.sendOutputData(outputDataMapper); } // if this was successful delete the data from the queue if(outputDataMapper.data().empty()) m_deque.pop_front(); } } const std::vector<const runtime::Description*> Queue::setupInputs() { std::vector<const Description*> inputs; Description* input = new Description(INPUT, Variant::DATA); input->setTitle("Input"); input->setOperatorThread(INPUT_THREAD); inputs.push_back(input); return inputs; } const std::vector<const Description*> Queue::setupOutputs() { std::vector<const Description*> outputs; Description* output = new Description(OUTPUT, Variant::DATA); output->setTitle("Output"); output->setOperatorThread(OUTPUT_THREAD); outputs.push_back(output); return outputs; } const std::vector<const Parameter*> Queue::setupParameters() { std::vector<const runtime::Parameter*> parameters; NumericParameter<UInt32>* size = new NumericParameter<UInt32>(SIZE); size->setTitle("Size"); size->setMin(UInt32(1)); size->setAccessMode(runtime::Parameter::INITIALIZED_WRITE); parameters.push_back(size); return parameters; } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/desktop_capture/mouse_cursor.h" #include "webrtc/modules/desktop_capture/desktop_frame.h" namespace webrtc { MouseCursor::MouseCursor() {} MouseCursor::MouseCursor(DesktopFrame* image, const DesktopVector& hotspot) : image_(image), hotspot_(hotspot) { assert(0 <= hotspot_.x() && hotspot_.x() <= image_->size().width()); assert(0 <= hotspot_.y() && hotspot_.y() <= image_->size().height()); } MouseCursor::~MouseCursor() {} // static MouseCursor* MouseCursor::CopyOf(const MouseCursor& cursor) { return new MouseCursor( cursor.image() ? NULL : BasicDesktopFrame::CopyOf(*cursor.image()), cursor.hotspot()); } } // namespace webrtc <commit_msg>Fix crash in MouseCursor::CopyOf()<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/desktop_capture/mouse_cursor.h" #include "webrtc/modules/desktop_capture/desktop_frame.h" namespace webrtc { MouseCursor::MouseCursor() {} MouseCursor::MouseCursor(DesktopFrame* image, const DesktopVector& hotspot) : image_(image), hotspot_(hotspot) { assert(0 <= hotspot_.x() && hotspot_.x() <= image_->size().width()); assert(0 <= hotspot_.y() && hotspot_.y() <= image_->size().height()); } MouseCursor::~MouseCursor() {} // static MouseCursor* MouseCursor::CopyOf(const MouseCursor& cursor) { return cursor.image() ? new MouseCursor(BasicDesktopFrame::CopyOf(*cursor.image()), cursor.hotspot()) : new MouseCursor(); } } // namespace webrtc <|endoftext|>
<commit_before>/***************************************************************************** * preferences.cpp : Preferences ***************************************************************************** * Copyright (C) 2006-2007 the VideoLAN team * $Id$ * * Authors: Clément Stenac <zorglub@videolan.org> * Jean-Baptiste Kempf <jb@videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "dialogs/preferences.hpp" #include "dialogs_provider.hpp" #include "util/qvlcframe.hpp" #include "components/complete_preferences.hpp" #include "components/simple_preferences.hpp" #include <QHBoxLayout> #include <QGroupBox> #include <QRadioButton> #include <QVBoxLayout> #include <QPushButton> #include <QCheckBox> #include <QMessageBox> #include <QDialogButtonBox> PrefsDialog *PrefsDialog::instance = NULL; PrefsDialog::PrefsDialog( QWidget *parent, intf_thread_t *_p_intf ) : QVLCDialog( parent, _p_intf ) { QGridLayout *main_layout = new QGridLayout( this ); setWindowTitle( qtr( "Preferences" ) ); /* Create Panels */ tree_panel = new QWidget; tree_panel_l = new QHBoxLayout; tree_panel->setLayout( tree_panel_l ); main_panel = new QWidget; main_panel_l = new QHBoxLayout; main_panel->setLayout( main_panel_l ); /* Choice for types */ types = new QGroupBox( "Show settings" ); types->setAlignment( Qt::AlignHCenter ); QHBoxLayout *types_l = new QHBoxLayout; types_l->setSpacing( 3 ); types_l->setMargin( 3 ); small = new QRadioButton( qtr("Basic"), types ); types_l->addWidget( small ); all = new QRadioButton( qtr("All"), types ); types_l->addWidget( all ); types->setLayout( types_l ); small->setChecked( true ); /* Tree and panel initialisations */ advanced_tree = NULL; simple_tree = NULL; current_simple_panel = NULL; advanced_panel = NULL; /* Buttons */ QDialogButtonBox *buttonsBox = new QDialogButtonBox(); QPushButton *save = new QPushButton( qtr( "&Save" ) ); QPushButton *cancel = new QPushButton( qtr( "&Cancel" ) ); QPushButton *reset = new QPushButton( qtr( "&Reset Preferences" ) ); buttonsBox->addButton( save, QDialogButtonBox::AcceptRole ); buttonsBox->addButton( cancel, QDialogButtonBox::RejectRole ); buttonsBox->addButton( reset, QDialogButtonBox::ResetRole ); /* Layout */ main_layout->addWidget( tree_panel, 0, 0, 3, 1 ); main_layout->addWidget( types, 3, 0, 2, 1 ); main_layout->addWidget( main_panel, 0, 1, 4, 2 ); main_layout->addWidget( buttonsBox, 4, 2, 1 ,1 ); main_layout->setColumnMinimumWidth( 0, 150 ); main_layout->setColumnMinimumWidth( 1, 10 ); main_layout->setColumnStretch( 0, 1 ); main_layout->setColumnStretch( 1, 0 ); main_layout->setColumnStretch( 2, 3 ); main_layout->setRowStretch( 2, 4 ); setLayout( main_layout ); /* Margins */ tree_panel_l->setMargin( 1 ); main_panel_l->setMargin( 3 ); for( int i = 0; i < SPrefsMax ; i++ ) simple_panels[i] = NULL; if( config_GetInt( p_intf, "qt-advanced-pref" ) == 1 ) setAdvanced(); else setSmall(); BUTTONACT( save, save() ); BUTTONACT( cancel, cancel() ); BUTTONACT( reset, reset() ); BUTTONACT( small, setSmall() ); BUTTONACT( all, setAdvanced() ); resize( 750, sizeHint().height() ); } void PrefsDialog::setAdvanced() { /* We already have a simple TREE, and we just want to hide it */ if( simple_tree ) if( simple_tree->isVisible() ) simple_tree->hide(); /* If don't have already and advanced TREE, then create it */ if( !advanced_tree ) { /* Creation */ advanced_tree = new PrefsTree( p_intf, tree_panel ); /* and connections */ CONNECT( advanced_tree, currentItemChanged( QTreeWidgetItem *, QTreeWidgetItem * ), this, changeAdvPanel( QTreeWidgetItem * ) ); tree_panel_l->addWidget( advanced_tree ); } /* Show it */ advanced_tree->show(); /* Remove the simple current panel from the main panels*/ if( current_simple_panel ) if( current_simple_panel->isVisible() ) current_simple_panel->hide(); /* If no advanced Panel exist, create one, attach it and show it*/ if( !advanced_panel ) { advanced_panel = new AdvPrefsPanel( main_panel ); main_panel_l->addWidget( advanced_panel ); } advanced_panel->show(); /* Select the first Item of the preferences. Maybe you want to select a specified category... */ advanced_tree->setCurrentIndex( advanced_tree->model()->index( 0, 0, QModelIndex() ) ); all->setChecked( true ); } void PrefsDialog::setSmall() { /* If an advanced TREE exists, remove and hide it */ if( advanced_tree ) if( advanced_tree->isVisible() ) advanced_tree->hide(); /* If no simple_tree, create one, connect it */ if( !simple_tree ) { simple_tree = new SPrefsCatList( p_intf, tree_panel ); CONNECT( simple_tree, currentItemChanged( int ), this, changeSimplePanel( int ) ); tree_panel_l->addWidget( simple_tree ); } /*show it */ simple_tree->show(); /* If an Advanced PANEL exists, remove it */ if( advanced_panel ) if( advanced_panel->isVisible() ) advanced_panel->hide(); if( !current_simple_panel ) { current_simple_panel = new SPrefsPanel( p_intf, main_panel, SPrefsDefaultCat ); simple_panels[SPrefsDefaultCat] = current_simple_panel; main_panel_l->addWidget( current_simple_panel ); } current_simple_panel->show(); small->setChecked( true ); } /* Switching from on simple panel to another */ void PrefsDialog::changeSimplePanel( int number ) { if( current_simple_panel ) if( current_simple_panel->isVisible() ) current_simple_panel->hide(); current_simple_panel = simple_panels[number]; if( !current_simple_panel ) { current_simple_panel = new SPrefsPanel( p_intf, main_panel, number ); simple_panels[number] = current_simple_panel; main_panel_l->addWidget( current_simple_panel ); } current_simple_panel->show(); } /* Changing from one Advanced Panel to another */ void PrefsDialog::changeAdvPanel( QTreeWidgetItem *item ) { PrefsItemData *data = item->data( 0, Qt::UserRole ).value<PrefsItemData*>(); if( advanced_panel ) if( advanced_panel->isVisible() ) advanced_panel->hide(); if( !data->panel ) { data->panel = new AdvPrefsPanel( p_intf, main_panel , data ); main_panel_l->addWidget( data->panel ); } advanced_panel = data->panel; advanced_panel->show(); } #if 0 /*Called from extended settings, is not used anymore, but could be useful one day*/ void PrefsDialog::showModulePrefs( char *psz_module ) { setAdvanced(); all->setChecked( true ); for( int i_cat_index = 0 ; i_cat_index < advanced_tree->topLevelItemCount(); i_cat_index++ ) { QTreeWidgetItem *cat_item = advanced_tree->topLevelItem( i_cat_index ); PrefsItemData *data = cat_item->data( 0, Qt::UserRole ). value<PrefsItemData *>(); for( int i_sc_index = 0; i_sc_index < cat_item->childCount(); i_sc_index++ ) { QTreeWidgetItem *subcat_item = cat_item->child( i_sc_index ); PrefsItemData *sc_data = subcat_item->data(0, Qt::UserRole). value<PrefsItemData *>(); for( int i_module = 0; i_module < subcat_item->childCount(); i_module++ ) { QTreeWidgetItem *module_item = subcat_item->child( i_module ); PrefsItemData *mod_data = module_item->data( 0, Qt::UserRole ). value<PrefsItemData *>(); if( !strcmp( mod_data->psz_name, psz_module ) ) { advanced_tree->setCurrentItem( module_item ); } } } } show(); } #endif /* Actual apply and save for the preferences */ void PrefsDialog::save() { if( small->isChecked() && simple_tree->isVisible() ) { msg_Dbg( p_intf, "Saving the simple preferences" ); for( int i = 0 ; i< SPrefsMax; i++ ){ if( simple_panels[i] )simple_panels[i]->apply(); } } else if( all->isChecked() && advanced_tree->isVisible() ) { msg_Dbg( p_intf, "Saving the advanced preferences" ); advanced_tree->applyAll(); } /* Save to file */ config_SaveConfigFile( p_intf, NULL ); destroyPanels(); hide(); } void PrefsDialog::destroyPanels() { msg_Dbg( p_intf, "Destroying the Panels" ); /* Delete the other panel in order to force its reload after clicking on apply. In fact, if we don't do that, the preferences from the other panels won't be accurate, so we would have to recreate the whole dialog, and we don't want that.*/ if( small->isChecked() && advanced_panel ) { /* Deleting only the active panel from the advanced config doesn't work because the data records of PrefsItemData contains still a reference to it only cleanAll() is sure to remove all Panels! */ advanced_tree->cleanAll(); advanced_panel = NULL; } if( all->isChecked() && current_simple_panel ) { for( int i = 0 ; i< SPrefsMax; i++ ) { if( simple_panels[i] ) { delete simple_panels[i]; simple_panels[i] = NULL; } } current_simple_panel = NULL; } } /* Clean the preferences, dunno if it does something really */ void PrefsDialog::cancel() { if( small->isChecked() && simple_tree ) { for( int i = 0 ; i< SPrefsMax; i++ ) if( simple_panels[i] ) simple_panels[i]->clean(); } else if( all->isChecked() && advanced_tree ) { advanced_tree->cleanAll(); advanced_panel = NULL; } hide(); } /* Reset all the preferences, when you click the button */ void PrefsDialog::reset() { int ret = QMessageBox::question( this, qtr( "Reset Preferences" ), qtr( "This will reset your VLC media player preferences.\n" "Are you sure you want to continue?" ), QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Ok); if( ret == QMessageBox::Ok ) { config_ResetAll( p_intf ); config_SaveConfigFile( p_intf, NULL ); /* FIXME reset the panels */ destroyPanels(); } } <commit_msg>Smaller margins.<commit_after>/***************************************************************************** * preferences.cpp : Preferences ***************************************************************************** * Copyright (C) 2006-2007 the VideoLAN team * $Id$ * * Authors: Clément Stenac <zorglub@videolan.org> * Jean-Baptiste Kempf <jb@videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "dialogs/preferences.hpp" #include "dialogs_provider.hpp" #include "util/qvlcframe.hpp" #include "components/complete_preferences.hpp" #include "components/simple_preferences.hpp" #include <QHBoxLayout> #include <QGroupBox> #include <QRadioButton> #include <QVBoxLayout> #include <QPushButton> #include <QCheckBox> #include <QMessageBox> #include <QDialogButtonBox> PrefsDialog *PrefsDialog::instance = NULL; PrefsDialog::PrefsDialog( QWidget *parent, intf_thread_t *_p_intf ) : QVLCDialog( parent, _p_intf ) { QGridLayout *main_layout = new QGridLayout( this ); setWindowTitle( qtr( "Preferences" ) ); /* Create Panels */ tree_panel = new QWidget; tree_panel_l = new QHBoxLayout; tree_panel->setLayout( tree_panel_l ); main_panel = new QWidget; main_panel_l = new QHBoxLayout; main_panel->setLayout( main_panel_l ); /* Choice for types */ types = new QGroupBox( "Show settings" ); types->setAlignment( Qt::AlignHCenter ); QHBoxLayout *types_l = new QHBoxLayout; types_l->setSpacing( 3 ); types_l->setMargin( 3 ); small = new QRadioButton( qtr("Basic"), types ); types_l->addWidget( small ); all = new QRadioButton( qtr("All"), types ); types_l->addWidget( all ); types->setLayout( types_l ); small->setChecked( true ); /* Tree and panel initialisations */ advanced_tree = NULL; simple_tree = NULL; current_simple_panel = NULL; advanced_panel = NULL; /* Buttons */ QDialogButtonBox *buttonsBox = new QDialogButtonBox(); QPushButton *save = new QPushButton( qtr( "&Save" ) ); QPushButton *cancel = new QPushButton( qtr( "&Cancel" ) ); QPushButton *reset = new QPushButton( qtr( "&Reset Preferences" ) ); buttonsBox->addButton( save, QDialogButtonBox::AcceptRole ); buttonsBox->addButton( cancel, QDialogButtonBox::RejectRole ); buttonsBox->addButton( reset, QDialogButtonBox::ResetRole ); /* Layout */ main_layout->addWidget( tree_panel, 0, 0, 3, 1 ); main_layout->addWidget( types, 3, 0, 2, 1 ); main_layout->addWidget( main_panel, 0, 1, 4, 2 ); main_layout->addWidget( buttonsBox, 4, 2, 1 ,1 ); main_layout->setColumnMinimumWidth( 0, 150 ); main_layout->setColumnMinimumWidth( 1, 10 ); main_layout->setColumnStretch( 0, 1 ); main_layout->setColumnStretch( 1, 0 ); main_layout->setColumnStretch( 2, 3 ); main_layout->setRowStretch( 2, 4 ); main_layout->setMargin( 9 ); setLayout( main_layout ); /* Margins */ tree_panel_l->setMargin( 1 ); main_panel_l->setContentsMargins( 6, 0, 0, 3 ); for( int i = 0; i < SPrefsMax ; i++ ) simple_panels[i] = NULL; if( config_GetInt( p_intf, "qt-advanced-pref" ) == 1 ) setAdvanced(); else setSmall(); BUTTONACT( save, save() ); BUTTONACT( cancel, cancel() ); BUTTONACT( reset, reset() ); BUTTONACT( small, setSmall() ); BUTTONACT( all, setAdvanced() ); resize( 750, sizeHint().height() ); } void PrefsDialog::setAdvanced() { /* We already have a simple TREE, and we just want to hide it */ if( simple_tree ) if( simple_tree->isVisible() ) simple_tree->hide(); /* If don't have already and advanced TREE, then create it */ if( !advanced_tree ) { /* Creation */ advanced_tree = new PrefsTree( p_intf, tree_panel ); /* and connections */ CONNECT( advanced_tree, currentItemChanged( QTreeWidgetItem *, QTreeWidgetItem * ), this, changeAdvPanel( QTreeWidgetItem * ) ); tree_panel_l->addWidget( advanced_tree ); } /* Show it */ advanced_tree->show(); /* Remove the simple current panel from the main panels*/ if( current_simple_panel ) if( current_simple_panel->isVisible() ) current_simple_panel->hide(); /* If no advanced Panel exist, create one, attach it and show it*/ if( !advanced_panel ) { advanced_panel = new AdvPrefsPanel( main_panel ); main_panel_l->addWidget( advanced_panel ); } advanced_panel->show(); /* Select the first Item of the preferences. Maybe you want to select a specified category... */ advanced_tree->setCurrentIndex( advanced_tree->model()->index( 0, 0, QModelIndex() ) ); all->setChecked( true ); } void PrefsDialog::setSmall() { /* If an advanced TREE exists, remove and hide it */ if( advanced_tree ) if( advanced_tree->isVisible() ) advanced_tree->hide(); /* If no simple_tree, create one, connect it */ if( !simple_tree ) { simple_tree = new SPrefsCatList( p_intf, tree_panel ); CONNECT( simple_tree, currentItemChanged( int ), this, changeSimplePanel( int ) ); tree_panel_l->addWidget( simple_tree ); } /*show it */ simple_tree->show(); /* If an Advanced PANEL exists, remove it */ if( advanced_panel ) if( advanced_panel->isVisible() ) advanced_panel->hide(); if( !current_simple_panel ) { current_simple_panel = new SPrefsPanel( p_intf, main_panel, SPrefsDefaultCat ); simple_panels[SPrefsDefaultCat] = current_simple_panel; main_panel_l->addWidget( current_simple_panel ); } current_simple_panel->show(); small->setChecked( true ); } /* Switching from on simple panel to another */ void PrefsDialog::changeSimplePanel( int number ) { if( current_simple_panel ) if( current_simple_panel->isVisible() ) current_simple_panel->hide(); current_simple_panel = simple_panels[number]; if( !current_simple_panel ) { current_simple_panel = new SPrefsPanel( p_intf, main_panel, number ); simple_panels[number] = current_simple_panel; main_panel_l->addWidget( current_simple_panel ); } current_simple_panel->show(); } /* Changing from one Advanced Panel to another */ void PrefsDialog::changeAdvPanel( QTreeWidgetItem *item ) { PrefsItemData *data = item->data( 0, Qt::UserRole ).value<PrefsItemData*>(); if( advanced_panel ) if( advanced_panel->isVisible() ) advanced_panel->hide(); if( !data->panel ) { data->panel = new AdvPrefsPanel( p_intf, main_panel , data ); main_panel_l->addWidget( data->panel ); } advanced_panel = data->panel; advanced_panel->show(); } #if 0 /*Called from extended settings, is not used anymore, but could be useful one day*/ void PrefsDialog::showModulePrefs( char *psz_module ) { setAdvanced(); all->setChecked( true ); for( int i_cat_index = 0 ; i_cat_index < advanced_tree->topLevelItemCount(); i_cat_index++ ) { QTreeWidgetItem *cat_item = advanced_tree->topLevelItem( i_cat_index ); PrefsItemData *data = cat_item->data( 0, Qt::UserRole ). value<PrefsItemData *>(); for( int i_sc_index = 0; i_sc_index < cat_item->childCount(); i_sc_index++ ) { QTreeWidgetItem *subcat_item = cat_item->child( i_sc_index ); PrefsItemData *sc_data = subcat_item->data(0, Qt::UserRole). value<PrefsItemData *>(); for( int i_module = 0; i_module < subcat_item->childCount(); i_module++ ) { QTreeWidgetItem *module_item = subcat_item->child( i_module ); PrefsItemData *mod_data = module_item->data( 0, Qt::UserRole ). value<PrefsItemData *>(); if( !strcmp( mod_data->psz_name, psz_module ) ) { advanced_tree->setCurrentItem( module_item ); } } } } show(); } #endif /* Actual apply and save for the preferences */ void PrefsDialog::save() { if( small->isChecked() && simple_tree->isVisible() ) { msg_Dbg( p_intf, "Saving the simple preferences" ); for( int i = 0 ; i< SPrefsMax; i++ ){ if( simple_panels[i] )simple_panels[i]->apply(); } } else if( all->isChecked() && advanced_tree->isVisible() ) { msg_Dbg( p_intf, "Saving the advanced preferences" ); advanced_tree->applyAll(); } /* Save to file */ config_SaveConfigFile( p_intf, NULL ); destroyPanels(); hide(); } void PrefsDialog::destroyPanels() { msg_Dbg( p_intf, "Destroying the Panels" ); /* Delete the other panel in order to force its reload after clicking on apply. In fact, if we don't do that, the preferences from the other panels won't be accurate, so we would have to recreate the whole dialog, and we don't want that.*/ if( small->isChecked() && advanced_panel ) { /* Deleting only the active panel from the advanced config doesn't work because the data records of PrefsItemData contains still a reference to it only cleanAll() is sure to remove all Panels! */ advanced_tree->cleanAll(); advanced_panel = NULL; } if( all->isChecked() && current_simple_panel ) { for( int i = 0 ; i< SPrefsMax; i++ ) { if( simple_panels[i] ) { delete simple_panels[i]; simple_panels[i] = NULL; } } current_simple_panel = NULL; } } /* Clean the preferences, dunno if it does something really */ void PrefsDialog::cancel() { if( small->isChecked() && simple_tree ) { for( int i = 0 ; i< SPrefsMax; i++ ) if( simple_panels[i] ) simple_panels[i]->clean(); } else if( all->isChecked() && advanced_tree ) { advanced_tree->cleanAll(); advanced_panel = NULL; } hide(); } /* Reset all the preferences, when you click the button */ void PrefsDialog::reset() { int ret = QMessageBox::question( this, qtr( "Reset Preferences" ), qtr( "This will reset your VLC media player preferences.\n" "Are you sure you want to continue?" ), QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Ok); if( ret == QMessageBox::Ok ) { config_ResetAll( p_intf ); config_SaveConfigFile( p_intf, NULL ); /* FIXME reset the panels */ destroyPanels(); } } <|endoftext|>
<commit_before>/***************************************************************************** * x11_dragdrop.cpp ***************************************************************************** * Copyright (C) 2003 the VideoLAN team * $Id$ * * Authors: Cyril Deguet <asmax@via.ecp.fr> * Olivier Teulière <ipkiss@via.ecp.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef X11_SKINS #include <X11/Xlib.h> #include <X11/Xatom.h> #include "x11_dragdrop.hpp" #include "x11_display.hpp" #include "x11_factory.hpp" #include "../commands/cmd_add_item.hpp" #include <string> #include <list> X11DragDrop::X11DragDrop( intf_thread_t *pIntf, X11Display &rDisplay, Window win, bool playOnDrop ): SkinObject( pIntf ), m_rDisplay( rDisplay ), m_wnd( win ), m_playOnDrop( playOnDrop ) { } void X11DragDrop::dndEnter( ldata_t data ) { Window src = data[0]; // Retrieve available data types list<string> dataTypes; if( data[1] & 1 ) // More than 3 data types ? { Atom type; int format; unsigned long nitems, nbytes; Atom *dataList; Atom typeListAtom = XInternAtom( XDISPLAY, "XdndTypeList", 0 ); XGetWindowProperty( XDISPLAY, src, typeListAtom, 0, 65536, False, XA_ATOM, &type, &format, &nitems, &nbytes, (unsigned char**)&dataList ); for( unsigned long i=0; i<nitems; i++ ) { string dataType = XGetAtomName( XDISPLAY, dataList[i] ); dataTypes.push_back( dataType ); } XFree( (void*)dataList ); } else { for( int i = 2; i < 5; i++ ) { if( data[i] != None ) { string dataType = XGetAtomName( XDISPLAY, data[i] ); dataTypes.push_back( dataType ); } } } // Find the right target m_target = None; list<string>::iterator it; for( it = dataTypes.begin(); it != dataTypes.end(); ++it ) { if( *it == "text/plain" || *it == "STRING" ) { m_target = XInternAtom( XDISPLAY, (*it).c_str(), 0 ); break; } } } void X11DragDrop::dndPosition( ldata_t data ) { Window src = data[0]; Time time = data[2]; Atom selectionAtom = XInternAtom( XDISPLAY, "XdndSelection", 0 ); Atom targetAtom = XInternAtom( XDISPLAY, "text/plain", 0 ); Atom propAtom = XInternAtom( XDISPLAY, "VLC_SELECTION", 0 ); Atom actionAtom = XInternAtom( XDISPLAY, "XdndActionCopy", 0 ); Atom typeAtom = XInternAtom( XDISPLAY, "XdndFinished", 0 ); // Convert the selection into the given target // NEEDED or it doesn't work! XConvertSelection( XDISPLAY, selectionAtom, targetAtom, propAtom, src, time ); actionAtom = XInternAtom( XDISPLAY, "XdndActionCopy", 0 ); typeAtom = XInternAtom( XDISPLAY, "XdndStatus", 0 ); XEvent event; event.type = ClientMessage; event.xclient.window = src; event.xclient.display = XDISPLAY; event.xclient.message_type = typeAtom; event.xclient.format = 32; event.xclient.data.l[0] = m_wnd; // Accept the drop (1), or not (0). event.xclient.data.l[1] = m_target != None ? 1 : 0; OSFactory *pOsFactory = X11Factory::instance( getIntf() ); int w = pOsFactory->getScreenWidth(); int h = pOsFactory->getScreenHeight(); event.xclient.data.l[2] = 0; event.xclient.data.l[3] = (w << 16) | h; event.xclient.data.l[4] = actionAtom; // Tell the source whether we accept the drop XSendEvent( XDISPLAY, src, False, 0, &event ); } void X11DragDrop::dndLeave( ldata_t data ) { } void X11DragDrop::dndDrop( ldata_t data ) { Window src = data[0]; Time time = data[2]; Atom selectionAtom = XInternAtom( XDISPLAY, "XdndSelection", 0 ); Atom targetAtom = XInternAtom( XDISPLAY, "text/plain", 0 ); Atom propAtom = XInternAtom( XDISPLAY, "VLC_SELECTION", 0 ); Atom actionAtom = XInternAtom( XDISPLAY, "XdndActionCopy", 0 ); Atom typeAtom = XInternAtom( XDISPLAY, "XdndFinished", 0 ); // Convert the selection into the given target XConvertSelection( XDISPLAY, selectionAtom, targetAtom, propAtom, src, time ); // Read the selection Atom type; int format; unsigned long nitems, nbytes; char *buffer; XGetWindowProperty( XDISPLAY, src, propAtom, 0, 1024, False, AnyPropertyType, &type, &format, &nitems, &nbytes, (unsigned char**)&buffer ); if( buffer != NULL ) { char* psz_dup = strdup( buffer ); char* psz_new = psz_dup; while( psz_new && *psz_new ) { char* psz_end = strchr( psz_new, '\n' ); if( psz_end ) *psz_end = '\0'; CmdAddItem cmd( getIntf(), psz_new, m_playOnDrop ); cmd.execute(); psz_new = psz_end ? psz_end + 1 : NULL; } free( psz_dup ); XFree( buffer ); } // Tell the source we accepted the drop XEvent event; event.type = ClientMessage; event.xclient.window = src; event.xclient.display = XDISPLAY; event.xclient.message_type = typeAtom; event.xclient.format = 32; event.xclient.data.l[0] = m_wnd; event.xclient.data.l[1] = 1; // drop accepted event.xclient.data.l[2] = actionAtom; XSendEvent( XDISPLAY, src, False, 0, &event ); } #endif <commit_msg>skins2(Linux): fix some drag&drop issues<commit_after>/***************************************************************************** * x11_dragdrop.cpp ***************************************************************************** * Copyright (C) 2003 the VideoLAN team * $Id$ * * Authors: Cyril Deguet <asmax@via.ecp.fr> * Olivier Teulière <ipkiss@via.ecp.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef X11_SKINS #include <X11/Xlib.h> #include <X11/Xatom.h> #include "x11_dragdrop.hpp" #include "x11_display.hpp" #include "x11_factory.hpp" #include "../commands/cmd_add_item.hpp" #include <string> #include <list> X11DragDrop::X11DragDrop( intf_thread_t *pIntf, X11Display &rDisplay, Window win, bool playOnDrop ): SkinObject( pIntf ), m_rDisplay( rDisplay ), m_wnd( win ), m_playOnDrop( playOnDrop ) { } void X11DragDrop::dndEnter( ldata_t data ) { Window src = data[0]; // Retrieve available data types list<string> dataTypes; if( data[1] & 1 ) // More than 3 data types ? { Atom type; int format; unsigned long nitems, nbytes; Atom *dataList; Atom typeListAtom = XInternAtom( XDISPLAY, "XdndTypeList", 0 ); XGetWindowProperty( XDISPLAY, src, typeListAtom, 0, 65536, False, XA_ATOM, &type, &format, &nitems, &nbytes, (unsigned char**)&dataList ); for( unsigned long i=0; i<nitems; i++ ) { string dataType = XGetAtomName( XDISPLAY, dataList[i] ); dataTypes.push_back( dataType ); } XFree( (void*)dataList ); } else { for( int i = 2; i < 5; i++ ) { if( data[i] != None ) { string dataType = XGetAtomName( XDISPLAY, data[i] ); dataTypes.push_back( dataType ); } } } // Find the right target m_target = None; list<string>::iterator it; for( it = dataTypes.begin(); it != dataTypes.end(); ++it ) { if( *it == "text/plain" || *it == "STRING" ) { m_target = XInternAtom( XDISPLAY, (*it).c_str(), 0 ); break; } } } void X11DragDrop::dndPosition( ldata_t data ) { Window src = data[0]; Time time = data[2]; Atom selectionAtom = XInternAtom( XDISPLAY, "XdndSelection", 0 ); Atom targetAtom = XInternAtom( XDISPLAY, "text/plain", 0 ); Atom propAtom = XInternAtom( XDISPLAY, "VLC_SELECTION", 0 ); Atom actionAtom = XInternAtom( XDISPLAY, "XdndActionCopy", 0 ); Atom typeAtom = XInternAtom( XDISPLAY, "XdndFinished", 0 ); // Convert the selection into the given target // NEEDED or it doesn't work! XConvertSelection( XDISPLAY, selectionAtom, targetAtom, propAtom, src, time ); actionAtom = XInternAtom( XDISPLAY, "XdndActionCopy", 0 ); typeAtom = XInternAtom( XDISPLAY, "XdndStatus", 0 ); XEvent event; event.type = ClientMessage; event.xclient.window = src; event.xclient.display = XDISPLAY; event.xclient.message_type = typeAtom; event.xclient.format = 32; event.xclient.data.l[0] = m_wnd; // Accept the drop (1), or not (0). event.xclient.data.l[1] = m_target != None ? 1 : 0; OSFactory *pOsFactory = X11Factory::instance( getIntf() ); int w = pOsFactory->getScreenWidth(); int h = pOsFactory->getScreenHeight(); event.xclient.data.l[2] = 0; event.xclient.data.l[3] = (w << 16) | h; event.xclient.data.l[4] = actionAtom; // Tell the source whether we accept the drop XSendEvent( XDISPLAY, src, False, 0, &event ); } void X11DragDrop::dndLeave( ldata_t data ) { } void X11DragDrop::dndDrop( ldata_t data ) { Window src = data[0]; Time time = data[2]; Atom selectionAtom = XInternAtom( XDISPLAY, "XdndSelection", 0 ); Atom targetAtom = XInternAtom( XDISPLAY, "text/plain", 0 ); Atom propAtom = XInternAtom( XDISPLAY, "VLC_SELECTION", 0 ); Atom actionAtom = XInternAtom( XDISPLAY, "XdndActionCopy", 0 ); Atom typeAtom = XInternAtom( XDISPLAY, "XdndFinished", 0 ); // Convert the selection into the given target XConvertSelection( XDISPLAY, selectionAtom, targetAtom, propAtom, src, time ); // Read the selection Atom type; int format; unsigned long nitems, nbytes; char *buffer; XGetWindowProperty( XDISPLAY, src, propAtom, 0, 1024, False, AnyPropertyType, &type, &format, &nitems, &nbytes, (unsigned char**)&buffer ); if( buffer != NULL ) { char* psz_dup = strdup( buffer ); char* psz_new = psz_dup; bool first = true; while( psz_new && *psz_new ) { int skip = 0; const char* sep[] = { "\r\n", "\n", NULL }; for( int i = 0; sep[i]; i++ ) { char* psz_end = strstr( psz_new, sep[i] ); if( !psz_end ) continue; *psz_end = '\0'; skip = strlen( sep[i] ); break; } if( *psz_new ) { bool playOnDrop = m_playOnDrop && first; CmdAddItem( getIntf(), psz_new, playOnDrop ).execute(); first = false; } psz_new += strlen( psz_new ) + skip; } free( psz_dup ); XFree( buffer ); } // Tell the source we accepted the drop XEvent event; event.type = ClientMessage; event.xclient.window = src; event.xclient.display = XDISPLAY; event.xclient.message_type = typeAtom; event.xclient.format = 32; event.xclient.data.l[0] = m_wnd; event.xclient.data.l[1] = 1; // drop accepted event.xclient.data.l[2] = actionAtom; XSendEvent( XDISPLAY, src, False, 0, &event ); } #endif <|endoftext|>
<commit_before>#include <chrono> #include <iostream> #include <memory> // unique_ptr #include <set> #include <utility> // pair #include <sdd/sdd.hh> #include "mc/live.hh" #include "mc/post.hh" #include "mc/pre.hh" #include "mc/work.hh" namespace pnmc { namespace mc { namespace chrono = std::chrono; typedef sdd::conf1 sdd_conf; typedef sdd::SDD<sdd_conf> SDD; typedef sdd::homomorphism<sdd_conf> homomorphism; using sdd::Composition; using sdd::Fixpoint; using sdd::Sum; using sdd::ValuesFunction; /*------------------------------------------------------------------------------------------------*/ struct mk_order_visitor : public boost::static_visitor<std::pair<std::string, sdd::order_builder<sdd_conf>>> { // Place: base case of the recursion, there's no more possible nested hierarchies. std::pair<std::string, sdd::order_builder<sdd_conf>> operator()(const pn::place* p) const noexcept { return make_pair(p->id, sdd::order_builder<sdd_conf>()); } // Hierarchy. std::pair<std::string, sdd::order_builder<sdd_conf>> operator()(const pn::module_node& m) const noexcept { sdd::order_builder<sdd_conf> ob; for (const auto& h : m.nested) { const auto res = boost::apply_visitor(mk_order_visitor(), *h); ob.push(res.first, res.second); } return make_pair(m.id , ob); } }; /*------------------------------------------------------------------------------------------------*/ sdd::order<sdd_conf> mk_order(const pn::net& net) { if (net.modules) { return sdd::order<sdd_conf>(boost::apply_visitor(mk_order_visitor(), *net.modules).second); } else { sdd::order_builder<sdd_conf> ob; for (const auto& place : net.places()) { ob.push(place.id); } return sdd::order<sdd_conf>(ob); } } /*------------------------------------------------------------------------------------------------*/ SDD initial_state(const sdd::order<sdd_conf>& order, const pn::net& net) { return SDD(order, [&](const std::string& id) -> sdd::values::flat_set<unsigned int> { return {net.places().find(id)->marking}; }); } /*------------------------------------------------------------------------------------------------*/ homomorphism transition_relation( const conf::pnmc_configuration& conf, const sdd::order<sdd_conf>& o , const pn::net& net, boost::dynamic_bitset<>& transitions_bitset) { chrono::time_point<chrono::system_clock> start; chrono::time_point<chrono::system_clock> end; std::size_t elapsed; start = chrono::system_clock::now(); std::set<homomorphism> operands; operands.insert(sdd::Id<sdd_conf>()); for (const auto& transition : net.transitions()) { homomorphism h_t = sdd::Id<sdd_conf>(); if (conf.compute_dead_transitions) { const auto f = ValuesFunction<sdd_conf>( o, transition.post.begin()->first , live(transition.index, transitions_bitset)); h_t = sdd::carrier(o, transition.post.begin()->first, f); } // post actions. for (const auto& arc : transition.post) { homomorphism f = ValuesFunction<sdd_conf>(o, arc.first, post(arc.second)); h_t = Composition(h_t, sdd::carrier(o, arc.first, f)); } // pre actions. for (const auto& arc : transition.pre) { homomorphism f = ValuesFunction<sdd_conf>(o, arc.first, pre(arc.second)); h_t = Composition(h_t, sdd::carrier(o, arc.first, f)); } operands.insert(h_t); } end = chrono::system_clock::now(); elapsed = chrono::duration_cast<chrono::seconds>(end-start).count(); if (conf.show_time) { std::cout << "Transition relation time: " << elapsed << "s" << std::endl; } start = chrono::system_clock::now(); const auto res = sdd::rewrite(Fixpoint(Sum<sdd_conf>(o, operands.cbegin(), operands.cend())), o); end = chrono::system_clock::now(); elapsed = chrono::duration_cast<chrono::seconds>(end-start).count(); if (conf.show_time) { std::cout << "Rewrite time: " << elapsed << "s" << std::endl; } return res; } /*------------------------------------------------------------------------------------------------*/ SDD state_space( const conf::pnmc_configuration& conf, const sdd::order<sdd_conf>& o, SDD m , homomorphism h) { chrono::time_point<chrono::system_clock> start = chrono::system_clock::now(); const auto res = h(o, m); chrono::time_point<chrono::system_clock> end = chrono::system_clock::now(); const std::size_t elapsed = chrono::duration_cast<chrono::seconds>(end-start).count(); if (conf.show_time) { std::cout << "State space computation time: " << elapsed << "s" << std::endl; } return res; } /*------------------------------------------------------------------------------------------------*/ void work(const conf::pnmc_configuration& conf, const pn::net& net) { auto manager = sdd::manager<sdd_conf>::init(); boost::dynamic_bitset<> transitions_bitset(net.transitions().size()); const sdd::order<sdd_conf>& o = mk_order(net); if (conf.show_order) { std::cout << o << std::endl; } const SDD m0 = initial_state(o, net); const homomorphism h = transition_relation(conf, o, net, transitions_bitset); if (conf.show_relation) { std::cout << h << std::endl; } const SDD m = state_space(conf, o, m0, h); const auto n = sdd::count_combinations(m); long double n_prime = n.template convert_to<long double>(); std::cout << n_prime << " states" << std::endl; if (conf.compute_dead_transitions) { std::deque<std::string> dead_transitions; for (auto i = 0; i < net.transitions().size(); ++i) { if (not transitions_bitset[i]) { dead_transitions.push_back(net.get_transition_by_index(i).id); } } std::cout << dead_transitions.size() << " dead transitions." << std::endl; if (not dead_transitions.empty()) { std::copy( dead_transitions.cbegin(), std::prev(dead_transitions.cend()) , std::ostream_iterator<std::string>(std::cout, ",")); std::cout << *std::prev(dead_transitions.cend()); } } if (conf.show_hash_tables_stats) { std::cout << manager << std::endl; } } /*------------------------------------------------------------------------------------------------*/ }} // namespace pnmc::mc <commit_msg>Correct handling of transitions with no post places, when creating the live homomorphism.<commit_after>#include <chrono> #include <iostream> #include <memory> // unique_ptr #include <set> #include <utility> // pair #include <sdd/sdd.hh> #include "mc/live.hh" #include "mc/post.hh" #include "mc/pre.hh" #include "mc/work.hh" namespace pnmc { namespace mc { namespace chrono = std::chrono; typedef sdd::conf1 sdd_conf; typedef sdd::SDD<sdd_conf> SDD; typedef sdd::homomorphism<sdd_conf> homomorphism; using sdd::Composition; using sdd::Fixpoint; using sdd::Sum; using sdd::ValuesFunction; /*------------------------------------------------------------------------------------------------*/ struct mk_order_visitor : public boost::static_visitor<std::pair<std::string, sdd::order_builder<sdd_conf>>> { // Place: base case of the recursion, there's no more possible nested hierarchies. std::pair<std::string, sdd::order_builder<sdd_conf>> operator()(const pn::place* p) const noexcept { return make_pair(p->id, sdd::order_builder<sdd_conf>()); } // Hierarchy. std::pair<std::string, sdd::order_builder<sdd_conf>> operator()(const pn::module_node& m) const noexcept { sdd::order_builder<sdd_conf> ob; for (const auto& h : m.nested) { const auto res = boost::apply_visitor(mk_order_visitor(), *h); ob.push(res.first, res.second); } return make_pair(m.id , ob); } }; /*------------------------------------------------------------------------------------------------*/ sdd::order<sdd_conf> mk_order(const pn::net& net) { if (net.modules) { return sdd::order<sdd_conf>(boost::apply_visitor(mk_order_visitor(), *net.modules).second); } else { sdd::order_builder<sdd_conf> ob; for (const auto& place : net.places()) { ob.push(place.id); } return sdd::order<sdd_conf>(ob); } } /*------------------------------------------------------------------------------------------------*/ SDD initial_state(const sdd::order<sdd_conf>& order, const pn::net& net) { return SDD(order, [&](const std::string& id) -> sdd::values::flat_set<unsigned int> { return {net.places().find(id)->marking}; }); } /*------------------------------------------------------------------------------------------------*/ homomorphism transition_relation( const conf::pnmc_configuration& conf, const sdd::order<sdd_conf>& o , const pn::net& net, boost::dynamic_bitset<>& transitions_bitset) { chrono::time_point<chrono::system_clock> start; chrono::time_point<chrono::system_clock> end; std::size_t elapsed; start = chrono::system_clock::now(); std::set<homomorphism> operands; operands.insert(sdd::Id<sdd_conf>()); for (const auto& transition : net.transitions()) { homomorphism h_t = sdd::Id<sdd_conf>(); if (conf.compute_dead_transitions) { if (not transition.post.empty()) { const auto f = ValuesFunction<sdd_conf>( o, transition.post.begin()->first , live(transition.index, transitions_bitset)); h_t = sdd::carrier(o, transition.post.begin()->first, f); } } // post actions. for (const auto& arc : transition.post) { homomorphism f = ValuesFunction<sdd_conf>(o, arc.first, post(arc.second)); h_t = Composition(h_t, sdd::carrier(o, arc.first, f)); } // pre actions. for (const auto& arc : transition.pre) { homomorphism f = ValuesFunction<sdd_conf>(o, arc.first, pre(arc.second)); h_t = Composition(h_t, sdd::carrier(o, arc.first, f)); } operands.insert(h_t); } end = chrono::system_clock::now(); elapsed = chrono::duration_cast<chrono::seconds>(end-start).count(); if (conf.show_time) { std::cout << "Transition relation time: " << elapsed << "s" << std::endl; } start = chrono::system_clock::now(); const auto res = sdd::rewrite(Fixpoint(Sum<sdd_conf>(o, operands.cbegin(), operands.cend())), o); end = chrono::system_clock::now(); elapsed = chrono::duration_cast<chrono::seconds>(end-start).count(); if (conf.show_time) { std::cout << "Rewrite time: " << elapsed << "s" << std::endl; } return res; } /*------------------------------------------------------------------------------------------------*/ SDD state_space( const conf::pnmc_configuration& conf, const sdd::order<sdd_conf>& o, SDD m , homomorphism h) { chrono::time_point<chrono::system_clock> start = chrono::system_clock::now(); const auto res = h(o, m); chrono::time_point<chrono::system_clock> end = chrono::system_clock::now(); const std::size_t elapsed = chrono::duration_cast<chrono::seconds>(end-start).count(); if (conf.show_time) { std::cout << "State space computation time: " << elapsed << "s" << std::endl; } return res; } /*------------------------------------------------------------------------------------------------*/ void work(const conf::pnmc_configuration& conf, const pn::net& net) { auto manager = sdd::manager<sdd_conf>::init(); boost::dynamic_bitset<> transitions_bitset(net.transitions().size()); const sdd::order<sdd_conf>& o = mk_order(net); if (conf.show_order) { std::cout << o << std::endl; } const SDD m0 = initial_state(o, net); const homomorphism h = transition_relation(conf, o, net, transitions_bitset); if (conf.show_relation) { std::cout << h << std::endl; } const SDD m = state_space(conf, o, m0, h); const auto n = sdd::count_combinations(m); long double n_prime = n.template convert_to<long double>(); std::cout << n_prime << " states" << std::endl; if (conf.compute_dead_transitions) { std::deque<std::string> dead_transitions; for (auto i = 0; i < net.transitions().size(); ++i) { if (not transitions_bitset[i]) { dead_transitions.push_back(net.get_transition_by_index(i).id); } } std::cout << dead_transitions.size() << " dead transitions." << std::endl; if (not dead_transitions.empty()) { std::copy( dead_transitions.cbegin(), std::prev(dead_transitions.cend()) , std::ostream_iterator<std::string>(std::cout, ",")); std::cout << *std::prev(dead_transitions.cend()); } } if (conf.show_hash_tables_stats) { std::cout << manager << std::endl; } } /*------------------------------------------------------------------------------------------------*/ }} // namespace pnmc::mc <|endoftext|>
<commit_before>/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mem_map.h" #include <sys/mman.h> #include "ScopedFd.h" #include "utils.h" #define USE_ASHMEM 1 #ifdef USE_ASHMEM #include <cutils/ashmem.h> #endif namespace art { #if !defined(NDEBUG) static size_t ParseHex(const std::string& string) { CHECK_EQ(8U, string.size()); const char* str = string.c_str(); char* end; size_t value = strtoul(str, &end, 16); CHECK(end != str) << "Failed to parse hexadecimal value from " << string; CHECK_EQ(*end, '\0') << "Failed to parse hexadecimal value from " << string; return value; } static void CheckMapRegion(uint32_t base, uint32_t limit, uint32_t start, uint32_t end, const std::string& maps) { CHECK(!(base >= start && base < end) // start of new within old && !(limit > start && limit < end) // end of new within old && !(base <= start && limit > end)) // start/end of new includes all of old << StringPrintf("Requested region %08x-%08x overlaps with existing map %08x-%08x\n", base, limit, start, end) << maps; } void CheckMapRequest(byte* addr, size_t length) { if (addr == NULL) { return; } uint32_t base = reinterpret_cast<size_t>(addr); uint32_t limit = base + length; #if defined(__APPLE__) // Mac OS vmmap(1) output currently looks something like this: // Virtual Memory Map of process 51036 (dex2oatd) // Output report format: 2.2 -- 32-bit process // // ==== regions for process 51036 (non-writable and writable regions are interleaved) // __PAGEZERO 00000000-00001000 [ 4K 0K 0K] ---/--- SM=NUL out/host/darwin-x86/bin/dex2oatd // __TEXT 00001000-00015000 [ 80K 80K 0K] r-x/rwx SM=COW out/host/darwin-x86/bin/dex2oatd // __DATA 00015000-00016000 [ 4K 4K 4K] rw-/rwx SM=PRV out/host/darwin-x86/bin/dex2oatd // __LINKEDIT 00016000-00044000 [ 184K 184K 0K] r--/rwx SM=COW out/host/darwin-x86/bin/dex2oatd // __TEXT 00044000-00046000 [ 8K 8K 4K] r-x/rwx SM=COW out/host/darwin-x86/obj/lib/libnativehelper.dylib // __DATA 00046000-00047000 [ 4K 4K 4K] rw-/rwx SM=ZER out/host/darwin-x86/obj/lib/libnativehelper.dylib // __LINKEDIT 00047000-0004a000 [ 12K 12K 0K] r--/rwx SM=COW out/host/darwin-x86/obj/lib/libnativehelper.dylib // ... // TODO: the -v option replaces "-w -resident -dirty -purge -submap -allSplitLibs -noCoalesce" >= 10.6. std::string command(StringPrintf("vmmap -w -resident -submap -allSplitLibs -noCoalesce -interleaved %d", getpid())); FILE* fp = popen(command.c_str(), "r"); if (fp == NULL) { PLOG(FATAL) << "popen failed"; } std::vector<char> chars(512); std::string maps; while (fgets(&chars[0], chars.size(), fp) != NULL) { std::string line(&chars[0]); maps += line; if (line.size() < 40 || line[31] != '-') { continue; } std::string start_str(line.substr(23, 8)); std::string end_str(line.substr(32, 8)); uint32_t start = ParseHex(start_str); uint32_t end = ParseHex(end_str); CheckMapRegion(base, limit, start, end, maps); } if (ferror(fp)) { PLOG(FATAL) << "fgets failed"; } if (pclose(fp) == -1) { PLOG(FATAL) << "pclose failed"; } #else // Linux std::string maps; bool read = ReadFileToString("/proc/self/maps", &maps); if (!read) { PLOG(FATAL) << "Failed to read /proc/self/maps"; } // Quick and dirty parse of output like shown below. We only focus // on grabbing the two 32-bit hex values at the start of each line // and will fail on wider addresses found on 64-bit systems. // 00008000-0001f000 r-xp 00000000 b3:01 273 /system/bin/toolbox // 0001f000-00021000 rw-p 00017000 b3:01 273 /system/bin/toolbox // 00021000-00029000 rw-p 00000000 00:00 0 [heap] // 40011000-40053000 r-xp 00000000 b3:01 1050 /system/lib/libc.so // 40053000-40056000 rw-p 00042000 b3:01 1050 /system/lib/libc.so // 40056000-40061000 rw-p 00000000 00:00 0 // 40061000-40063000 r-xp 00000000 b3:01 1107 /system/lib/libusbhost.so // 40063000-40064000 rw-p 00002000 b3:01 1107 /system/lib/libusbhost.so // 4009d000-400a0000 r-xp 00000000 b3:01 1022 /system/lib/liblog.so // 400a0000-400a1000 rw-p 00003000 b3:01 1022 /system/lib/liblog.so // 400b7000-400cc000 r-xp 00000000 b3:01 932 /system/lib/libm.so // 400cc000-400cd000 rw-p 00015000 b3:01 932 /system/lib/libm.so // 400cf000-400d0000 r--p 00000000 00:00 0 // 400e4000-400ec000 r--s 00000000 00:0b 388 /dev/__properties__ (deleted) // 400ec000-400fa000 r-xp 00000000 b3:01 1101 /system/lib/libcutils.so // 400fa000-400fb000 rw-p 0000e000 b3:01 1101 /system/lib/libcutils.so // 400fb000-4010a000 rw-p 00000000 00:00 0 // 4010d000-4010e000 r-xp 00000000 b3:01 929 /system/lib/libstdc++.so // 4010e000-4010f000 rw-p 00001000 b3:01 929 /system/lib/libstdc++.so // b0001000-b0009000 r-xp 00001000 b3:01 1098 /system/bin/linker // b0009000-b000a000 rw-p 00009000 b3:01 1098 /system/bin/linker // b000a000-b0015000 rw-p 00000000 00:00 0 // bee35000-bee56000 rw-p 00000000 00:00 0 [stack] // ffff0000-ffff1000 r-xp 00000000 00:00 0 [vectors] for (size_t i = 0; i < maps.size(); i++) { size_t remaining = maps.size() - i; if (remaining < 8+1+8) { // 00008000-0001f000 LOG(FATAL) << "Failed to parse at pos " << i << "\n" << maps; } std::string start_str(maps.substr(i, 8)); std::string end_str(maps.substr(i+1+8, 8)); uint32_t start = ParseHex(start_str); uint32_t end = ParseHex(end_str); CheckMapRegion(base, limit, start, end, maps); i += 8+1+8; i = maps.find('\n', i); CHECK(i != std::string::npos) << "Failed to find newline from pos " << i << "\n" << maps; } #endif } #else static void CheckMapRequest(byte*, size_t) { } #endif MemMap* MemMap::MapAnonymous(const char* name, byte* addr, size_t length, int prot) { CHECK_NE(0U, length); CHECK_NE(0, prot); size_t page_aligned_size = RoundUp(length, kPageSize); CheckMapRequest(addr, page_aligned_size); #ifdef USE_ASHMEM ScopedFd fd(ashmem_create_region(name, page_aligned_size)); int flags = MAP_PRIVATE; if (fd.get() == -1) { PLOG(ERROR) << "ashmem_create_region failed (" << name << ")"; return NULL; } #else ScopedFd fd(-1); int flags = MAP_PRIVATE | MAP_ANONYMOUS; #endif byte* actual = reinterpret_cast<byte*>(mmap(addr, page_aligned_size, prot, flags, fd.get(), 0)); if (actual == MAP_FAILED) { PLOG(ERROR) << "mmap failed (" << name << ")"; return NULL; } return new MemMap(actual, length, actual, page_aligned_size); } MemMap* MemMap::MapFileAtAddress(byte* addr, size_t length, int prot, int flags, int fd, off_t start) { CHECK_NE(0U, length); CHECK_NE(0, prot); CHECK_NE(0, flags & (MAP_SHARED | MAP_PRIVATE)); // adjust to be page-aligned int page_offset = start % kPageSize; off_t page_aligned_offset = start - page_offset; size_t page_aligned_size = RoundUp(length + page_offset, kPageSize); CheckMapRequest(addr, page_aligned_size); byte* actual = reinterpret_cast<byte*>(mmap(addr, page_aligned_size, prot, flags, fd, page_aligned_offset)); if (actual == MAP_FAILED) { PLOG(ERROR) << "mmap failed"; return NULL; } return new MemMap(actual + page_offset, length, actual, page_aligned_size); } MemMap::~MemMap() { if (base_begin_ == NULL && base_size_ == 0) { return; } int result = munmap(base_begin_, base_size_); if (result == -1) { PLOG(FATAL) << "munmap failed"; } } MemMap::MemMap(byte* begin, size_t size, void* base_begin, size_t base_size) : begin_(begin), size_(size), base_begin_(base_begin), base_size_(base_size) { CHECK(begin_ != NULL); CHECK_NE(size_, 0U); CHECK(base_begin_ != NULL); CHECK_NE(base_size_, 0U); }; } // namespace art <commit_msg>Keep trying to guess the 10.5 vmmap(1) syntax...<commit_after>/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mem_map.h" #include <sys/mman.h> #include "ScopedFd.h" #include "utils.h" #define USE_ASHMEM 1 #ifdef USE_ASHMEM #include <cutils/ashmem.h> #endif namespace art { #if !defined(NDEBUG) static size_t ParseHex(const std::string& string) { CHECK_EQ(8U, string.size()); const char* str = string.c_str(); char* end; size_t value = strtoul(str, &end, 16); CHECK(end != str) << "Failed to parse hexadecimal value from " << string; CHECK_EQ(*end, '\0') << "Failed to parse hexadecimal value from " << string; return value; } static void CheckMapRegion(uint32_t base, uint32_t limit, uint32_t start, uint32_t end, const std::string& maps) { CHECK(!(base >= start && base < end) // start of new within old && !(limit > start && limit < end) // end of new within old && !(base <= start && limit > end)) // start/end of new includes all of old << StringPrintf("Requested region %08x-%08x overlaps with existing map %08x-%08x\n", base, limit, start, end) << maps; } void CheckMapRequest(byte* addr, size_t length) { if (addr == NULL) { return; } uint32_t base = reinterpret_cast<size_t>(addr); uint32_t limit = base + length; #if defined(__APPLE__) // Mac OS vmmap(1) output currently looks something like this: // Virtual Memory Map of process 51036 (dex2oatd) // Output report format: 2.2 -- 32-bit process // // ==== regions for process 51036 (non-writable and writable regions are interleaved) // __PAGEZERO 00000000-00001000 [ 4K 0K 0K] ---/--- SM=NUL out/host/darwin-x86/bin/dex2oatd // __TEXT 00001000-00015000 [ 80K 80K 0K] r-x/rwx SM=COW out/host/darwin-x86/bin/dex2oatd // __DATA 00015000-00016000 [ 4K 4K 4K] rw-/rwx SM=PRV out/host/darwin-x86/bin/dex2oatd // __LINKEDIT 00016000-00044000 [ 184K 184K 0K] r--/rwx SM=COW out/host/darwin-x86/bin/dex2oatd // __TEXT 00044000-00046000 [ 8K 8K 4K] r-x/rwx SM=COW out/host/darwin-x86/obj/lib/libnativehelper.dylib // __DATA 00046000-00047000 [ 4K 4K 4K] rw-/rwx SM=ZER out/host/darwin-x86/obj/lib/libnativehelper.dylib // __LINKEDIT 00047000-0004a000 [ 12K 12K 0K] r--/rwx SM=COW out/host/darwin-x86/obj/lib/libnativehelper.dylib // ... // TODO: the -v option replaces "-w -resident -dirty -purge -submap -allSplitLibs -noCoalesce" >= 10.6. std::string command(StringPrintf("vmmap -w -resident -submap -allSplitLibs -interleaved %d", getpid())); FILE* fp = popen(command.c_str(), "r"); if (fp == NULL) { PLOG(FATAL) << "popen failed"; } std::vector<char> chars(512); std::string maps; while (fgets(&chars[0], chars.size(), fp) != NULL) { std::string line(&chars[0]); maps += line; if (line.size() < 40 || line[31] != '-') { continue; } std::string start_str(line.substr(23, 8)); std::string end_str(line.substr(32, 8)); uint32_t start = ParseHex(start_str); uint32_t end = ParseHex(end_str); CheckMapRegion(base, limit, start, end, maps); } if (ferror(fp)) { PLOG(FATAL) << "fgets failed"; } if (pclose(fp) == -1) { PLOG(FATAL) << "pclose failed"; } #else // Linux std::string maps; bool read = ReadFileToString("/proc/self/maps", &maps); if (!read) { PLOG(FATAL) << "Failed to read /proc/self/maps"; } // Quick and dirty parse of output like shown below. We only focus // on grabbing the two 32-bit hex values at the start of each line // and will fail on wider addresses found on 64-bit systems. // 00008000-0001f000 r-xp 00000000 b3:01 273 /system/bin/toolbox // 0001f000-00021000 rw-p 00017000 b3:01 273 /system/bin/toolbox // 00021000-00029000 rw-p 00000000 00:00 0 [heap] // 40011000-40053000 r-xp 00000000 b3:01 1050 /system/lib/libc.so // 40053000-40056000 rw-p 00042000 b3:01 1050 /system/lib/libc.so // 40056000-40061000 rw-p 00000000 00:00 0 // 40061000-40063000 r-xp 00000000 b3:01 1107 /system/lib/libusbhost.so // 40063000-40064000 rw-p 00002000 b3:01 1107 /system/lib/libusbhost.so // 4009d000-400a0000 r-xp 00000000 b3:01 1022 /system/lib/liblog.so // 400a0000-400a1000 rw-p 00003000 b3:01 1022 /system/lib/liblog.so // 400b7000-400cc000 r-xp 00000000 b3:01 932 /system/lib/libm.so // 400cc000-400cd000 rw-p 00015000 b3:01 932 /system/lib/libm.so // 400cf000-400d0000 r--p 00000000 00:00 0 // 400e4000-400ec000 r--s 00000000 00:0b 388 /dev/__properties__ (deleted) // 400ec000-400fa000 r-xp 00000000 b3:01 1101 /system/lib/libcutils.so // 400fa000-400fb000 rw-p 0000e000 b3:01 1101 /system/lib/libcutils.so // 400fb000-4010a000 rw-p 00000000 00:00 0 // 4010d000-4010e000 r-xp 00000000 b3:01 929 /system/lib/libstdc++.so // 4010e000-4010f000 rw-p 00001000 b3:01 929 /system/lib/libstdc++.so // b0001000-b0009000 r-xp 00001000 b3:01 1098 /system/bin/linker // b0009000-b000a000 rw-p 00009000 b3:01 1098 /system/bin/linker // b000a000-b0015000 rw-p 00000000 00:00 0 // bee35000-bee56000 rw-p 00000000 00:00 0 [stack] // ffff0000-ffff1000 r-xp 00000000 00:00 0 [vectors] for (size_t i = 0; i < maps.size(); i++) { size_t remaining = maps.size() - i; if (remaining < 8+1+8) { // 00008000-0001f000 LOG(FATAL) << "Failed to parse at pos " << i << "\n" << maps; } std::string start_str(maps.substr(i, 8)); std::string end_str(maps.substr(i+1+8, 8)); uint32_t start = ParseHex(start_str); uint32_t end = ParseHex(end_str); CheckMapRegion(base, limit, start, end, maps); i += 8+1+8; i = maps.find('\n', i); CHECK(i != std::string::npos) << "Failed to find newline from pos " << i << "\n" << maps; } #endif } #else static void CheckMapRequest(byte*, size_t) { } #endif MemMap* MemMap::MapAnonymous(const char* name, byte* addr, size_t length, int prot) { CHECK_NE(0U, length); CHECK_NE(0, prot); size_t page_aligned_size = RoundUp(length, kPageSize); CheckMapRequest(addr, page_aligned_size); #ifdef USE_ASHMEM ScopedFd fd(ashmem_create_region(name, page_aligned_size)); int flags = MAP_PRIVATE; if (fd.get() == -1) { PLOG(ERROR) << "ashmem_create_region failed (" << name << ")"; return NULL; } #else ScopedFd fd(-1); int flags = MAP_PRIVATE | MAP_ANONYMOUS; #endif byte* actual = reinterpret_cast<byte*>(mmap(addr, page_aligned_size, prot, flags, fd.get(), 0)); if (actual == MAP_FAILED) { PLOG(ERROR) << "mmap failed (" << name << ")"; return NULL; } return new MemMap(actual, length, actual, page_aligned_size); } MemMap* MemMap::MapFileAtAddress(byte* addr, size_t length, int prot, int flags, int fd, off_t start) { CHECK_NE(0U, length); CHECK_NE(0, prot); CHECK_NE(0, flags & (MAP_SHARED | MAP_PRIVATE)); // adjust to be page-aligned int page_offset = start % kPageSize; off_t page_aligned_offset = start - page_offset; size_t page_aligned_size = RoundUp(length + page_offset, kPageSize); CheckMapRequest(addr, page_aligned_size); byte* actual = reinterpret_cast<byte*>(mmap(addr, page_aligned_size, prot, flags, fd, page_aligned_offset)); if (actual == MAP_FAILED) { PLOG(ERROR) << "mmap failed"; return NULL; } return new MemMap(actual + page_offset, length, actual, page_aligned_size); } MemMap::~MemMap() { if (base_begin_ == NULL && base_size_ == 0) { return; } int result = munmap(base_begin_, base_size_); if (result == -1) { PLOG(FATAL) << "munmap failed"; } } MemMap::MemMap(byte* begin, size_t size, void* base_begin, size_t base_size) : begin_(begin), size_(size), base_begin_(base_begin), base_size_(base_size) { CHECK(begin_ != NULL); CHECK_NE(size_, 0U); CHECK(base_begin_ != NULL); CHECK_NE(base_size_, 0U); }; } // namespace art <|endoftext|>
<commit_before>#include "musicpp.h" static Interval INTERVAL_TABLE[12][2] = { { Interval(IntervalQuality::PERFECT, IntervalNumber::UNISON), Interval(IntervalQuality::DIMINISHED, IntervalNumber::SECOND) }, { Interval(IntervalQuality::MINOR, IntervalNumber::SECOND), Interval(IntervalQuality::AUGMENTED, IntervalNumber::UNISON) }, { Interval(IntervalQuality::MAJOR, IntervalNumber::SECOND), Interval(IntervalQuality::DIMINISHED, IntervalNumber::THIRD) }, { Interval(IntervalQuality::MINOR, IntervalNumber::THIRD), Interval(IntervalQuality::AUGMENTED, IntervalNumber::SECOND) }, { Interval(IntervalQuality::MAJOR, IntervalNumber::THIRD), Interval(IntervalQuality::DIMINISHED, IntervalNumber::FOURTH) }, { Interval(IntervalQuality::PERFECT, IntervalNumber::FOURTH), Interval(IntervalQuality::AUGMENTED, IntervalNumber::THIRD) }, { Interval(IntervalQuality::AUGMENTED, IntervalNumber::FOURTH), Interval(IntervalQuality::DIMINISHED, IntervalNumber::FIFTH) }, { Interval(IntervalQuality::PERFECT, IntervalNumber::FIFTH), Interval(IntervalQuality::DIMINISHED, IntervalNumber::SIXTH) }, { Interval(IntervalQuality::MINOR, IntervalNumber::SIXTH), Interval(IntervalQuality::AUGMENTED, IntervalNumber::FIFTH) }, { Interval(IntervalQuality::MAJOR, IntervalNumber::SIXTH), Interval(IntervalQuality::DIMINISHED, IntervalNumber::SEVENTH) }, { Interval(IntervalQuality::MINOR, IntervalNumber::SEVENTH), Interval(IntervalQuality::AUGMENTED, IntervalNumber::SIXTH) }, { Interval(IntervalQuality::MAJOR, IntervalNumber::SEVENTH), Interval(IntervalQuality::DIMINISHED, IntervalNumber::UNISON) }}; PitchClass NamedPitch::Class() const { return static_cast<PitchClass>((static_cast<int>(BASE_CLASS_PITCHES[static_cast<int>(p_)]) + acc_count_ * static_cast<int>(acc_type_)) % NUM_PITCH_CLASSES); } Interval IntervalBetween(NamedPitch lower, NamedPitch upper) { IntervalNumber number = static_cast<IntervalNumber>( ((static_cast<int>(upper.Base()) - static_cast<int>(lower.Base())) % NUM_BASE_PITCHES) + 1); int delta = (static_cast<int>(upper.Class()) - static_cast<int>(lower.Class())) % NUM_PITCH_CLASSES; for (const Interval& candidate : INTERVAL_TABLE[delta]) { if (candidate.Number() == number) return candidate; } CHECK(false); } <commit_msg>Add comments to interval table<commit_after>#include "musicpp.h" static Interval INTERVAL_TABLE[12][2] = { { Interval(IntervalQuality::PERFECT, IntervalNumber::UNISON), Interval(IntervalQuality::DIMINISHED, IntervalNumber::SECOND) }, // 0 semitones { Interval(IntervalQuality::MINOR, IntervalNumber::SECOND), Interval(IntervalQuality::AUGMENTED, IntervalNumber::UNISON) }, // 1 semitones { Interval(IntervalQuality::MAJOR, IntervalNumber::SECOND), Interval(IntervalQuality::DIMINISHED, IntervalNumber::THIRD) }, // 2 semitones { Interval(IntervalQuality::MINOR, IntervalNumber::THIRD), Interval(IntervalQuality::AUGMENTED, IntervalNumber::SECOND) }, // 3 semitones { Interval(IntervalQuality::MAJOR, IntervalNumber::THIRD), Interval(IntervalQuality::DIMINISHED, IntervalNumber::FOURTH) }, // 4 semitones { Interval(IntervalQuality::PERFECT, IntervalNumber::FOURTH), Interval(IntervalQuality::AUGMENTED, IntervalNumber::THIRD) }, // 5 semitones { Interval(IntervalQuality::AUGMENTED, IntervalNumber::FOURTH), Interval(IntervalQuality::DIMINISHED, IntervalNumber::FIFTH) }, // 6 semitones { Interval(IntervalQuality::PERFECT, IntervalNumber::FIFTH), Interval(IntervalQuality::DIMINISHED, IntervalNumber::SIXTH) }, // 7 semitones { Interval(IntervalQuality::MINOR, IntervalNumber::SIXTH), Interval(IntervalQuality::AUGMENTED, IntervalNumber::FIFTH) }, // 8 semitones { Interval(IntervalQuality::MAJOR, IntervalNumber::SIXTH), Interval(IntervalQuality::DIMINISHED, IntervalNumber::SEVENTH) }, // 9 semitones { Interval(IntervalQuality::MINOR, IntervalNumber::SEVENTH), Interval(IntervalQuality::AUGMENTED, IntervalNumber::SIXTH) }, // 10 semitones { Interval(IntervalQuality::MAJOR, IntervalNumber::SEVENTH), Interval(IntervalQuality::DIMINISHED, IntervalNumber::UNISON) }, // 11 semitones }; PitchClass NamedPitch::Class() const { return static_cast<PitchClass>((static_cast<int>(BASE_CLASS_PITCHES[static_cast<int>(p_)]) + acc_count_ * static_cast<int>(acc_type_)) % NUM_PITCH_CLASSES); } Interval IntervalBetween(NamedPitch lower, NamedPitch upper) { IntervalNumber number = static_cast<IntervalNumber>( ((static_cast<int>(upper.Base()) - static_cast<int>(lower.Base())) % NUM_BASE_PITCHES) + 1); int delta = (static_cast<int>(upper.Class()) - static_cast<int>(lower.Class())) % NUM_PITCH_CLASSES; for (const Interval& candidate : INTERVAL_TABLE[delta]) { if (candidate.Number() == number) return candidate; } CHECK(false); } <|endoftext|>
<commit_before>#include "../../../src/contents.hh" #include "../../../src/configuration.hh" #include "../../../src/show_message.hh" #include "move.hh" namespace vick { namespace move { boost::optional<std::shared_ptr<change> > mvmatch(contents& contents, boost::optional<int>) { if(MATCHES.size() % 2 != 0) { show_message("MATCHES variable doesn't have an even number of elements, don't know how to make matches"); return boost::none; } auto y = contents.y; size_t x_fin = contents.cont[y].find_first_of(MATCHES, contents.x); while(x_fin == std::string::npos) { if(++y >= contents.cont.size()) { show_message("Can't find any matches in string"); return boost::none; } x_fin = contents.cont[y].find_first_of(MATCHES); } size_t index_match = MATCHES.find_first_of(contents.cont[y][x_fin]); bool forward = index_match % 2 == 0; if(forward) index_match++; else index_match--; char match = MATCHES[index_match]; size_t x_beg; if(forward) { x_beg = contents.cont[y].find_first_of(match, x_fin+1); while(x_beg == std::string::npos) { if(++y >= contents.cont.size()) { show_message(std::string("Can't find any matches in string for ") + match); return boost::none; } x_beg = contents.cont[y].find_first_of(MATCHES); } } else { x_beg = contents.cont[y].find_last_of(match, x_fin-1); while(x_beg == std::string::npos) { if(--y < contents.cont.size()) { show_message(std::string("Can't find corresponding match for ") + match); return boost::none; } x_beg = contents.cont[y].find_last_of(match); } } contents.y = y; contents.x = x_beg; return boost::none; } } } <commit_msg>`mvmatch()` now properly jumps over pairs of its own type it is seeking<commit_after>#include "../../../src/contents.hh" #include "../../../src/configuration.hh" #include "../../../src/show_message.hh" #include "move.hh" namespace vick { namespace move { boost::optional<std::shared_ptr<change> > mvmatch(contents& contents, boost::optional<int>) { if(MATCHES.size() % 2 != 0) { show_message("MATCHES variable doesn't have an even number of elements, don't know how to make matches"); return boost::none; } auto y = contents.y; size_t x_fin = contents.cont[y].find_first_of(MATCHES, contents.x); while(x_fin == std::string::npos) { if(++y >= contents.cont.size()) { show_message("Can't find any matches in string"); return boost::none; } x_fin = contents.cont[y].find_first_of(MATCHES); } size_t index_match = MATCHES.find_first_of(contents.cont[y][x_fin]); bool forward = index_match % 2 == 0; char match = MATCHES[index_match + (forward ? 1 : -1)]; char skipme = MATCHES[index_match]; std::string both {match,skipme,'\0'}; size_t x_beg = x_fin; int numskipped = 0; #define dasif \ if (contents.cont[y][x_beg] == skipme) { \ numskipped++; \ } else if (numskipped) { \ numskipped--; \ } else { \ goto set; \ } #define testnumskipped(expr, direction, check0) \ while (x_beg != std::string::npos and \ (not check0 or x_beg != 0)) { \ dasif; \ x_beg = contents.cont[y].find_##direction##_of(both, \ x_beg expr); \ } \ if (check0 and x_beg == 0) { \ dasif; \ } #define testforward testnumskipped(+1, first, false) #define testbackward testnumskipped(-1, last, true) if(forward) { x_beg = contents.cont[y].find_first_of(both, x_beg+1); testforward; while(x_beg == std::string::npos) { if(++y >= contents.cont.size()) { show_message(std::string("Can't find any matches in string for ") + match); return boost::none; } x_beg = contents.cont[y].find_first_of(both); testforward; } } else { x_beg = contents.cont[y].find_last_of(both, x_beg-1); testbackward; while(x_beg == std::string::npos || x_beg == 0) { if(y == 0) { show_message(std::string("Can't find corresponding match for ") + match); return boost::none; } x_beg = contents.cont[--y].find_last_of(both); testbackward; } } set: contents.y = y; contents.x = x_beg; return boost::none; } } } <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <boost/bind.hpp> #include <asio/ip/host_name.hpp> #include "libtorrent/natpmp.hpp" #include "libtorrent/io.hpp" #include "libtorrent/assert.hpp" #include "libtorrent/enum_net.hpp" using boost::bind; using namespace libtorrent; enum { num_mappings = 2 }; namespace libtorrent { // defined in upnp.cpp bool is_local(address const& a); address guess_local_address(asio::io_service&); } natpmp::natpmp(io_service& ios, address const& listen_interface, portmap_callback_t const& cb) : m_callback(cb) , m_currently_mapping(-1) , m_retry_count(0) , m_socket(ios) , m_send_timer(ios) , m_refresh_timer(ios) , m_disabled(false) { m_mappings[0].protocol = 2; // tcp m_mappings[1].protocol = 1; // udp #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log.open("natpmp.log", std::ios::in | std::ios::out | std::ios::trunc); #endif rebind(listen_interface); } void natpmp::rebind(address const& listen_interface) try { address local = address_v4::any(); if (listen_interface != address_v4::any()) { local = listen_interface; } else { local = guess_local_address(m_socket.io_service()); if (local == address_v4::any()) { throw std::runtime_error("local host is probably not on a NATed " "network. disabling NAT-PMP"); } } #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " local ip: " << local.to_string() << std::endl; #endif if (!is_local(local)) { // the local address seems to be an external // internet address. Assume it is not behind a NAT throw std::runtime_error("local IP is not on a local network"); } m_disabled = false; asio::error_code ec; udp::endpoint nat_endpoint(router_for_interface(local, ec), 5351); if (ec) throw std::runtime_error("cannot retrieve router address"); if (nat_endpoint == m_nat_endpoint) return; m_nat_endpoint = nat_endpoint; #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "assuming router is at: " << m_nat_endpoint.address().to_string() << std::endl; #endif m_socket.open(udp::v4()); m_socket.bind(udp::endpoint(address_v4::any(), 0)); for (int i = 0; i < num_mappings; ++i) { if (m_mappings[i].local_port == 0) continue; refresh_mapping(i); } } catch (std::exception& e) { m_disabled = true; std::stringstream msg; msg << "NAT-PMP disabled: " << e.what(); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << msg.str() << std::endl; #endif m_callback(0, 0, msg.str()); }; void natpmp::set_mappings(int tcp, int udp) { if (m_disabled) return; update_mapping(0, tcp); update_mapping(1, udp); } void natpmp::update_mapping(int i, int port) { natpmp::mapping& m = m_mappings[i]; if (port <= 0) return; if (m.local_port != port) m.need_update = true; m.local_port = port; // prefer the same external port as the local port if (m.external_port == 0) m.external_port = port; if (m_currently_mapping == -1) { // the socket is not currently in use // send out a mapping request m_retry_count = 0; send_map_request(i); m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, self(), _1, _2)); } } void natpmp::send_map_request(int i) try { using namespace libtorrent::detail; TORRENT_ASSERT(m_currently_mapping == -1 || m_currently_mapping == i); m_currently_mapping = i; mapping& m = m_mappings[i]; char buf[12]; char* out = buf; write_uint8(0, out); // NAT-PMP version write_uint8(m.protocol, out); // map "protocol" write_uint16(0, out); // reserved write_uint16(m.local_port, out); // private port write_uint16(m.external_port, out); // requested public port int ttl = m.external_port == 0 ? 0 : 3600; write_uint32(ttl, out); // port mapping lifetime #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " ==> port map request: " << (m.protocol == 1 ? "udp" : "tcp") << " local: " << m.local_port << " external: " << m.external_port << " ttl: " << ttl << std::endl; #endif m_socket.send_to(asio::buffer(buf, 12), m_nat_endpoint); // linear back-off instead of exponential ++m_retry_count; m_send_timer.expires_from_now(milliseconds(250 * m_retry_count)); m_send_timer.async_wait(bind(&natpmp::resend_request, self(), i, _1)); } catch (std::exception& e) { std::string err = e.what(); }; void natpmp::resend_request(int i, asio::error_code const& e) { if (e) return; if (m_currently_mapping != i) return; if (m_retry_count >= 9) { m_mappings[i].need_update = false; // try again in two hours m_mappings[i].expires = time_now() + hours(2); return; } send_map_request(i); } void natpmp::on_reply(asio::error_code const& e , std::size_t bytes_transferred) { using namespace libtorrent::detail; if (e) return; try { if (m_remote != m_nat_endpoint) { m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, self(), _1, _2)); return; } m_send_timer.cancel(); TORRENT_ASSERT(m_currently_mapping >= 0); int i = m_currently_mapping; mapping& m = m_mappings[i]; char* in = m_response_buffer; int version = read_uint8(in); int cmd = read_uint8(in); int result = read_uint16(in); int time = read_uint32(in); int private_port = read_uint16(in); int public_port = read_uint16(in); int lifetime = read_uint32(in); (void)time; // to remove warning #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== port map response: " << (cmd - 128 == 1 ? "udp" : "tcp") << " local: " << private_port << " external: " << public_port << " ttl: " << lifetime << std::endl; #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (version != 0) { m_log << "*** unexpected version: " << version << std::endl; } #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (private_port != m.local_port) { m_log << "*** unexpected local port: " << private_port << std::endl; } #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (cmd != 128 + m.protocol) { m_log << "*** unexpected protocol: " << (cmd - 128) << std::endl; } #endif if (public_port == 0 || lifetime == 0) { // this means the mapping was // successfully closed m.local_port = 0; } else { m.expires = time_now() + seconds(int(lifetime * 0.7f)); m.external_port = public_port; } if (result != 0) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "*** ERROR: " << result << std::endl; #endif std::stringstream errmsg; errmsg << "NAT router reports error (" << result << ") "; switch (result) { case 1: errmsg << "Unsupported protocol version"; break; case 2: errmsg << "Not authorized to create port map (enable NAT-PMP on your router)"; break; case 3: errmsg << "Network failure"; break; case 4: errmsg << "Out of resources"; break; case 5: errmsg << "Unsupported opcode"; break; } throw std::runtime_error(errmsg.str()); } // don't report when we remove mappings if (m.local_port != 0) { int tcp_port = 0; int udp_port = 0; if (m.protocol == 1) udp_port = m.external_port; else tcp_port = public_port; m_callback(tcp_port, udp_port, ""); } } catch (std::exception& e) { // try again in two hours m_mappings[m_currently_mapping].expires = time_now() + hours(2); m_callback(0, 0, e.what()); } int i = m_currently_mapping; m_currently_mapping = -1; m_mappings[i].need_update = false; m_send_timer.cancel(); update_expiration_timer(); try_next_mapping(i); } void natpmp::update_expiration_timer() { ptime now = time_now(); ptime min_expire = now + seconds(3600); int min_index = -1; for (int i = 0; i < num_mappings; ++i) if (m_mappings[i].expires < min_expire && m_mappings[i].local_port != 0) { min_expire = m_mappings[i].expires; min_index = i; } if (min_index >= 0) { m_refresh_timer.expires_from_now(min_expire - now); m_refresh_timer.async_wait(bind(&natpmp::mapping_expired, self(), _1, min_index)); } } void natpmp::mapping_expired(asio::error_code const& e, int i) { if (e) return; #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "*** mapping " << i << " expired, updating" << std::endl; #endif refresh_mapping(i); } void natpmp::refresh_mapping(int i) { m_mappings[i].need_update = true; if (m_currently_mapping == -1) { // the socket is not currently in use // send out a mapping request m_retry_count = 0; send_map_request(i); m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, self(), _1, _2)); } } void natpmp::try_next_mapping(int i) { ++i; if (i >= num_mappings) i = 0; if (m_mappings[i].need_update) refresh_mapping(i); } void natpmp::close() { if (m_disabled) return; for (int i = 0; i < num_mappings; ++i) { if (m_mappings[i].local_port == 0) continue; m_mappings[i].external_port = 0; refresh_mapping(i); } } <commit_msg>natpmp close fix<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <boost/bind.hpp> #include <asio/ip/host_name.hpp> #include "libtorrent/natpmp.hpp" #include "libtorrent/io.hpp" #include "libtorrent/assert.hpp" #include "libtorrent/enum_net.hpp" using boost::bind; using namespace libtorrent; enum { num_mappings = 2 }; namespace libtorrent { // defined in upnp.cpp bool is_local(address const& a); address guess_local_address(asio::io_service&); } natpmp::natpmp(io_service& ios, address const& listen_interface, portmap_callback_t const& cb) : m_callback(cb) , m_currently_mapping(-1) , m_retry_count(0) , m_socket(ios) , m_send_timer(ios) , m_refresh_timer(ios) , m_disabled(false) { m_mappings[0].protocol = 2; // tcp m_mappings[1].protocol = 1; // udp #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log.open("natpmp.log", std::ios::in | std::ios::out | std::ios::trunc); #endif rebind(listen_interface); } void natpmp::rebind(address const& listen_interface) try { address local = address_v4::any(); if (listen_interface != address_v4::any()) { local = listen_interface; } else { local = guess_local_address(m_socket.io_service()); if (local == address_v4::any()) { throw std::runtime_error("local host is probably not on a NATed " "network. disabling NAT-PMP"); } } #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " local ip: " << local.to_string() << std::endl; #endif if (!is_local(local)) { // the local address seems to be an external // internet address. Assume it is not behind a NAT throw std::runtime_error("local IP is not on a local network"); } m_disabled = false; asio::error_code ec; udp::endpoint nat_endpoint(router_for_interface(local, ec), 5351); if (ec) throw std::runtime_error("cannot retrieve router address"); if (nat_endpoint == m_nat_endpoint) return; m_nat_endpoint = nat_endpoint; #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "assuming router is at: " << m_nat_endpoint.address().to_string() << std::endl; #endif m_socket.open(udp::v4()); m_socket.bind(udp::endpoint(address_v4::any(), 0)); for (int i = 0; i < num_mappings; ++i) { if (m_mappings[i].local_port == 0) continue; refresh_mapping(i); } } catch (std::exception& e) { m_disabled = true; std::stringstream msg; msg << "NAT-PMP disabled: " << e.what(); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << msg.str() << std::endl; #endif m_callback(0, 0, msg.str()); }; void natpmp::set_mappings(int tcp, int udp) { if (m_disabled) return; update_mapping(0, tcp); update_mapping(1, udp); } void natpmp::update_mapping(int i, int port) { natpmp::mapping& m = m_mappings[i]; if (port <= 0) return; if (m.local_port != port) m.need_update = true; m.local_port = port; // prefer the same external port as the local port if (m.external_port == 0) m.external_port = port; if (m_currently_mapping == -1) { // the socket is not currently in use // send out a mapping request m_retry_count = 0; send_map_request(i); m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, self(), _1, _2)); } } void natpmp::send_map_request(int i) try { using namespace libtorrent::detail; TORRENT_ASSERT(m_currently_mapping == -1 || m_currently_mapping == i); m_currently_mapping = i; mapping& m = m_mappings[i]; char buf[12]; char* out = buf; write_uint8(0, out); // NAT-PMP version write_uint8(m.protocol, out); // map "protocol" write_uint16(0, out); // reserved write_uint16(m.local_port, out); // private port write_uint16(m.external_port, out); // requested public port int ttl = m.external_port == 0 ? 0 : 3600; write_uint32(ttl, out); // port mapping lifetime #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " ==> port map request: " << (m.protocol == 1 ? "udp" : "tcp") << " local: " << m.local_port << " external: " << m.external_port << " ttl: " << ttl << std::endl; #endif m_socket.send_to(asio::buffer(buf, 12), m_nat_endpoint); // linear back-off instead of exponential ++m_retry_count; m_send_timer.expires_from_now(milliseconds(250 * m_retry_count)); m_send_timer.async_wait(bind(&natpmp::resend_request, self(), i, _1)); } catch (std::exception& e) { std::string err = e.what(); }; void natpmp::resend_request(int i, asio::error_code const& e) { if (e) return; if (m_currently_mapping != i) return; if (m_retry_count >= 9) { m_mappings[i].need_update = false; // try again in two hours m_mappings[i].expires = time_now() + hours(2); return; } send_map_request(i); } void natpmp::on_reply(asio::error_code const& e , std::size_t bytes_transferred) { using namespace libtorrent::detail; if (e) return; try { if (m_remote != m_nat_endpoint) { m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, self(), _1, _2)); return; } m_send_timer.cancel(); TORRENT_ASSERT(m_currently_mapping >= 0); int i = m_currently_mapping; mapping& m = m_mappings[i]; char* in = m_response_buffer; int version = read_uint8(in); int cmd = read_uint8(in); int result = read_uint16(in); int time = read_uint32(in); int private_port = read_uint16(in); int public_port = read_uint16(in); int lifetime = read_uint32(in); (void)time; // to remove warning #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== port map response: " << (cmd - 128 == 1 ? "udp" : "tcp") << " local: " << private_port << " external: " << public_port << " ttl: " << lifetime << std::endl; #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (version != 0) { m_log << "*** unexpected version: " << version << std::endl; } #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (private_port != m.local_port) { m_log << "*** unexpected local port: " << private_port << std::endl; } #endif #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) if (cmd != 128 + m.protocol) { m_log << "*** unexpected protocol: " << (cmd - 128) << std::endl; } #endif if (public_port == 0 || lifetime == 0) { // this means the mapping was // successfully closed m.local_port = 0; } else { m.expires = time_now() + seconds(int(lifetime * 0.7f)); m.external_port = public_port; } if (result != 0) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "*** ERROR: " << result << std::endl; #endif std::stringstream errmsg; errmsg << "NAT router reports error (" << result << ") "; switch (result) { case 1: errmsg << "Unsupported protocol version"; break; case 2: errmsg << "Not authorized to create port map (enable NAT-PMP on your router)"; break; case 3: errmsg << "Network failure"; break; case 4: errmsg << "Out of resources"; break; case 5: errmsg << "Unsupported opcode"; break; } throw std::runtime_error(errmsg.str()); } // don't report when we remove mappings if (m.local_port != 0) { int tcp_port = 0; int udp_port = 0; if (m.protocol == 1) udp_port = m.external_port; else tcp_port = public_port; m_callback(tcp_port, udp_port, ""); } } catch (std::exception& e) { // try again in two hours m_mappings[m_currently_mapping].expires = time_now() + hours(2); m_callback(0, 0, e.what()); } int i = m_currently_mapping; m_currently_mapping = -1; m_mappings[i].need_update = false; m_send_timer.cancel(); update_expiration_timer(); try_next_mapping(i); } void natpmp::update_expiration_timer() { ptime now = time_now(); ptime min_expire = now + seconds(3600); int min_index = -1; for (int i = 0; i < num_mappings; ++i) if (m_mappings[i].expires < min_expire && m_mappings[i].local_port != 0) { min_expire = m_mappings[i].expires; min_index = i; } if (min_index >= 0) { m_refresh_timer.expires_from_now(min_expire - now); m_refresh_timer.async_wait(bind(&natpmp::mapping_expired, self(), _1, min_index)); } } void natpmp::mapping_expired(asio::error_code const& e, int i) { if (e) return; #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "*** mapping " << i << " expired, updating" << std::endl; #endif refresh_mapping(i); } void natpmp::refresh_mapping(int i) { m_mappings[i].need_update = true; if (m_currently_mapping == -1) { // the socket is not currently in use // send out a mapping request m_retry_count = 0; send_map_request(i); m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16) , m_remote, bind(&natpmp::on_reply, self(), _1, _2)); } } void natpmp::try_next_mapping(int i) { ++i; if (i >= num_mappings) i = 0; if (m_mappings[i].need_update) refresh_mapping(i); } void natpmp::close() { asio::error_code ec; m_socket.close(ec); if (m_disabled) return; for (int i = 0; i < num_mappings; ++i) { if (m_mappings[i].local_port == 0) continue; m_mappings[i].external_port = 0; refresh_mapping(i); } m_refresh_timer.cancel(); m_send_timer.cancel(); } <|endoftext|>
<commit_before>#include <string> #include <vector> #include <boost/optional.hpp> #include "prompt.hh" #include "configuration.hh" #include "to_str.hh" #include "newmove.hh" #include "show_message.hh" #include "visual.hh" void mvline(contents& contents, boost::optional<int> line) { if(line) { contents.x = 0; int cont = line.get(); if(cont < 0) { show_message("Can't move to a negative line!"); contents.y = 0; return; } contents.y = cont; if(cont >= contents.cont.size()) { contents.y = contents.cont.size() - 1; show_message("Can't move past end of buffer!"); } } else { while(true) { std::string str = prompt("Goto line: "); try { int res = std::stoi(str); mvline(contents, res); return; } catch(std::invalid_argument) { continue; } } } } void mv(contents& contents, unsigned long _y, unsigned long _x) { contents.y = _y; contents.x = _x; if((long) contents.y < 0) contents.y = 0; if(contents.y >= contents.cont.size()) contents.y = contents.cont.size() - 1; if((long) contents.x < 0) contents.x = 0; if(contents.x >= contents.cont[contents.y].size()) contents.x = contents.cont[contents.y].size() - 1; } void mvrel(contents& contents, long y, long x) { if(y < 0) mvu(contents,-y); else mvd(contents, y); if(x < 0) mvb(contents,-x); else mvf(contents, x); } void mvcol(contents& contents, boost::optional<int> col) { if(col) { unsigned int len = contents.cont[contents.y].length(); if(len >= col.get()) { contents.x = col.get(); contents.waiting_for_desired = false; } else { show_message((std::string("Can't move to column: ") + int_to_str(col.get())).c_str()); } } else { while(true) { std::string str = prompt("Goto column: "); try { int res = std::stoi(str); mvcol(contents, res); return; } catch(std::invalid_argument) { continue; } } } } void mvsot(contents& contents, boost::optional<int> op) { mvsol(contents, op); const std::string& str = contents.cont[contents.y]; for(unsigned int i = 0; i < str.length(); i++) { if(str[i] == ' ' || str[i] == '\t') mvf(contents, op); else break; } } void mveol(contents& contents, boost::optional<int>) { mvcol(contents,contents.cont[contents.y].length() - 1); } void mvsol(contents& contents, boost::optional<int>) { mvcol(contents,0); } void mvsop(contents& contents, boost::optional<int>) { contents.y = 0; contents.x = 0; contents.waiting_for_desired = false; } void mveop(contents& contents, boost::optional<int>) { contents.y = contents.cont.size() - 1; contents.x = 0; contents.y_offset = contents.y - contents.max_y; contents.waiting_for_desired = false; } void mvd(contents& contents, boost::optional<int> op) { int times = op ? op.get() : 1; if(contents.y + times < 0 || contents.y + times >= contents.cont.size()) { show_message("Can't move to that location (start/end of buffer)"); return; } int vis = to_visual(contents.cont[contents.y],contents.x); contents.y += times; unsigned int len = contents.cont[contents.y].length(); if(contents.waiting_for_desired) { if((int)contents.x < 0) { contents.x = len - 1; unsigned int vis = from_visual(contents.cont[contents.y], contents.desired_x); if(vis < contents.x) { contents.x = vis; contents.waiting_for_desired = false; } } else if(contents.x >= len) { contents.x = len - 1; } else if((contents.desired_x > contents.x && contents.desired_x < len) || contents.desired_x == 0) { // x desired len contents.x = contents.desired_x; contents.waiting_for_desired = false; } else { // x len desired contents.x = len - 1; } } else if(len <= contents.x && len > 0) { contents.waiting_for_desired = true; contents.desired_x = contents.x; contents.x = len - 1; } else { int des = contents.x; contents.x = from_visual(contents.cont[contents.y],vis); if(len == 0) { contents.waiting_for_desired = true; contents.desired_x = des; } } contents.x = contents.x >= 0 ? contents.x : 0; } void mvu(contents& contents, boost::optional<int> op) { if(op) mvd(contents,-op.get()); else mvd(contents,-1); } static bool isDeliminator(char ch) { for(unsigned int i = 0; i < DELIMINATORS.length(); i++) if(DELIMINATORS[i] == ch) return true; return false; } void mvfw(contents& contents, boost::optional<int> op) { } void mvbw(contents& contents, boost::optional<int> op) { } inline static unsigned int fixLen(unsigned int len) { return len ? len : 1; } void mvf(contents& contents, boost::optional<int> op) { int times = op ? op.get() : 1; long newx = contents.x + times; try { while(fixLen(contents.cont.at(contents.y).length()) <= newx) { newx -= fixLen(contents.cont[contents.y].length()); contents.y++; } } catch(...) { } if(contents.y >= contents.cont.size()) contents.y = contents.cont.size()-1; if(contents.x < 0) contents.x = 0; else contents.x = newx; contents.waiting_for_desired = false; } void mvb(contents& contents, boost::optional<int> op) { int times = op ? op.get() : 1; if(contents.y == 0 && contents.x == 0) return; long newx = contents.x - times; try { while(newx < 0) { contents.y--; newx += fixLen(contents.cont.at(contents.y).length()); } } catch(...) { } if(newx < 0) contents.x = 0; else contents.x = newx; contents.waiting_for_desired = false; } <commit_msg>Use ``:'' for loop<commit_after>#include <string> #include <vector> #include <boost/optional.hpp> #include "prompt.hh" #include "configuration.hh" #include "to_str.hh" #include "newmove.hh" #include "show_message.hh" #include "visual.hh" void mvline(contents& contents, boost::optional<int> line) { if(line) { contents.x = 0; int cont = line.get(); if(cont < 0) { show_message("Can't move to a negative line!"); contents.y = 0; return; } contents.y = cont; if(cont >= contents.cont.size()) { contents.y = contents.cont.size() - 1; show_message("Can't move past end of buffer!"); } } else { while(true) { std::string str = prompt("Goto line: "); try { int res = std::stoi(str); mvline(contents, res); return; } catch(std::invalid_argument) { continue; } } } } void mv(contents& contents, unsigned long _y, unsigned long _x) { contents.y = _y; contents.x = _x; if((long) contents.y < 0) contents.y = 0; if(contents.y >= contents.cont.size()) contents.y = contents.cont.size() - 1; if((long) contents.x < 0) contents.x = 0; if(contents.x >= contents.cont[contents.y].size()) contents.x = contents.cont[contents.y].size() - 1; } void mvrel(contents& contents, long y, long x) { if(y < 0) mvu(contents,-y); else mvd(contents, y); if(x < 0) mvb(contents,-x); else mvf(contents, x); } void mvcol(contents& contents, boost::optional<int> col) { if(col) { unsigned int len = contents.cont[contents.y].length(); if(len >= col.get()) { contents.x = col.get(); contents.waiting_for_desired = false; } else { show_message((std::string("Can't move to column: ") + int_to_str(col.get())).c_str()); } } else { while(true) { std::string str = prompt("Goto column: "); try { int res = std::stoi(str); mvcol(contents, res); return; } catch(std::invalid_argument) { continue; } } } } void mvsot(contents& contents, boost::optional<int> op) { mvsol(contents, op); const std::string& str = contents.cont[contents.y]; for(unsigned int i = 0; i < str.length(); i++) { if(str[i] == ' ' || str[i] == '\t') mvf(contents, op); else break; } } void mveol(contents& contents, boost::optional<int>) { mvcol(contents,contents.cont[contents.y].length() - 1); } void mvsol(contents& contents, boost::optional<int>) { mvcol(contents,0); } void mvsop(contents& contents, boost::optional<int>) { contents.y = 0; contents.x = 0; contents.waiting_for_desired = false; } void mveop(contents& contents, boost::optional<int>) { contents.y = contents.cont.size() - 1; contents.x = 0; contents.y_offset = contents.y - contents.max_y; contents.waiting_for_desired = false; } void mvd(contents& contents, boost::optional<int> op) { int times = op ? op.get() : 1; if(contents.y + times < 0 || contents.y + times >= contents.cont.size()) { show_message("Can't move to that location (start/end of buffer)"); return; } int vis = to_visual(contents.cont[contents.y],contents.x); contents.y += times; unsigned int len = contents.cont[contents.y].length(); if(contents.waiting_for_desired) { if((int)contents.x < 0) { contents.x = len - 1; unsigned int vis = from_visual(contents.cont[contents.y], contents.desired_x); if(vis < contents.x) { contents.x = vis; contents.waiting_for_desired = false; } } else if(contents.x >= len) { contents.x = len - 1; } else if((contents.desired_x > contents.x && contents.desired_x < len) || contents.desired_x == 0) { // x desired len contents.x = contents.desired_x; contents.waiting_for_desired = false; } else { // x len desired contents.x = len - 1; } } else if(len <= contents.x && len > 0) { contents.waiting_for_desired = true; contents.desired_x = contents.x; contents.x = len - 1; } else { int des = contents.x; contents.x = from_visual(contents.cont[contents.y],vis); if(len == 0) { contents.waiting_for_desired = true; contents.desired_x = des; } } contents.x = contents.x >= 0 ? contents.x : 0; } void mvu(contents& contents, boost::optional<int> op) { if(op) mvd(contents,-op.get()); else mvd(contents,-1); } static bool isDeliminator(char ch) { for(auto i : DELIMINATORS) if(i == ch) return true; return false; } void mvfw(contents& contents, boost::optional<int> op) { } void mvbw(contents& contents, boost::optional<int> op) { } inline static unsigned int fixLen(unsigned int len) { return len ? len : 1; } void mvf(contents& contents, boost::optional<int> op) { int times = op ? op.get() : 1; long newx = contents.x + times; try { while(fixLen(contents.cont.at(contents.y).length()) <= newx) { newx -= fixLen(contents.cont[contents.y].length()); contents.y++; } } catch(...) { } if(contents.y >= contents.cont.size()) contents.y = contents.cont.size()-1; if(contents.x < 0) contents.x = 0; else contents.x = newx; contents.waiting_for_desired = false; } void mvb(contents& contents, boost::optional<int> op) { int times = op ? op.get() : 1; if(contents.y == 0 && contents.x == 0) return; long newx = contents.x - times; try { while(newx < 0) { contents.y--; newx += fixLen(contents.cont.at(contents.y).length()); } } catch(...) { } if(newx < 0) contents.x = 0; else contents.x = newx; contents.waiting_for_desired = false; } <|endoftext|>
<commit_before><commit_msg>Disable URLRequestTest.CancelTest4 since it started leaking. I understand the bug now, but need more time to fix it. Will look at this tomorrow.<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2013 Dropbox, Inc. * * 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 "json11.h" #include <cassert> #include <cstdlib> #include <cstdio> #include <limits> #include <type_traits> namespace json11 { static const int max_depth = 200; // Check that Value has the properties we want. #define CHECK_TRAIT(x) static_assert(std::x::value, #x) CHECK_TRAIT(is_nothrow_constructible<Value>); CHECK_TRAIT(is_nothrow_default_constructible<Value>); CHECK_TRAIT(is_copy_constructible<Value>); CHECK_TRAIT(is_nothrow_move_constructible<Value>); CHECK_TRAIT(is_copy_assignable<Value>); CHECK_TRAIT(is_nothrow_move_assignable<Value>); CHECK_TRAIT(is_nothrow_destructible<Value>); /* * * * * * * * * * * * * * * * * * * * * Parsing */ /* esc(c) * * Format char c suitable for printing in an error message. */ static inline std::string esc(char c) { char buf[12]; if ((uint8_t)c >= 0x20 && (uint8_t)c <= 0x7f) { snprintf(buf, sizeof buf, "'%c' (%d)", c, c); } else { snprintf(buf, sizeof buf, "(%d)", c); } return std::string(buf); } static inline bool in_range(long x, long lower, long upper) { return (x >= lower && x <= upper); } /* JsonParser * * Object that tracks all state of an in-progress parse. */ struct JsonParser { /* State */ const std::string &str; size_t i; std::string &err; bool failed; /* fail(msg, err_ret = Value()) * * Mark this parse as failed. */ Value fail(std::string &&msg) { return fail(std::move(msg), Value()); } template <typename T> T fail(std::string &&msg, const T err_ret) { if (!failed) err = std::move(msg); failed = true; return err_ret; } /* consume_whitespace() * * Advance until the current character is non-whitespace. */ void consume_whitespace() { while (str[i] == ' ' || str[i] == '\r' || str[i] == '\n' || str[i] == '\t') i++; } /* get_next_token() * * Return the next non-whitespace character. If the end of the input is reached, * flag an error and return 0. */ char get_next_token() { consume_whitespace(); if (i == str.size()) return fail("unexpected end of input", 0); return str[i++]; } /* encode_utf8(pt, out) * * Encode pt as UTF-8 and add it to out. */ void encode_utf8(long pt, std::string & out) { if (pt < 0) return; if (pt < 0x80) { out += pt; } else if (pt < 0x800) { out += (pt >> 6) | 0xC0; out += (pt & 0x3F) | 0x80; } else if (pt < 0x10000) { out += (pt >> 12) | 0xE0; out += ((pt >> 6) & 0x3F) | 0x80; out += (pt & 0x3F) | 0x80; } else { out += (pt >> 18) | 0xF0; out += ((pt >> 12) & 0x3F) | 0x80; out += ((pt >> 6) & 0x3F) | 0x80; out += (pt & 0x3F) | 0x80; } } /* parse_string() * * Parse a std::string, starting at the current position. */ std::string parse_string() { std::string out; long last_escaped_codepoint = -1; while (true) { if (i == str.size()) return fail("unexpected end of input in std::string", ""); char ch = str[i++]; if (ch == '"') { encode_utf8(last_escaped_codepoint, out); return out; } if (in_range(ch, 0, 0x1f)) return fail("unescaped " + esc(ch) + " in std::string", ""); // The usual case: non-escaped characters if (ch != '\\') { encode_utf8(last_escaped_codepoint, out); last_escaped_codepoint = -1; out += ch; continue; } // Handle escapes if (i == str.size()) return fail("unexpected end of input in std::string", ""); ch = str[i++]; if (ch == 'u') { // Extract 4-byte escape sequence std::string esc = str.substr(i, 4); // Explicitly check length of the substring. The following loop // relies on std::string returning the terminating NUL when // accessing str[length]. Checking here reduces brittleness. if (esc.length() < 4) { return fail("bad \\u escape: " + esc, ""); } for (int j = 0; j < 4; j++) { if (!in_range(esc[j], 'a', 'f') && !in_range(esc[j], 'A', 'F') && !in_range(esc[j], '0', '9')) return fail("bad \\u escape: " + esc, ""); } long codepoint = strtol(esc.data(), nullptr, 16); // JSON specifies that characters outside the BMP shall be encoded as a pair // of 4-hex-digit \u escapes encoding their surrogate pair components. Check // whether we're in the middle of such a beast: the previous codepoint was an // escaped lead (high) surrogate, and this is a trail (low) surrogate. if (in_range(last_escaped_codepoint, 0xD800, 0xDBFF) && in_range(codepoint, 0xDC00, 0xDFFF)) { // Reassemble the two surrogate pairs into one astral-plane character, per // the UTF-16 algorithm. encode_utf8((((last_escaped_codepoint - 0xD800) << 10) | (codepoint - 0xDC00)) + 0x10000, out); last_escaped_codepoint = -1; } else { encode_utf8(last_escaped_codepoint, out); last_escaped_codepoint = codepoint; } i += 4; continue; } encode_utf8(last_escaped_codepoint, out); last_escaped_codepoint = -1; if (ch == 'b') { out += '\b'; } else if (ch == 'f') { out += '\f'; } else if (ch == 'n') { out += '\n'; } else if (ch == 'r') { out += '\r'; } else if (ch == 't') { out += '\t'; } else if (ch == '"' || ch == '\\' || ch == '/') { out += ch; } else { return fail("invalid escape character " + esc(ch), ""); } } } /* parse_number() * * Parse a double. */ Value parse_number() { size_t start_pos = i; if (str[i] == '-') i++; // Integer part if (str[i] == '0') { i++; if (in_range(str[i], '0', '9')) return fail("leading 0s not permitted in numbers"); } else if (in_range(str[i], '1', '9')) { i++; while (in_range(str[i], '0', '9')) i++; } else { return fail("invalid " + esc(str[i]) + " in number"); } if (str[i] != '.' && str[i] != 'e' && str[i] != 'E' && (i - start_pos) <= (size_t)std::numeric_limits<int>::digits10) { return std::atol(str.c_str() + start_pos); } // Decimal part if (str[i] == '.') { i++; if (!in_range(str[i], '0', '9')) return fail("at least one digit required in fractional part"); while (in_range(str[i], '0', '9')) i++; } // Exponent part if (str[i] == 'e' || str[i] == 'E') { i++; if (str[i] == '+' || str[i] == '-') i++; if (!in_range(str[i], '0', '9')) return fail("at least one digit required in exponent"); while (in_range(str[i], '0', '9')) i++; } return std::strtod(str.c_str() + start_pos, nullptr); } /* expect(str, res) * * Expect that 'str' starts at the character that was just read. If it does, advance * the input and return res. If not, flag an error. */ Value expect(const std::string &expected, Value res) { assert(i != 0); i--; if (str.compare(i, expected.length(), expected) == 0) { i += expected.length(); return res; } else { return fail("parse error: expected " + expected + ", got " + str.substr(i, expected.length())); } } /* parse_json() * * Parse a JSON object. */ Value parse_json(int depth) { if (depth > max_depth) { return fail("exceeded maximum nesting depth"); } char ch = get_next_token(); if (failed) return Value(); if (ch == '-' || (ch >= '0' && ch <= '9')) { i--; return parse_number(); } if (ch == 't') return expect("true", true); if (ch == 'f') return expect("false", false); if (ch == 'n') return expect("null", Value()); if (ch == '"') return parse_string(); if (ch == '{') { std::map<std::string, Value> data; ch = get_next_token(); if (ch == '}') return data; while (1) { if (ch != '"') return fail("expected '\"' in object, got " + esc(ch)); std::string key = parse_string(); if (failed) return Value(); ch = get_next_token(); if (ch != ':') return fail("expected ':' in object, got " + esc(ch)); data[std::move(key)] = parse_json(depth + 1); if (failed) return Value(); ch = get_next_token(); if (ch == '}') break; if (ch != ',') return fail("expected ',' in object, got " + esc(ch)); ch = get_next_token(); } return data; } if (ch == '[') { std::vector<Value> data; ch = get_next_token(); if (ch == ']') return data; while (1) { i--; data.push_back(parse_json(depth + 1)); if (failed) return Value(); ch = get_next_token(); if (ch == ']') break; if (ch != ',') return fail("expected ',' in list, got " + esc(ch)); ch = get_next_token(); (void)ch; } return data; } return fail("expected value, got " + esc(ch)); } }; Value parse(const std::string &in, std::string &err) { JsonParser parser { in, 0, err, false }; Value result = parser.parse_json(0); // Check for any trailing garbage parser.consume_whitespace(); if (parser.i != in.size()) return parser.fail("unexpected trailing " + esc(in[parser.i])); return result; } // Documented in json11.hpp std::vector<Value> parse_multi(const std::string &in, std::string &err) { JsonParser parser { in, 0, err, false }; std::vector<Value> vals; while (parser.i != in.size() && !parser.failed) { vals.push_back(parser.parse_json(0)); // Check for another object parser.consume_whitespace(); } return vals; } } // namespace json11 <commit_msg>use std::move<commit_after>/* Copyright (c) 2013 Dropbox, Inc. * * 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 "json11.h" #include <cassert> #include <cstdlib> #include <cstdio> #include <limits> #include <type_traits> namespace json11 { static const int max_depth = 200; // Check that Value has the properties we want. #define CHECK_TRAIT(x) static_assert(std::x::value, #x) CHECK_TRAIT(is_nothrow_constructible<Value>); CHECK_TRAIT(is_nothrow_default_constructible<Value>); CHECK_TRAIT(is_copy_constructible<Value>); CHECK_TRAIT(is_nothrow_move_constructible<Value>); CHECK_TRAIT(is_copy_assignable<Value>); CHECK_TRAIT(is_nothrow_move_assignable<Value>); CHECK_TRAIT(is_nothrow_destructible<Value>); /* * * * * * * * * * * * * * * * * * * * * Parsing */ /* esc(c) * * Format char c suitable for printing in an error message. */ static inline std::string esc(char c) { char buf[12]; if ((uint8_t)c >= 0x20 && (uint8_t)c <= 0x7f) { snprintf(buf, sizeof buf, "'%c' (%d)", c, c); } else { snprintf(buf, sizeof buf, "(%d)", c); } return std::string(buf); } static inline bool in_range(long x, long lower, long upper) { return (x >= lower && x <= upper); } /* JsonParser * * Object that tracks all state of an in-progress parse. */ struct JsonParser { /* State */ const std::string &str; size_t i; std::string &err; bool failed; /* fail(msg, err_ret = Value()) * * Mark this parse as failed. */ Value fail(std::string &&msg) { return fail(std::move(msg), Value()); } template <typename T> T fail(std::string &&msg, const T err_ret) { if (!failed) err = std::move(msg); failed = true; return err_ret; } /* consume_whitespace() * * Advance until the current character is non-whitespace. */ void consume_whitespace() { while (str[i] == ' ' || str[i] == '\r' || str[i] == '\n' || str[i] == '\t') i++; } /* get_next_token() * * Return the next non-whitespace character. If the end of the input is reached, * flag an error and return 0. */ char get_next_token() { consume_whitespace(); if (i == str.size()) return fail("unexpected end of input", 0); return str[i++]; } /* encode_utf8(pt, out) * * Encode pt as UTF-8 and add it to out. */ void encode_utf8(long pt, std::string & out) { if (pt < 0) return; if (pt < 0x80) { out += pt; } else if (pt < 0x800) { out += (pt >> 6) | 0xC0; out += (pt & 0x3F) | 0x80; } else if (pt < 0x10000) { out += (pt >> 12) | 0xE0; out += ((pt >> 6) & 0x3F) | 0x80; out += (pt & 0x3F) | 0x80; } else { out += (pt >> 18) | 0xF0; out += ((pt >> 12) & 0x3F) | 0x80; out += ((pt >> 6) & 0x3F) | 0x80; out += (pt & 0x3F) | 0x80; } } /* parse_string() * * Parse a std::string, starting at the current position. */ std::string parse_string() { std::string out; long last_escaped_codepoint = -1; while (true) { if (i == str.size()) return fail("unexpected end of input in std::string", ""); char ch = str[i++]; if (ch == '"') { encode_utf8(last_escaped_codepoint, out); return out; } if (in_range(ch, 0, 0x1f)) return fail("unescaped " + esc(ch) + " in std::string", ""); // The usual case: non-escaped characters if (ch != '\\') { encode_utf8(last_escaped_codepoint, out); last_escaped_codepoint = -1; out += ch; continue; } // Handle escapes if (i == str.size()) return fail("unexpected end of input in std::string", ""); ch = str[i++]; if (ch == 'u') { // Extract 4-byte escape sequence std::string esc = str.substr(i, 4); // Explicitly check length of the substring. The following loop // relies on std::string returning the terminating NUL when // accessing str[length]. Checking here reduces brittleness. if (esc.length() < 4) { return fail("bad \\u escape: " + esc, ""); } for (int j = 0; j < 4; j++) { if (!in_range(esc[j], 'a', 'f') && !in_range(esc[j], 'A', 'F') && !in_range(esc[j], '0', '9')) return fail("bad \\u escape: " + esc, ""); } long codepoint = strtol(esc.data(), nullptr, 16); // JSON specifies that characters outside the BMP shall be encoded as a pair // of 4-hex-digit \u escapes encoding their surrogate pair components. Check // whether we're in the middle of such a beast: the previous codepoint was an // escaped lead (high) surrogate, and this is a trail (low) surrogate. if (in_range(last_escaped_codepoint, 0xD800, 0xDBFF) && in_range(codepoint, 0xDC00, 0xDFFF)) { // Reassemble the two surrogate pairs into one astral-plane character, per // the UTF-16 algorithm. encode_utf8((((last_escaped_codepoint - 0xD800) << 10) | (codepoint - 0xDC00)) + 0x10000, out); last_escaped_codepoint = -1; } else { encode_utf8(last_escaped_codepoint, out); last_escaped_codepoint = codepoint; } i += 4; continue; } encode_utf8(last_escaped_codepoint, out); last_escaped_codepoint = -1; if (ch == 'b') { out += '\b'; } else if (ch == 'f') { out += '\f'; } else if (ch == 'n') { out += '\n'; } else if (ch == 'r') { out += '\r'; } else if (ch == 't') { out += '\t'; } else if (ch == '"' || ch == '\\' || ch == '/') { out += ch; } else { return fail("invalid escape character " + esc(ch), ""); } } } /* parse_number() * * Parse a double. */ Value parse_number() { size_t start_pos = i; if (str[i] == '-') i++; // Integer part if (str[i] == '0') { i++; if (in_range(str[i], '0', '9')) return fail("leading 0s not permitted in numbers"); } else if (in_range(str[i], '1', '9')) { i++; while (in_range(str[i], '0', '9')) i++; } else { return fail("invalid " + esc(str[i]) + " in number"); } if (str[i] != '.' && str[i] != 'e' && str[i] != 'E' && (i - start_pos) <= (size_t)std::numeric_limits<int>::digits10) { return std::atol(str.c_str() + start_pos); } // Decimal part if (str[i] == '.') { i++; if (!in_range(str[i], '0', '9')) return fail("at least one digit required in fractional part"); while (in_range(str[i], '0', '9')) i++; } // Exponent part if (str[i] == 'e' || str[i] == 'E') { i++; if (str[i] == '+' || str[i] == '-') i++; if (!in_range(str[i], '0', '9')) return fail("at least one digit required in exponent"); while (in_range(str[i], '0', '9')) i++; } return std::strtod(str.c_str() + start_pos, nullptr); } /* expect(str, res) * * Expect that 'str' starts at the character that was just read. If it does, advance * the input and return res. If not, flag an error. */ Value expect(const std::string &expected, Value res) { assert(i != 0); i--; if (str.compare(i, expected.length(), expected) == 0) { i += expected.length(); return res; } else { return fail("parse error: expected " + expected + ", got " + str.substr(i, expected.length())); } } /* parse_json() * * Parse a JSON object. */ Value parse_json(int depth) { if (depth > max_depth) { return fail("exceeded maximum nesting depth"); } char ch = get_next_token(); if (failed) return Value(); if (ch == '-' || (ch >= '0' && ch <= '9')) { i--; return parse_number(); } if (ch == 't') return expect("true", true); if (ch == 'f') return expect("false", false); if (ch == 'n') return expect("null", Value()); if (ch == '"') return parse_string(); if (ch == '{') { std::map<std::string, Value> data; ch = get_next_token(); if (ch == '}') return std::move(data); while (1) { if (ch != '"') return fail("expected '\"' in object, got " + esc(ch)); std::string key = parse_string(); if (failed) return Value(); ch = get_next_token(); if (ch != ':') return fail("expected ':' in object, got " + esc(ch)); data[std::move(key)] = parse_json(depth + 1); if (failed) return Value(); ch = get_next_token(); if (ch == '}') break; if (ch != ',') return fail("expected ',' in object, got " + esc(ch)); ch = get_next_token(); } return std::move(data); } if (ch == '[') { std::vector<Value> data; ch = get_next_token(); if (ch == ']') return std::move(data); while (1) { i--; data.push_back(parse_json(depth + 1)); if (failed) return Value(); ch = get_next_token(); if (ch == ']') break; if (ch != ',') return fail("expected ',' in list, got " + esc(ch)); ch = get_next_token(); (void)ch; } return std::move(data); } return fail("expected value, got " + esc(ch)); } }; Value parse(const std::string &in, std::string &err) { JsonParser parser { in, 0, err, false }; Value result = parser.parse_json(0); // Check for any trailing garbage parser.consume_whitespace(); if (parser.i != in.size()) return parser.fail("unexpected trailing " + esc(in[parser.i])); return result; } // Documented in json11.hpp std::vector<Value> parse_multi(const std::string &in, std::string &err) { JsonParser parser { in, 0, err, false }; std::vector<Value> vals; while (parser.i != in.size() && !parser.failed) { vals.push_back(parser.parse_json(0)); // Check for another object parser.consume_whitespace(); } return vals; } } // namespace json11 <|endoftext|>
<commit_before>#include "ast.hpp" #include "output.hpp" #include "to_string.hpp" namespace Sass { Output::Output(Context* ctx) : Inspect(Emitter(ctx)), charset(""), top_nodes(0) {} Output::~Output() { } void Output::fallback_impl(AST_Node* n) { return n->perform(this); } void Output::operator()(Number* n) { // use values to_string facility To_String to_string(ctx); std::string res = n->perform(&to_string); // check for a valid unit here // includes result for reporting if (n->numerator_units().size() > 1 || n->denominator_units().size() > 0 || (n->numerator_units().size() && n->numerator_units()[0].find_first_of('/') != std::string::npos) || (n->numerator_units().size() && n->numerator_units()[0].find_first_of('*') != std::string::npos) ) { error(res + " isn't a valid CSS value.", n->pstate()); } // output the final token append_token(res, n); } void Output::operator()(Import* imp) { top_nodes.push_back(imp); } void Output::operator()(Map* m) { To_String to_string(ctx); std::string dbg(m->perform(&to_string)); error(dbg + " isn't a valid CSS value.", m->pstate()); } OutputBuffer Output::get_buffer(void) { Emitter emitter(ctx); Inspect inspect(emitter); size_t size_nodes = top_nodes.size(); for (size_t i = 0; i < size_nodes; i++) { top_nodes[i]->perform(&inspect); inspect.append_mandatory_linefeed(); } // flush scheduled outputs inspect.finalize(); // prepend buffer on top prepend_output(inspect.output()); // make sure we end with a linefeed if (!ends_with(wbuf.buffer, ctx->linefeed)) { // if the output is not completely empty if (!wbuf.buffer.empty()) append_string(ctx->linefeed); } // search for unicode char for(const char& chr : wbuf.buffer) { // skip all ascii chars if (chr >= 0) continue; // declare the charset if (output_style() != SASS_STYLE_COMPRESSED) charset = "@charset \"UTF-8\";" + ctx->linefeed; else charset = "\xEF\xBB\xBF"; // abort search break; } // add charset as first line, before comments and imports if (!charset.empty()) prepend_string(charset); return wbuf; } void Output::operator()(Comment* c) { To_String to_string(ctx); std::string txt = c->text()->perform(&to_string); // if (indentation && txt == "/**/") return; bool important = c->is_important(); if (output_style() != SASS_STYLE_COMPRESSED || important) { if (buffer().size() == 0) { top_nodes.push_back(c); } else { in_comment = true; append_indentation(); c->text()->perform(this); in_comment = false; if (indentation == 0) { append_mandatory_linefeed(); } else { append_optional_linefeed(); } } } } void Output::operator()(Ruleset* r) { Selector* s = r->selector(); Block* b = r->block(); bool decls = false; // Filter out rulesets that aren't printable (process its children though) if (!Util::isPrintable(r, output_style())) { for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (dynamic_cast<Has_Block*>(stm)) { stm->perform(this); } } return; } if (b->has_non_hoistable()) { decls = true; if (output_style() == SASS_STYLE_NESTED) indentation += r->tabs(); if (ctx && ctx->c_options->source_comments) { std::stringstream ss; append_indentation(); std::string path = Sass::File::abs2rel(r->pstate().path, ctx->cwd()); ss << "/* line " << r->pstate().line + 1 << ", " << path << " */"; append_string(ss.str()); append_optional_linefeed(); } s->perform(this); append_scope_opener(b); for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; bool bPrintExpression = true; // Check print conditions if (typeid(*stm) == typeid(Declaration)) { Declaration* dec = static_cast<Declaration*>(stm); if (dec->value()->concrete_type() == Expression::STRING) { String_Constant* valConst = static_cast<String_Constant*>(dec->value()); std::string val(valConst->value()); if (auto qstr = dynamic_cast<String_Quoted*>(valConst)) { if (!qstr->quote_mark() && val.empty()) { bPrintExpression = false; } } } else if (dec->value()->concrete_type() == Expression::LIST) { List* list = static_cast<List*>(dec->value()); bool all_invisible = true; for (size_t list_i = 0, list_L = list->length(); list_i < list_L; ++list_i) { Expression* item = (*list)[list_i]; if (!item->is_invisible()) all_invisible = false; } if (all_invisible) bPrintExpression = false; } } // Print if OK if (!stm->is_hoistable() && bPrintExpression) { stm->perform(this); } } if (output_style() == SASS_STYLE_NESTED) indentation -= r->tabs(); append_scope_closer(b); } if (b->has_hoistable()) { if (decls) ++indentation; for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (stm->is_hoistable()) { stm->perform(this); } } if (decls) --indentation; } } void Output::operator()(Keyframe_Rule* r) { Block* b = r->block(); Selector* v = r->selector(); if (v) { v->perform(this); } if (!b) { append_colon_separator(); return; } append_scope_opener(); for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (!stm->is_hoistable()) { stm->perform(this); if (i < L - 1) append_special_linefeed(); } } for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (stm->is_hoistable()) { stm->perform(this); } } append_scope_closer(); } void Output::operator()(Supports_Block* f) { if (f->is_invisible()) return; Supports_Condition* c = f->condition(); Block* b = f->block(); // Filter out feature blocks that aren't printable (process its children though) if (!Util::isPrintable(f, output_style())) { for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (dynamic_cast<Has_Block*>(stm)) { stm->perform(this); } } return; } if (output_style() == SASS_STYLE_NESTED) indentation += f->tabs(); append_indentation(); append_token("@supports", f); append_mandatory_space(); c->perform(this); append_scope_opener(); if (b->has_non_hoistable()) { // JMA - hoisted, output the non-hoistable in a nested block, followed by the hoistable append_scope_opener(); for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (!stm->is_hoistable()) { stm->perform(this); } } append_scope_closer(); for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (stm->is_hoistable()) { stm->perform(this); } } } else { // JMA - not hoisted, just output in order for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; stm->perform(this); if (i < L - 1) append_special_linefeed(); } } if (output_style() == SASS_STYLE_NESTED) indentation -= f->tabs(); append_scope_closer(); } void Output::operator()(Media_Block* m) { if (m->is_invisible()) return; List* q = m->media_queries(); Block* b = m->block(); // Filter out media blocks that aren't printable (process its children though) if (!Util::isPrintable(m, output_style())) { for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (dynamic_cast<Has_Block*>(stm)) { stm->perform(this); } } return; } if (output_style() == SASS_STYLE_NESTED) indentation += m->tabs(); append_indentation(); append_token("@media", m); append_mandatory_space(); in_media_block = true; q->perform(this); in_media_block = false; append_scope_opener(); for (size_t i = 0, L = b->length(); i < L; ++i) { if ((*b)[i]) (*b)[i]->perform(this); if (i < L - 1) append_special_linefeed(); } if (output_style() == SASS_STYLE_NESTED) indentation -= m->tabs(); append_scope_closer(); } void Output::operator()(At_Rule* a) { std::string kwd = a->keyword(); Selector* s = a->selector(); Expression* v = a->value(); Block* b = a->block(); append_indentation(); append_token(kwd, a); if (s) { append_mandatory_space(); in_wrapped = true; s->perform(this); in_wrapped = false; } if (v) { append_mandatory_space(); v->perform(this); } if (!b) { append_delimiter(); return; } if (b->is_invisible() || b->length() == 0) { return append_string(" {}"); } append_scope_opener(); bool format = kwd != "@font-face";; for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (!stm->is_hoistable()) { stm->perform(this); if (i < L - 1 && format) append_special_linefeed(); } } for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (stm->is_hoistable()) { stm->perform(this); if (i < L - 1 && format) append_special_linefeed(); } } append_scope_closer(); } void Output::operator()(String_Quoted* s) { if (s->quote_mark()) { append_token(quote(s->value(), s->quote_mark()), s); } else if (!in_comment) { append_token(string_to_output(s->value()), s); } else { append_token(s->value(), s); } } void Output::operator()(String_Constant* s) { std::string value(s->value()); if (s->can_compress_whitespace() && output_style() == SASS_STYLE_COMPRESSED) { value.erase(std::remove_if(value.begin(), value.end(), ::isspace), value.end()); } if (!in_comment) { append_token(string_to_output(value), s); } else { append_token(value, s); } } } <commit_msg>Line comment should be absolute<commit_after>#include "ast.hpp" #include "output.hpp" #include "to_string.hpp" namespace Sass { Output::Output(Context* ctx) : Inspect(Emitter(ctx)), charset(""), top_nodes(0) {} Output::~Output() { } void Output::fallback_impl(AST_Node* n) { return n->perform(this); } void Output::operator()(Number* n) { // use values to_string facility To_String to_string(ctx); std::string res = n->perform(&to_string); // check for a valid unit here // includes result for reporting if (n->numerator_units().size() > 1 || n->denominator_units().size() > 0 || (n->numerator_units().size() && n->numerator_units()[0].find_first_of('/') != std::string::npos) || (n->numerator_units().size() && n->numerator_units()[0].find_first_of('*') != std::string::npos) ) { error(res + " isn't a valid CSS value.", n->pstate()); } // output the final token append_token(res, n); } void Output::operator()(Import* imp) { top_nodes.push_back(imp); } void Output::operator()(Map* m) { To_String to_string(ctx); std::string dbg(m->perform(&to_string)); error(dbg + " isn't a valid CSS value.", m->pstate()); } OutputBuffer Output::get_buffer(void) { Emitter emitter(ctx); Inspect inspect(emitter); size_t size_nodes = top_nodes.size(); for (size_t i = 0; i < size_nodes; i++) { top_nodes[i]->perform(&inspect); inspect.append_mandatory_linefeed(); } // flush scheduled outputs inspect.finalize(); // prepend buffer on top prepend_output(inspect.output()); // make sure we end with a linefeed if (!ends_with(wbuf.buffer, ctx->linefeed)) { // if the output is not completely empty if (!wbuf.buffer.empty()) append_string(ctx->linefeed); } // search for unicode char for(const char& chr : wbuf.buffer) { // skip all ascii chars if (chr >= 0) continue; // declare the charset if (output_style() != SASS_STYLE_COMPRESSED) charset = "@charset \"UTF-8\";" + ctx->linefeed; else charset = "\xEF\xBB\xBF"; // abort search break; } // add charset as first line, before comments and imports if (!charset.empty()) prepend_string(charset); return wbuf; } void Output::operator()(Comment* c) { To_String to_string(ctx); std::string txt = c->text()->perform(&to_string); // if (indentation && txt == "/**/") return; bool important = c->is_important(); if (output_style() != SASS_STYLE_COMPRESSED || important) { if (buffer().size() == 0) { top_nodes.push_back(c); } else { in_comment = true; append_indentation(); c->text()->perform(this); in_comment = false; if (indentation == 0) { append_mandatory_linefeed(); } else { append_optional_linefeed(); } } } } void Output::operator()(Ruleset* r) { Selector* s = r->selector(); Block* b = r->block(); bool decls = false; // Filter out rulesets that aren't printable (process its children though) if (!Util::isPrintable(r, output_style())) { for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (dynamic_cast<Has_Block*>(stm)) { stm->perform(this); } } return; } if (b->has_non_hoistable()) { decls = true; if (output_style() == SASS_STYLE_NESTED) indentation += r->tabs(); if (ctx && ctx->c_options->source_comments) { std::stringstream ss; append_indentation(); ss << "/* line " << r->pstate().line + 1 << ", " << r->pstate().path << " */"; append_string(ss.str()); append_optional_linefeed(); } s->perform(this); append_scope_opener(b); for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; bool bPrintExpression = true; // Check print conditions if (typeid(*stm) == typeid(Declaration)) { Declaration* dec = static_cast<Declaration*>(stm); if (dec->value()->concrete_type() == Expression::STRING) { String_Constant* valConst = static_cast<String_Constant*>(dec->value()); std::string val(valConst->value()); if (auto qstr = dynamic_cast<String_Quoted*>(valConst)) { if (!qstr->quote_mark() && val.empty()) { bPrintExpression = false; } } } else if (dec->value()->concrete_type() == Expression::LIST) { List* list = static_cast<List*>(dec->value()); bool all_invisible = true; for (size_t list_i = 0, list_L = list->length(); list_i < list_L; ++list_i) { Expression* item = (*list)[list_i]; if (!item->is_invisible()) all_invisible = false; } if (all_invisible) bPrintExpression = false; } } // Print if OK if (!stm->is_hoistable() && bPrintExpression) { stm->perform(this); } } if (output_style() == SASS_STYLE_NESTED) indentation -= r->tabs(); append_scope_closer(b); } if (b->has_hoistable()) { if (decls) ++indentation; for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (stm->is_hoistable()) { stm->perform(this); } } if (decls) --indentation; } } void Output::operator()(Keyframe_Rule* r) { Block* b = r->block(); Selector* v = r->selector(); if (v) { v->perform(this); } if (!b) { append_colon_separator(); return; } append_scope_opener(); for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (!stm->is_hoistable()) { stm->perform(this); if (i < L - 1) append_special_linefeed(); } } for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (stm->is_hoistable()) { stm->perform(this); } } append_scope_closer(); } void Output::operator()(Supports_Block* f) { if (f->is_invisible()) return; Supports_Condition* c = f->condition(); Block* b = f->block(); // Filter out feature blocks that aren't printable (process its children though) if (!Util::isPrintable(f, output_style())) { for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (dynamic_cast<Has_Block*>(stm)) { stm->perform(this); } } return; } if (output_style() == SASS_STYLE_NESTED) indentation += f->tabs(); append_indentation(); append_token("@supports", f); append_mandatory_space(); c->perform(this); append_scope_opener(); if (b->has_non_hoistable()) { // JMA - hoisted, output the non-hoistable in a nested block, followed by the hoistable append_scope_opener(); for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (!stm->is_hoistable()) { stm->perform(this); } } append_scope_closer(); for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (stm->is_hoistable()) { stm->perform(this); } } } else { // JMA - not hoisted, just output in order for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; stm->perform(this); if (i < L - 1) append_special_linefeed(); } } if (output_style() == SASS_STYLE_NESTED) indentation -= f->tabs(); append_scope_closer(); } void Output::operator()(Media_Block* m) { if (m->is_invisible()) return; List* q = m->media_queries(); Block* b = m->block(); // Filter out media blocks that aren't printable (process its children though) if (!Util::isPrintable(m, output_style())) { for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (dynamic_cast<Has_Block*>(stm)) { stm->perform(this); } } return; } if (output_style() == SASS_STYLE_NESTED) indentation += m->tabs(); append_indentation(); append_token("@media", m); append_mandatory_space(); in_media_block = true; q->perform(this); in_media_block = false; append_scope_opener(); for (size_t i = 0, L = b->length(); i < L; ++i) { if ((*b)[i]) (*b)[i]->perform(this); if (i < L - 1) append_special_linefeed(); } if (output_style() == SASS_STYLE_NESTED) indentation -= m->tabs(); append_scope_closer(); } void Output::operator()(At_Rule* a) { std::string kwd = a->keyword(); Selector* s = a->selector(); Expression* v = a->value(); Block* b = a->block(); append_indentation(); append_token(kwd, a); if (s) { append_mandatory_space(); in_wrapped = true; s->perform(this); in_wrapped = false; } if (v) { append_mandatory_space(); v->perform(this); } if (!b) { append_delimiter(); return; } if (b->is_invisible() || b->length() == 0) { return append_string(" {}"); } append_scope_opener(); bool format = kwd != "@font-face";; for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (!stm->is_hoistable()) { stm->perform(this); if (i < L - 1 && format) append_special_linefeed(); } } for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (stm->is_hoistable()) { stm->perform(this); if (i < L - 1 && format) append_special_linefeed(); } } append_scope_closer(); } void Output::operator()(String_Quoted* s) { if (s->quote_mark()) { append_token(quote(s->value(), s->quote_mark()), s); } else if (!in_comment) { append_token(string_to_output(s->value()), s); } else { append_token(s->value(), s); } } void Output::operator()(String_Constant* s) { std::string value(s->value()); if (s->can_compress_whitespace() && output_style() == SASS_STYLE_COMPRESSED) { value.erase(std::remove_if(value.begin(), value.end(), ::isspace), value.end()); } if (!in_comment) { append_token(string_to_output(value), s); } else { append_token(value, s); } } } <|endoftext|>
<commit_before>#pragma warning( disable: 4097 ) #pragma warning( disable: 4096 ) #include "test.h" extern "C" { #include "lauxlib.h" #include "lualib.h" } namespace { LUABIND_ANONYMOUS_FIX int feedback = 0; LUABIND_ANONYMOUS_FIX std::string str; struct internal { std::string name_; }; struct property_test { property_test(): o(6) { m_internal.name_ = "internal name"; } std::string name_; int a_; float o; internal m_internal; void set(int a) { a_ = a; feedback = a; } int get() const { feedback = a_; return a_; } void set_name(const char* name) { name_ = name; str = name; feedback = 0; } const char* get_name() const { return name_.c_str(); } const internal& get_internal() const { return m_internal; } }; int tester(lua_State* L) { if (!lua_isnumber(L, 1)) { feedback = 0; if (lua_isstring(L, 1)) { str = lua_tostring(L, 1); } } else { feedback = static_cast<int>(lua_tonumber(L, 1)); } return 0; } } // anonymous namespace bool test_attributes() { using namespace luabind; lua_State* L = lua_open(); lua_baselibopen(L); lua_closer c(L); int top = lua_gettop(L); luabind::open(L); lua_pushstring(L, "tester"); lua_pushcfunction(L, tester); lua_settable(L, LUA_GLOBALSINDEX); module(L) [ luabind::class_<internal>("internal") .def_readonly("name", &internal::name_), luabind::class_<property_test>("property") .def(luabind::constructor<>()) .def("get", &property_test::get) .def("get_name", &property_test::get_name) .property("a", &property_test::get, &property_test::set) .property("name", &property_test::get_name, &property_test::set_name) .def_readonly("o", &property_test::o) //#ifndef BOOST_MSVC .property("internal", &property_test::get_internal, luabind::dependency(luabind::result, luabind::self)) //#endif ]; if (dostring(L, "test = property()")) return false; if (dostring(L, "test.a = 5")) return false; if (feedback != 5) return false; if (dostring(L, "test.name = 'Dew'")) return false; if (dostring(L, "tester(test.name)")) return false; if (feedback != 0) return false; if (str != "Dew") return false; if (dostring(L, "function d(x) end d(test.a)")) return false; if (feedback != 5) return false; if (dostring(L, "test.name = 'mango'")) return false; if (feedback != 0) return false; if (str != "mango") return false; if (dostring(L, "tester(test.o)")) return false; if (feedback != 6) return false; luabind::object glob = luabind::get_globals(L); if (dostring(L, "a = 4")) return false; if (glob["a"].type() != LUA_TNUMBER) return false; if (dostring(L, "a = test[nil]")) return false; if (glob["a"].type() != LUA_TNIL) return false; if (dostring(L, "a = test[3.6]")) return false; if (glob["a"].type() != LUA_TNIL) return false; lua_pushstring(L, "test"); glob["test_string"].set(); if (luabind::object_cast<std::string>(glob["test_string"]) != "test") return false; luabind::object t = glob["t"]; lua_pushnumber(L, 4); t.set(); if (luabind::object_cast<int>(t) != 4) return false; glob["test_string"] = std::string("barfoo"); // swap overloads doesn't work on vc #if !defined(BOOST_MSVC) std::swap(glob["test_string"], glob["a"]); if (object_cast<std::string>(glob["a"]) != "barfoo") return false; int type = glob["test_string"].type(); if (type != LUA_TNIL) return false; if (glob["test_string"].type() != LUA_TNIL) return false; #endif if (dostring2(L, "test.o = 5") != 1) return false; if (std::string("cannot set attribute 'property.o'") != lua_tostring(L, -1)) return false; lua_pop(L, 1); if (dostring(L, "tester(test.name)")) return false; if (feedback != 0) return false; if (str != "mango") return false; if (top != lua_gettop(L)) return false; dostring(L, "a = property()"); dostring(L, "b = a.internal"); dostring(L, "a = nil"); dostring(L, "collectgarbage(0)"); dostring(L, "collectgarbage(0)"); return true; } <commit_msg>*** empty log message ***<commit_after>#pragma warning( disable: 4097 ) #pragma warning( disable: 4096 ) #include "test.h" extern "C" { #include "lauxlib.h" #include "lualib.h" } namespace { LUABIND_ANONYMOUS_FIX int feedback = 0; LUABIND_ANONYMOUS_FIX std::string str; struct internal { std::string name_; }; struct property_test { property_test(): o(6) { m_internal.name_ = "internal name"; } std::string name_; int a_; float o; internal m_internal; void set(int a) { a_ = a; feedback = a; } int get() const { feedback = a_; return a_; } void set_name(const char* name) { name_ = name; str = name; feedback = 0; } const char* get_name() const { return name_.c_str(); } const internal& get_internal() const { return m_internal; } }; int tester(lua_State* L) { if (!lua_isnumber(L, 1)) { feedback = 0; if (lua_isstring(L, 1)) { str = lua_tostring(L, 1); } } else { feedback = static_cast<int>(lua_tonumber(L, 1)); } return 0; } } // anonymous namespace bool test_attributes() { using namespace luabind; lua_State* L = lua_open(); lua_baselibopen(L); lua_closer c(L); int top = lua_gettop(L); luabind::open(L); lua_pushstring(L, "tester"); lua_pushcfunction(L, tester); lua_settable(L, LUA_GLOBALSINDEX); module(L) [ luabind::class_<internal>("internal") .def_readonly("name", &internal::name_), luabind::class_<property_test>("property") .def(luabind::constructor<>()) .def("get", &property_test::get) .def("get_name", &property_test::get_name) .property("a", &property_test::get, &property_test::set) .property("name", &property_test::get_name, &property_test::set_name) .def_readonly("o", &property_test::o) //#ifndef BOOST_MSVC .property("internal", &property_test::get_internal, luabind::dependency(luabind::result, luabind::self)) //#endif ]; if (dostring(L, "test = property()")) return false; if (dostring(L, "test.a = 5")) return false; if (feedback != 5) return false; if (dostring(L, "test.name = 'Dew'")) return false; if (dostring(L, "tester(test.name)")) return false; if (feedback != 0) return false; if (str != "Dew") return false; if (dostring(L, "function d(x) end d(test.a)")) return false; if (feedback != 5) return false; if (dostring(L, "test.name = 'mango'")) return false; if (feedback != 0) return false; if (str != "mango") return false; if (dostring(L, "tester(test.o)")) return false; if (feedback != 6) return false; luabind::object glob = luabind::get_globals(L); if (dostring(L, "a = 4")) return false; if (glob["a"].type() != LUA_TNUMBER) return false; if (dostring(L, "a = test[nil]")) return false; if (glob["a"].type() != LUA_TNIL) return false; if (dostring(L, "a = test[3.6]")) return false; if (glob["a"].type() != LUA_TNIL) return false; lua_pushstring(L, "test"); glob["test_string"].set(); if (luabind::object_cast<std::string>(glob["test_string"]) != "test") return false; luabind::object t = glob["t"]; lua_pushnumber(L, 4); t.set(); if (luabind::object_cast<int>(t) != 4) return false; glob["test_string"] = std::string("barfoo"); // swap overloads doesn't work on vc #if !defined(BOOST_MSVC) && !defined(BOOST_INTEL_CXX_VERSION) std::swap(glob["test_string"], glob["a"]); if (object_cast<std::string>(glob["a"]) != "barfoo") return false; int type = glob["test_string"].type(); if (type != LUA_TNIL) return false; if (glob["test_string"].type() != LUA_TNIL) return false; #endif if (dostring2(L, "test.o = 5") != 1) return false; if (std::string("cannot set attribute 'property.o'") != lua_tostring(L, -1)) return false; lua_pop(L, 1); if (dostring(L, "tester(test.name)")) return false; if (feedback != 0) return false; if (str != "mango") return false; if (top != lua_gettop(L)) return false; dostring(L, "a = property()"); dostring(L, "b = a.internal"); dostring(L, "a = nil"); dostring(L, "collectgarbage(0)"); dostring(L, "collectgarbage(0)"); return true; } <|endoftext|>
<commit_before>#include "pb_conn.h" #include "pink_define.h" #include "worker_thread.h" #include "xdebug.h" #include <string> namespace pink { PbConn::PbConn(const int fd, const std::string &ip_port) : PinkConn(fd, ip_port), header_len_(-1), cur_pos_(0), rbuf_len_(0), connStatus_(kHeader), wbuf_len_(0), wbuf_pos_(0) { rbuf_ = (char *)malloc(sizeof(char) * PB_MAX_MESSAGE); wbuf_ = (char *)malloc(sizeof(char) * PB_MAX_MESSAGE); } PbConn::~PbConn() { free(rbuf_); free(wbuf_); } ReadStatus PbConn::GetRequest() { ssize_t nread = 0; nread = read(fd(), rbuf_ + rbuf_len_, PB_MAX_MESSAGE); if (nread == -1) { if (errno == EAGAIN) { return kReadHalf; } else { return kReadError; } } else if (nread == 0) { return kReadClose; } uint32_t integer = 0; bool flag = true; if (nread) { rbuf_len_ += nread; while (flag) { switch (connStatus_) { case kHeader: if (rbuf_len_ - cur_pos_ >= COMMAND_HEADER_LENGTH) { memcpy((char *)(&integer), rbuf_ + cur_pos_, sizeof(uint32_t)); header_len_ = ntohl(integer); log_info("Header_len %u", header_len_); connStatus_ = kPacket; cur_pos_ += COMMAND_HEADER_LENGTH; } else { flag = false; } break; case kPacket: if (rbuf_len_ >= header_len_ + COMMAND_HEADER_LENGTH) { cur_pos_ += header_len_; log_info("k Packet cur_pos_ %d rbuf_len_ %d", cur_pos_, rbuf_len_); connStatus_ = kComplete; } else { flag = false; } break; case kComplete: DealMessage(); connStatus_ = kHeader; log_info("%d %d", cur_pos_, rbuf_len_); if (cur_pos_ == rbuf_len_) { cur_pos_ = 0; rbuf_len_ = 0; } return kReadAll; /* * Add this switch case just for delete compile warning */ case kBuildObuf: break; case kWriteObuf: break; } } } return kReadHalf; } WriteStatus PbConn::SendReply() { BuildObuf(); ssize_t nwritten = 0; while (wbuf_len_ > 0) { nwritten = write(fd(), wbuf_ + wbuf_pos_, wbuf_len_ - wbuf_pos_); if (nwritten <= 0) { break; } wbuf_pos_ += nwritten; if (wbuf_pos_ == wbuf_len_) { wbuf_len_ = 0; wbuf_pos_ = 0; } } if (nwritten == -1) { if (errno == EAGAIN) { return kWriteHalf; } else { // Here we should close the connection return kWriteError; } } if (wbuf_len_ == 0) { return kWriteAll; } else { return kWriteHalf; } } Status PbConn::BuildObuf() { wbuf_len_ = res_->ByteSize(); res_->SerializeToArray(wbuf_ + 4, wbuf_len_); uint32_t u; u = htonl(wbuf_len_); memcpy(wbuf_, &u, sizeof(uint32_t)); wbuf_len_ += COMMAND_HEADER_LENGTH; return Status::OK(); } } <commit_msg>fix bug of PbConn<commit_after>#include "pb_conn.h" #include "pink_define.h" #include "worker_thread.h" #include "xdebug.h" #include <string> namespace pink { PbConn::PbConn(const int fd, const std::string &ip_port) : PinkConn(fd, ip_port), header_len_(-1), cur_pos_(0), rbuf_len_(0), connStatus_(kHeader), wbuf_len_(0), wbuf_pos_(0) { rbuf_ = (char *)malloc(sizeof(char) * PB_MAX_MESSAGE); wbuf_ = (char *)malloc(sizeof(char) * PB_MAX_MESSAGE); } PbConn::~PbConn() { free(rbuf_); free(wbuf_); } // Msg is [ length(COMMAND_HEADER_LENGTH) | body(length bytes) ] // step 1. kHeader, we read COMMAND_HEADER_LENGTH bytes; // step 2. kPacket, we read header_len bytes; ReadStatus PbConn::GetRequest() { bool flag = true; // TODO cur_pos_ can be omitted while (flag) { switch (connStatus_) { case kHeader: { ssize_t nread = read(fd(), rbuf_ + rbuf_len_, COMMAND_HEADER_LENGTH - rbuf_len_); if (nread == -1) { if (errno == EAGAIN) { return kReadHalf; } else { return kReadError; } } else if (nread == 0) { return kReadClose; } else { rbuf_len_ += nread; if (rbuf_len_ - cur_pos_ >= COMMAND_HEADER_LENGTH) { uint32_t integer = 0; memcpy((char *)(&integer), rbuf_ + cur_pos_, sizeof(uint32_t)); header_len_ = ntohl(integer); log_info("Header_len %u", header_len_); cur_pos_ += COMMAND_HEADER_LENGTH; connStatus_ = kPacket; } flag = false; } break; } case kPacket: { if (header_len_ >= PB_MAX_MESSAGE - COMMAND_HEADER_LENGTH) { return kFullError; } else { // read msg body ssize_t nread = read(fd(), rbuf_ + rbuf_len_, header_len_); if (nread == -1) { if (errno == EAGAIN) { return kReadHalf; } else { return kReadError; } } else if (nread == 0) { return kReadClose; } rbuf_len_ += nread; if (rbuf_len_ - cur_pos_ == header_len_) { cur_pos_ += header_len_; log_info("k Packet cur_pos_ %d rbuf_len_ %d", cur_pos_, rbuf_len_); connStatus_ = kComplete; } } break; } case kComplete: { DealMessage(); connStatus_ = kHeader; log_info("%d %d", cur_pos_, rbuf_len_); cur_pos_ = 0; rbuf_len_ = 0; return kReadAll; } // Add this switch case just for delete compile warning case kBuildObuf: break; case kWriteObuf: break; } } return kReadHalf; } WriteStatus PbConn::SendReply() { BuildObuf(); ssize_t nwritten = 0; while (wbuf_len_ > 0) { nwritten = write(fd(), wbuf_ + wbuf_pos_, wbuf_len_ - wbuf_pos_); if (nwritten <= 0) { break; } wbuf_pos_ += nwritten; if (wbuf_pos_ == wbuf_len_) { wbuf_len_ = 0; wbuf_pos_ = 0; } } if (nwritten == -1) { if (errno == EAGAIN) { return kWriteHalf; } else { // Here we should close the connection return kWriteError; } } if (wbuf_len_ == 0) { return kWriteAll; } else { return kWriteHalf; } } Status PbConn::BuildObuf() { wbuf_len_ = res_->ByteSize(); res_->SerializeToArray(wbuf_ + 4, wbuf_len_); uint32_t u; u = htonl(wbuf_len_); memcpy(wbuf_, &u, sizeof(uint32_t)); wbuf_len_ += COMMAND_HEADER_LENGTH; return Status::OK(); } } <|endoftext|>
<commit_before>#include "pbview.h" #include <cinttypes> #include <cstdio> #include <cstring> #include <curses.h> #include <iostream> #include <sstream> #include "config.h" #include "configcontainer.h" #include "dllist.h" #include "download.h" #include "fmtstrformatter.h" #include "help.h" #include "listformatter.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) , colorman(ctrl->get_colormanager()) , downloads_list("dls", dllist_form, ctrl->get_cfgcont()->get_configvalue_as_int("scrolloff")) , help_textview("helptext", help_form) { if (getenv("ESCDELAY") == nullptr) { set_escdelay(25); } } PbView::~PbView() { Stfl::reset(); } void PbView::run(bool auto_download, bool wrap_scroll) { bool quit = false; // Make sure curses is initialized dllist_form.run(-3); // Hide cursor using curses curs_set(0); set_dllist_keymap_hint(); do { if (ctrl->view_update_necessary()) { const double total_kbps = ctrl->get_total_kbps(); const auto speed = get_speed_human_readable(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 %s total%s"), static_cast<unsigned int>( ctrl->downloads_in_progress()), static_cast<unsigned int>( ctrl->downloads().size()), speed.first, speed.second.c_str(), parbuf); dllist_form.set("head", buf); LOG(Level::DEBUG, "PbView::run: updating view... " "downloads().size() " "= %" PRIu64, static_cast<uint64_t>(ctrl->downloads().size())); ListFormatter listfmt; std::string formatstring = ctrl->get_formatstr(); dllist_form.run(-3); // compute all widget dimensions const unsigned int width = downloads_list.get_width(); unsigned int i = 0; for (const auto& dl : ctrl->downloads()) { auto lbuf = format_line(formatstring, dl, i, width); listfmt.add_line(lbuf); i++; } downloads_list.stfl_replace_lines(listfmt); 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; } if (strcmp(event, "RESIZE") == 0) { handle_resize(); continue; } Operation op = keys->get_operation(event, "podboat"); if (dllist_form.get("msg").length() > 0) { dllist_form.set("msg", ""); ctrl->set_view_update_necessary(true); } switch (op) { case OP_REDRAW: Stfl::reset(); break; case OP_PREV: case OP_SK_UP: downloads_list.move_up(wrap_scroll); break; case OP_NEXT: case OP_SK_DOWN: downloads_list.move_down(wrap_scroll); break; case OP_SK_HOME: downloads_list.move_to_first(); break; case OP_SK_END: downloads_list.move_to_last(); break; case OP_SK_PGUP: downloads_list.move_page_up(wrap_scroll); break; case OP_SK_PGDOWN: downloads_list.move_page_down(wrap_scroll); break; 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: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); if (ctrl->downloads()[idx].status() != DlStatus::DOWNLOADING) { std::thread t{PodDlThread( &ctrl->downloads()[idx], ctrl->get_cfgcont())}; t.detach(); } } } break; case OP_PB_PLAY: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); 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: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); DlStatus status = ctrl->downloads()[idx].status(); if (status == DlStatus::PLAYED) { ctrl->downloads()[idx].set_status( DlStatus::FINISHED); } } } break; case OP_PB_CANCEL: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); if (ctrl->downloads()[idx].status() == DlStatus::DOWNLOADING) { ctrl->downloads()[idx].set_status( DlStatus::CANCELLED); } } } break; case OP_PB_DELETE: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); 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->purge_queue(); } ctrl->set_view_update_necessary(true); break; case OP_HELP: run_help(); break; default: break; } if (dllist_form.get("msg").length() == 0) { const auto idx = downloads_list.get_position(); dllist_form.set("msg", ctrl->downloads()[idx].status_msg()); } } while (!quit); } void PbView::handle_resize() { std::vector<std::reference_wrapper<newsboat::Stfl::Form>> forms = {dllist_form, help_form}; for (const auto form : forms) { form.get().run(-3); } ctrl->set_view_update_necessary(true); } void PbView::apply_colors_to_all_forms() { colorman.apply_colors(dllist_form); colorman.apply_colors(help_form); } std::pair<double, std::string> PbView::get_speed_human_readable(double kbps) { if (kbps < 1024) { return std::make_pair(kbps, _("KB/s")); } else if (kbps < 1024 * 1024) { return std::make_pair(kbps / 1024, _("MB/s")); } else { return std::make_pair(kbps / 1024 / 1024, _("GB/s")); } } void PbView::run_help() { set_help_keymap_hint(); help_form.set("head", _("Help")); const auto descs = keys->get_keymap_descriptions("podboat"); ListFormatter listfmt; for (const auto& desc : descs) { 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); listfmt.add_line(descline); } help_textview.stfl_replace_lines(listfmt.get_lines_count(), listfmt.format_list()); bool quit = false; do { const char* event = help_form.run(0); if (!event) { continue; } if (strcmp(event, "RESIZE") == 0) { handle_resize(); continue; } Operation op = keys->get_operation(event, "help"); switch (op) { case OP_SK_UP: help_textview.scroll_up(); break; case OP_SK_DOWN: help_textview.scroll_down(); break; case OP_SK_HOME: help_textview.scroll_to_top(); break; case OP_SK_END: help_textview.scroll_to_bottom(); break; case OP_SK_PGUP: help_textview.scroll_page_up(); break; case OP_SK_PGDOWN: help_textview.scroll_page_down(); break; 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) { std::string bound_keys = utils::join(keys->get_keys(hints[i].op, "podboat"), ","); if (bound_keys.empty()) { bound_keys = "<none>"; } keymap_hint.append(bound_keys); 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; const double speed_kbps = dl.kbps(); const auto speed = get_speed_human_readable(speed_kbps); 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", speed_kbps)); fmt.register_fmt('K', strprintf::fmt("%.2f %s", speed.first, speed.second)); 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); formattedLine = utils::quote_for_stfl(formattedLine); return formattedLine; } } // namespace podboat <commit_msg>Fixed SIGSEGV when there are no downloads<commit_after>#include "pbview.h" #include <cinttypes> #include <cstdio> #include <cstring> #include <curses.h> #include <iostream> #include <sstream> #include "config.h" #include "configcontainer.h" #include "dllist.h" #include "download.h" #include "fmtstrformatter.h" #include "help.h" #include "listformatter.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) , colorman(ctrl->get_colormanager()) , downloads_list("dls", dllist_form, ctrl->get_cfgcont()->get_configvalue_as_int("scrolloff")) , help_textview("helptext", help_form) { if (getenv("ESCDELAY") == nullptr) { set_escdelay(25); } } PbView::~PbView() { Stfl::reset(); } void PbView::run(bool auto_download, bool wrap_scroll) { bool quit = false; // Make sure curses is initialized dllist_form.run(-3); // Hide cursor using curses curs_set(0); set_dllist_keymap_hint(); do { if (ctrl->view_update_necessary()) { const double total_kbps = ctrl->get_total_kbps(); const auto speed = get_speed_human_readable(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 %s total%s"), static_cast<unsigned int>( ctrl->downloads_in_progress()), static_cast<unsigned int>( ctrl->downloads().size()), speed.first, speed.second.c_str(), parbuf); dllist_form.set("head", buf); LOG(Level::DEBUG, "PbView::run: updating view... " "downloads().size() " "= %" PRIu64, static_cast<uint64_t>(ctrl->downloads().size())); ListFormatter listfmt; std::string formatstring = ctrl->get_formatstr(); dllist_form.run(-3); // compute all widget dimensions const unsigned int width = downloads_list.get_width(); unsigned int i = 0; for (const auto& dl : ctrl->downloads()) { auto lbuf = format_line(formatstring, dl, i, width); listfmt.add_line(lbuf); i++; } downloads_list.stfl_replace_lines(listfmt); 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; } if (strcmp(event, "RESIZE") == 0) { handle_resize(); continue; } Operation op = keys->get_operation(event, "podboat"); if (dllist_form.get("msg").length() > 0) { dllist_form.set("msg", ""); ctrl->set_view_update_necessary(true); } switch (op) { case OP_REDRAW: Stfl::reset(); break; case OP_PREV: case OP_SK_UP: downloads_list.move_up(wrap_scroll); break; case OP_NEXT: case OP_SK_DOWN: downloads_list.move_down(wrap_scroll); break; case OP_SK_HOME: downloads_list.move_to_first(); break; case OP_SK_END: downloads_list.move_to_last(); break; case OP_SK_PGUP: downloads_list.move_page_up(wrap_scroll); break; case OP_SK_PGDOWN: downloads_list.move_page_down(wrap_scroll); break; 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: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); if (ctrl->downloads()[idx].status() != DlStatus::DOWNLOADING) { std::thread t{PodDlThread( &ctrl->downloads()[idx], ctrl->get_cfgcont())}; t.detach(); } } } break; case OP_PB_PLAY: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); 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: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); DlStatus status = ctrl->downloads()[idx].status(); if (status == DlStatus::PLAYED) { ctrl->downloads()[idx].set_status( DlStatus::FINISHED); } } } break; case OP_PB_CANCEL: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); if (ctrl->downloads()[idx].status() == DlStatus::DOWNLOADING) { ctrl->downloads()[idx].set_status( DlStatus::CANCELLED); } } } break; case OP_PB_DELETE: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); 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->purge_queue(); } ctrl->set_view_update_necessary(true); break; case OP_HELP: run_help(); break; default: break; } if (ctrl->downloads().size() >= 1 && dllist_form.get("msg").length() == 0) { const auto idx = downloads_list.get_position(); dllist_form.set("msg", ctrl->downloads()[idx].status_msg()); } } while (!quit); } void PbView::handle_resize() { std::vector<std::reference_wrapper<newsboat::Stfl::Form>> forms = {dllist_form, help_form}; for (const auto form : forms) { form.get().run(-3); } ctrl->set_view_update_necessary(true); } void PbView::apply_colors_to_all_forms() { colorman.apply_colors(dllist_form); colorman.apply_colors(help_form); } std::pair<double, std::string> PbView::get_speed_human_readable(double kbps) { if (kbps < 1024) { return std::make_pair(kbps, _("KB/s")); } else if (kbps < 1024 * 1024) { return std::make_pair(kbps / 1024, _("MB/s")); } else { return std::make_pair(kbps / 1024 / 1024, _("GB/s")); } } void PbView::run_help() { set_help_keymap_hint(); help_form.set("head", _("Help")); const auto descs = keys->get_keymap_descriptions("podboat"); ListFormatter listfmt; for (const auto& desc : descs) { 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); listfmt.add_line(descline); } help_textview.stfl_replace_lines(listfmt.get_lines_count(), listfmt.format_list()); bool quit = false; do { const char* event = help_form.run(0); if (!event) { continue; } if (strcmp(event, "RESIZE") == 0) { handle_resize(); continue; } Operation op = keys->get_operation(event, "help"); switch (op) { case OP_SK_UP: help_textview.scroll_up(); break; case OP_SK_DOWN: help_textview.scroll_down(); break; case OP_SK_HOME: help_textview.scroll_to_top(); break; case OP_SK_END: help_textview.scroll_to_bottom(); break; case OP_SK_PGUP: help_textview.scroll_page_up(); break; case OP_SK_PGDOWN: help_textview.scroll_page_down(); break; 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) { std::string bound_keys = utils::join(keys->get_keys(hints[i].op, "podboat"), ","); if (bound_keys.empty()) { bound_keys = "<none>"; } keymap_hint.append(bound_keys); 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; const double speed_kbps = dl.kbps(); const auto speed = get_speed_human_readable(speed_kbps); 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", speed_kbps)); fmt.register_fmt('K', strprintf::fmt("%.2f %s", speed.first, speed.second)); 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); formattedLine = utils::quote_for_stfl(formattedLine); return formattedLine; } } // namespace podboat <|endoftext|>
<commit_before>#include "pbview.h" #include <cinttypes> #include <cstdio> #include <cstring> #include <curses.h> #include <iostream> #include <sstream> #include "config.h" #include "configcontainer.h" #include "dllist.h" #include "download.h" #include "fmtstrformatter.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() " "= %" PRIu64, static_cast<uint64_t>(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); } } std::pair<double, std::string> PbView::get_speed_human_readable(double kbps) { if (kbps < 1024) { return std::make_pair(kbps, _("KB/s")); } else if (kbps < 1024 * 1024) { return std::make_pair(kbps / 1024, _("MB/s")); } else { return std::make_pair(kbps / 1024 / 1024, _("GB/s")); } } 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; const double speed_kbps = dl.kbps(); const auto speed = get_speed_human_readable(speed_kbps); 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 %s", speed.first, speed.second)); 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 <commit_msg>Podboat: Automatically change between KB/s,MB/s,GB/s for total speed<commit_after>#include "pbview.h" #include <cinttypes> #include <cstdio> #include <cstring> #include <curses.h> #include <iostream> #include <sstream> #include "config.h" #include "configcontainer.h" #include "dllist.h" #include "download.h" #include "fmtstrformatter.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()) { const double total_kbps = ctrl->get_total_kbps(); const auto speed = get_speed_human_readable(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 %s total%s"), static_cast<unsigned int>( ctrl->downloads_in_progress()), static_cast<unsigned int>( ctrl->downloads().size()), speed.first, speed.second.c_str(), parbuf); dllist_form.set("head", buf); LOG(Level::DEBUG, "PbView::run: updating view... " "downloads().size() " "= %" PRIu64, static_cast<uint64_t>(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); } } std::pair<double, std::string> PbView::get_speed_human_readable(double kbps) { if (kbps < 1024) { return std::make_pair(kbps, _("KB/s")); } else if (kbps < 1024 * 1024) { return std::make_pair(kbps / 1024, _("MB/s")); } else { return std::make_pair(kbps / 1024 / 1024, _("GB/s")); } } 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; const double speed_kbps = dl.kbps(); const auto speed = get_speed_human_readable(speed_kbps); 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 %s", speed.first, speed.second)); 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 <|endoftext|>
<commit_before>#pragma once #include <string> #include <vector> #include <limits> #include <utility> #include <glm/glm.hpp> // Immutable state class Planet { public: class Orbit { public: Orbit() = default; Orbit(double ecc, double sma, double inc, double lan, double arg, double m0); glm::dvec3 computePosition(double epoch, double parentGM) const; private: // Kepler orbital parameters (Meters & radians) double _ecc = 0.0; double _sma = 0.0; double _inc = 0.0; double _lan = 0.0; double _arg = 0.0; double _m0 = 0.0; }; class Atmo { public: Atmo() = default; Atmo(glm::vec4 K, float density, float maxHeight, float scaleHeight); std::vector<float> generateLookupTable(size_t size, float radius) const; glm::vec4 getScatteringConstant() const; float getDensity() const; float getMaxHeight() const; float getScaleHeight() const; private: glm::vec4 _K = glm::vec4(0.0); float _density = 0.0; float _maxHeight = 0.0; /// Max atmospheric height float _scaleHeight = 0.0; /// Scale height }; class Ring { public: Ring() = default; Ring(float innerDistance, float outerDistance, glm::vec3 normal, const std::string &backscatFilename, const std::string &forwardscatFilename, const std::string &unlitFilename, const std::string &transparencyFilename, const std::string &colorFilename); std::vector<float> loadFile(const std::string &filename) const; float getInnerDistance() const; float getOuterDistance() const; glm::vec3 getNormal() const; std::string getBackscatFilename() const; std::string getForwardscatFilename() const; std::string getUnlitFilename() const; std::string getTransparencyFilename() const; std::string getColorFilename() const; private: float _innerDistance = 0.0; /// distance to planet of inner ring float _outerDistance = 0.0; /// distance to planet of outer ring glm::vec3 _normal = glm::vec3(0.0); /// Plane normal (normalized) // Assets std::string _backscatFilename; std::string _forwardscatFilename; std::string _unlitFilename; std::string _transparencyFilename; std::string _colorFilename; }; class Body { public: Body() = default; Body( float radius, double GM, glm::vec3 rotAxis, float rotPeriod, glm::vec3 meanColor, const std::string &diffuseFilename); glm::vec3 getRotationAxis() const; float getRotationPeriod() const; glm::vec3 getMeanColor() const; float getRadius() const; double getGM() const; std::string getDiffuseFilename() const; private: glm::vec3 _rotAxis = glm::vec3(0.0,0.0,1.0); // Seconds per revolution float _rotPeriod = std::numeric_limits<float>::infinity(); glm::vec3 _meanColor = glm::vec3(0.0); // Color seen from far away float _radius = 0.0; // km double _GM = 0.0; // gravitational parameter // Asset paths std::string _diffuseFilename; }; class Star { public: Star() = default; explicit Star(float brightness); float getBrightness() const; private: float _brightness; }; class Clouds { public: Clouds() = default; explicit Clouds(const std::string &filename, float period=0); std::string getFilename() const; float getPeriod() const; private: std::string _filename; float _period; }; class Night { public: Night() = default; explicit Night(const std::string &filename, float intensity=1); std::string getFilename() const; float getIntensity() const; private: std::string _filename; float _intensity; }; class Specular { public: struct Mask { glm::vec3 color; float hardness; }; Specular() = default; explicit Specular(const std::string &filename, Mask mask0, Mask mask1); Mask getMask0() const; Mask getMask1() const; std::string getFilename() const; private: std::string _filename; Mask _mask0; Mask _mask1; }; Planet() = default; void setName(const std::string &name); void setParentName(const std::string &name); void setBody(const Body &body); void setOrbit(const Orbit &orbit); void setAtmo(const Atmo &atmo); void setRing(const Ring &ring); void setStar(const Star &star); void setClouds(const Clouds &clouds); void setNight(const Night &night); void setSpecular(const Specular &specular); bool hasOrbit() const; bool hasAtmo() const; bool hasRing() const; bool isStar() const; bool hasClouds() const; bool hasNight() const; bool hasSpecular() const; std::string getName() const; std::string getParentName() const; const Body &getBody() const; const Orbit &getOrbit() const; const Atmo &getAtmo() const; const Ring &getRing() const; const Star &getStar() const; const Clouds &getClouds() const; const Night &getNight() const; const Specular &getSpecular() const; private: std::string _name = "Undefined"; std::string _parentName = ""; Body _body = Body(); std::pair<bool, Orbit> _orbit = std::make_pair(false, Orbit()); std::pair<bool, Atmo> _atmo = std::make_pair(false, Atmo()); std::pair<bool, Ring> _ring = std::make_pair(false, Ring()); std::pair<bool, Star> _star = std::make_pair(false, Star()); std::pair<bool, Clouds> _clouds = std::make_pair(false, Clouds()); std::pair<bool, Night> _night = std::make_pair(false, Night()); std::pair<bool, Specular> _specular = std::make_pair(false, Specular()); }; // Mutable state class PlanetState { public: PlanetState() = default; PlanetState(const glm::dvec3 &pos, float rotationAngle, float cloudDisp); glm::dvec3 getPosition() const; float getRotationAngle() const; float getCloudDisp() const; private: glm::dvec3 _position = glm::dvec3(0.0); float _rotationAngle = 0.0; float _cloudDisp = 0.0; };<commit_msg>Add documentation<commit_after>#pragma once #include <string> #include <vector> #include <limits> #include <utility> #include <glm/glm.hpp> // Immutable state class Planet { public: class Orbit { public: Orbit() = default; /** * @param ecc Eccentricity * @param sma Semi-Major Axis (meters) * @param inc Inclination (radians) * @param lan Longitude of ascending node (radians) * @param arg Argument of periapsis (radians) * @param m0 Mean anomaly at epoch (radians) */ Orbit(double ecc, double sma, double inc, double lan, double arg, double m0); /** * Computes cartesian coordinates of body around parent body * @param epoch epoch in seconds * @param parentGM gravitational parameter of parent body * @return cartesian coordinates around parent body */ glm::dvec3 computePosition(double epoch, double parentGM) const; private: // Kepler orbital parameters (Meters & radians) /// Eccentricity double _ecc = 0.0; /// Semi-Major Axis (meters) double _sma = 0.0; /// Inclination (radians) double _inc = 0.0; /// Longitude of ascending node (radians) double _lan = 0.0; /// Argument of periapsis (radians) double _arg = 0.0; /// Mean anomaly at epoch (radians) double _m0 = 0.0; }; class Atmo { public: Atmo() = default; /** * @param K scattering constants * @param density density at sea level * @param maxHeight Atmospheric ceiling (0 pressure above) * @param scaleHeight Scale height of atmosphere */ Atmo(glm::vec4 K, float density, float maxHeight, float scaleHeight); /** * Generate lookup texture for atmosphere rendering * @param size width and height of texture * @param radius radius of planet */ std::vector<float> generateLookupTable(size_t size, float radius) const; glm::vec4 getScatteringConstant() const; float getDensity() const; float getMaxHeight() const; float getScaleHeight() const; private: /// Scattering constants glm::vec4 _K = glm::vec4(0.0); /// Density at sea level float _density = 0.0; /// Atmospheric ceiling float _maxHeight = 0.0; /// Atmospheric scale height float _scaleHeight = 0.0; }; class Ring { public: Ring() = default; /** * @param innerDistance distance of inner edge of rings from planet center * @param outerDistance distance of outer edge of rings from planet center * @param normal ring plane normal * @param backscatFilename backscattering brightness amount * @param forwardscatFilename forward scattering brightness amount * @param unlitFilename unlit side brightness amount * @param transparencyFilename transparency amount * @param colorFilename ring color texture */ Ring(float innerDistance, float outerDistance, glm::vec3 normal, const std::string &backscatFilename, const std::string &forwardscatFilename, const std::string &unlitFilename, const std::string &transparencyFilename, const std::string &colorFilename); /** Load txt files for rings */ std::vector<float> loadFile(const std::string &filename) const; float getInnerDistance() const; float getOuterDistance() const; glm::vec3 getNormal() const; std::string getBackscatFilename() const; std::string getForwardscatFilename() const; std::string getUnlitFilename() const; std::string getTransparencyFilename() const; std::string getColorFilename() const; private: /// distance from planet center to inner edge float _innerDistance = 0.0; /// distance from planet center to outer edge float _outerDistance = 0.0; /// Plane normal glm::vec3 _normal = glm::vec3(0.0); // Assets std::string _backscatFilename; std::string _forwardscatFilename; std::string _unlitFilename; std::string _transparencyFilename; std::string _colorFilename; }; class Body { public: Body() = default; Body( float radius, double GM, glm::vec3 rotAxis, float rotPeriod, glm::vec3 meanColor, const std::string &diffuseFilename); glm::vec3 getRotationAxis() const; float getRotationPeriod() const; glm::vec3 getMeanColor() const; float getRadius() const; double getGM() const; std::string getDiffuseFilename() const; private: /// Planet rotation axis glm::vec3 _rotAxis = glm::vec3(0.0,0.0,1.0); /// Seconds per revolution float _rotPeriod = std::numeric_limits<float>::infinity(); /// Color seen from far away glm::vec3 _meanColor = glm::vec3(0.0); /// Radius in km float _radius = 0.0; /// Gravitational parameter double _GM = 0.0; /// Diffuse texture filename std::string _diffuseFilename; }; class Star { public: Star() = default; explicit Star(float brightness); float getBrightness() const; private: float _brightness; }; class Clouds { public: Clouds() = default; explicit Clouds(const std::string &filename, float period=0); std::string getFilename() const; float getPeriod() const; private: std::string _filename; float _period; }; class Night { public: Night() = default; explicit Night(const std::string &filename, float intensity=1); std::string getFilename() const; float getIntensity() const; private: std::string _filename; float _intensity; }; class Specular { public: struct Mask { glm::vec3 color; float hardness; }; Specular() = default; explicit Specular(const std::string &filename, Mask mask0, Mask mask1); Mask getMask0() const; Mask getMask1() const; std::string getFilename() const; private: std::string _filename; Mask _mask0; Mask _mask1; }; Planet() = default; void setName(const std::string &name); void setParentName(const std::string &name); void setBody(const Body &body); void setOrbit(const Orbit &orbit); void setAtmo(const Atmo &atmo); void setRing(const Ring &ring); void setStar(const Star &star); void setClouds(const Clouds &clouds); void setNight(const Night &night); void setSpecular(const Specular &specular); bool hasOrbit() const; bool hasAtmo() const; bool hasRing() const; bool isStar() const; bool hasClouds() const; bool hasNight() const; bool hasSpecular() const; std::string getName() const; std::string getParentName() const; const Body &getBody() const; const Orbit &getOrbit() const; const Atmo &getAtmo() const; const Ring &getRing() const; const Star &getStar() const; const Clouds &getClouds() const; const Night &getNight() const; const Specular &getSpecular() const; private: std::string _name = "Undefined"; std::string _parentName = ""; Body _body = Body(); std::pair<bool, Orbit> _orbit = std::make_pair(false, Orbit()); std::pair<bool, Atmo> _atmo = std::make_pair(false, Atmo()); std::pair<bool, Ring> _ring = std::make_pair(false, Ring()); std::pair<bool, Star> _star = std::make_pair(false, Star()); std::pair<bool, Clouds> _clouds = std::make_pair(false, Clouds()); std::pair<bool, Night> _night = std::make_pair(false, Night()); std::pair<bool, Specular> _specular = std::make_pair(false, Specular()); }; // Mutable state class PlanetState { public: PlanetState() = default; PlanetState(const glm::dvec3 &pos, float rotationAngle, float cloudDisp); glm::dvec3 getPosition() const; float getRotationAngle() const; float getCloudDisp() const; private: glm::dvec3 _position = glm::dvec3(0.0); float _rotationAngle = 0.0; float _cloudDisp = 0.0; };<|endoftext|>
<commit_before>#include "penguin.h" #include "util.h" #include <math.h> sf::Texture Player::texture; sf::SoundBuffer Player::walkSoundBuffer; Player::Player(int icefloe) { loadTexture(texture, "res/img/bear.png"); sprite.setTexture(texture); centerSprite(sprite); loadSoundBuffer(walkSoundBuffer, "res/sound/walk.ogg"); walkSound.setBuffer(walkSoundBuffer); walkSound.setLoop(true); this->icefloe = icefloe; pos = sf::Vector2f(0.0f, 0.0f); rot = 0.0f; height = 0.0f; vel = sf::Vector2f(0.0f, 0.0f); velY = 0.0f; } Player::~Player() { //walkSound.stop(); } void Player::update(Game* game) { const auto leftKey = sf::Keyboard::Key::A; const auto rightKey = sf::Keyboard::Key::D; const auto runKey = sf::Keyboard::Key::W; const auto backKey = sf::Keyboard::Key::S; const auto jumpKey = sf::Keyboard::Key::Space; float runSpeed = 1200.0f - length(vel); const float reverseFraction = 0.25f; const float turnSpeed = 1.7f; const float friction = 3.0f; sf::Vector2f forward = sf::Vector2f(cos(rot - M_PI / 2.0f), sin(rot - M_PI / 2.0f)); bool moving = false; // Move forward/backward if (height == 0.0f) { if (sf::Keyboard::isKeyPressed(runKey)) { vel += game->dt * forward * runSpeed; moving = true; } if (sf::Keyboard::isKeyPressed(backKey)) { vel -= game->dt * forward * runSpeed * reverseFraction; moving = true; } } // Rotate left/right if (sf::Keyboard::isKeyPressed(leftKey)) { rot -= game->dt * turnSpeed; moving = true; } if (sf::Keyboard::isKeyPressed(rightKey)) { rot += game->dt * turnSpeed; moving = true; } // Update position and velocity pos += vel * game->dt; if (height == 0.0f) vel -= vel * friction * game->dt; // Walk sound if (moving && walkSound.getStatus() != sf::SoundSource::Status::Playing) { walkSound.play(); } else if (!moving && walkSound.getStatus() == sf::SoundSource::Status::Playing) { walkSound.stop(); } // Jumping if (height == 0.0f && sf::Keyboard::isKeyPressed(jumpKey)) { height = 0.01; pos = getRealPos(game); icefloe = -1; velY = 1.5f; } height += velY * game->dt; velY -= 5.0f * game->dt; // Landing if (height < 0.0f && velY < 0.0f) { velY = height = 0.0f; for (auto f : game->icefloes) { sf::Vector2f relativePos = getRealPos(game) - f.second->pos; if (f.second->inside(relativePos)) { icefloe = f.first; pos = relativePos; break; } } } // Check for drowning if ((icefloe == -1 && height == 0.0f) || (icefloe != -1 && !game->icefloes[icefloe]->inside(pos))) { game->over = true; } } void Player::render(Game* game) { sprite.setPosition(getRealPos(game)); sprite.setRotation(rot * 180.0f / M_PI); float scale = 1.0f + height; sprite.setScale(scale, scale); drawSprite(sprite, game); } sf::Vector2f Player::getRealPos(Game* game) { sf::Vector2f realPos = pos; if (icefloe != -1) { Icefloe* floe = game->icefloes[icefloe]; realPos += floe->pos; } return realPos; } <commit_msg>Fix moving between floes<commit_after>#include "penguin.h" #include "util.h" #include <math.h> sf::Texture Player::texture; sf::SoundBuffer Player::walkSoundBuffer; Player::Player(int icefloe) { loadTexture(texture, "res/img/bear.png"); sprite.setTexture(texture); centerSprite(sprite); loadSoundBuffer(walkSoundBuffer, "res/sound/walk.ogg"); walkSound.setBuffer(walkSoundBuffer); walkSound.setLoop(true); this->icefloe = icefloe; pos = sf::Vector2f(0.0f, 0.0f); rot = 0.0f; height = 0.0f; vel = sf::Vector2f(0.0f, 0.0f); velY = 0.0f; } Player::~Player() { //walkSound.stop(); } void Player::update(Game* game) { const auto leftKey = sf::Keyboard::Key::A; const auto rightKey = sf::Keyboard::Key::D; const auto runKey = sf::Keyboard::Key::W; const auto backKey = sf::Keyboard::Key::S; const auto jumpKey = sf::Keyboard::Key::Space; float runSpeed = 1200.0f - length(vel); const float reverseFraction = 0.25f; const float turnSpeed = 1.7f; const float friction = 3.0f; sf::Vector2f forward = sf::Vector2f(cos(rot - M_PI / 2.0f), sin(rot - M_PI / 2.0f)); bool moving = false; // Move forward/backward if (height == 0.0f) { if (sf::Keyboard::isKeyPressed(runKey)) { vel += game->dt * forward * runSpeed; moving = true; } if (sf::Keyboard::isKeyPressed(backKey)) { vel -= game->dt * forward * runSpeed * reverseFraction; moving = true; } } // Rotate left/right if (sf::Keyboard::isKeyPressed(leftKey)) { rot -= game->dt * turnSpeed; moving = true; } if (sf::Keyboard::isKeyPressed(rightKey)) { rot += game->dt * turnSpeed; moving = true; } // Update position and velocity pos += vel * game->dt; if (height == 0.0f) vel -= vel * friction * game->dt; // Walk sound if (moving && walkSound.getStatus() != sf::SoundSource::Status::Playing) { walkSound.play(); } else if (!moving && walkSound.getStatus() == sf::SoundSource::Status::Playing) { walkSound.stop(); } // Jumping if (height == 0.0f && sf::Keyboard::isKeyPressed(jumpKey)) { height = 0.01; pos = getRealPos(game); icefloe = -1; velY = 1.5f; } height += velY * game->dt; velY -= 5.0f * game->dt; // Detect if we moved outside our floe if (icefloe != -1 && !game->icefloes[icefloe]->inside(pos)) { pos = getRealPos(game); icefloe = -1; } // Landing and switching ice floe if (height <= 0.0f && velY <= 0.0f) { velY = height = 0.0f; if (icefloe == -1) { for (auto f : game->icefloes) { sf::Vector2f relativePos = getRealPos(game) - f.second->pos; if (f.second->inside(relativePos)) { icefloe = f.first; pos = relativePos; break; } } if (icefloe == -1) { game->over = true; } } } } void Player::render(Game* game) { sprite.setPosition(getRealPos(game)); sprite.setRotation(rot * 180.0f / M_PI); float scale = 1.0f + height; sprite.setScale(scale, scale); drawSprite(sprite, game); } sf::Vector2f Player::getRealPos(Game* game) { sf::Vector2f realPos = pos; if (icefloe != -1) { Icefloe* floe = game->icefloes[icefloe]; realPos += floe->pos; } return realPos; } <|endoftext|>
<commit_before>// player.cpp /*********************************************************************** * Copyright (C) 2011 Holework Project * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *************************************************************************/ #include "player.h" #include "events.h" #include "log.h" #include "network/connection.h" #include "network/request.h" #include "network/response.h" #include <sstream> #define MAX_DELTA 10000 //change this or make it configurable? namespace boostcraft { Player::Player(boost::asio::io_service& io) : Connection(io), timer_(new interval_timer( 5000, std::bind(&Player::deliver, this, network::keepalive()))) { } void Player::log(std::string message) { boostcraft::log(INFO, "Player: " + this->name_, message); } void Player::deliver(network::Response const& packet) { Connection::deliver(packet); } void Player::dispatch(network::Request const& packet) { packet.dispatch(*this); } void Player::handshake(std::string const& username) { if (name_.empty()) { name_ = username; deliver(network::handshake("-")); log("Handshake request for user " + name_); } else { log("Received handshake " + username + " when username already set to " + name_); } } void Player::updatePosition(double x, double y, double z) { x_ = x; x_ = y; x_ = z; /* TODO: Something that tells everyone the player position changed. */ } void Player::updateLook(float yaw, float pitch) { yaw_ = yaw; pitch_ = pitch; /* TODO: Something that tells everyone the player look changed. */ } void Player::updateHealth(short health) { if (health >= 20) { health_ = 20; } else if (health <= 0) { health = 0; } else { health_ = health; } } std::string Player::name() { return this->name_; } } // end namespace boostcraft <commit_msg>Fixed player keepalive timer; should work correctly now<commit_after>// player.cpp /*********************************************************************** * Copyright (C) 2011 Holework Project * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *************************************************************************/ #include "player.h" #include "events.h" #include "log.h" #include "network/connection.h" #include "network/request.h" #include "network/response.h" #include <sstream> #define MAX_DELTA 10000 //change this or make it configurable? namespace boostcraft { Player::Player(boost::asio::io_service& io) : Connection(io), timer_(0) { } void Player::log(std::string message) { boostcraft::log(INFO, "Player: " + this->name_, message); } void Player::deliver(network::Response const& packet) { Connection::deliver(packet); } void Player::dispatch(network::Request const& packet) { packet.dispatch(*this); } void Player::handshake(std::string const& username) { if (name_.empty()) { name_ = username; deliver(network::handshake("-")); log("Handshake request for user " + name_); // Initialize the keepalive timer timer_.reset(new interval_timer(5000, [this]() { this->deliver(network::keepalive()); })); } else { log("Received handshake " + username + " when username already set to " + name_); } } void Player::updatePosition(double x, double y, double z) { x_ = x; x_ = y; x_ = z; /* TODO: Something that tells everyone the player position changed. */ } void Player::updateLook(float yaw, float pitch) { yaw_ = yaw; pitch_ = pitch; /* TODO: Something that tells everyone the player look changed. */ } void Player::updateHealth(short health) { if (health >= 20) { health_ = 20; } else if (health <= 0) { health = 0; } else { health_ = health; } } std::string Player::name() { return this->name_; } } // end namespace boostcraft <|endoftext|>
<commit_before>#include "libtorrent/tracker_manager.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/buffer.hpp" #include "libtorrent/xml_parse.hpp" #include "libtorrent/upnp.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/torrent_info.hpp" #include <boost/tuple/tuple.hpp> #include <boost/tuple/tuple_comparison.hpp> #include <boost/bind.hpp> #include "test.hpp" using namespace libtorrent; using namespace boost::tuples; using boost::bind; tuple<int, int> feed_bytes(http_parser& parser, char const* str) { tuple<int, int> ret(0, 0); buffer::const_interval recv_buf(str, str + 1); for (; *str; ++str) { recv_buf.end = str + 1; int payload, protocol; tie(payload, protocol) = parser.incoming(recv_buf); ret.get<0>() += payload; ret.get<1>() += protocol; } return ret; } void parser_callback(std::string& out, int token, char const* s, char const* val) { switch (token) { case xml_start_tag: out += "B"; break; case xml_end_tag: out += "F"; break; case xml_empty_tag: out += "E"; break; case xml_declaration_tag: out += "D"; break; case xml_comment: out += "C"; break; case xml_string: out += "S"; break; case xml_attribute: out += "A"; break; case xml_parse_error: out += "P"; break; default: TEST_CHECK(false); } out += s; if (token == xml_attribute) { TEST_CHECK(val != 0); out += "V"; out += val; } else { TEST_CHECK(val == 0); } } int test_main() { using namespace libtorrent; TEST_CHECK(parse_url_components("http://foo:bar@host.com:80/path/to/file") == make_tuple("http", "foo:bar", "host.com", 80, "/path/to/file")); TEST_CHECK(parse_url_components("http://host.com/path/to/file") == make_tuple("http", "", "host.com", 80, "/path/to/file")); TEST_CHECK(parse_url_components("ftp://host.com:21/path/to/file") == make_tuple("ftp", "", "host.com", 21, "/path/to/file")); TEST_CHECK(parse_url_components("http://host.com/path?foo:bar@foo:") == make_tuple("http", "", "host.com", 80, "/path?foo:bar@foo:")); TEST_CHECK(parse_url_components("http://192.168.0.1/path/to/file") == make_tuple("http", "", "192.168.0.1", 80, "/path/to/file")); TEST_CHECK(parse_url_components("http://[::1]/path/to/file") == make_tuple("http", "", "[::1]", 80, "/path/to/file")); // base64 test vectors from http://www.faqs.org/rfcs/rfc4648.html TEST_CHECK(base64encode("") == ""); TEST_CHECK(base64encode("f") == "Zg=="); TEST_CHECK(base64encode("fo") == "Zm8="); TEST_CHECK(base64encode("foo") == "Zm9v"); TEST_CHECK(base64encode("foob") == "Zm9vYg=="); TEST_CHECK(base64encode("fooba") == "Zm9vYmE="); TEST_CHECK(base64encode("foobar") == "Zm9vYmFy"); // HTTP request parser http_parser parser; boost::tuple<int, int> received = feed_bytes(parser , "HTTP/1.1 200 OK\r\n" "Content-Length: 4\r\n" "Content-Type: text/plain\r\n" "\r\n" "test"); TEST_CHECK(received == make_tuple(4, 64)); TEST_CHECK(parser.finished()); TEST_CHECK(std::equal(parser.get_body().begin, parser.get_body().end, "test")); TEST_CHECK(parser.header<std::string>("content-type") == "text/plain"); TEST_CHECK(parser.header<int>("content-length") == 4); parser.reset(); TEST_CHECK(!parser.finished()); char const* upnp_response = "HTTP/1.1 200 OK\r\n" "ST:upnp:rootdevice\r\n" "USN:uuid:000f-66d6-7296000099dc::upnp:rootdevice\r\n" "Location: http://192.168.1.1:5431/dyndev/uuid:000f-66d6-7296000099dc\r\n" "Server: Custom/1.0 UPnP/1.0 Proc/Ver\r\n" "EXT:\r\n" "Cache-Control:max-age=180\r\n" "DATE: Fri, 02 Jan 1970 08:10:38 GMT\r\n\r\n"; received = feed_bytes(parser, upnp_response); TEST_CHECK(received == make_tuple(0, int(strlen(upnp_response)))); TEST_CHECK(parser.get_body().left() == 0); TEST_CHECK(parser.header<std::string>("st") == "upnp:rootdevice"); TEST_CHECK(parser.header<std::string>("location") == "http://192.168.1.1:5431/dyndev/uuid:000f-66d6-7296000099dc"); TEST_CHECK(parser.header<std::string>("ext") == ""); TEST_CHECK(parser.header<std::string>("date") == "Fri, 02 Jan 1970 08:10:38 GMT"); parser.reset(); TEST_CHECK(!parser.finished()); char const* upnp_notify = "NOTIFY * HTTP/1.1\r\n" "Host:239.255.255.250:1900\r\n" "NT:urn:schemas-upnp-org:device:MediaServer:1\r\n" "NTS:ssdp:alive\r\n" "Location:http://10.0.1.15:2353/upnphost/udhisapi.dll?content=uuid:c17f2c31-d19b-4912-af94-651945c8a84e\r\n" "USN:uuid:c17f0c32-d1db-4be8-ae94-25f94583026e::urn:schemas-upnp-org:device:MediaServer:1\r\n" "Cache-Control:max-age=900\r\n" "Server:Microsoft-Windows-NT/5.1 UPnP/1.0 UPnP-Device-Host/1.0\r\n"; received = feed_bytes(parser, upnp_notify); TEST_CHECK(received == make_tuple(0, int(strlen(upnp_notify)))); TEST_CHECK(parser.method() == "notify"); TEST_CHECK(parser.path() == "*"); // test xml parser char xml1[] = "<a>foo<b/>bar</a>"; std::string out1; xml_parse(xml1, xml1 + sizeof(xml1) - 1, bind(&parser_callback , boost::ref(out1), _1, _2, _3)); std::cerr << out1 << std::endl; TEST_CHECK(out1 == "BaSfooEbSbarFa"); char xml2[] = "<?xml version = \"1.0\"?><c x=\"1\" \t y=\"3\"/><d foo='bar'></d boo='foo'><!--comment-->"; std::string out2; xml_parse(xml2, xml2 + sizeof(xml2) - 1, bind(&parser_callback , boost::ref(out2), _1, _2, _3)); std::cerr << out2 << std::endl; TEST_CHECK(out2 == "DxmlAversionV1.0EcAxV1AyV3BdAfooVbarFdAbooVfooCcomment"); char xml3[] = "<a f=1>foo</a f='b>"; std::string out3; xml_parse(xml3, xml3 + sizeof(xml3) - 1, bind(&parser_callback , boost::ref(out3), _1, _2, _3)); std::cerr << out3 << std::endl; TEST_CHECK(out3 == "BaPunquoted attribute valueSfooFaPmissing end quote on attribute"); char xml4[] = "<a f>foo</a v >"; std::string out4; xml_parse(xml4, xml4 + sizeof(xml4) - 1, bind(&parser_callback , boost::ref(out4), _1, _2, _3)); std::cerr << out4 << std::endl; TEST_CHECK(out4 == "BaPgarbage inside element bracketsSfooFaPgarbage inside element brackets"); // test network functions TEST_CHECK(is_local(address::from_string("192.168.0.1"))); TEST_CHECK(is_local(address::from_string("10.1.1.56"))); TEST_CHECK(!is_local(address::from_string("14.14.251.63"))); // test torrent parsing entry info; info["pieces"] = "aaaaaaaaaaaaaaaaaaaa"; info["name.utf-8"] = "test1"; info["name"] = "test__"; info["piece length"] = 16 * 1024; info["length"] = 3245; entry torrent; torrent["info"] = info; torrent_info ti(torrent); TEST_CHECK(ti.name() == "test1"); return 0; } <commit_msg>added more address utility function tests<commit_after>#include "libtorrent/tracker_manager.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/buffer.hpp" #include "libtorrent/xml_parse.hpp" #include "libtorrent/upnp.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/torrent_info.hpp" #include <boost/tuple/tuple.hpp> #include <boost/tuple/tuple_comparison.hpp> #include <boost/bind.hpp> #include "test.hpp" using namespace libtorrent; using namespace boost::tuples; using boost::bind; tuple<int, int> feed_bytes(http_parser& parser, char const* str) { tuple<int, int> ret(0, 0); buffer::const_interval recv_buf(str, str + 1); for (; *str; ++str) { recv_buf.end = str + 1; int payload, protocol; tie(payload, protocol) = parser.incoming(recv_buf); ret.get<0>() += payload; ret.get<1>() += protocol; } return ret; } void parser_callback(std::string& out, int token, char const* s, char const* val) { switch (token) { case xml_start_tag: out += "B"; break; case xml_end_tag: out += "F"; break; case xml_empty_tag: out += "E"; break; case xml_declaration_tag: out += "D"; break; case xml_comment: out += "C"; break; case xml_string: out += "S"; break; case xml_attribute: out += "A"; break; case xml_parse_error: out += "P"; break; default: TEST_CHECK(false); } out += s; if (token == xml_attribute) { TEST_CHECK(val != 0); out += "V"; out += val; } else { TEST_CHECK(val == 0); } } int test_main() { using namespace libtorrent; TEST_CHECK(parse_url_components("http://foo:bar@host.com:80/path/to/file") == make_tuple("http", "foo:bar", "host.com", 80, "/path/to/file")); TEST_CHECK(parse_url_components("http://host.com/path/to/file") == make_tuple("http", "", "host.com", 80, "/path/to/file")); TEST_CHECK(parse_url_components("ftp://host.com:21/path/to/file") == make_tuple("ftp", "", "host.com", 21, "/path/to/file")); TEST_CHECK(parse_url_components("http://host.com/path?foo:bar@foo:") == make_tuple("http", "", "host.com", 80, "/path?foo:bar@foo:")); TEST_CHECK(parse_url_components("http://192.168.0.1/path/to/file") == make_tuple("http", "", "192.168.0.1", 80, "/path/to/file")); TEST_CHECK(parse_url_components("http://[::1]/path/to/file") == make_tuple("http", "", "[::1]", 80, "/path/to/file")); // base64 test vectors from http://www.faqs.org/rfcs/rfc4648.html TEST_CHECK(base64encode("") == ""); TEST_CHECK(base64encode("f") == "Zg=="); TEST_CHECK(base64encode("fo") == "Zm8="); TEST_CHECK(base64encode("foo") == "Zm9v"); TEST_CHECK(base64encode("foob") == "Zm9vYg=="); TEST_CHECK(base64encode("fooba") == "Zm9vYmE="); TEST_CHECK(base64encode("foobar") == "Zm9vYmFy"); // HTTP request parser http_parser parser; boost::tuple<int, int> received = feed_bytes(parser , "HTTP/1.1 200 OK\r\n" "Content-Length: 4\r\n" "Content-Type: text/plain\r\n" "\r\n" "test"); TEST_CHECK(received == make_tuple(4, 64)); TEST_CHECK(parser.finished()); TEST_CHECK(std::equal(parser.get_body().begin, parser.get_body().end, "test")); TEST_CHECK(parser.header<std::string>("content-type") == "text/plain"); TEST_CHECK(parser.header<int>("content-length") == 4); parser.reset(); TEST_CHECK(!parser.finished()); char const* upnp_response = "HTTP/1.1 200 OK\r\n" "ST:upnp:rootdevice\r\n" "USN:uuid:000f-66d6-7296000099dc::upnp:rootdevice\r\n" "Location: http://192.168.1.1:5431/dyndev/uuid:000f-66d6-7296000099dc\r\n" "Server: Custom/1.0 UPnP/1.0 Proc/Ver\r\n" "EXT:\r\n" "Cache-Control:max-age=180\r\n" "DATE: Fri, 02 Jan 1970 08:10:38 GMT\r\n\r\n"; received = feed_bytes(parser, upnp_response); TEST_CHECK(received == make_tuple(0, int(strlen(upnp_response)))); TEST_CHECK(parser.get_body().left() == 0); TEST_CHECK(parser.header<std::string>("st") == "upnp:rootdevice"); TEST_CHECK(parser.header<std::string>("location") == "http://192.168.1.1:5431/dyndev/uuid:000f-66d6-7296000099dc"); TEST_CHECK(parser.header<std::string>("ext") == ""); TEST_CHECK(parser.header<std::string>("date") == "Fri, 02 Jan 1970 08:10:38 GMT"); parser.reset(); TEST_CHECK(!parser.finished()); char const* upnp_notify = "NOTIFY * HTTP/1.1\r\n" "Host:239.255.255.250:1900\r\n" "NT:urn:schemas-upnp-org:device:MediaServer:1\r\n" "NTS:ssdp:alive\r\n" "Location:http://10.0.1.15:2353/upnphost/udhisapi.dll?content=uuid:c17f2c31-d19b-4912-af94-651945c8a84e\r\n" "USN:uuid:c17f0c32-d1db-4be8-ae94-25f94583026e::urn:schemas-upnp-org:device:MediaServer:1\r\n" "Cache-Control:max-age=900\r\n" "Server:Microsoft-Windows-NT/5.1 UPnP/1.0 UPnP-Device-Host/1.0\r\n"; received = feed_bytes(parser, upnp_notify); TEST_CHECK(received == make_tuple(0, int(strlen(upnp_notify)))); TEST_CHECK(parser.method() == "notify"); TEST_CHECK(parser.path() == "*"); // test xml parser char xml1[] = "<a>foo<b/>bar</a>"; std::string out1; xml_parse(xml1, xml1 + sizeof(xml1) - 1, bind(&parser_callback , boost::ref(out1), _1, _2, _3)); std::cerr << out1 << std::endl; TEST_CHECK(out1 == "BaSfooEbSbarFa"); char xml2[] = "<?xml version = \"1.0\"?><c x=\"1\" \t y=\"3\"/><d foo='bar'></d boo='foo'><!--comment-->"; std::string out2; xml_parse(xml2, xml2 + sizeof(xml2) - 1, bind(&parser_callback , boost::ref(out2), _1, _2, _3)); std::cerr << out2 << std::endl; TEST_CHECK(out2 == "DxmlAversionV1.0EcAxV1AyV3BdAfooVbarFdAbooVfooCcomment"); char xml3[] = "<a f=1>foo</a f='b>"; std::string out3; xml_parse(xml3, xml3 + sizeof(xml3) - 1, bind(&parser_callback , boost::ref(out3), _1, _2, _3)); std::cerr << out3 << std::endl; TEST_CHECK(out3 == "BaPunquoted attribute valueSfooFaPmissing end quote on attribute"); char xml4[] = "<a f>foo</a v >"; std::string out4; xml_parse(xml4, xml4 + sizeof(xml4) - 1, bind(&parser_callback , boost::ref(out4), _1, _2, _3)); std::cerr << out4 << std::endl; TEST_CHECK(out4 == "BaPgarbage inside element bracketsSfooFaPgarbage inside element brackets"); // test network functions asio::error_code ec; TEST_CHECK(is_local(address::from_string("192.168.0.1", ec))); TEST_CHECK(is_local(address::from_string("10.1.1.56", ec))); TEST_CHECK(!is_local(address::from_string("14.14.251.63", ec))); TEST_CHECK(is_loopback(address::from_string("127.0.0.1", ec))); TEST_CHECK(is_loopback(address::from_string("::1", ec))); TEST_CHECK(is_any(address_v6::any())); TEST_CHECK(is_any(address_v4::any())); TEST_CHECK(!is_any(address::from_string("31.53.21.64", ec))); // test torrent parsing entry info; info["pieces"] = "aaaaaaaaaaaaaaaaaaaa"; info["name.utf-8"] = "test1"; info["name"] = "test__"; info["piece length"] = 16 * 1024; info["length"] = 3245; entry torrent; torrent["info"] = info; torrent_info ti(torrent); TEST_CHECK(ti.name() == "test1"); return 0; } <|endoftext|>
<commit_before>#include <cassert> #include <ostream> #include "lisp_ptr.hh" #include "printer.hh" #include "symbol.hh" #include "cons.hh" #include "cons_util.hh" #include "number.hh" #include "util.hh" #include "delay.hh" #include "vm.hh" #include "eval.hh" #include "s_closure.hh" #include "builtin.hh" using namespace std; namespace { void print_vector(ostream& f, const Vector* v){ auto i = v->begin(); const auto e = v->end(); f.write("#(", 2); while(i != e){ print(f, *i); ++i; if(i != e) f.put(' '); } f.put(')'); } void print_list(ostream& f, Lisp_ptr l){ assert(l.tag() == Ptr_tag::cons); f.put('('); do_list(l, [&f](Cons* cell) -> bool{ print(f, cell->car()); if(cell->cdr().get<Cons*>()) f.put(' '); return true; }, [&f](Lisp_ptr dot_cdr){ if(!nullp(dot_cdr)){ f.write(" . ", 3); print(f, dot_cdr); } }); f.put(')'); } void print_char(ostream& f, char c, print_human_readable flag){ if(flag == print_human_readable::t){ f.put(c); }else{ switch(c){ case ' ': f << "#\\space"; break; case '\n': f << "#\\newline"; break; default: f.write("#\\", 2); f.put(c); } } } void print_string(ostream& f, const char* str, print_human_readable flag){ if(flag == print_human_readable::t){ f << str; }else{ f.put('\"'); for(auto s = str; *s; ++s){ switch(*s){ case '"': f.write("\\\"", 2); break; case '\\': f.write("\\\\", 2); break; default: f.put(*s); } } f.put('\"'); } } } // namespace void print(ostream& f, Lisp_ptr p, print_human_readable flag){ switch(p.tag()){ case Ptr_tag::undefined: f << "#<undefined>"; break; case Ptr_tag::boolean: f << ((p.get<bool>()) ? "#t" : "#f"); break; case Ptr_tag::character: print_char(f, p.get<char>(), flag); break; case Ptr_tag::cons: print_list(f, p); break; case Ptr_tag::symbol: { auto sym = p.get<Symbol*>(); if(vm.symtable().find(sym->name()) != vm.symtable().end()){ f << sym->name(); }else{ f << "#<uninterned '" << sym->name() << "' " << c_cast<void*>(sym) << ">"; } break; } case Ptr_tag::number: print(f, *p.get<Number*>()); break; case Ptr_tag::string: print_string(f, p.get<String*>()->c_str(), flag); break; case Ptr_tag::vector: print_vector(f, p.get<Vector*>()); break; case Ptr_tag::delay: { auto d = p.get<Delay*>(); if(flag == print_human_readable::t || !d->forced()){ f << "#<delay (" << (d->forced() ? "forced" : "delayed") << ") ["; } print(f, d->get(), flag); if(flag == print_human_readable::t || !d->forced()){ f << "]>"; } break; } case Ptr_tag::syntactic_closure: { auto sc = p.get<SyntacticClosure*>(); if(flag == print_human_readable::t){ f << "#<SyntacticClosure ["; } print(f, sc->expr(), flag); if(flag == print_human_readable::t){ f << ']'; if(identifierp(p)) f << " (identifier)"; f << '>'; } break; } case Ptr_tag::vm_argcount: f << "#<argcount " << p.get<int>() << ">"; break; case Ptr_tag::vm_op: f << "#<VMop " << stringify(p.get<VMop>()) << ">"; break; case Ptr_tag::n_procedure: f << "#<NativeProcedure [" << find_builtin_nproc_name(p.get<const Procedure::NProcedure*>()) << "]>"; break; case Ptr_tag::i_procedure: case Ptr_tag::continuation: case Ptr_tag::input_port: case Ptr_tag::output_port: case Ptr_tag::env: case Ptr_tag::syntax_rules: f << "#<" << stringify(p.tag()) << " " << p.get<void*>() << ">"; break; default: UNEXP_DEFAULT(); } } <commit_msg>fixed printer<commit_after>#include <cassert> #include <ostream> #include "lisp_ptr.hh" #include "printer.hh" #include "symbol.hh" #include "cons.hh" #include "cons_util.hh" #include "number.hh" #include "util.hh" #include "delay.hh" #include "vm.hh" #include "eval.hh" #include "s_closure.hh" #include "builtin.hh" using namespace std; namespace { void print_vector(ostream& f, const Vector* v, print_human_readable flag){ auto i = v->begin(); const auto e = v->end(); f.write("#(", 2); while(i != e){ print(f, *i, flag); ++i; if(i != e) f.put(' '); } f.put(')'); } void print_list(ostream& f, Lisp_ptr l, print_human_readable flag){ assert(l.tag() == Ptr_tag::cons); f.put('('); do_list(l, [&](Cons* cell) -> bool{ print(f, cell->car(), flag); if(cell->cdr().get<Cons*>()) f.put(' '); return true; }, [&](Lisp_ptr dot_cdr){ if(!nullp(dot_cdr)){ f.write(" . ", 3); print(f, dot_cdr, flag); } }); f.put(')'); } void print_char(ostream& f, char c, print_human_readable flag){ if(flag == print_human_readable::t){ f.put(c); }else{ switch(c){ case ' ': f << "#\\space"; break; case '\n': f << "#\\newline"; break; default: f.write("#\\", 2); f.put(c); } } } void print_string(ostream& f, const char* str, print_human_readable flag){ if(flag == print_human_readable::t){ f << str; }else{ f.put('\"'); for(auto s = str; *s; ++s){ switch(*s){ case '"': f.write("\\\"", 2); break; case '\\': f.write("\\\\", 2); break; default: f.put(*s); } } f.put('\"'); } } } // namespace void print(ostream& f, Lisp_ptr p, print_human_readable flag){ switch(p.tag()){ case Ptr_tag::undefined: f << "#<undefined>"; break; case Ptr_tag::boolean: f << ((p.get<bool>()) ? "#t" : "#f"); break; case Ptr_tag::character: print_char(f, p.get<char>(), flag); break; case Ptr_tag::cons: print_list(f, p, flag); break; case Ptr_tag::symbol: { auto sym = p.get<Symbol*>(); if(vm.symtable().find(sym->name()) != vm.symtable().end()){ f << sym->name(); }else{ f << "#<uninterned '" << sym->name() << "' " << c_cast<void*>(sym) << ">"; } break; } case Ptr_tag::number: print(f, *p.get<Number*>()); break; case Ptr_tag::string: print_string(f, p.get<String*>()->c_str(), flag); break; case Ptr_tag::vector: print_vector(f, p.get<Vector*>(), flag); break; case Ptr_tag::delay: { auto d = p.get<Delay*>(); if(flag == print_human_readable::t || !d->forced()){ f << "#<delay (" << (d->forced() ? "forced" : "delayed") << ") ["; } print(f, d->get(), flag); if(flag == print_human_readable::t || !d->forced()){ f << "]>"; } break; } case Ptr_tag::syntactic_closure: { auto sc = p.get<SyntacticClosure*>(); if(flag == print_human_readable::t){ f << "#<SyntacticClosure ["; } print(f, sc->expr(), flag); if(flag == print_human_readable::t){ f << ']'; if(identifierp(p)) f << " (alias)"; f << '>'; } break; } case Ptr_tag::vm_argcount: f << "#<argcount " << p.get<int>() << ">"; break; case Ptr_tag::vm_op: f << "#<VMop " << stringify(p.get<VMop>()) << ">"; break; case Ptr_tag::n_procedure: f << "#<NativeProcedure [" << find_builtin_nproc_name(p.get<const Procedure::NProcedure*>()) << "]>"; break; case Ptr_tag::i_procedure: case Ptr_tag::continuation: case Ptr_tag::input_port: case Ptr_tag::output_port: case Ptr_tag::env: case Ptr_tag::syntax_rules: f << "#<" << stringify(p.tag()) << " " << p.get<void*>() << ">"; break; default: UNEXP_DEFAULT(); } } <|endoftext|>
<commit_before>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- #include "grins_config.h" #ifdef GRINS_HAVE_CPPUNIT #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <string> #include <vector> #include <iostream> #include "grins/string_utils.h" namespace GRINSTesting { class StringUtilitiesTest : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE( StringUtilitiesTest ); CPPUNIT_TEST( test_split_string ); CPPUNIT_TEST_SUITE_END(); public: void test_split_string() { { std::string str_1("N->N2"); std::vector<std::string> test_1_split_exact(2); test_1_split_exact[0] = std::string("N"); test_1_split_exact[1] = std::string("N2"); std::vector<std::string> str_1_split; GRINS::StringUtilities::split_string( str_1, "->", str_1_split); this->test_string( str_1_split, test_1_split_exact ); } { std::string str_2("N+C(s)->CN"); std::vector<std::string> test_2_split_exact(2); test_2_split_exact[0] = std::string("N+C(s)"); test_2_split_exact[1] = std::string("CN"); std::vector<std::string> str_2_split; GRINS::StringUtilities::split_string( str_2, "->", str_2_split); this->test_string( str_2_split, test_2_split_exact ); } { std::string str_3("u:v:w:T:p:w_N:w_N2:p0"); std::vector<std::string> test_3_split_exact(8); test_3_split_exact[0] = std::string("u"); test_3_split_exact[1] = std::string("v"); test_3_split_exact[2] = std::string("w"); test_3_split_exact[3] = std::string("T"); test_3_split_exact[4] = std::string("p"); test_3_split_exact[5] = std::string("w_N"); test_3_split_exact[6] = std::string("w_N2"); test_3_split_exact[7] = std::string("p0"); std::vector<std::string> str_3_split; GRINS::StringUtilities::split_string( str_3, ":", str_3_split); this->test_string( str_3_split, test_3_split_exact ); } { std::string str_4("u v w T p w_N w_N2 p0"); std::vector<std::string> test_4_split_exact(8); test_4_split_exact[0] = std::string("u"); test_4_split_exact[1] = std::string("v"); test_4_split_exact[2] = std::string("w"); test_4_split_exact[3] = std::string("T"); test_4_split_exact[4] = std::string("p"); test_4_split_exact[5] = std::string("w_N"); test_4_split_exact[6] = std::string("w_N2"); test_4_split_exact[7] = std::string("p0"); std::vector<std::string> str_4_split; GRINS::StringUtilities::split_string( str_4, " ", str_4_split); this->test_string( str_4_split, test_4_split_exact ); } } private: void test_string( const std::vector<std::string>& test, const std::vector<std::string>& exact ) { CPPUNIT_ASSERT_EQUAL(test.size(), exact.size() ); for( unsigned int s = 0; s < test.size(); s++ ) CPPUNIT_ASSERT_EQUAL( test[s], exact[s] ); } }; CPPUNIT_TEST_SUITE_REGISTRATION( StringUtilitiesTest ); } // end namespace GRINSTesting #endif // GRINS_HAVE_CPPUNIT <commit_msg>Add test_string_to_T<commit_after>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- #include "grins_config.h" #ifdef GRINS_HAVE_CPPUNIT #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <string> #include <vector> #include <iostream> #include <limits> #include "grins/string_utils.h" namespace GRINSTesting { class StringUtilitiesTest : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE( StringUtilitiesTest ); CPPUNIT_TEST( test_split_string ); CPPUNIT_TEST( test_string_to_T ); CPPUNIT_TEST_SUITE_END(); public: void test_split_string() { { std::string str_1("N->N2"); std::vector<std::string> test_1_split_exact(2); test_1_split_exact[0] = std::string("N"); test_1_split_exact[1] = std::string("N2"); std::vector<std::string> str_1_split; GRINS::StringUtilities::split_string( str_1, "->", str_1_split); this->test_string( str_1_split, test_1_split_exact ); } { std::string str_2("N+C(s)->CN"); std::vector<std::string> test_2_split_exact(2); test_2_split_exact[0] = std::string("N+C(s)"); test_2_split_exact[1] = std::string("CN"); std::vector<std::string> str_2_split; GRINS::StringUtilities::split_string( str_2, "->", str_2_split); this->test_string( str_2_split, test_2_split_exact ); } { std::string str_3("u:v:w:T:p:w_N:w_N2:p0"); std::vector<std::string> test_3_split_exact(8); test_3_split_exact[0] = std::string("u"); test_3_split_exact[1] = std::string("v"); test_3_split_exact[2] = std::string("w"); test_3_split_exact[3] = std::string("T"); test_3_split_exact[4] = std::string("p"); test_3_split_exact[5] = std::string("w_N"); test_3_split_exact[6] = std::string("w_N2"); test_3_split_exact[7] = std::string("p0"); std::vector<std::string> str_3_split; GRINS::StringUtilities::split_string( str_3, ":", str_3_split); this->test_string( str_3_split, test_3_split_exact ); } { std::string str_4("u v w T p w_N w_N2 p0"); std::vector<std::string> test_4_split_exact(8); test_4_split_exact[0] = std::string("u"); test_4_split_exact[1] = std::string("v"); test_4_split_exact[2] = std::string("w"); test_4_split_exact[3] = std::string("T"); test_4_split_exact[4] = std::string("p"); test_4_split_exact[5] = std::string("w_N"); test_4_split_exact[6] = std::string("w_N2"); test_4_split_exact[7] = std::string("p0"); std::vector<std::string> str_4_split; GRINS::StringUtilities::split_string( str_4, " ", str_4_split); this->test_string( str_4_split, test_4_split_exact ); } } void test_string_to_T() { std::string one = "1"; int ione = GRINS::StringUtilities::string_to_T<int>(one); unsigned int uione = GRINS::StringUtilities::string_to_T<unsigned int>(one); CPPUNIT_ASSERT_EQUAL(1,ione); CPPUNIT_ASSERT_EQUAL((unsigned int)1,uione); std::string tenp1 = "10.1"; double dtenp1 = GRINS::StringUtilities::string_to_T<double>(tenp1); CPPUNIT_ASSERT_DOUBLES_EQUAL(10.1, dtenp1, std::numeric_limits<double>::epsilon()); } private: void test_string( const std::vector<std::string>& test, const std::vector<std::string>& exact ) { CPPUNIT_ASSERT_EQUAL(test.size(), exact.size() ); for( unsigned int s = 0; s < test.size(); s++ ) CPPUNIT_ASSERT_EQUAL( test[s], exact[s] ); } }; CPPUNIT_TEST_SUITE_REGISTRATION( StringUtilitiesTest ); } // end namespace GRINSTesting #endif // GRINS_HAVE_CPPUNIT <|endoftext|>
<commit_before>#include "tensorflow_types.hpp" // TODO: Capture error text rather than PyError_Print // TODO: Capture ... (named and un-named args) and forward to call // TODO: py_object_convert (convert from Python to R) // TODO: consider R6 wrapper (would allow custom $ functions) using namespace Rcpp; // https://docs.python.org/2/c-api/object.html // [[Rcpp::export]] void py_initialize() { ::Py_Initialize(); } // [[Rcpp::export]] void py_finalize() { ::Py_Finalize(); } // helper function to wrap a PyObject in an XPtr PyObjectPtr py_object_ptr(PyObject* object, bool decref = true) { PyObjectPtr ptr(object); ptr.attr("class") = "py_object"; return ptr; } //' @export // [[Rcpp::export]] void py_run_string(const std::string& code) { ::PyRun_SimpleString(code.c_str()); } //' @export // [[Rcpp::export]] void py_run_file(const std::string& file) { FILE* fp = ::fopen(file.c_str(), "r"); if (fp) ::PyRun_SimpleFile(fp, file.c_str()); else stop("Unable to read script file '%s' (does the file exist?)", file); } //' @export // [[Rcpp::export]] PyObjectPtr py_main_module() { return py_object_ptr(::PyImport_AddModule("__main__"), false); } //' @export // [[Rcpp::export]] PyObjectPtr py_import(const std::string& module) { PyObject* pModule = ::PyImport_ImportModule(module.c_str()); if (pModule == NULL) { ::PyErr_Print(); stop("Unable to import module '%s'", module); } return py_object_ptr(pModule); } //' @export // [[Rcpp::export(print.py_object)]] void py_object_print(PyObjectPtr pObject) { ::PyObject_Print(pObject.get(), stdout, Py_PRINT_RAW); } //' @export // [[Rcpp::export]] PyObjectPtr py_object_get_attr(PyObjectPtr pObject, const std::string& name) { PyObject* attr = ::PyObject_GetAttrString(pObject.get(), name.c_str()); if (attr == NULL) { ::PyErr_Print(); stop("Attribute '%s' not found.", name); } return py_object_ptr(attr); } //' @export // [[Rcpp::export]] bool py_object_is_callable(PyObjectPtr pObject) { return ::PyCallable_Check(pObject.get()) == 1; } //' @export // [[Rcpp::export]] PyObjectPtr py_object_call(PyObjectPtr pObject) { PyObject *args = PyTuple_New(0); PyObject *keywords = ::PyDict_New(); PyObject* res = ::PyObject_Call(pObject.get(), args, keywords); Py_DECREF(args); Py_DECREF(keywords); if (res == NULL) { ::PyErr_Print(); stop("Error calling python function"); } return py_object_ptr(res); } <commit_msg>more notes on object conversion<commit_after>#include "tensorflow_types.hpp" // TODO: Capture error text rather than PyError_Print // TODO: Capture ... (named and un-named args) and forward to call // TODO: py_object_convert (convert from Python to R). could be as.character, // as.matrix, as.logical, etc. Could also be done automatically or via // some sort of dynamic type annotation mechanism // TODO: consider R6 wrapper (would allow custom $ functions) using namespace Rcpp; // https://docs.python.org/2/c-api/object.html // [[Rcpp::export]] void py_initialize() { ::Py_Initialize(); } // [[Rcpp::export]] void py_finalize() { ::Py_Finalize(); } // helper function to wrap a PyObject in an XPtr PyObjectPtr py_object_ptr(PyObject* object, bool decref = true) { PyObjectPtr ptr(object); ptr.attr("class") = "py_object"; return ptr; } //' @export // [[Rcpp::export]] void py_run_string(const std::string& code) { ::PyRun_SimpleString(code.c_str()); } //' @export // [[Rcpp::export]] void py_run_file(const std::string& file) { FILE* fp = ::fopen(file.c_str(), "r"); if (fp) ::PyRun_SimpleFile(fp, file.c_str()); else stop("Unable to read script file '%s' (does the file exist?)", file); } //' @export // [[Rcpp::export]] PyObjectPtr py_main_module() { return py_object_ptr(::PyImport_AddModule("__main__"), false); } //' @export // [[Rcpp::export]] PyObjectPtr py_import(const std::string& module) { PyObject* pModule = ::PyImport_ImportModule(module.c_str()); if (pModule == NULL) { ::PyErr_Print(); stop("Unable to import module '%s'", module); } return py_object_ptr(pModule); } //' @export // [[Rcpp::export(print.py_object)]] void py_object_print(PyObjectPtr pObject) { ::PyObject_Print(pObject.get(), stdout, Py_PRINT_RAW); } //' @export // [[Rcpp::export]] PyObjectPtr py_object_get_attr(PyObjectPtr pObject, const std::string& name) { PyObject* attr = ::PyObject_GetAttrString(pObject.get(), name.c_str()); if (attr == NULL) { ::PyErr_Print(); stop("Attribute '%s' not found.", name); } return py_object_ptr(attr); } //' @export // [[Rcpp::export]] bool py_object_is_callable(PyObjectPtr pObject) { return ::PyCallable_Check(pObject.get()) == 1; } //' @export // [[Rcpp::export]] PyObjectPtr py_object_call(PyObjectPtr pObject) { PyObject *args = PyTuple_New(0); PyObject *keywords = ::PyDict_New(); PyObject* res = ::PyObject_Call(pObject.get(), args, keywords); Py_DECREF(args); Py_DECREF(keywords); if (res == NULL) { ::PyErr_Print(); stop("Error calling python function"); } return py_object_ptr(res); } <|endoftext|>
<commit_before>#include <boost/tokenizer.hpp> #include <iostream> #include <unistd.h> #include <string.h> #include <cstdlib> #include <errno.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <string> #include <sstream> #include <vector> #include <sys/stat.h> #include <fcntl.h> int oldstdin = dup(0); int oldstdout = dup(1); int oldstderr = dup(2); using namespace std; using namespace boost; void execvp(char **ye, int k) { ye[k] = NULL; int pid = fork(); if(pid == -1) { perror("fork"); exit(1); } if(pid == 0) { int r = execvp(ye[0], ye); if(r == -1) { perror("execvp"); exit(1); } } else { if(-1 == waitpid(pid, &pid, 0)) { perror("waitpid"); } } } void rshell(string &x) { char *argv[9]; int i = 0; string going; string saad; vector<string> arg_s; typedef tokenizer< char_separator<char> > tokenizer; char_separator<char> sep (" ", "<>>>\"#-;||&&", drop_empty_tokens); tokenizer tokens(x, sep); for(tokenizer::iterator tok_iter=tokens.begin(); tok_iter != tokens.end(); ++tok_iter) { if(saad == "-") { going += *tok_iter; going += " "; saad.append(*tok_iter); arg_s.push_back(saad); argv[i] = new char[12]; strcpy(argv[i], const_cast<char*>(saad.c_str())); if(*tok_iter == "exit") exit(0); ++i; continue; } // if((*tok_iter).size() == 1) { // going += *tok_iter; // cerr << mok << endl; // ++tok_iter; // going += *tok_iter; // cerr << mok << endl; // ++tok_iter; // going += *tok_iter; // going += " "; // cerr << mok << endl; // ++tok_iter; // continue; // } if(*tok_iter == "-") { saad = *tok_iter; going += *tok_iter; going += " "; continue; } if(*tok_iter == "#") { break; } if(*tok_iter == ";") { ++tok_iter; rshell(going); going.erase(0, going.find(*tok_iter, i)); arg_s.clear(); i = 0; argv[i] = new char[12]; } if(*tok_iter == "&") { ++tok_iter; if(*tok_iter == "&") { ++tok_iter; rshell(going); going.erase(0, going.find(*tok_iter, i)); arg_s.clear(); i = 0; argv[i] = new char[12]; } } if(*tok_iter == "<") { ++tok_iter; if(*tok_iter == "<") { // going += *tok_iter; ++tok_iter; // going += *tok_iter; if(*tok_iter == "<") { //EXTRA CREDIT 1 HERE!!!!!!!!!!! string blah = "ok"; void *buf; int fd2 = creat(const_cast<char*>(blah.c_str()), S_IRWXU); if(fd2 == -1) { perror("creat"); exit(1); } ++tok_iter; going += *tok_iter; string leggo; if(*tok_iter == "\"") { ++tok_iter; while(*tok_iter != "\"") { cout << *tok_iter << endl; leggo += *tok_iter; leggo += " "; ++tok_iter; } buf = malloc(leggo.length()); //leggo += *tok_iter; //going += " "; //going += leggo; int bag = write(fd2, buf, leggo.length()); if(bag == -1) { perror("write"); exit(1); } } } } string cake = *tok_iter; int savestdin; if(-1 == (savestdin = dup(0))) { perror("dup"); exit(1); } int fd = open(cake.c_str(), O_RDWR); if(fd == -1) { perror("open"); exit(1); } int drag = dup2(fd, 0); if(drag == -1) { perror("dup2"); exit(1); } //if(-1 == dup2(savestdin, 0)) //{ // perror("dup2"); // exit(1); //} continue; } if(*tok_iter == ">") { ++tok_iter; if(*tok_iter == ">") { ++tok_iter; string swerve = *tok_iter; int fd2 = open(swerve.c_str(), O_RDWR|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR); if(fd2 == -1) { perror("open"); exit(1); } int grag = dup2(fd2, 1); if(grag == -1) { perror("dup2"); exit(1); } continue; } else { string hold = *tok_iter; int fd = open(hold.c_str(), O_RDWR|O_CREAT|O_TRUNC, S_IRUSR | S_IWUSR); if(fd == -1) { perror("open"); exit(1); } int drag = dup2(fd, 1); if(drag == -1) { perror("dup2"); exit(1); } continue; } } if(*tok_iter == "|") { ++tok_iter; tokenizer::iterator coward; if(*tok_iter != "|") { //piping int pipefd[2]; pid_t cpid; //char buf; if(pipe(pipefd) == -1) { perror("pipe"); exit(1); } cpid = fork(); if(cpid == -1) { perror("fork"); exit(1); } else if(cpid == 0) { if(-1 == dup2(pipefd[1],1)) { perror("dup2"); exit(1); } if(-1 == close(pipefd[0])) { perror("close"); exit(1); } argv[i] = NULL; if(-1 == execvp(argv[0], argv)) { perror("execvp"); } exit(1); } else if(cpid > 0) { int savestdin; if(-1 == (savestdin = dup(0))) { perror("dup"); exit(1); } if(-1 == dup2(pipefd[0], 0)) { perror("dup2"); exit(1); } if(-1 == close(pipefd[1])) { perror("close"); exit(1); } if(-1 == waitpid(cpid, &cpid, 0)) { perror("waitpid"); exit(1); } int pipefd2[2]; pid_t cpid2; if(pipe(pipefd2) == -1) { perror("pipe"); exit(1); } cpid2 = fork(); if(cpid2 == -1) { perror("fork"); exit(1); } else if(cpid2 == 0) { if(-1 == dup2(pipefd2[1], 1)) { perror("dup2"); exit(1); } if(-1 == close(pipefd2[0])) { perror("close"); exit(1); } coward = tok_iter; char *toby[9]; int l = 0; vector<string> baby; string mok; while(tok_iter != tokens.end()) { if(*tok_iter == "|") break; //cerr << *tok_iter << endl; if((*tok_iter).size() == 1) { mok += *tok_iter; // cerr << mok << endl; ++tok_iter; mok += *tok_iter; // cerr << mok << endl; ++tok_iter; mok += *tok_iter; mok += " "; // cerr << mok << endl; ++tok_iter; continue; } mok += *tok_iter; //NEED TO PARSE MOK TO EXECUTE EXECVP - COME BACK LATER mok += " "; //++tok_iter; baby.push_back(mok); toby[l] = new char [12]; strcpy(toby[l], const_cast<char*>(baby[l].c_str())); //going += mok; ++l; ++tok_iter; } cerr << mok << "HEERRRRRREEEEEE" << endl; //rshell(mok); cerr << "BLAH BLAH BLAH" << endl; toby[l] = NULL; if(-1 == execvp(toby[0], toby)) perror("execvp"); exit(1); } else if(cpid > 0) { int savestdin; if(-1 == (savestdin = dup(0))) { perror("dup"); exit(1); } if(-1 == dup2(pipefd2[0], 0)) { perror("dup2"); exit(1); } if(-1 == close(pipefd2[1])) { perror("close"); exit(1); } if(-1 == waitpid(cpid2, &cpid2, 0)) { perror("waitpid"); exit(1); } //if(-1 == dup2(savestdout, 1)) // perror("dup2"); } //if(-1 == dup2(savestdin, 0)) // perror("dup2"); } //tok_iter = coward; continue; } //end piping if(*tok_iter == "|") { ++tok_iter; rshell(going); going.erase(0, going.find(*tok_iter, i)); arg_s.clear(); i = 0; argv[i] = new char[12]; } } tokenizer::iterator daw = tok_iter; string lop = *tok_iter; string llop; if((*tok_iter).size() == 1) { ++tok_iter; if(*tok_iter == "-") { llop += lop; llop += *tok_iter; // cerr << mok << endl; ++tok_iter; // llop += *tok_iter; // cerr << mok << endl; // ++tok_iter; llop += *tok_iter; llop += " "; // cerr << mok << endl; ++tok_iter; going += llop; going += " "; // cerr << llop << "ADASDOAKSDOKAS" << endl; arg_s.push_back(llop); argv[i] = new char[12]; strcpy(argv[i], const_cast<char*>(arg_s[i].c_str())); ++i; continue; } tok_iter = daw; } going += *tok_iter; going += " "; cout << going << endl; arg_s.push_back(*tok_iter); argv[i] = new char[12]; strcpy(argv[i], const_cast<char*>(arg_s[i].c_str())); if(*tok_iter == "exit") exit(0); ++i; } execvp(argv, i); return; } int main() { string args; while(1 != 2) { cout << "$ "; getline(cin, args); rshell(args); int ok = dup2(oldstdin, 0); if(ok == -1) { perror("dup2"); exit(1); } int ok2 = dup2(oldstdout, 1); if(ok2 == -1) { perror("dup2"); exit(1); } int ok3 = dup2(oldstderr, 2); if(ok3 == -1) { perror("dup2"); exit(1); } } return 0; } <commit_msg>boom pipe<commit_after>#include <boost/tokenizer.hpp> #include <iostream> #include <unistd.h> #include <string.h> #include <cstdlib> #include <errno.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <string> #include <sstream> #include <vector> #include <sys/stat.h> #include <fcntl.h> int oldstdin = dup(0); int oldstdout = dup(1); int oldstderr = dup(2); using namespace std; using namespace boost; void execvp(char **ye, int k) { ye[k] = NULL; int pid = fork(); if(pid == -1) { perror("fork"); exit(1); } if(pid == 0) { int r = execvp(ye[0], ye); if(r == -1) { perror("execvp"); exit(1); } } else { if(-1 == waitpid(pid, &pid, 0)) { perror("waitpid"); } } } void rshell(string &x) { char *argv[9]; int i = 0; string going; string saad; vector<string> arg_s; typedef tokenizer< char_separator<char> > tokenizer; char_separator<char> sep (" ", "<>>>\"#-;||&&", drop_empty_tokens); tokenizer tokens(x, sep); for(tokenizer::iterator tok_iter=tokens.begin(); tok_iter != tokens.end(); ++tok_iter) { if(saad == "-") { if(*tok_iter == "-") { saad += *tok_iter; going += *tok_iter; continue; } going += *tok_iter; going += " "; saad.append(*tok_iter); arg_s.push_back(saad); argv[i] = new char[12]; strcpy(argv[i], const_cast<char*>(saad.c_str())); if(*tok_iter == "exit") exit(0); ++i; continue; } if(*tok_iter == "-") { saad = *tok_iter; going += *tok_iter; continue; } if(*tok_iter == "#") { break; } if(*tok_iter == ";") { ++tok_iter; rshell(going); going.erase(0, going.find(*tok_iter, i)); arg_s.clear(); i = 0; argv[i] = new char[12]; } if(*tok_iter == "&") { ++tok_iter; if(*tok_iter == "&") { ++tok_iter; rshell(going); going.erase(0, going.find(*tok_iter, i)); arg_s.clear(); i = 0; argv[i] = new char[12]; } } if(*tok_iter == "<") { ++tok_iter; if(*tok_iter == "<") { // going += *tok_iter; ++tok_iter; // going += *tok_iter; if(*tok_iter == "<") { //EXTRA CREDIT 1 HERE!!!!!!!!!! char *buf = new char[sizeof(BUFSIZ)]; int fd2 = open(".manny", O_CREAT|O_RDWR|O_TRUNC, S_IRUSR|S_IWUSR); if(fd2 == -1) { perror("open"); exit(1); } int bag = write(fd2, buf, BUFSIZ); if(bag == -1) { perror("write"); exit(1); } ++tok_iter; going += *tok_iter; string leggo; if(*tok_iter == "\"") { ++tok_iter; while(*tok_iter != "\"") { int bag = write(fd2, buf, BUFSIZ); if(bag == -1) { perror("write"); exit(1); } cout << *tok_iter << endl; leggo += *tok_iter; leggo += " "; ++tok_iter; } //leggo += *tok_iter; //going += " "; //going += leggo; //int bag = write(fd2, buf, BUFSIZ); //if(bag == -1) { // perror("write"); // exit(1); //} } int claw = read(fd2, buf, BUFSIZ); if(claw == -1) perror("read"); int mk = close(fd2); if(mk == -1) perror("close"); delete [] buf; } } string cake = *tok_iter; int savestdin; if(-1 == (savestdin = dup(0))) { perror("dup"); exit(1); } int fd = open(cake.c_str(), O_RDWR); if(fd == -1) { perror("open"); exit(1); } int drag = dup2(fd, 0); if(drag == -1) { perror("dup2"); exit(1); } //if(-1 == dup2(savestdin, 0)) //{ // perror("dup2"); // exit(1); //} continue; } if(*tok_iter == ">") { ++tok_iter; if(*tok_iter == ">") { ++tok_iter; string swerve = *tok_iter; int fd2 = open(swerve.c_str(), O_RDWR|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR); if(fd2 == -1) { perror("open"); exit(1); } int grag = dup2(fd2, 1); if(grag == -1) { perror("dup2"); exit(1); } continue; } else { string hold = *tok_iter; int fd = open(hold.c_str(), O_RDWR|O_CREAT|O_TRUNC, S_IRUSR | S_IWUSR); if(fd == -1) { perror("open"); exit(1); } int drag = dup2(fd, 1); if(drag == -1) { perror("dup2"); exit(1); } continue; } } if(*tok_iter == "|") { ++tok_iter; tokenizer::iterator coward; if(*tok_iter != "|") { //piping int pipefd[2]; pid_t cpid; //char buf; if(pipe(pipefd) == -1) { perror("pipe"); exit(1); } cpid = fork(); if(cpid == -1) { perror("fork"); exit(1); } else if(cpid == 0) { if(-1 == dup2(pipefd[1],1)) { perror("dup2"); exit(1); } if(-1 == close(pipefd[0])) { perror("close"); exit(1); } argv[i] = NULL; if(-1 == execvp(argv[0], argv)) { perror("execvp"); } exit(1); } else if(cpid > 0) { int savestdin; if(-1 == (savestdin = dup(0))) { perror("dup"); exit(1); } if(-1 == dup2(pipefd[0], 0)) { perror("dup2"); exit(1); } if(-1 == close(pipefd[1])) { perror("close"); exit(1); } if(-1 == waitpid(cpid, &cpid, 0)) { perror("waitpid"); exit(1); } int pipefd2[2]; pid_t cpid2; if(pipe(pipefd2) == -1) { perror("pipe"); exit(1); } cpid2 = fork(); if(cpid2 == -1) { perror("fork"); exit(1); } else if(cpid2 == 0) { if(-1 == dup2(pipefd2[1], 1)) { perror("dup2"); exit(1); } if(-1 == close(pipefd2[0])) { perror("close"); exit(1); } coward = tok_iter; char *toby[9]; int l = 0; vector<string> baby; string mok; while(tok_iter != tokens.end()) { if(*tok_iter == "|") break; //cerr << *tok_iter << endl; if((*tok_iter).size() == 1) { mok += *tok_iter; // cerr << mok << endl; ++tok_iter; mok += *tok_iter; // cerr << mok << endl; ++tok_iter; mok += *tok_iter; mok += " "; // cerr << mok << endl; ++tok_iter; baby.push_back(mok); toby[l] = new char[12]; strcpy(toby[l], const_cast<char*>(baby[l].c_str())); ++l; cerr << toby[l] << " " << "TOBY!!!!!!" << endl; mok.erase(mok.begin(), mok.end()); continue; } mok += *tok_iter; //NEED TO PARSE MOK TO EXECUTE EXECVP - COME BACK LATER cerr << mok << endl; //++tok_iter; baby.push_back(mok); toby[l] = new char [12]; strcpy(toby[l], const_cast<char*>(baby[l].c_str())); //going += mok; cerr << toby[l] << " " << "EFWQFEWFWFDFSAFSA" << endl; ++l; mok.erase(mok.begin(), mok.end()); ++tok_iter; } cerr << mok << "HEERRRRRREEEEEE" << endl; //rshell(mok); cerr << "BLAH BLAH BLAH" << endl; //cerr << toby[0] << endl; toby[l] = NULL; if(-1 == execvp(toby[0], toby)) perror("execvp"); cerr << "DID IT!" << endl; exit(1); } else if(cpid > 0) { int savestdin; if(-1 == (savestdin = dup(0))) { perror("dup"); exit(1); } if(-1 == dup2(pipefd2[0], 0)) { perror("dup2"); exit(1); } if(-1 == close(pipefd2[1])) { perror("close"); exit(1); } if(-1 == waitpid(cpid2, &cpid2, 0)) { perror("waitpid"); exit(1); } //if(-1 == dup2(savestdout, 1)) // perror("dup2"); } //if(-1 == dup2(savestdin, 0)) // perror("dup2"); } //tok_iter = coward; continue; } //end piping if(*tok_iter == "|") { ++tok_iter; rshell(going); going.erase(0, going.find(*tok_iter, i)); arg_s.clear(); i = 0; argv[i] = new char[12]; } } tokenizer::iterator daw = tok_iter; string lop = *tok_iter; string llop; if((*tok_iter).size() == 1) { ++tok_iter; if(*tok_iter == "-") { llop += lop; llop += *tok_iter; // cerr << mok << endl; ++tok_iter; // llop += *tok_iter; // cerr << mok << endl; // ++tok_iter; llop += *tok_iter; llop += " "; // cerr << mok << endl; ++tok_iter; going += llop; going += " "; // cerr << llop << "ADASDOAKSDOKAS" << endl; arg_s.push_back(llop); argv[i] = new char[12]; strcpy(argv[i], const_cast<char*>(arg_s[i].c_str())); ++i; continue; } tok_iter = daw; } going += *tok_iter; going += " "; cout << going << endl; arg_s.push_back(*tok_iter); argv[i] = new char[12]; strcpy(argv[i], const_cast<char*>(arg_s[i].c_str())); if(*tok_iter == "exit") exit(0); ++i; } execvp(argv, i); return; } int main() { string args; while(1 != 2) { cout << "$ "; getline(cin, args); rshell(args); int ok = dup2(oldstdin, 0); if(ok == -1) { perror("dup2"); exit(1); } int ok2 = dup2(oldstdout, 1); if(ok2 == -1) { perror("dup2"); exit(1); } int ok3 = dup2(oldstderr, 2); if(ok3 == -1) { perror("dup2"); exit(1); } } return 0; } <|endoftext|>
<commit_before>#include "server.h" #include "HttpRequest.h" #include "HttpResponse.h" #include <unistd.h> #include <iostream> #include <event2/bufferevent.h> #include <event2/buffer.h> #include <arpa/inet.h> #include <sys/stat.h> #include <fcntl.h> #include <Foundation/Foundation.h> #include <AVFoundation/AVFoundation.h> std::string Server::rootDirectory = "/Users/dmitry/Desktop/http-test-suite-master/httptest"; void Server::read(bufferevent *bev, void *ctx) { evbuffer *input = bufferevent_get_input(bev); evbuffer *output = bufferevent_get_output(bev); size_t inputSize = evbuffer_get_length(input); try { HttpRequest request(evbuffer_pullup(input, inputSize), inputSize); string fileName = rootDirectory + request.getPath(); if (fileName.back() == '/') { fileName = fileName + INDEX_FILE; } int fileDescriptor = open(fileName.c_str(), O_RDONLY | O_NONBLOCK); struct stat fileStat; HttpResponse response; if (fileDescriptor != FILE_NOT_FOUND) { fstat(fileDescriptor, &fileStat); *((int *) ctx) = fileDescriptor; string contentType = "text/html"; response.setStatusCode(HTTP_CODE_OK); response.setContentLength((size_t) fileStat.st_size); response.setContentType(contentType); } else { string contentType = "text/html"; response.setStatusCode(HTTP_CODE_NOT_FOUND); response.setContentLength(0); response.setContentType(contentType); } string responseHeader = response.getRawHeader(); evbuffer_add(output, (void *) responseHeader.c_str(), response.getHeaderLength()); if (request.getMethod() != "HEAD" && response.getStatusCode() == HTTP_CODE_OK) { evbuffer_add_file(output, fileDescriptor, 0, fileStat.st_size); } } catch (BadRequestException &e) { std::cout << "Bad request" << std::endl; } } void Server::dropConnection(bufferevent *bev, void *ctx) { bufferevent_free(bev); close(*((int *)ctx)); delete (int *)ctx; } void Server::eventCallback(bufferevent *bev, short events, void *ctx) { if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) { bufferevent_free(bev); } } void Server::acceptConnection(evconnlistener *listener, evutil_socket_t fd, sockaddr *address, int socketLength, void *ctx) { event_base *base = evconnlistener_get_base(listener); bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE); int *fileDescriptor = new int(0); bufferevent_setcb(bev, read, dropConnection, eventCallback, fileDescriptor); bufferevent_enable(bev, EV_READ); } void Server::acceptError(evconnlistener *listener, void *ctx) { event_base *base = evconnlistener_get_base(listener); int err = EVUTIL_SOCKET_ERROR(); fprintf(stderr, "Got an error %d (%s) on the listener. " "Shutting down.\n", err, evutil_socket_error_to_string(err)); event_base_loopexit(base, NULL); } void Server::start() { event_base *base; evconnlistener *listener; sockaddr_in sin; int port = 8010; base = event_base_new(); if (!base) { puts("Couldn't open event base"); return; } memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(0); sin.sin_port = htons(port); listener = evconnlistener_new_bind(base, acceptConnection, NULL, LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1, (sockaddr*)&sin, sizeof(sin)); if (!listener) { perror("Couldn't create listener"); return; } evconnlistener_set_error_cb(listener, acceptError); numberOfWorkers = sysconf( _SC_NPROCESSORS_ONLN ) + 1; for (long i = 0; i < numberOfWorkers; i++) { auto pid = fork(); if (!pid) { event_reinit(base); break; } } event_base_dispatch(base); }<commit_msg>bad request<commit_after>#include "server.h" #include "HttpRequest.h" #include "HttpResponse.h" #include <unistd.h> #include <iostream> #include <event2/bufferevent.h> #include <event2/buffer.h> #include <arpa/inet.h> #include <sys/stat.h> #include <fcntl.h> #include <Foundation/Foundation.h> #include <AVFoundation/AVFoundation.h> std::string Server::rootDirectory = "/Users/dmitry/Desktop/http-test-suite-master/httptest"; void Server::read(bufferevent *bev, void *ctx) { evbuffer *input = bufferevent_get_input(bev); evbuffer *output = bufferevent_get_output(bev); HttpResponse response; bool sendFile = true; int fileDescriptor = 0; struct stat fileStat; try { size_t inputSize = evbuffer_get_length(input); HttpRequest request(evbuffer_pullup(input, inputSize), inputSize); string fileName = rootDirectory + request.getPath(); if (fileName.back() == '/') { fileName = fileName + INDEX_FILE; } fileDescriptor = open(fileName.c_str(), O_RDONLY | O_NONBLOCK); if (fileDescriptor != FILE_NOT_FOUND) { fstat(fileDescriptor, &fileStat); *((int *) ctx) = fileDescriptor; string contentType = "text/html"; response.setStatusCode(HTTP_CODE_OK); response.setContentLength((size_t) fileStat.st_size); response.setContentType(contentType); } else { string contentType = "text/html"; response.setStatusCode(HTTP_CODE_NOT_FOUND); response.setContentLength(0); response.setContentType(contentType); sendFile = false; } } catch (BadRequestException &e) { string contentType = "text/html"; response.setStatusCode(HTTP_CODE_BAD_REQUEST); response.setContentLength(0); response.setContentType(contentType); sendFile = false; } string responseHeader = response.getRawHeader(); evbuffer_add(output, (void *) responseHeader.c_str(), response.getHeaderLength()); if (sendFile) { evbuffer_add_file(output, fileDescriptor, 0, fileStat.st_size); } } void Server::dropConnection(bufferevent *bev, void *ctx) { bufferevent_free(bev); close(*((int *)ctx)); delete (int *)ctx; } void Server::eventCallback(bufferevent *bev, short events, void *ctx) { if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) { bufferevent_free(bev); } } void Server::acceptConnection(evconnlistener *listener, evutil_socket_t fd, sockaddr *address, int socketLength, void *ctx) { event_base *base = evconnlistener_get_base(listener); bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE); int *fileDescriptor = new int(0); bufferevent_setcb(bev, read, dropConnection, eventCallback, fileDescriptor); bufferevent_enable(bev, EV_READ); } void Server::acceptError(evconnlistener *listener, void *ctx) { event_base *base = evconnlistener_get_base(listener); int err = EVUTIL_SOCKET_ERROR(); fprintf(stderr, "Got an error %d (%s) on the listener. " "Shutting down.\n", err, evutil_socket_error_to_string(err)); event_base_loopexit(base, NULL); } void Server::start() { event_base *base; evconnlistener *listener; sockaddr_in sin; int port = 8010; base = event_base_new(); if (!base) { puts("Couldn't open event base"); return; } memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(0); sin.sin_port = htons(port); listener = evconnlistener_new_bind(base, acceptConnection, NULL, LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1, (sockaddr*)&sin, sizeof(sin)); if (!listener) { perror("Couldn't create listener"); return; } evconnlistener_set_error_cb(listener, acceptError); numberOfWorkers = sysconf( _SC_NPROCESSORS_ONLN ) + 1; for (long i = 0; i < numberOfWorkers; i++) { auto pid = fork(); if (!pid) { event_reinit(base); break; } } event_base_dispatch(base); }<|endoftext|>
<commit_before>#include <iostream> #include <chrono> #include <random> #include <numeric> #include <blaze/Math.h> #include "etl/etl.hpp" typedef std::chrono::high_resolution_clock timer_clock; typedef std::chrono::milliseconds milliseconds; typedef std::chrono::microseconds microseconds; namespace { template<typename T, std::enable_if_t<std::is_same<T, blaze::DynamicMatrix<double>>::value, int> = 42> void randomize_double(T& container){ static std::default_random_engine rand_engine(std::time(nullptr)); static std::uniform_real_distribution<double> real_distribution(-1000.0, 1000.0); static auto generator = std::bind(real_distribution, rand_engine); for(std::size_t i=0UL; i<container.rows(); ++i ) { for(std::size_t j=0UL; j<container.columns(); ++j ) { container(i,j) = generator(); } } } template<typename T, std::enable_if_t<!std::is_same<T, blaze::DynamicMatrix<double>>::value, int> = 42> void randomize_double(T& container){ static std::default_random_engine rand_engine(std::time(nullptr)); static std::uniform_real_distribution<double> real_distribution(-1000.0, 1000.0); static auto generator = std::bind(real_distribution, rand_engine); for(auto& v : container){ v = generator(); } } template<typename T1> void b_randomize(T1& container){ randomize_double(container); } template<typename T1, typename... TT> void b_randomize(T1& container, TT&... containers){ randomize_double(container); b_randomize(containers...); } std::string clean_duration(std::string value){ while(value.size() > 1 && value.back() == '0'){ value.pop_back(); } return value; } std::string duration_str(std::size_t duration_us){ if(duration_us > 1000 * 1000){ return clean_duration(std::to_string(duration_us / 1000.0 / 1000.0)) + "s"; } else if(duration_us > 1000){ return clean_duration(std::to_string(duration_us / 1000.0)) + "ms"; } else { return clean_duration(std::to_string(duration_us)) + "us"; } } template<typename Functor, typename... T> auto measure_only(Functor&& functor, T&... references){ for(std::size_t i = 0; i < 100; ++i){ b_randomize(references...); functor(); } std::size_t duration_acc = 0; for(std::size_t i = 0; i < 100; ++i){ b_randomize(references...); auto start_time = timer_clock::now(); functor(); auto end_time = timer_clock::now(); auto duration = std::chrono::duration_cast<microseconds>(end_time - start_time); duration_acc += duration.count(); } return duration_acc; } template<typename Functor, typename... T> void measure(const std::string& title, const std::string& reference, Functor&& functor, T&... references){ std::cout << title << " took " << duration_str(measure_only(functor, references...)) << " (reference: " << reference << ")\n"; } template<template<typename, std::size_t> class T, std::size_t D> struct add_static { static auto get(){ T<double, D> a,b,c; return measure_only([&a, &b, &c](){c = a + b;}, a, b); } }; template<template<typename> class T, std::size_t D> struct add_dynamic { static auto get(){ T<double> a(D), b(D), c(D); return measure_only([&a, &b, &c](){c = a + b;}, a, b); } }; template<template<typename> class T, std::size_t D> struct add_complex { static auto get(){ T<double> a(D), b(D), c(D); return measure_only([&a, &b, &c](){c = a + b + a + b + a + a + b + a + a;}, a, b); } }; template<template<typename> class T, std::size_t D> struct mix { static auto get(){ T<double> a(D), b(D), c(D); return measure_only([&a, &b, &c](){c = a + a * 5.9 + a + b - b / 2.3 - a + b * 1.1;}, a, b); } }; template<template<typename> class T, std::size_t D1, std::size_t D2> struct mix_matrix { static auto get(){ T<double> a(D1, D2), b(D1, D2), c(D1, D2); return measure_only([&a, &b, &c](){c = a + a * 5.9 + a + b - b / 2.3 - a + b * 1.1;}, a, b); } }; std::string format(std::string value, std::size_t max){ return value + (value.size() < max ? std::string(std::max(0UL, max - value.size()), ' ') : ""); } template<template<template<typename, std::size_t> class, std::size_t> class T, template<typename, std::size_t> class B, template<typename, std::size_t> class E, std::size_t D> void bench_static(const std::string& title){ std::cout << "| "; std::cout << format(title + ":" + std::to_string(D), 29) << " | "; std::cout << format(duration_str(T<B,D>::get()), 9) << " | "; std::cout << format(duration_str(T<E,D>::get()), 9) << " | "; std::cout << std::endl; } template<template<template<typename> class, std::size_t> class T, template<typename> class B, template<typename> class E, std::size_t D> void bench_dyn(const std::string& title){ std::cout << "| "; std::cout << format(title + ":" + std::to_string(D), 29) << " | "; std::cout << format(duration_str(T<B,D>::get()), 9) << " | "; std::cout << format(duration_str(T<E,D>::get()), 9) << " | "; std::cout << std::endl; } template<template<template<typename> class, std::size_t, std::size_t> class T, template<typename> class B, template<typename> class E, std::size_t D1, std::size_t D2> void bench_dyn(const std::string& title){ std::cout << "| "; std::cout << format(title + ":" + std::to_string(D1) + "x" + std::to_string(D2), 29) << " | "; std::cout << format(duration_str(T<B,D1,D2>::get()), 9) << " | "; std::cout << format(duration_str(T<E,D1,D2>::get()), 9) << " | "; std::cout << std::endl; } template<typename T, std::size_t D> using etl_static_vector = etl::fast_vector<T, D>; template<typename T, std::size_t D> using blaze_static_vector = blaze::StaticVector<T, D>; template<typename T> using etl_dyn_vector = etl::dyn_vector<T>; template<typename T> using blaze_dyn_vector = blaze::DynamicVector<T>; template<typename T> using etl_dyn_matrix = etl::dyn_matrix<T>; template<typename T> using blaze_dyn_matrix = blaze::DynamicMatrix<T>; } //end of anonymous namespace int main(){ std::cout << "| Name | Blaze | ETL |" << std::endl; std::cout << "---------------------------------------------------------" << std::endl; bench_static<add_static, blaze_static_vector, etl_static_vector, 8192>("static_add"); bench_dyn<add_dynamic, blaze_dyn_vector, etl_dyn_vector, 1 * 32768>("dynamic_add"); bench_dyn<add_dynamic, blaze_dyn_vector, etl_dyn_vector, 2 * 32768>("dynamic_add"); bench_dyn<add_dynamic, blaze_dyn_vector, etl_dyn_vector, 4 * 32768>("dynamic_add"); bench_dyn<add_complex, blaze_dyn_vector, etl_dyn_vector, 1 * 32768>("dynamic_add_complex"); bench_dyn<add_complex, blaze_dyn_vector, etl_dyn_vector, 2 * 32768>("dynamic_add_complex"); bench_dyn<add_complex, blaze_dyn_vector, etl_dyn_vector, 4 * 32768>("dynamic_add_complex"); bench_dyn<mix, blaze_dyn_vector, etl_dyn_vector, 1 * 32768>("dynamic_mix"); bench_dyn<mix, blaze_dyn_vector, etl_dyn_vector, 2 * 32768>("dynamic_mix"); bench_dyn<mix, blaze_dyn_vector, etl_dyn_vector, 4 * 32768>("dynamic_mix"); bench_dyn<mix_matrix, blaze_dyn_matrix, etl_dyn_matrix, 256, 256>("dynamic_mix_matrix"); bench_dyn<mix_matrix, blaze_dyn_matrix, etl_dyn_matrix, 512, 512>("dynamic_mix_matrix"); bench_dyn<mix_matrix, blaze_dyn_matrix, etl_dyn_matrix, 578, 769>("dynamic_mix_matrix"); std::cout << "---------------------------------------------------------" << std::endl; return 0; } <commit_msg>Add mmul to the benchmark<commit_after>#include <iostream> #include <chrono> #include <random> #include <numeric> #include <blaze/Math.h> #include "etl/etl.hpp" #include "etl/multiplication.hpp" typedef std::chrono::high_resolution_clock timer_clock; typedef std::chrono::milliseconds milliseconds; typedef std::chrono::microseconds microseconds; namespace { template<typename T, std::enable_if_t<std::is_same<T, blaze::DynamicMatrix<double>>::value, int> = 42> void randomize_double(T& container){ static std::default_random_engine rand_engine(std::time(nullptr)); static std::uniform_real_distribution<double> real_distribution(-1000.0, 1000.0); static auto generator = std::bind(real_distribution, rand_engine); for(std::size_t i=0UL; i<container.rows(); ++i ) { for(std::size_t j=0UL; j<container.columns(); ++j ) { container(i,j) = generator(); } } } template<typename T, std::enable_if_t<!std::is_same<T, blaze::DynamicMatrix<double>>::value, int> = 42> void randomize_double(T& container){ static std::default_random_engine rand_engine(std::time(nullptr)); static std::uniform_real_distribution<double> real_distribution(-1000.0, 1000.0); static auto generator = std::bind(real_distribution, rand_engine); for(auto& v : container){ v = generator(); } } template<typename T1> void b_randomize(T1& container){ randomize_double(container); } template<typename T1, typename... TT> void b_randomize(T1& container, TT&... containers){ randomize_double(container); b_randomize(containers...); } std::string clean_duration(std::string value){ while(value.size() > 1 && value.back() == '0'){ value.pop_back(); } return value; } std::string duration_str(std::size_t duration_us){ if(duration_us > 1000 * 1000){ return clean_duration(std::to_string(duration_us / 1000.0 / 1000.0)) + "s"; } else if(duration_us > 1000){ return clean_duration(std::to_string(duration_us / 1000.0)) + "ms"; } else { return clean_duration(std::to_string(duration_us)) + "us"; } } template<typename Functor, typename... T> auto measure_only(Functor&& functor, T&... references){ for(std::size_t i = 0; i < 100; ++i){ b_randomize(references...); functor(); } std::size_t duration_acc = 0; for(std::size_t i = 0; i < 100; ++i){ b_randomize(references...); auto start_time = timer_clock::now(); functor(); auto end_time = timer_clock::now(); auto duration = std::chrono::duration_cast<microseconds>(end_time - start_time); duration_acc += duration.count(); } return duration_acc; } template<typename Functor, typename... T> void measure(const std::string& title, const std::string& reference, Functor&& functor, T&... references){ std::cout << title << " took " << duration_str(measure_only(functor, references...)) << " (reference: " << reference << ")\n"; } template<template<typename, std::size_t> class T, std::size_t D> struct add_static { static auto get(){ T<double, D> a,b,c; return measure_only([&a, &b, &c](){c = a + b;}, a, b); } }; template<template<typename> class T, std::size_t D> struct add_dynamic { static auto get(){ T<double> a(D), b(D), c(D); return measure_only([&a, &b, &c](){c = a + b;}, a, b); } }; template<template<typename> class T, std::size_t D> struct add_complex { static auto get(){ T<double> a(D), b(D), c(D); return measure_only([&a, &b, &c](){c = a + b + a + b + a + a + b + a + a;}, a, b); } }; template<template<typename> class T, std::size_t D> struct mix { static auto get(){ T<double> a(D), b(D), c(D); return measure_only([&a, &b, &c](){c = a + a * 5.9 + a + b - b / 2.3 - a + b * 1.1;}, a, b); } }; template<template<typename> class T, std::size_t D1, std::size_t D2> struct mix_matrix { static auto get(){ T<double> a(D1, D2), b(D1, D2), c(D1, D2); return measure_only([&a, &b, &c](){c = a + a * 5.9 + a + b - b / 2.3 - a + b * 1.1;}, a, b); } }; template<template<typename> class T, std::size_t D1, std::size_t D2, std::size_t D3, typename Enable = void> struct mmul { static auto get(){ T<double> a(D1, D2), b(D2, D3), c(D1, D3); return measure_only([&a, &b, &c](){etl::mmul(a, b, c);}, a, b); } }; template<template<typename> class T, std::size_t D1, std::size_t D2, std::size_t D3> struct mmul<T, D1, D2, D3, std::enable_if_t<std::is_same<T<double>, blaze::DynamicMatrix<double>>::value>> { static auto get(){ T<double> a(D1, D2), b(D2, D3), c(D1, D3); return measure_only([&a, &b, &c](){c = a * b;}, a, b); } }; std::string format(std::string value, std::size_t max){ return value + (value.size() < max ? std::string(std::max(0UL, max - value.size()), ' ') : ""); } template<template<template<typename, std::size_t> class, std::size_t> class T, template<typename, std::size_t> class B, template<typename, std::size_t> class E, std::size_t D> void bench_static(const std::string& title){ std::cout << "| "; std::cout << format(title + ":" + std::to_string(D), 29) << " | "; std::cout << format(duration_str(T<B,D>::get()), 9) << " | "; std::cout << format(duration_str(T<E,D>::get()), 9) << " | "; std::cout << std::endl; } template<template<template<typename> class, std::size_t> class T, template<typename> class B, template<typename> class E, std::size_t D> void bench_dyn(const std::string& title){ std::cout << "| "; std::cout << format(title + ":" + std::to_string(D), 29) << " | "; std::cout << format(duration_str(T<B,D>::get()), 9) << " | "; std::cout << format(duration_str(T<E,D>::get()), 9) << " | "; std::cout << std::endl; } template<template<template<typename> class, std::size_t, std::size_t> class T, template<typename> class B, template<typename> class E, std::size_t D1, std::size_t D2> void bench_dyn(const std::string& title){ std::cout << "| "; std::cout << format(title + ":" + std::to_string(D1) + "x" + std::to_string(D2), 29) << " | "; std::cout << format(duration_str(T<B,D1,D2>::get()), 9) << " | "; std::cout << format(duration_str(T<E,D1,D2>::get()), 9) << " | "; std::cout << std::endl; } template<template<template<typename> class, std::size_t, std::size_t, std::size_t, typename = void> class T, template<typename> class B, template<typename> class E, std::size_t D1, std::size_t D2, std::size_t D3> void bench_dyn(const std::string& title){ std::cout << "| "; std::cout << format(title + ":" + std::to_string(D1) + "x" + std::to_string(D2) + "x" + std::to_string(D3), 29) << " | "; std::cout << format(duration_str(T<B,D1,D2,D3>::get()), 9) << " | "; std::cout << format(duration_str(T<E,D1,D2,D3>::get()), 9) << " | "; std::cout << std::endl; } template<typename T, std::size_t D> using etl_static_vector = etl::fast_vector<T, D>; template<typename T, std::size_t D> using blaze_static_vector = blaze::StaticVector<T, D>; template<typename T> using etl_dyn_vector = etl::dyn_vector<T>; template<typename T> using blaze_dyn_vector = blaze::DynamicVector<T>; template<typename T> using etl_dyn_matrix = etl::dyn_matrix<T>; template<typename T> using blaze_dyn_matrix = blaze::DynamicMatrix<T>; } //end of anonymous namespace int main(){ std::cout << "| Name | Blaze | ETL |" << std::endl; std::cout << "---------------------------------------------------------" << std::endl; bench_static<add_static, blaze_static_vector, etl_static_vector, 8192>("static_add"); bench_dyn<add_dynamic, blaze_dyn_vector, etl_dyn_vector, 1 * 32768>("dynamic_add"); bench_dyn<add_dynamic, blaze_dyn_vector, etl_dyn_vector, 2 * 32768>("dynamic_add"); bench_dyn<add_dynamic, blaze_dyn_vector, etl_dyn_vector, 4 * 32768>("dynamic_add"); bench_dyn<add_complex, blaze_dyn_vector, etl_dyn_vector, 1 * 32768>("dynamic_add_complex"); bench_dyn<add_complex, blaze_dyn_vector, etl_dyn_vector, 2 * 32768>("dynamic_add_complex"); bench_dyn<add_complex, blaze_dyn_vector, etl_dyn_vector, 4 * 32768>("dynamic_add_complex"); bench_dyn<mix, blaze_dyn_vector, etl_dyn_vector, 1 * 32768>("dynamic_mix"); bench_dyn<mix, blaze_dyn_vector, etl_dyn_vector, 2 * 32768>("dynamic_mix"); bench_dyn<mix, blaze_dyn_vector, etl_dyn_vector, 4 * 32768>("dynamic_mix"); bench_dyn<mix_matrix, blaze_dyn_matrix, etl_dyn_matrix, 256, 256>("dynamic_mix_matrix"); bench_dyn<mix_matrix, blaze_dyn_matrix, etl_dyn_matrix, 512, 512>("dynamic_mix_matrix"); bench_dyn<mix_matrix, blaze_dyn_matrix, etl_dyn_matrix, 578, 769>("dynamic_mix_matrix"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 128,32,64>("dynamic_mmul"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 128,128,128>("dynamic_mmul"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 256,128,256>("dynamic_mmul"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 256,256,256>("dynamic_mmul"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 300,200,400>("dynamic_mmul"); bench_dyn<mmul, blaze_dyn_matrix, etl_dyn_matrix, 512,512,512>("dynamic_mmul"); std::cout << "---------------------------------------------------------" << std::endl; return 0; } <|endoftext|>
<commit_before> /* * 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 "SkBenchmark.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkColorPriv.h" #include "SkPaint.h" #include "SkShader.h" #include "SkString.h" static const char* gConfigName[] = { "ERROR", "a1", "a8", "index8", "565", "4444", "8888" }; static void drawIntoBitmap(const SkBitmap& bm) { const int w = bm.width(); const int h = bm.height(); SkCanvas canvas(bm); SkPaint p; p.setAntiAlias(true); p.setColor(SK_ColorRED); canvas.drawCircle(SkIntToScalar(w)/2, SkIntToScalar(h)/2, SkIntToScalar(SkMin32(w, h))*3/8, p); SkRect r; r.set(0, 0, SkIntToScalar(w), SkIntToScalar(h)); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SkIntToScalar(4)); p.setColor(SK_ColorBLUE); canvas.drawRect(r, p); } static int conv6ToByte(int x) { return x * 0xFF / 5; } static int convByteTo6(int x) { return x * 5 / 255; } static uint8_t compute666Index(SkPMColor c) { int r = SkGetPackedR32(c); int g = SkGetPackedG32(c); int b = SkGetPackedB32(c); return convByteTo6(r) * 36 + convByteTo6(g) * 6 + convByteTo6(b); } static void convertToIndex666(const SkBitmap& src, SkBitmap* dst) { SkColorTable* ctable = new SkColorTable(216); SkPMColor* colors = ctable->lockColors(); // rrr ggg bbb for (int r = 0; r < 6; r++) { int rr = conv6ToByte(r); for (int g = 0; g < 6; g++) { int gg = conv6ToByte(g); for (int b = 0; b < 6; b++) { int bb = conv6ToByte(b); *colors++ = SkPreMultiplyARGB(0xFF, rr, gg, bb); } } } ctable->unlockColors(true); dst->setConfig(SkBitmap::kIndex8_Config, src.width(), src.height()); dst->allocPixels(ctable); ctable->unref(); SkAutoLockPixels alps(src); SkAutoLockPixels alpd(*dst); for (int y = 0; y < src.height(); y++) { const SkPMColor* srcP = src.getAddr32(0, y); uint8_t* dstP = dst->getAddr8(0, y); for (int x = src.width() - 1; x >= 0; --x) { *dstP++ = compute666Index(*srcP++); } } } class RepeatTileBench : public SkBenchmark { SkPaint fPaint; SkString fName; enum { N = SkBENCHLOOP(20) }; public: RepeatTileBench(void* param, SkBitmap::Config c) : INHERITED(param) { const int w = 50; const int h = 50; SkBitmap bm; if (SkBitmap::kIndex8_Config == c) { bm.setConfig(SkBitmap::kARGB_8888_Config, w, h); } else { bm.setConfig(c, w, h); } bm.allocPixels(); bm.eraseColor(0); drawIntoBitmap(bm); if (SkBitmap::kIndex8_Config == c) { SkBitmap tmp; convertToIndex666(bm, &tmp); bm = tmp; } SkShader* s = SkShader::CreateBitmapShader(bm, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); fPaint.setShader(s)->unref(); fName.printf("repeatTile_%s", gConfigName[bm.config()]); } protected: virtual const char* onGetName() { return fName.c_str(); } virtual void onDraw(SkCanvas* canvas) { SkPaint paint(fPaint); this->setupPaint(&paint); for (int i = 0; i < N; i++) { canvas->drawPaint(paint); } } private: typedef SkBenchmark INHERITED; }; static SkBenchmark* Fact0(void* p) { return new RepeatTileBench(p, SkBitmap::kARGB_8888_Config); } static SkBenchmark* Fact1(void* p) { return new RepeatTileBench(p, SkBitmap::kRGB_565_Config); } static SkBenchmark* Fact2(void* p) { return new RepeatTileBench(p, SkBitmap::kARGB_4444_Config); } static SkBenchmark* Fact3(void* p) { return new RepeatTileBench(p, SkBitmap::kIndex8_Config); } static BenchRegistry gReg0(Fact0); static BenchRegistry gReg1(Fact1); static BenchRegistry gReg2(Fact2); static BenchRegistry gReg3(Fact3); <commit_msg>add opaque/alpha variants<commit_after> /* * 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 "SkBenchmark.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkColorPriv.h" #include "SkPaint.h" #include "SkShader.h" #include "SkString.h" static const char* gConfigName[] = { "ERROR", "a1", "a8", "index8", "565", "4444", "8888" }; static void drawIntoBitmap(const SkBitmap& bm) { const int w = bm.width(); const int h = bm.height(); SkCanvas canvas(bm); SkPaint p; p.setAntiAlias(true); p.setColor(SK_ColorRED); canvas.drawCircle(SkIntToScalar(w)/2, SkIntToScalar(h)/2, SkIntToScalar(SkMin32(w, h))*3/8, p); SkRect r; r.set(0, 0, SkIntToScalar(w), SkIntToScalar(h)); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SkIntToScalar(4)); p.setColor(SK_ColorBLUE); canvas.drawRect(r, p); } static int conv6ToByte(int x) { return x * 0xFF / 5; } static int convByteTo6(int x) { return x * 5 / 255; } static uint8_t compute666Index(SkPMColor c) { int r = SkGetPackedR32(c); int g = SkGetPackedG32(c); int b = SkGetPackedB32(c); return convByteTo6(r) * 36 + convByteTo6(g) * 6 + convByteTo6(b); } static void convertToIndex666(const SkBitmap& src, SkBitmap* dst) { SkColorTable* ctable = new SkColorTable(216); SkPMColor* colors = ctable->lockColors(); // rrr ggg bbb for (int r = 0; r < 6; r++) { int rr = conv6ToByte(r); for (int g = 0; g < 6; g++) { int gg = conv6ToByte(g); for (int b = 0; b < 6; b++) { int bb = conv6ToByte(b); *colors++ = SkPreMultiplyARGB(0xFF, rr, gg, bb); } } } ctable->unlockColors(true); dst->setConfig(SkBitmap::kIndex8_Config, src.width(), src.height()); dst->allocPixels(ctable); ctable->unref(); SkAutoLockPixels alps(src); SkAutoLockPixels alpd(*dst); for (int y = 0; y < src.height(); y++) { const SkPMColor* srcP = src.getAddr32(0, y); uint8_t* dstP = dst->getAddr8(0, y); for (int x = src.width() - 1; x >= 0; --x) { *dstP++ = compute666Index(*srcP++); } } } class RepeatTileBench : public SkBenchmark { SkPaint fPaint; SkString fName; enum { N = SkBENCHLOOP(20) }; public: RepeatTileBench(void* param, SkBitmap::Config c, bool isOpaque = false) : INHERITED(param) { const int w = 50; const int h = 50; SkBitmap bm; if (SkBitmap::kIndex8_Config == c) { bm.setConfig(SkBitmap::kARGB_8888_Config, w, h); } else { bm.setConfig(c, w, h); } bm.allocPixels(); bm.eraseColor(isOpaque ? SK_ColorWHITE : 0); bm.setIsOpaque(isOpaque); drawIntoBitmap(bm); if (SkBitmap::kIndex8_Config == c) { SkBitmap tmp; convertToIndex666(bm, &tmp); bm = tmp; } SkShader* s = SkShader::CreateBitmapShader(bm, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); fPaint.setShader(s)->unref(); fName.printf("repeatTile_%s_%c", gConfigName[bm.config()], isOpaque ? 'X' : 'A'); } protected: virtual const char* onGetName() { return fName.c_str(); } virtual void onDraw(SkCanvas* canvas) { SkPaint paint(fPaint); this->setupPaint(&paint); for (int i = 0; i < N; i++) { canvas->drawPaint(paint); } } private: typedef SkBenchmark INHERITED; }; DEF_BENCH(return new RepeatTileBench(p, SkBitmap::kARGB_8888_Config, true)) DEF_BENCH(return new RepeatTileBench(p, SkBitmap::kARGB_8888_Config, false)) DEF_BENCH(return new RepeatTileBench(p, SkBitmap::kRGB_565_Config)) DEF_BENCH(return new RepeatTileBench(p, SkBitmap::kARGB_4444_Config)) DEF_BENCH(return new RepeatTileBench(p, SkBitmap::kIndex8_Config)) <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "executefilter.h" #include <coreplugin/icore.h> #include <coreplugin/messagemanager.h> #include <coreplugin/variablemanager.h> #include <QMessageBox> using namespace Core; using namespace Core; using namespace Core::Internal; ExecuteFilter::ExecuteFilter() { setId("Execute custom commands"); setDisplayName(tr("Execute Custom Commands")); setShortcutString(QString(QLatin1Char('!'))); setIncludedByDefault(false); m_process = new Utils::QtcProcess(this); m_process->setEnvironment(Utils::Environment::systemEnvironment()); connect(m_process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(finished(int,QProcess::ExitStatus))); connect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(readStandardOutput())); connect(m_process, SIGNAL(readyReadStandardError()), this, SLOT(readStandardError())); m_runTimer.setSingleShot(true); connect(&m_runTimer, SIGNAL(timeout()), this, SLOT(runHeadCommand())); } QList<LocatorFilterEntry> ExecuteFilter::matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &entry) { QList<LocatorFilterEntry> value; if (!entry.isEmpty()) // avoid empty entry value.append(LocatorFilterEntry(this, entry, QVariant())); QList<LocatorFilterEntry> others; const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(entry); foreach (const QString &i, m_commandHistory) { if (future.isCanceled()) break; if (i == entry) // avoid repeated entry continue; if (i.startsWith(entry, caseSensitivityForPrefix)) value.append(LocatorFilterEntry(this, i, QVariant())); else others.append(LocatorFilterEntry(this, i, QVariant())); } value.append(others); return value; } void ExecuteFilter::accept(LocatorFilterEntry selection) const { ExecuteFilter *p = const_cast<ExecuteFilter *>(this); const QString value = selection.displayName.trimmed(); const int index = m_commandHistory.indexOf(value); if (index != -1 && index != 0) p->m_commandHistory.removeAt(index); if (index != 0) p->m_commandHistory.prepend(value); bool found; QString workingDirectory = Core::VariableManager::value("CurrentDocument:Path", &found); if (!found || workingDirectory.isEmpty()) workingDirectory = Core::VariableManager::value("CurrentProject:Path", &found); ExecuteData d; d.workingDirectory = workingDirectory; const int pos = value.indexOf(QLatin1Char(' ')); if (pos == -1) { d.executable = value; } else { d.executable = value.left(pos); d.arguments = value.right(value.length() - pos - 1); } if (m_process->state() != QProcess::NotRunning) { const QString info(tr("Previous command is still running (\"%1\").\nDo you want to kill it?") .arg(p->headCommand())); int r = QMessageBox::question(ICore::dialogParent(), tr("Kill Previous Process?"), info, QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Yes); if (r == QMessageBox::Yes) m_process->kill(); if (r != QMessageBox::Cancel) p->m_taskQueue.enqueue(d); return; } p->m_taskQueue.enqueue(d); p->runHeadCommand(); } void ExecuteFilter::finished(int exitCode, QProcess::ExitStatus status) { const QString commandName = headCommand(); QString message; if (status == QProcess::NormalExit && exitCode == 0) message = tr("Command \"%1\" finished.").arg(commandName); else message = tr("Command \"%1\" failed.").arg(commandName); MessageManager::write(message); m_taskQueue.dequeue(); if (!m_taskQueue.isEmpty()) m_runTimer.start(500); } void ExecuteFilter::readStandardOutput() { QByteArray data = m_process->readAllStandardOutput(); MessageManager::write(QTextCodec::codecForLocale()->toUnicode(data.constData(), data.size(), &m_stdoutState)); } void ExecuteFilter::readStandardError() { static QTextCodec::ConverterState state; QByteArray data = m_process->readAllStandardError(); MessageManager::write(QTextCodec::codecForLocale()->toUnicode(data.constData(), data.size(), &m_stderrState)); } void ExecuteFilter::runHeadCommand() { if (!m_taskQueue.isEmpty()) { const ExecuteData &d = m_taskQueue.head(); const QString fullPath = Utils::Environment::systemEnvironment().searchInPath(d.executable); if (fullPath.isEmpty()) { MessageManager::write(tr("Could not find executable for \"%1\".").arg(d.executable)); m_taskQueue.dequeue(); runHeadCommand(); return; } MessageManager::write(tr("Starting command \"%1\".").arg(headCommand())); m_process->setWorkingDirectory(d.workingDirectory); m_process->setCommand(fullPath, d.arguments); m_process->start(); m_process->closeWriteChannel(); if (!m_process->waitForStarted(1000)) { MessageManager::write(tr("Could not start process: %1.").arg(m_process->errorString())); m_taskQueue.dequeue(); runHeadCommand(); } } } QString ExecuteFilter::headCommand() const { if (m_taskQueue.isEmpty()) return QString(); const ExecuteData &data = m_taskQueue.head(); if (data.arguments.isEmpty()) return data.executable; else return data.executable + QLatin1Char(' ') + data.arguments; } <commit_msg>Remove duplicate code<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "executefilter.h" #include <coreplugin/icore.h> #include <coreplugin/messagemanager.h> #include <coreplugin/variablemanager.h> #include <QMessageBox> using namespace Core; using namespace Core::Internal; ExecuteFilter::ExecuteFilter() { setId("Execute custom commands"); setDisplayName(tr("Execute Custom Commands")); setShortcutString(QString(QLatin1Char('!'))); setIncludedByDefault(false); m_process = new Utils::QtcProcess(this); m_process->setEnvironment(Utils::Environment::systemEnvironment()); connect(m_process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(finished(int,QProcess::ExitStatus))); connect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(readStandardOutput())); connect(m_process, SIGNAL(readyReadStandardError()), this, SLOT(readStandardError())); m_runTimer.setSingleShot(true); connect(&m_runTimer, SIGNAL(timeout()), this, SLOT(runHeadCommand())); } QList<LocatorFilterEntry> ExecuteFilter::matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &entry) { QList<LocatorFilterEntry> value; if (!entry.isEmpty()) // avoid empty entry value.append(LocatorFilterEntry(this, entry, QVariant())); QList<LocatorFilterEntry> others; const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(entry); foreach (const QString &i, m_commandHistory) { if (future.isCanceled()) break; if (i == entry) // avoid repeated entry continue; if (i.startsWith(entry, caseSensitivityForPrefix)) value.append(LocatorFilterEntry(this, i, QVariant())); else others.append(LocatorFilterEntry(this, i, QVariant())); } value.append(others); return value; } void ExecuteFilter::accept(LocatorFilterEntry selection) const { ExecuteFilter *p = const_cast<ExecuteFilter *>(this); const QString value = selection.displayName.trimmed(); const int index = m_commandHistory.indexOf(value); if (index != -1 && index != 0) p->m_commandHistory.removeAt(index); if (index != 0) p->m_commandHistory.prepend(value); bool found; QString workingDirectory = Core::VariableManager::value("CurrentDocument:Path", &found); if (!found || workingDirectory.isEmpty()) workingDirectory = Core::VariableManager::value("CurrentProject:Path", &found); ExecuteData d; d.workingDirectory = workingDirectory; const int pos = value.indexOf(QLatin1Char(' ')); if (pos == -1) { d.executable = value; } else { d.executable = value.left(pos); d.arguments = value.right(value.length() - pos - 1); } if (m_process->state() != QProcess::NotRunning) { const QString info(tr("Previous command is still running (\"%1\").\nDo you want to kill it?") .arg(p->headCommand())); int r = QMessageBox::question(ICore::dialogParent(), tr("Kill Previous Process?"), info, QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Yes); if (r == QMessageBox::Yes) m_process->kill(); if (r != QMessageBox::Cancel) p->m_taskQueue.enqueue(d); return; } p->m_taskQueue.enqueue(d); p->runHeadCommand(); } void ExecuteFilter::finished(int exitCode, QProcess::ExitStatus status) { const QString commandName = headCommand(); QString message; if (status == QProcess::NormalExit && exitCode == 0) message = tr("Command \"%1\" finished.").arg(commandName); else message = tr("Command \"%1\" failed.").arg(commandName); MessageManager::write(message); m_taskQueue.dequeue(); if (!m_taskQueue.isEmpty()) m_runTimer.start(500); } void ExecuteFilter::readStandardOutput() { QByteArray data = m_process->readAllStandardOutput(); MessageManager::write(QTextCodec::codecForLocale()->toUnicode(data.constData(), data.size(), &m_stdoutState)); } void ExecuteFilter::readStandardError() { static QTextCodec::ConverterState state; QByteArray data = m_process->readAllStandardError(); MessageManager::write(QTextCodec::codecForLocale()->toUnicode(data.constData(), data.size(), &m_stderrState)); } void ExecuteFilter::runHeadCommand() { if (!m_taskQueue.isEmpty()) { const ExecuteData &d = m_taskQueue.head(); const QString fullPath = Utils::Environment::systemEnvironment().searchInPath(d.executable); if (fullPath.isEmpty()) { MessageManager::write(tr("Could not find executable for \"%1\".").arg(d.executable)); m_taskQueue.dequeue(); runHeadCommand(); return; } MessageManager::write(tr("Starting command \"%1\".").arg(headCommand())); m_process->setWorkingDirectory(d.workingDirectory); m_process->setCommand(fullPath, d.arguments); m_process->start(); m_process->closeWriteChannel(); if (!m_process->waitForStarted(1000)) { MessageManager::write(tr("Could not start process: %1.").arg(m_process->errorString())); m_taskQueue.dequeue(); runHeadCommand(); } } } QString ExecuteFilter::headCommand() const { if (m_taskQueue.isEmpty()) return QString(); const ExecuteData &data = m_taskQueue.head(); if (data.arguments.isEmpty()) return data.executable; else return data.executable + QLatin1Char(' ') + data.arguments; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004-2019 musikcube team // // 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 other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include "OpenMptDecoder.h" #include "OpenMptDataStream.h" #include <core/sdk/IDebug.h> #include <cassert> using namespace musik::core::sdk; extern IDebug* debug; static const int kSampleRate = 48000; static const int kSamplesPerChannel = 2048; static const int kChannels = 2; static size_t readCallback(void *user, void *dst, size_t bytes) { return (size_t) static_cast<IDataStream*>(user)->Read(dst, (PositionType) bytes); } static int seekCallback(void *user, int64_t offset, int whence) { IDataStream* stream = static_cast<IDataStream*>(user); switch (whence) { case OPENMPT_STREAM_SEEK_SET: return stream->SetPosition((PositionType) offset) ? 0 : -1; case OPENMPT_STREAM_SEEK_CUR: return stream->SetPosition((PositionType) offset + stream->Position()) ? 0 : -1; case OPENMPT_STREAM_SEEK_END: return stream->SetPosition(stream->Length() - 1 - (PositionType)offset) ? 0 : -1; } return -1; } static int64_t tellCallback(void *user) { return (int64_t) static_cast<IDataStream*>(user)->Position(); } static void logCallback(const char *message, void *userdata) { if (debug) { debug->Info("OpenMtpDecoder", message); } } OpenMptDecoder::OpenMptDecoder() { this->module = nullptr; } OpenMptDecoder::~OpenMptDecoder() { if (this->module) { openmpt_module_destroy(this->module); this->module = nullptr; } } bool OpenMptDecoder::Open(musik::core::sdk::IDataStream *stream) { openmpt_stream_callbacks callbacks = { 0 }; callbacks.read = readCallback; callbacks.seek = seekCallback; callbacks.tell = tellCallback; this->module = openmpt_module_create2( callbacks, stream, logCallback, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); if (this->module) { int track = static_cast<OpenMptDataStream*>(stream)->GetTrackNumber(); if (track >= 0 && track < openmpt_module_get_num_subsongs(module)) { openmpt_module_select_subsong(this->module, track); } return true; } return false; } void OpenMptDecoder::Release() { delete this; } double OpenMptDecoder::SetPosition(double seconds) { if (this->module) { return openmpt_module_set_position_seconds(this->module, seconds); } return 0.0; } double OpenMptDecoder::GetDuration() { if (this->module) { return openmpt_module_get_duration_seconds(this->module); } return 0.0; } bool OpenMptDecoder::GetBuffer(IBuffer *target) { if (this->module) { target->SetSampleRate(kSampleRate); target->SetSamples(kSamplesPerChannel * kChannels); int samplesWritten = openmpt_module_read_interleaved_float_stereo( this->module, kSampleRate, kSamplesPerChannel, target->BufferPointer()); if (samplesWritten > 0) { target->SetSamples(samplesWritten * kChannels); return true; } } return false; } bool OpenMptDecoder::Exhausted() { return false; } <commit_msg>Fixed OpenMtpDecoder::Exhausted() and cleaned up a couple compile warnings.<commit_after>////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004-2019 musikcube team // // 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 other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include "OpenMptDecoder.h" #include "OpenMptDataStream.h" #include <core/sdk/IDebug.h> #include <cassert> using namespace musik::core::sdk; extern IDebug* debug; static const int kSampleRate = 48000; static const int kSamplesPerChannel = 2048; static const int kChannels = 2; static size_t readCallback(void *user, void *dst, size_t bytes) { return (size_t) static_cast<IDataStream*>(user)->Read(dst, (PositionType) bytes); } static int seekCallback(void *user, int64_t offset, int whence) { IDataStream* stream = static_cast<IDataStream*>(user); switch (whence) { case OPENMPT_STREAM_SEEK_SET: return stream->SetPosition((PositionType) offset) ? 0 : -1; case OPENMPT_STREAM_SEEK_CUR: return stream->SetPosition((PositionType) offset + stream->Position()) ? 0 : -1; case OPENMPT_STREAM_SEEK_END: return stream->SetPosition(stream->Length() - 1 - (PositionType)offset) ? 0 : -1; } return -1; } static int64_t tellCallback(void *user) { return (int64_t) static_cast<IDataStream*>(user)->Position(); } static void logCallback(const char *message, void *userdata) { if (debug) { debug->Info("OpenMtpDecoder", message); } } OpenMptDecoder::OpenMptDecoder() { this->module = nullptr; } OpenMptDecoder::~OpenMptDecoder() { if (this->module) { openmpt_module_destroy(this->module); this->module = nullptr; } } bool OpenMptDecoder::Open(musik::core::sdk::IDataStream *stream) { openmpt_stream_callbacks callbacks = { 0 }; callbacks.read = readCallback; callbacks.seek = seekCallback; callbacks.tell = tellCallback; this->module = openmpt_module_create2( callbacks, stream, logCallback, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); if (this->module) { int track = static_cast<OpenMptDataStream*>(stream)->GetTrackNumber(); if (track >= 0 && track < openmpt_module_get_num_subsongs(module)) { openmpt_module_select_subsong(this->module, track); } return true; } return false; } void OpenMptDecoder::Release() { delete this; } double OpenMptDecoder::SetPosition(double seconds) { if (this->module) { return openmpt_module_set_position_seconds(this->module, seconds); } return 0.0; } double OpenMptDecoder::GetDuration() { if (this->module) { return openmpt_module_get_duration_seconds(this->module); } return 0.0; } bool OpenMptDecoder::GetBuffer(IBuffer *target) { if (this->module) { target->SetSampleRate(kSampleRate); target->SetSamples(kSamplesPerChannel * kChannels); int samplesWritten = (int) openmpt_module_read_interleaved_float_stereo( this->module, (int32_t) kSampleRate, (size_t) kSamplesPerChannel, target->BufferPointer()); if (samplesWritten > 0) { target->SetSamples(samplesWritten * kChannels); return true; } } return false; } bool OpenMptDecoder::Exhausted() { if (this->module) { return openmpt_module_get_position_seconds(this->module) >= this->GetDuration(); } return true; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the config.tests of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwaylandwindow.h" #include "qwaylandbuffer.h" #include "qwaylanddisplay.h" #include "qwaylandinputdevice.h" #include "qwaylandscreen.h" #ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT #include "windowmanager_integration/qwaylandwindowmanagerintegration.h" #endif #include <QCoreApplication> #include <QtGui/QWidget> #include <QtGui/QWindowSystemInterface> #include <QDebug> QWaylandWindow::QWaylandWindow(QWidget *window) : QPlatformWindow(window) , mSurface(0) , mDisplay(QWaylandScreen::waylandScreenFromWidget(window)->display()) , mBuffer(0) , mWaitingForFrameSync(false) { static WId id = 1; mWindowId = id++; #ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT mDisplay->windowManagerIntegration()->mapClientToProcess(qApp->applicationPid()); mDisplay->windowManagerIntegration()->authenticateWithToken(); #endif } QWaylandWindow::~QWaylandWindow() { if (mSurface) wl_surface_destroy(mSurface); QList<QWaylandInputDevice *> inputDevices = mDisplay->inputDevices(); for (int i = 0; i < inputDevices.size(); ++i) inputDevices.at(i)->handleWindowDestroyed(this); } WId QWaylandWindow::winId() const { return mWindowId; } void QWaylandWindow::setParent(const QPlatformWindow *parent) { Q_UNUSED(parent); qWarning("Sub window is not supported"); } void QWaylandWindow::setVisible(bool visible) { if (!mSurface && visible) { mSurface = mDisplay->createSurface(this); newSurfaceCreated(); } if (!visible) { wl_surface_destroy(mSurface); mSurface = NULL; } } void QWaylandWindow::configure(uint32_t time, uint32_t edges, int32_t x, int32_t y, int32_t width, int32_t height) { Q_UNUSED(time); Q_UNUSED(edges); QRect geometry = QRect(x, y, width, height); setGeometry(geometry); QWindowSystemInterface::handleGeometryChange(widget(), geometry); } void QWaylandWindow::attach(QWaylandBuffer *buffer) { mBuffer = buffer; if (mSurface) { wl_surface_attach(mSurface, buffer->buffer(),0,0); } } void QWaylandWindow::damage(const QRect &rect) { //We have to do sync stuff before calling damage, or we might //get a frame callback before we get the timestamp if (!mWaitingForFrameSync) { mDisplay->frameCallback(QWaylandWindow::frameCallback, mSurface, this); mWaitingForFrameSync = true; } wl_surface_damage(mSurface, rect.x(), rect.y(), rect.width(), rect.height()); } void QWaylandWindow::newSurfaceCreated() { if (mBuffer) { wl_surface_attach(mSurface,mBuffer->buffer(),0,0); wl_surface_damage(mSurface, 0,0,mBuffer->size().width(),mBuffer->size().height()); } } void QWaylandWindow::frameCallback(struct wl_surface *surface, void *data, uint32_t time) { Q_UNUSED(time); Q_UNUSED(surface); QWaylandWindow *self = static_cast<QWaylandWindow*>(data); self->mWaitingForFrameSync = false; } void QWaylandWindow::waitForFrameSync() { mDisplay->flushRequests(); while (mWaitingForFrameSync) mDisplay->blockingReadEvents(); } <commit_msg>Removed damaging of waylandsurface after creation<commit_after>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the config.tests of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwaylandwindow.h" #include "qwaylandbuffer.h" #include "qwaylanddisplay.h" #include "qwaylandinputdevice.h" #include "qwaylandscreen.h" #ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT #include "windowmanager_integration/qwaylandwindowmanagerintegration.h" #endif #include <QCoreApplication> #include <QtGui/QWidget> #include <QtGui/QWindowSystemInterface> #include <QDebug> QWaylandWindow::QWaylandWindow(QWidget *window) : QPlatformWindow(window) , mSurface(0) , mDisplay(QWaylandScreen::waylandScreenFromWidget(window)->display()) , mBuffer(0) , mWaitingForFrameSync(false) { static WId id = 1; mWindowId = id++; #ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT mDisplay->windowManagerIntegration()->mapClientToProcess(qApp->applicationPid()); mDisplay->windowManagerIntegration()->authenticateWithToken(); #endif } QWaylandWindow::~QWaylandWindow() { if (mSurface) wl_surface_destroy(mSurface); QList<QWaylandInputDevice *> inputDevices = mDisplay->inputDevices(); for (int i = 0; i < inputDevices.size(); ++i) inputDevices.at(i)->handleWindowDestroyed(this); } WId QWaylandWindow::winId() const { return mWindowId; } void QWaylandWindow::setParent(const QPlatformWindow *parent) { Q_UNUSED(parent); qWarning("Sub window is not supported"); } void QWaylandWindow::setVisible(bool visible) { if (!mSurface && visible) { mSurface = mDisplay->createSurface(this); newSurfaceCreated(); } if (!visible) { wl_surface_destroy(mSurface); mSurface = NULL; } } void QWaylandWindow::configure(uint32_t time, uint32_t edges, int32_t x, int32_t y, int32_t width, int32_t height) { Q_UNUSED(time); Q_UNUSED(edges); QRect geometry = QRect(x, y, width, height); setGeometry(geometry); QWindowSystemInterface::handleGeometryChange(widget(), geometry); } void QWaylandWindow::attach(QWaylandBuffer *buffer) { mBuffer = buffer; if (mSurface) { wl_surface_attach(mSurface, buffer->buffer(),0,0); } } void QWaylandWindow::damage(const QRect &rect) { //We have to do sync stuff before calling damage, or we might //get a frame callback before we get the timestamp if (!mWaitingForFrameSync) { mDisplay->frameCallback(QWaylandWindow::frameCallback, mSurface, this); mWaitingForFrameSync = true; } wl_surface_damage(mSurface, rect.x(), rect.y(), rect.width(), rect.height()); } void QWaylandWindow::newSurfaceCreated() { if (mBuffer) { wl_surface_attach(mSurface,mBuffer->buffer(),0,0); // do not damage the surface here, as this leads to graphical corruptions in the compositor until // the first frame has been rendered } } void QWaylandWindow::frameCallback(struct wl_surface *surface, void *data, uint32_t time) { Q_UNUSED(time); Q_UNUSED(surface); QWaylandWindow *self = static_cast<QWaylandWindow*>(data); self->mWaitingForFrameSync = false; } void QWaylandWindow::waitForFrameSync() { mDisplay->flushRequests(); while (mWaitingForFrameSync) mDisplay->blockingReadEvents(); } <|endoftext|>
<commit_before>#include "Console.h" #include <cstdio> #ifdef __linux__ #include <termios.h> #include <unistd.h> #include <fcntl.h> #elif _WIN32 #include <conio.h> #endif ConsoleColor::ConsoleColor(const ConsoleColorType foreColor_, const ConsoleColorType backColor_, const bool &foreIntensified_, const bool &backIntensified_) : foreColor(foreColor_), backColor(backColor_), foreIntensified(foreIntensified_), backIntensified(backIntensified_) { } #ifdef WIN32 WORD Console::setColor(const ConsoleColor &consoleColor) { WORD color = 0; switch (consoleColor.foreColor) { case WHITE: color |= FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE; break; case RED: color |= FOREGROUND_RED; break; case GREEN: color |= FOREGROUND_GREEN; break; case BLUE: color |= FOREGROUND_BLUE; break; case YELLOW: color |= FOREGROUND_RED | FOREGROUND_GREEN; break; case MAGENTA: color |= FOREGROUND_BLUE | FOREGROUND_RED; break; case CYAN: color |= FOREGROUND_BLUE | FOREGROUND_GREEN; break; case BLACK: default: break; } if (consoleColor.foreIntensified) { color |= FOREGROUND_INTENSITY; } switch (consoleColor.backColor) { case WHITE: color |= BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE; break; case RED: color |= BACKGROUND_RED; break; case GREEN: color |= BACKGROUND_GREEN; break; case BLUE: color |= BACKGROUND_BLUE; break; case YELLOW: color |= BACKGROUND_RED | BACKGROUND_GREEN; break; case MAGENTA: color |= BACKGROUND_BLUE | BACKGROUND_RED; break; case CYAN: color |= BACKGROUND_BLUE | BACKGROUND_GREEN; break; case BLACK: default: break; } if (consoleColor.backIntensified) { color |= BACKGROUND_INTENSITY; } // Get origin attribute CONSOLE_SCREEN_BUFFER_INFO info; HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(hStdout, &info); WORD originAttr = info.wAttributes; // Set new attribute HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hout, color); // Return the origin attribute return originAttr; } void Console::resetColor(const WORD &attr) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), attr); } #endif void Console::setCursor(const int &x, const int &y) { #ifdef __linux__ printf("\033[%d;%dH", y + 1, x); // Param: row and col #elif _WIN32 HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE); COORD coord; coord.X = x; coord.Y = y; SetConsoleCursorPosition(hout, coord); #else // Other platforms #endif } void Console::clear() { #ifdef __linux__ system("clear"); #elif _WIN32 system("cls"); #else // Other platforms #endif } void Console::write(const std::string &str) { printf("%s", str.c_str()); } void Console::writeWithColor(const std::string &str, const ConsoleColor &consoleColor) { #ifdef __linux__ int fore = -1, back = -1; switch (consoleColor.backColor) { case WHITE: back = 47; break; case RED: back = 41; break; case GREEN: back = 42; break; case BLUE: back = 44; break; case YELLOW: back = 43; break; case MAGENTA: back = 45; break; case CYAN: back = 46; break; case BLACK: back = 40; break; default: break; } switch (consoleColor.foreColor) { case WHITE: fore = 37; break; case RED: fore = 31; break; case GREEN: fore = 32; break; case BLUE: fore = 34; break; case YELLOW: fore = 33; break; case MAGENTA: fore = 35; break; case CYAN: fore = 36; break; case BLACK: fore = 30; break; default: break; } if (fore != -1 && back != -1) { printf("\033[%d;%dm%s\033[0m", fore, back, str.c_str()); } #elif _WIN32 WORD originAttr = setColor(consoleColor); printf("%s", str.c_str()); resetColor(originAttr); // Reset to origin output color #else // Other platforms #endif } char Console::getch() { #ifdef __linux__ struct termios oldattr, newattr; int ch; tcgetattr(STDIN_FILENO, &oldattr); newattr = oldattr; newattr.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newattr); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldattr); return ch; #elif _WIN32 return _getch(); #else // Other platforms #endif } int Console::kbhit() { #ifdef __linux__ struct termios oldt, newt; int ch; int oldf; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); oldf = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); fcntl(STDIN_FILENO, F_SETFL, oldf); if (ch != EOF) { ungetc(ch, stdin); return 1; } return 0; #elif _WIN32 return _kbhit(); #else // Other platforms #endif }<commit_msg>Sub linux conditions to linux or apple<commit_after>#include "Console.h" #include <cstdio> #include <cstdlib> #ifdef LINUX_OR_APPLE #include <termios.h> #include <unistd.h> #include <fcntl.h> #elif _WIN32 #include <conio.h> #endif ConsoleColor::ConsoleColor(const ConsoleColorType foreColor_, const ConsoleColorType backColor_, const bool &foreIntensified_, const bool &backIntensified_) : foreColor(foreColor_), backColor(backColor_), foreIntensified(foreIntensified_), backIntensified(backIntensified_) { } #ifdef WIN32 WORD Console::setColor(const ConsoleColor &consoleColor) { WORD color = 0; switch (consoleColor.foreColor) { case WHITE: color |= FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE; break; case RED: color |= FOREGROUND_RED; break; case GREEN: color |= FOREGROUND_GREEN; break; case BLUE: color |= FOREGROUND_BLUE; break; case YELLOW: color |= FOREGROUND_RED | FOREGROUND_GREEN; break; case MAGENTA: color |= FOREGROUND_BLUE | FOREGROUND_RED; break; case CYAN: color |= FOREGROUND_BLUE | FOREGROUND_GREEN; break; case BLACK: default: break; } if (consoleColor.foreIntensified) { color |= FOREGROUND_INTENSITY; } switch (consoleColor.backColor) { case WHITE: color |= BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE; break; case RED: color |= BACKGROUND_RED; break; case GREEN: color |= BACKGROUND_GREEN; break; case BLUE: color |= BACKGROUND_BLUE; break; case YELLOW: color |= BACKGROUND_RED | BACKGROUND_GREEN; break; case MAGENTA: color |= BACKGROUND_BLUE | BACKGROUND_RED; break; case CYAN: color |= BACKGROUND_BLUE | BACKGROUND_GREEN; break; case BLACK: default: break; } if (consoleColor.backIntensified) { color |= BACKGROUND_INTENSITY; } // Get origin attribute CONSOLE_SCREEN_BUFFER_INFO info; HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(hStdout, &info); WORD originAttr = info.wAttributes; // Set new attribute HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hout, color); // Return the origin attribute return originAttr; } void Console::resetColor(const WORD &attr) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), attr); } #endif void Console::setCursor(const int &x, const int &y) { #ifdef LINUX_OR_APPLE printf("\033[%d;%dH", y + 1, x); // Param: row and col #elif _WIN32 HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE); COORD coord; coord.X = x; coord.Y = y; SetConsoleCursorPosition(hout, coord); #else // Other platforms #endif } void Console::clear() { #ifdef LINUX_OR_APPLE system("clear"); #elif _WIN32 system("cls"); #else // Other platforms #endif } void Console::write(const std::string &str) { printf("%s", str.c_str()); } void Console::writeWithColor(const std::string &str, const ConsoleColor &consoleColor) { #ifdef LINUX_OR_APPLE int fore = -1, back = -1; switch (consoleColor.backColor) { case WHITE: back = 47; break; case RED: back = 41; break; case GREEN: back = 42; break; case BLUE: back = 44; break; case YELLOW: back = 43; break; case MAGENTA: back = 45; break; case CYAN: back = 46; break; case BLACK: back = 40; break; default: break; } switch (consoleColor.foreColor) { case WHITE: fore = 37; break; case RED: fore = 31; break; case GREEN: fore = 32; break; case BLUE: fore = 34; break; case YELLOW: fore = 33; break; case MAGENTA: fore = 35; break; case CYAN: fore = 36; break; case BLACK: fore = 30; break; default: break; } if (fore != -1 && back != -1) { printf("\033[%d;%dm%s\033[0m", fore, back, str.c_str()); } #elif _WIN32 WORD originAttr = setColor(consoleColor); printf("%s", str.c_str()); resetColor(originAttr); // Reset to origin output color #else // Other platforms #endif } char Console::getch() { #ifdef LINUX_OR_APPLE struct termios oldattr, newattr; int ch; tcgetattr(STDIN_FILENO, &oldattr); newattr = oldattr; newattr.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newattr); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldattr); return ch; #elif _WIN32 return _getch(); #else // Other platforms #endif } int Console::kbhit() { #ifdef LINUX_OR_APPLE struct termios oldt, newt; int ch; int oldf; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); oldf = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); fcntl(STDIN_FILENO, F_SETFL, oldf); if (ch != EOF) { ungetc(ch, stdin); return 1; } return 0; #elif _WIN32 return _kbhit(); #else // Other platforms #endif } <|endoftext|>
<commit_before>/** * @file Context.hpp * @brief The Context manage all ZeroMQ sockets of an application. * * Copyright (c) 2013 Sebastien Rombauts (sebastien.rombauts@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #pragma once #include "zmq.h" // Compatibility defines // TODO : move those defines in a central ZMQCpp.hpp include file #ifndef ZMQ_DONTWAIT # define ZMQ_DONTWAIT ZMQ_NOBLOCK #endif #ifndef ZMQ_RCVHWM # define ZMQ_RCVHWM ZMQ_HWM #endif #ifndef ZMQ_SNDHWM # define ZMQ_SNDHWM ZMQ_HWM #endif #if ZMQ_VERSION_MAJOR == 2 # define more_t int64_t # define zmq_ctx_destroy(context) zmq_term(context) # define zmq_msg_send(msg,sock,opt) zmq_send (sock, msg, opt) # define zmq_msg_recv(msg,sock,opt) zmq_recv (sock, msg, opt) # define ZMQ_POLL_MSEC 1000 // zmq_poll is usec #elif ZMQ_VERSION_MAJOR == 3 # define more_t int # define ZMQ_POLL_MSEC 1 // zmq_poll is msec #endif #ifndef ZMQ_IO_THREADS_DFLT # define ZMQ_IO_THREADS_DFLT 1 #endif /** * @brief The Context manage all ZeroMQ sockets of an application. * * TODO A ØMQ context is thread safe and may be shared among as many application threads as necessary, * without any additional locking required on the part of the caller. */ class Context { public: /// @brief Default constructor Context(void) : mpContext(NULL) { #if (ZMQ_VERSION_MAJOR < 3) mpContext = zmq_init(ZMQ_IO_THREADS_DFLT); #else mpContext = zmq_new(); #endif if (mpContext == NULL) { throw std::runtime_error(zmq_strerror(zmq_errno())); } } /// @brief Destructor ~Context(void) { int ret = zmq_ctx_destroy(mpContext); check(ret); } private: void check(int aRet) { if (aRet < 0) { throw std::runtime_error(zmq_strerror(zmq_errno())); } } void* mpContext; }; <commit_msg>Some comments and @todo<commit_after>/** * @file Context.hpp * @brief The Context manage all ZeroMQ sockets of an application. * * Copyright (c) 2013 Sebastien Rombauts (sebastien.rombauts@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #pragma once #include <zmq.h> // Compatibility defines // TODO : move those defines in a central ZMQCpp.hpp include file #ifndef ZMQ_DONTWAIT # define ZMQ_DONTWAIT ZMQ_NOBLOCK #endif #ifndef ZMQ_RCVHWM # define ZMQ_RCVHWM ZMQ_HWM #endif #ifndef ZMQ_SNDHWM # define ZMQ_SNDHWM ZMQ_HWM #endif #if ZMQ_VERSION_MAJOR == 2 # define more_t int64_t # define zmq_ctx_destroy(context) zmq_term(context) # define zmq_msg_send(msg,sock,opt) zmq_send (sock, msg, opt) # define zmq_msg_recv(msg,sock,opt) zmq_recv (sock, msg, opt) # define ZMQ_POLL_MSEC 1000 // zmq_poll is usec #elif ZMQ_VERSION_MAJOR == 3 # define more_t int # define ZMQ_POLL_MSEC 1 // zmq_poll is msec #endif #ifndef ZMQ_IO_THREADS_DFLT # define ZMQ_IO_THREADS_DFLT 1 #endif /** * @brief The Context manage ZeroMQ sockets of an application. * * @todo This Context maintain a list of all open socket. * Upon its destruction, it shall close them, in a non blocking fashion. * * @todo The underliying ØMQ context is thread safe and may be shared among as many application threads as necessary, * without any additional locking required on the part of the caller, * but this Context is NOT thread-safe ! */ class Context { friend class Socket; public: /** * @brief Constructor of a new ØMQ context with zmq_new(). */ Context(void) : mpContext(NULL) { #if (ZMQ_VERSION_MAJOR < 3) mpContext = zmq_init(ZMQ_IO_THREADS_DFLT); #else mpContext = zmq_new(); #endif if (mpContext == NULL) { throw std::runtime_error(zmq_strerror(zmq_errno())); } } /** * @brief Destructor shall destroy the ØMQ context context. * * @todo will close any * * @see http://api.zeromq.org/3-2:zmq-ctx-destroy */ ~Context(void) { int ret = zmq_ctx_destroy(mpContext); check(ret); } private: void check(int aRet) { if (aRet < 0) { throw std::runtime_error(zmq_strerror(zmq_errno())); } } void* mpContext; }; <|endoftext|>
<commit_before>#include <Element.h> #include <FWPlatform.h> #include <TextLabel.h> #include <LinearLayout.h> #include <Command.h> #include <FWApplication.h> #include <SysEvent.h> #include <OpenGLInitEvent.h> #include <cassert> using namespace std; void Element::initialize(FWPlatform * _platform) { assert(_platform); if (_platform) { platform = _platform; internal_id = platform->getNextInternalId(); } } void Element::initializeChildren() { if (isInitialized()) { for (auto & c : getChildren()){ c->initialize(platform); } } } void Element::sendCommand(const Command & command){ assert(this != platform); assert(platform); platform->sendCommand2(command); } Element & Element::addChild(const std::string & text) { return addChild(make_shared<TextLabel>(text)); } LinearLayout & Element::addHorizontalLayout() { auto l = make_shared<LinearLayout>(FW_HORIZONTAL); addChild(l); return *l; } LinearLayout & Element::addVerticalLayout() { auto l = make_shared<LinearLayout>(FW_VERTICAL); addChild(l); return *l; } void Element::onEvent(Event & ev) { if (!ev.isHandled()) { if (ev.isBroadcast()) { for (auto & c : getChildren()){ ev.dispatch(*c); } } else if (parent) { ev.dispatch(*parent); } } } void Element::showMessageDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_MESSAGE_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); } std::string Element::showInputDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_INPUT_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); return platform->getModalResultText(); } FWApplication & Element::getApplication() { auto p = getPlatform().getFirstChild(); return dynamic_cast<FWApplication&>(*p); } const FWApplication & Element::getApplication() const { auto p = getPlatform().getFirstChild(); return dynamic_cast<const FWApplication&>(*p); } <commit_msg>initialize children<commit_after>#include <Element.h> #include <FWPlatform.h> #include <TextLabel.h> #include <LinearLayout.h> #include <Command.h> #include <FWApplication.h> #include <SysEvent.h> #include <OpenGLInitEvent.h> #include <cassert> using namespace std; void Element::initialize(FWPlatform * _platform) { assert(_platform); if (_platform) { platform = _platform; internal_id = platform->getNextInternalId(); } } void Element::initializeChildren() { if (isInitialized()) { for (auto & c : getChildren()){ c->initialize(platform); c->initializeChildren(); } } } void Element::sendCommand(const Command & command){ assert(this != platform); assert(platform); platform->sendCommand2(command); } Element & Element::addChild(const std::string & text) { return addChild(make_shared<TextLabel>(text)); } LinearLayout & Element::addHorizontalLayout() { auto l = make_shared<LinearLayout>(FW_HORIZONTAL); addChild(l); return *l; } LinearLayout & Element::addVerticalLayout() { auto l = make_shared<LinearLayout>(FW_VERTICAL); addChild(l); return *l; } void Element::onEvent(Event & ev) { if (!ev.isHandled()) { if (ev.isBroadcast()) { for (auto & c : getChildren()){ ev.dispatch(*c); } } else if (parent) { ev.dispatch(*parent); } } } void Element::showMessageDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_MESSAGE_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); } std::string Element::showInputDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_INPUT_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); return platform->getModalResultText(); } FWApplication & Element::getApplication() { auto p = getPlatform().getFirstChild(); return dynamic_cast<FWApplication&>(*p); } const FWApplication & Element::getApplication() const { auto p = getPlatform().getFirstChild(); return dynamic_cast<const FWApplication&>(*p); } <|endoftext|>
<commit_before>#include <Element.h> #include <FWPlatform.h> #include <HeadingText.h> #include <TextLabel.h> #include <LinearLayout.h> #include <FWApplication.h> #include <cassert> using namespace std; int Element::nextInternalId = 1; void Element::initialize(FWPlatform * _platform) { assert(_platform); if (_platform) { platform = _platform; create(); for (auto & c : pendingCommands){ sendCommand(c); } pendingCommands.clear(); } assert(isInitialized()); } void Element::initializeChildren() { assert(isInitialized()); if (isInitialized()) { for (auto & c : getChildren()) { c->initialize(platform); c->initializeChildren(); } } } void Element::setError(bool t) { if ((t && !has_error) || (!t && has_error)) { has_error = t; cerr << "setting error to " << has_error << endl; Command c(Command::SET_ERROR, getInternalId()); c.setValue(t ? 1 : 0); if (t) c.setTextValue("Arvo ei kelpaa!"); sendCommand(c); } } void Element::style(const std::string & key, const std::string & value) { Command c(Command::SET_STYLE, getInternalId()); c.setTextValue(key); c.setTextValue2(value); sendCommand(c); } void Element::sendCommand(const Command & command) { if (platform){ platform->sendCommand2(command); } else { pendingCommands.push_back(command); } } Element & Element::addHeading(const std::string & text) { return addChild(make_shared<HeadingText>(text)); } Element & Element::addText(const std::string & text) { return addChild(make_shared<TextLabel>(text)); } Element & Element::addHorizontalLayout(int _id) { return addChild(make_shared<LinearLayout>(FW_HORIZONTAL, _id)); } Element & Element::addVerticalLayout(int _id) { return addChild(make_shared<LinearLayout>(FW_VERTICAL, _id)); } void Element::onEvent(Event & ev) { if (!ev.isHandled()) { if (ev.isBroadcast()) { for (auto & c : getChildren()){ ev.dispatch(*c); } } else if (parent) { ev.dispatch(*parent); } } } void Element::showMessageDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_MESSAGE_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); } std::string Element::showInputDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_INPUT_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); return platform->getModalResultText(); } FWApplication & Element::getApplication() { auto p = getPlatform().getFirstChild(); return dynamic_cast<FWApplication&>(*p); } const FWApplication & Element::getApplication() const { auto p = getPlatform().getFirstChild(); return dynamic_cast<const FWApplication&>(*p); } void Element::removeChild(Element * child) { for (auto it = children.begin(); it != children.end(); it++) { if (it->get() == child) { sendCommand(Command(Command::DELETE_ELEMENT, getInternalId(), child->getInternalId())); children.erase(it); return; } } } <commit_msg>refactor<commit_after>#include <Element.h> #include <FWPlatform.h> #include <HeadingText.h> #include <TextLabel.h> #include <LinearLayout.h> #include <FWApplication.h> #include <cassert> using namespace std; int Element::nextInternalId = 1; void Element::initialize(FWPlatform * _platform) { assert(_platform); if (_platform) { platform = _platform; create(); for (auto & c : pendingCommands) { sendCommand(c); } pendingCommands.clear(); } assert(isInitialized()); } void Element::initializeChildren() { assert(isInitialized()); if (isInitialized()) { for (auto & c : getChildren()) { c->initialize(platform); c->initializeChildren(); } } } void Element::setError(bool t) { if ((t && !has_error) || (!t && has_error)) { has_error = t; cerr << "setting error to " << has_error << endl; Command c(Command::SET_ERROR, getInternalId()); c.setValue(t ? 1 : 0); if (t) c.setTextValue("Arvo ei kelpaa!"); sendCommand(c); } } void Element::style(const std::string & key, const std::string & value) { Command c(Command::SET_STYLE, getInternalId()); c.setTextValue(key); c.setTextValue2(value); sendCommand(c); } void Element::sendCommand(const Command & command) { if (platform) { platform->sendCommand2(command); } else { pendingCommands.push_back(command); } } Element & Element::addHeading(const std::string & text) { return addChild(make_shared<HeadingText>(text)); } Element & Element::addText(const std::string & text) { return addChild(make_shared<TextLabel>(text)); } Element & Element::addHorizontalLayout(int _id) { return addChild(make_shared<LinearLayout>(FW_HORIZONTAL, _id)); } Element & Element::addVerticalLayout(int _id) { return addChild(make_shared<LinearLayout>(FW_VERTICAL, _id)); } void Element::onEvent(Event & ev) { if (!ev.isHandled()) { if (ev.isBroadcast()) { for (auto & c : getChildren()){ ev.dispatch(*c); } } else if (parent) { ev.dispatch(*parent); } } } void Element::showMessageDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_MESSAGE_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); } std::string Element::showInputDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_INPUT_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); return platform->getModalResultText(); } FWApplication & Element::getApplication() { auto p = getPlatform().getFirstChild(); return dynamic_cast<FWApplication&>(*p); } const FWApplication & Element::getApplication() const { auto p = getPlatform().getFirstChild(); return dynamic_cast<const FWApplication&>(*p); } void Element::removeChild(Element * child) { for (auto it = children.begin(); it != children.end(); it++) { if (it->get() == child) { sendCommand(Command(Command::DELETE_ELEMENT, getInternalId(), child->getInternalId())); children.erase(it); return; } } } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <vector> #include <string> #include <sstream> #include <iomanip> //#include "orc_proto.pb.h" #include "wrap/orc-proto-wrapper.hh" using namespace orc::proto; long getTotalPaddingSize(Footer footer); StripeFooter readStripeFooter(StripeInformation stripe); std::ifstream input; int main(int argc, char* argv[]) { GOOGLE_PROTOBUF_VERIFY_VERSION; if (argc < 2) { std::cout << "Usage: file-metadata <filename>\n"; } std::cout << "Structure for " << argv[1] << std::endl; input.open(argv[1], std::ios::in | std::ios::binary); input.seekg(0,input.end); unsigned int fileSize = input.tellg(); // Read the postscript size input.seekg(fileSize-1); unsigned int postscriptSize = (int)input.get() ; // Read the postscript input.seekg(fileSize - postscriptSize-1); std::vector<char> buffer(postscriptSize) ; input.read(buffer.data(), postscriptSize); PostScript postscript ; postscript.ParseFromArray(buffer.data(), postscriptSize); std::cout << std::endl << "Postscript: " << std::endl ; postscript.PrintDebugString(); // Everything but the postscript is compressed switch (static_cast<int>(postscript.compression())) { case NONE: break; case ZLIB: case SNAPPY: case LZO: default: std::cout << "ORC files with compression are not supported" << std::endl ; input.close(); return -1; }; int footerSize = postscript.footerlength(); int metadataSize = postscript.metadatalength(); // Read the metadata input.seekg(fileSize - 1 - postscriptSize - footerSize - metadataSize); buffer.resize(metadataSize); input.read(buffer.data(), metadataSize); Metadata metadata ; metadata.ParseFromArray(buffer.data(), metadataSize); std::cout << std::endl << "Metadata: " << std::endl ; // get stripe statistics from metadata std::cout << "Has " << metadata.stripestats_size() << " stripes in this file\n"; postscript.PrintDebugString(); // Read the footer //input.seekg(fileSize -1 - postscriptSize-footerSize); buffer.resize(footerSize); input.read(buffer.data(), footerSize); Footer footer ; footer.ParseFromArray(buffer.data(), footerSize); std::cout << std::endl << "Footer: " << std::endl ; postscript.PrintDebugString(); std::cout << std::endl << "Rows: " << footer.numberofrows() << std::endl; std::cout << "Compression: " << postscript.compression() << std::endl; if (postscript.compression() != NONE) std::cout << "Compression size: " << postscript.compressionblocksize() << std::endl; std::cout << "Type: " ; for (int typeIx=0; typeIx < footer.types_size(); typeIx++) { Type type = footer.types(typeIx); type.PrintDebugString(); }; std::cout << "\nStripe Information:" << std::endl; StripeInformation stripe ; Stream section; ColumnEncoding encoding; for (int stripeIx=0; stripeIx<footer.stripes_size(); stripeIx++) { std::cout << " Stripe " << stripeIx+1 <<": " << std::endl ; stripe = footer.stripes(stripeIx); stripe.PrintDebugString(); long offset = stripe.offset() + stripe.indexlength() + stripe.datalength(); int tailLength = stripe.footerlength(); // read the stripe footer input.seekg(offset); buffer.resize(tailLength); input.read(buffer.data(), tailLength); StripeFooter stripeFooter; stripeFooter.ParseFromArray(buffer.data(), tailLength); //stripeFooter.PrintDebugString(); long stripeStart = stripe.offset(); long sectionStart = stripeStart; for (int streamIx=0; streamIx<stripeFooter.streams_size(); streamIx++) { section = stripeFooter.streams(streamIx); std::cout << " Stream: column " << section.column() << " section " << section.kind() << " start: " << sectionStart << " length " << section.length() << std::endl; sectionStart += section.length(); }; for (int columnIx=0; columnIx<stripeFooter.columns_size(); columnIx++) { encoding = stripeFooter.columns(columnIx); std::cout << " Encoding column " << columnIx << ": " << encoding.kind() ; if (encoding.kind() == ColumnEncoding_Kind_DICTIONARY || encoding.kind() == ColumnEncoding_Kind_DICTIONARY_V2) std::cout << "[" << encoding.dictionarysize() << "]"; std::cout << std::endl; }; }; long paddedBytes = getTotalPaddingSize(footer); // empty ORC file is ~45 bytes. Assumption here is file length always >0 double percentPadding = ((double) paddedBytes / (double) fileSize) * 100; std::cout << "File length: " << fileSize << " bytes" << std::endl; std::cout <<"Padding length: " << paddedBytes << " bytes" << std::endl; std::cout <<"Padding ratio: " << std::fixed << std::setprecision(2) << percentPadding << " %" << std::endl; input.close(); google::protobuf::ShutdownProtobufLibrary(); return 0; } StripeFooter readStripeFooter(StripeInformation stripe) { long offset = stripe.offset() + stripe.indexlength() + stripe.datalength(); int tailLength = (int) stripe.footerlength(); std::vector<char> buffer(tailLength); input.seekg(offset); input.read(buffer.data(), tailLength); StripeFooter stripeFooter ; stripeFooter.ParseFromArray(buffer.data(), tailLength); return stripeFooter; } long getTotalPaddingSize(Footer footer) { long paddedBytes = 0; StripeInformation stripe; for (int stripeIx=1; stripeIx<footer.stripes_size(); stripeIx++) { stripe = footer.stripes(stripeIx-1); long prevStripeOffset = stripe.offset(); long prevStripeLen = stripe.datalength() + stripe.indexlength() + stripe.footerlength(); paddedBytes += footer.stripes(stripeIx).offset() - (prevStripeOffset + prevStripeLen); }; return paddedBytes; } <commit_msg>printout metadata<commit_after>#include <iostream> #include <fstream> #include <vector> #include <string> #include <sstream> #include <iomanip> //#include "orc_proto.pb.h" #include "wrap/orc-proto-wrapper.hh" using namespace orc::proto; long getTotalPaddingSize(Footer footer); StripeFooter readStripeFooter(StripeInformation stripe); std::ifstream input; int main(int argc, char* argv[]) { GOOGLE_PROTOBUF_VERIFY_VERSION; if (argc < 2) { std::cout << "Usage: file-metadata <filename>\n"; } std::cout << "Structure for " << argv[1] << std::endl; input.open(argv[1], std::ios::in | std::ios::binary); input.seekg(0,input.end); unsigned int fileSize = input.tellg(); // Read the postscript size input.seekg(fileSize-1); unsigned int postscriptSize = (int)input.get() ; // Read the postscript input.seekg(fileSize - postscriptSize-1); std::vector<char> buffer(postscriptSize) ; input.read(buffer.data(), postscriptSize); PostScript postscript ; postscript.ParseFromArray(buffer.data(), postscriptSize); std::cout << std::endl << "Postscript: " << std::endl ; postscript.PrintDebugString(); // Everything but the postscript is compressed switch (static_cast<int>(postscript.compression())) { case NONE: break; case ZLIB: case SNAPPY: case LZO: default: std::cout << "ORC files with compression are not supported" << std::endl ; input.close(); return -1; }; int footerSize = postscript.footerlength(); int metadataSize = postscript.metadatalength(); // Read the metadata input.seekg(fileSize - 1 - postscriptSize - footerSize - metadataSize); buffer.resize(metadataSize); input.read(buffer.data(), metadataSize); Metadata metadata ; metadata.ParseFromArray(buffer.data(), metadataSize); std::cout << std::endl << "Metadata: " << std::endl ; // get stripe statistics from metadata std::cout << "Has " << metadata.stripestats_size() << " stripes in this file\n"; for(int i = 0; i < metadata.stripestats_size(); ++i){ // TODO for stripe } postscript.PrintDebugString(); // Read the footer //input.seekg(fileSize -1 - postscriptSize-footerSize); buffer.resize(footerSize); input.read(buffer.data(), footerSize); Footer footer ; footer.ParseFromArray(buffer.data(), footerSize); std::cout << std::endl << "Footer: " << std::endl ; postscript.PrintDebugString(); std::cout << std::endl << "Rows: " << footer.numberofrows() << std::endl; std::cout << "Compression: " << postscript.compression() << std::endl; if (postscript.compression() != NONE) std::cout << "Compression size: " << postscript.compressionblocksize() << std::endl; std::cout << "Type: " ; for (int typeIx=0; typeIx < footer.types_size(); typeIx++) { Type type = footer.types(typeIx); type.PrintDebugString(); }; std::cout << "Has " << footer.statistics_size() << " Columns statistics in file" << std::endl; for(int i = 0; i < footer.statistics_size(); ++i){ ColumnStatistics col = footer.statistics(i); if(col.has_intstatistics()) { std::cout << "column " << i << "is INT.\n" << "Minimum = " << col.intstatistics().minimum() << std::endl << "Maximum = " << col.intstatistics().maximum() << std::endl; }else if(col.has_stringstatistics()){ std::cout << "column " << i << "is STRING.\n" << "Minimum = " << col.stringstatistics().minimum() << std::endl << "Maximum = " << col.stringstatistics().maximum() << std::endl; } if(col.has_numberofvalues()){ std::cout << "column has "<< col.numberofvalues() << " number of values\n"; } } std::cout << "\nStripe Information:" << std::endl; StripeInformation stripe ; Stream section; ColumnEncoding encoding; for (int stripeIx=0; stripeIx<footer.stripes_size(); stripeIx++) { std::cout << " Stripe " << stripeIx+1 <<": " << std::endl ; stripe = footer.stripes(stripeIx); stripe.PrintDebugString(); long offset = stripe.offset() + stripe.indexlength() + stripe.datalength(); int tailLength = stripe.footerlength(); // read the stripe footer input.seekg(offset); buffer.resize(tailLength); input.read(buffer.data(), tailLength); StripeFooter stripeFooter; stripeFooter.ParseFromArray(buffer.data(), tailLength); //stripeFooter.PrintDebugString(); long stripeStart = stripe.offset(); long sectionStart = stripeStart; for (int streamIx=0; streamIx<stripeFooter.streams_size(); streamIx++) { section = stripeFooter.streams(streamIx); std::cout << " Stream: column " << section.column() << " section " << section.kind() << " start: " << sectionStart << " length " << section.length() << std::endl; sectionStart += section.length(); }; for (int columnIx=0; columnIx<stripeFooter.columns_size(); columnIx++) { encoding = stripeFooter.columns(columnIx); std::cout << " Encoding column " << columnIx << ": " << encoding.kind() ; if (encoding.kind() == ColumnEncoding_Kind_DICTIONARY || encoding.kind() == ColumnEncoding_Kind_DICTIONARY_V2) std::cout << "[" << encoding.dictionarysize() << "]"; std::cout << std::endl; }; }; long paddedBytes = getTotalPaddingSize(footer); // empty ORC file is ~45 bytes. Assumption here is file length always >0 double percentPadding = ((double) paddedBytes / (double) fileSize) * 100; std::cout << "File length: " << fileSize << " bytes" << std::endl; std::cout <<"Padding length: " << paddedBytes << " bytes" << std::endl; std::cout <<"Padding ratio: " << std::fixed << std::setprecision(2) << percentPadding << " %" << std::endl; input.close(); google::protobuf::ShutdownProtobufLibrary(); return 0; } StripeFooter readStripeFooter(StripeInformation stripe) { long offset = stripe.offset() + stripe.indexlength() + stripe.datalength(); int tailLength = (int) stripe.footerlength(); std::vector<char> buffer(tailLength); input.seekg(offset); input.read(buffer.data(), tailLength); StripeFooter stripeFooter ; stripeFooter.ParseFromArray(buffer.data(), tailLength); return stripeFooter; } long getTotalPaddingSize(Footer footer) { long paddedBytes = 0; StripeInformation stripe; for (int stripeIx=1; stripeIx<footer.stripes_size(); stripeIx++) { stripe = footer.stripes(stripeIx-1); long prevStripeOffset = stripe.offset(); long prevStripeLen = stripe.datalength() + stripe.indexlength() + stripe.footerlength(); paddedBytes += footer.stripes(stripeIx).offset() - (prevStripeOffset + prevStripeLen); }; return paddedBytes; } <|endoftext|>
<commit_before>// -*- mode: c++, coding: utf-8 -*- /** * tbrpg – Text based roll playing game * * Copyright © 2012 Mattias Andrée (maandree@kth.se) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "GamePlay.hpp" /** * Text based roll playing game * * DD2387 Program construction with C++ * Laboration 3 * * @author Mattias Andrée <maandree@kth.se> */ namespace tbrpg { /** * Construction * * @param senario The game senario */ GamePlay::GamePlay(Senario& senario) { this->game = senario; } /** * Copy construction */ GamePlay::GamePlay(const GamePlay& original) { this->game = original.game; } /** * Destructor */ GamePlay::~GamePlay() { // do nothing } /** * Copy operator */ GamePlay& GamePlay::operator =(const GamePlay& original) { this->game = original.game; return *this; } /** * Play the next round, it may be an AI's turn * * @return Whether there is a next turn */ bool GamePlay::next() { std::vector<std::string> actions = {}; std::vector<char (GamePlay::*)()> functions = {}; #define __add(cmd, f) \ actions.push_back(cmd); \ functions.push_back(&GamePlay::f) __add("examine map", action_map); __add("examine area", action_area); __add("examine party", action_party); __add("examine inventory", action_inventory); __add("turn undead", action_turn_undead); __add("turn undead off", action_turn_undead_off); __add("find traps", action_find_traps); __add("find traps off", action_find_traps_off); __add("stealth", action_stealth); __add("stealth off", action_stealth_off); __add("pick pocket", action_pick_pocket); __add("disarm", action_disarm); __add("unlock", action_pick_lock); __add("bash", action_bash); __add("specials", action_specials); __add("talk", action_talk); __add("cast", action_cast); __add("attack", action_attack); __add("weapon", action_weapon); __add("quiver", action_quiver); __add("rest", action_rest); __add("!", action_redo); __add(".", action_wait); __add("quit", action_quit); // TODO special abilities // TODO quick magic #undef __add for (;;) { int index = promptIndex(":: ", actions); if (index >= 0) { char r = (this->*functions[index])(); if (r == 2) continue; if (r == 0) return false; } else std::flush(std::cout << "Type . to wait one turn" << std::endl); } return true; } /** * Action: quit * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_quit() { return 0; } /** * Action: wait one turn * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_wait() { return 1; } /** * Action: redo last action by any party member * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_redo() { return 2; } /** * Action: rest * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_rest() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: select ammunition to use from the quiver * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_quiver() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: select weapon to use from the quick weapons * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_weapon() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: attack * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_attack() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: cast non-quick spell * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_cast() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: talk * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_talk() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: list special usable abilities * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_specials() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: bash a lock * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_bash() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: pick a lock * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_pick_lock() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: disarm a trap * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_disarm() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: pick pocket * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_pick_pocket() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: turn on stealth mode * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_stealth() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: turn off stealth mode * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_stealth_off() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: turn on find traps mode * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_find_traps() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: turn off find traps mode * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_find_traps_off() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: turn on turn undead mode * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_turn_undead() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: turn off turn undead mode * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_turn_undead_off() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: examine inventory * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_inventory() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: examine party * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_party() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: examine world map * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_map() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: examine area * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_area() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } } <commit_msg>m<commit_after>// -*- mode: c++, coding: utf-8 -*- /** * tbrpg – Text based roll playing game * * Copyright © 2012 Mattias Andrée (maandree@kth.se) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "GamePlay.hpp" /** * Text based roll playing game * * DD2387 Program construction with C++ * Laboration 3 * * @author Mattias Andrée <maandree@kth.se> */ namespace tbrpg { /** * Construction * * @param senario The game senario */ GamePlay::GamePlay(Senario& senario) { this->game = senario; } /** * Copy construction */ GamePlay::GamePlay(const GamePlay& original) { this->game = original.game; } /** * Destructor */ GamePlay::~GamePlay() { // do nothing } /** * Copy operator */ GamePlay& GamePlay::operator =(const GamePlay& original) { this->game = original.game; return *this; } /** * Play the next round, it may be an AI's turn * * @return Whether there is a next turn */ bool GamePlay::next() { std::vector<std::string> actions = {}; std::vector<char (GamePlay::*)()> functions = {}; #define __add(cmd, f) \ actions.push_back(cmd); \ functions.push_back(&GamePlay::f) __add("examine map", action_map); __add("examine area", action_area); __add("examine party", action_party); __add("examine inventory", action_inventory); __add("turn undead", action_turn_undead); __add("turn undead off", action_turn_undead_off); __add("find traps", action_find_traps); __add("find traps off", action_find_traps_off); __add("stealth", action_stealth); __add("stealth off", action_stealth_off); __add("pick pocket", action_pick_pocket); __add("disarm", action_disarm); __add("unlock", action_pick_lock); __add("bash", action_bash); __add("specials", action_specials); __add("talk", action_talk); __add("cast", action_cast); __add("attack", action_attack); __add("weapon", action_weapon); __add("quiver", action_quiver); __add("rest", action_rest); __add("!", action_redo); __add(".", action_wait); __add("quit", action_quit); // TODO special abilities // TODO quick spells #undef __add for (;;) { int index = promptIndex(":: ", actions); if (index >= 0) { char r = (this->*functions[index])(); if (r == 2) continue; if (r == 0) return false; } else std::flush(std::cout << "Type . to wait one turn" << std::endl); } return true; } /** * Action: quit * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_quit() { return 0; } /** * Action: wait one turn * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_wait() { return 1; } /** * Action: redo last action by any party member * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_redo() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: rest * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_rest() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: select ammunition to use from the quiver * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_quiver() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: select weapon to use from the quick weapons * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_weapon() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: attack * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_attack() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: cast non-quick spell * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_cast() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: talk * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_talk() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: list special usable abilities * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_specials() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: bash a lock * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_bash() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: pick a lock * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_pick_lock() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: disarm a trap * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_disarm() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: pick pocket * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_pick_pocket() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: turn on stealth mode * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_stealth() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: turn off stealth mode * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_stealth_off() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: turn on find traps mode * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_find_traps() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: turn off find traps mode * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_find_traps_off() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: turn on turn undead mode * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_turn_undead() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: turn off turn undead mode * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_turn_undead_off() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: examine inventory * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_inventory() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: examine party * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_party() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: examine world map * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_map() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } /** * Action: examine area * * @return 0 for stop playing, 1 for continue playing, 2 for one mor time */ char GamePlay::action_area() { std::flush(std::cout << "Not implement..." << std::endl); return 2; } } <|endoftext|>
<commit_before>// Gripper.cpp #include "stdafx.h" #include "Gripper.h" #include "../interface/HeeksColor.h" static unsigned char circle[18] = {0x1c, 0x00, 0x63, 0x00, 0x41, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x41, 0x00, 0x63, 0x00, 0x1c, 0x00}; static unsigned char translation_circle[30] = {0x00, 0x80, 0x01, 0xc0, 0x00, 0x80, 0x01, 0xc0, 0x06, 0x30, 0x04, 0x10, 0x28, 0x0a, 0x78, 0x0f, 0x28, 0x0a, 0x04, 0x10, 0x06, 0x30, 0x01, 0xc0, 0x00, 0x80, 0x01, 0xc0, 0x00, 0x80}; static unsigned char rotation_circle[26] = {0x01, 0xc0, 0x06, 0x30, 0x04, 0x10, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x04, 0x10, 0x06, 0x31, 0x61, 0xc2, 0x60, 0x02, 0x10, 0x04, 0x0c, 0x18, 0x03, 0xe0}; static unsigned char rotation_object_circle[26] = {0x01, 0xc0, 0x06, 0xb0, 0x04, 0x90, 0x08, 0x88, 0x0f, 0xf8, 0x08, 0x88, 0x04, 0x90, 0x06, 0xb1, 0x61, 0xc2, 0x60, 0x02, 0x10, 0x04, 0x0c, 0x18, 0x03, 0xe0}; static unsigned char scale_circle[30] = {0x03, 0xe0, 0x0c, 0x18, 0x10, 0x04, 0x21, 0xc2, 0x26, 0x32, 0x44, 0x11, 0x48, 0x09, 0x48, 0x09, 0x48, 0x09, 0x44, 0x11, 0x26, 0x32, 0x21, 0xc2, 0x10, 0x04, 0x0c, 0x18, 0x03, 0xe0}; static unsigned char angle_circle[32] = {0x10, 0x04, 0x10, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x10, 0x04, 0x10, 0x02, 0x40, 0x03, 0xe0, 0x07, 0x70, 0x05, 0x50, 0x08, 0x88, 0x08, 0x88, 0x08, 0x08, 0x04, 0x10, 0x06, 0x30, 0x01, 0xc0}; Gripper::Gripper(const gp_Pnt& pos, const wxChar* str, EnumGripperType gripper_type){ position = pos; prompt = wxString(str); m_gripper_type = gripper_type; } void Gripper::glCommands(bool select, bool marked, bool no_color){ if(!no_color){ wxGetApp().glColorEnsuringContrast(HeeksColor(0, 0, 0)); } if(select) { double s = 5.0 / wxGetApp().GetPixelScale(); double p[8][3] = { -s, -s, -s, s, -s, -s, s, s, -s, -s, s, -s, -s, -s, s, s, -s, s, s, s, s, -s, s, s }; for(int i = 0; i<8; i++){ p[i][0] += position.X(); p[i][1] += position.Y(); p[i][2] += position.Z(); } glBegin(GL_TRIANGLES); glVertex3dv(p[0]); glVertex3dv(p[2]); glVertex3dv(p[1]); glVertex3dv(p[0]); glVertex3dv(p[3]); glVertex3dv(p[2]); glVertex3dv(p[0]); glVertex3dv(p[1]); glVertex3dv(p[5]); glVertex3dv(p[0]); glVertex3dv(p[5]); glVertex3dv(p[4]); glVertex3dv(p[3]); glVertex3dv(p[0]); glVertex3dv(p[4]); glVertex3dv(p[3]); glVertex3dv(p[4]); glVertex3dv(p[7]); glVertex3dv(p[4]); glVertex3dv(p[5]); glVertex3dv(p[6]); glVertex3dv(p[4]); glVertex3dv(p[6]); glVertex3dv(p[7]); glVertex3dv(p[3]); glVertex3dv(p[7]); glVertex3dv(p[6]); glVertex3dv(p[3]); glVertex3dv(p[6]); glVertex3dv(p[2]); glVertex3dv(p[2]); glVertex3dv(p[6]); glVertex3dv(p[5]); glVertex3dv(p[2]); glVertex3dv(p[5]); glVertex3dv(p[1]); glEnd(); } else { glRasterPos3d(position.X(), position.Y(), position.Z()); switch(m_gripper_type){ case GripperTypeTranslate: glBitmap(16, 15, 8, 7, 10.0, 0.0, translation_circle); break; case GripperTypeRotateObject: glBitmap(16, 13, 8, 4, 10.0, 0.0, rotation_object_circle); break; case GripperTypeRotate: glBitmap(16, 13, 8, 4, 10.0, 0.0, rotation_circle); break; case GripperTypeScale: glBitmap(16, 15, 8, 7, 10.0, 0.0, scale_circle); break; case GripperTypeAngle: glBitmap(14, 16, 9, 11, 10.0, 0.0, angle_circle); break; case GripperTypeStretch: glBitmap(9, 9, 4, 4, 10.0, 0.0, circle); break; default: glBitmap(9, 9, 4, 4, 10.0, 0.0, circle); break; } } } bool Gripper::ModifyByMatrix(const double *m){ gp_Trsf mat = make_matrix(m); position.Transform(mat); return false; } <commit_msg>added "{" and "}" to make the previous change build on Linux<commit_after>// Gripper.cpp #include "stdafx.h" #include "Gripper.h" #include "../interface/HeeksColor.h" static unsigned char circle[18] = {0x1c, 0x00, 0x63, 0x00, 0x41, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x41, 0x00, 0x63, 0x00, 0x1c, 0x00}; static unsigned char translation_circle[30] = {0x00, 0x80, 0x01, 0xc0, 0x00, 0x80, 0x01, 0xc0, 0x06, 0x30, 0x04, 0x10, 0x28, 0x0a, 0x78, 0x0f, 0x28, 0x0a, 0x04, 0x10, 0x06, 0x30, 0x01, 0xc0, 0x00, 0x80, 0x01, 0xc0, 0x00, 0x80}; static unsigned char rotation_circle[26] = {0x01, 0xc0, 0x06, 0x30, 0x04, 0x10, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x04, 0x10, 0x06, 0x31, 0x61, 0xc2, 0x60, 0x02, 0x10, 0x04, 0x0c, 0x18, 0x03, 0xe0}; static unsigned char rotation_object_circle[26] = {0x01, 0xc0, 0x06, 0xb0, 0x04, 0x90, 0x08, 0x88, 0x0f, 0xf8, 0x08, 0x88, 0x04, 0x90, 0x06, 0xb1, 0x61, 0xc2, 0x60, 0x02, 0x10, 0x04, 0x0c, 0x18, 0x03, 0xe0}; static unsigned char scale_circle[30] = {0x03, 0xe0, 0x0c, 0x18, 0x10, 0x04, 0x21, 0xc2, 0x26, 0x32, 0x44, 0x11, 0x48, 0x09, 0x48, 0x09, 0x48, 0x09, 0x44, 0x11, 0x26, 0x32, 0x21, 0xc2, 0x10, 0x04, 0x0c, 0x18, 0x03, 0xe0}; static unsigned char angle_circle[32] = {0x10, 0x04, 0x10, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x10, 0x04, 0x10, 0x02, 0x40, 0x03, 0xe0, 0x07, 0x70, 0x05, 0x50, 0x08, 0x88, 0x08, 0x88, 0x08, 0x08, 0x04, 0x10, 0x06, 0x30, 0x01, 0xc0}; Gripper::Gripper(const gp_Pnt& pos, const wxChar* str, EnumGripperType gripper_type){ position = pos; prompt = wxString(str); m_gripper_type = gripper_type; } void Gripper::glCommands(bool select, bool marked, bool no_color){ if(!no_color){ wxGetApp().glColorEnsuringContrast(HeeksColor(0, 0, 0)); } if(select) { double s = 5.0 / wxGetApp().GetPixelScale(); double p[8][3] = { {-s, -s, -s}, {s, -s, -s}, {s, s, -s}, {-s, s, -s}, {-s, -s, s}, {s, -s, s}, {s, s, s}, {-s, s, s} }; for(int i = 0; i<8; i++){ p[i][0] += position.X(); p[i][1] += position.Y(); p[i][2] += position.Z(); } glBegin(GL_TRIANGLES); glVertex3dv(p[0]); glVertex3dv(p[2]); glVertex3dv(p[1]); glVertex3dv(p[0]); glVertex3dv(p[3]); glVertex3dv(p[2]); glVertex3dv(p[0]); glVertex3dv(p[1]); glVertex3dv(p[5]); glVertex3dv(p[0]); glVertex3dv(p[5]); glVertex3dv(p[4]); glVertex3dv(p[3]); glVertex3dv(p[0]); glVertex3dv(p[4]); glVertex3dv(p[3]); glVertex3dv(p[4]); glVertex3dv(p[7]); glVertex3dv(p[4]); glVertex3dv(p[5]); glVertex3dv(p[6]); glVertex3dv(p[4]); glVertex3dv(p[6]); glVertex3dv(p[7]); glVertex3dv(p[3]); glVertex3dv(p[7]); glVertex3dv(p[6]); glVertex3dv(p[3]); glVertex3dv(p[6]); glVertex3dv(p[2]); glVertex3dv(p[2]); glVertex3dv(p[6]); glVertex3dv(p[5]); glVertex3dv(p[2]); glVertex3dv(p[5]); glVertex3dv(p[1]); glEnd(); } else { glRasterPos3d(position.X(), position.Y(), position.Z()); switch(m_gripper_type){ case GripperTypeTranslate: glBitmap(16, 15, 8, 7, 10.0, 0.0, translation_circle); break; case GripperTypeRotateObject: glBitmap(16, 13, 8, 4, 10.0, 0.0, rotation_object_circle); break; case GripperTypeRotate: glBitmap(16, 13, 8, 4, 10.0, 0.0, rotation_circle); break; case GripperTypeScale: glBitmap(16, 15, 8, 7, 10.0, 0.0, scale_circle); break; case GripperTypeAngle: glBitmap(14, 16, 9, 11, 10.0, 0.0, angle_circle); break; case GripperTypeStretch: glBitmap(9, 9, 4, 4, 10.0, 0.0, circle); break; default: glBitmap(9, 9, 4, 4, 10.0, 0.0, circle); break; } } } bool Gripper::ModifyByMatrix(const double *m){ gp_Trsf mat = make_matrix(m); position.Transform(mat); return false; } <|endoftext|>
<commit_before>#include "MyServo.h" MyServo::MyServo(int pin): Motor(), pin(pin), servo() {} void MyServo::setup() { this->servo.attach(this->pin); } void MyServo::doWriteWithAnalog(AnalogInput& input) { int rawVal = input.read(-100, 100); int finalVal = rawVal / 10; this->servo.write(this->servo.read() + finalVal); } void MyServo::doWriteWithPosition(int position) { this->servo.write(position); } void MyServo::update() {} <commit_msg>MyServo value limits<commit_after>#include "MyServo.h" MyServo::MyServo(int pin): Motor(), pin(pin), servo() {} void MyServo::setup() { this->servo.attach(this->pin); } void MyServo::doWriteWithAnalog(AnalogInput& input) { int rawVal = input.read(-100, 100); int filteredVal = rawVal / 10; int finalVal = this->servo.read() + filteredVal; if (finalVal > 0 && finalVal < 180) { this->servo.write(finalVal); } } void MyServo::doWriteWithPosition(int position) { this->servo.write(position); } void MyServo::update() {} <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file PerLine.cxx ** Manages data associated with each line of the document **/ // Copyright 1998-2009 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <string.h> #include "Platform.h" #include "Scintilla.h" #include "SplitVector.h" #include "Partitioning.h" #include "CellBuffer.h" #include "PerLine.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif MarkerHandleSet::MarkerHandleSet() { root = 0; } MarkerHandleSet::~MarkerHandleSet() { MarkerHandleNumber *mhn = root; while (mhn) { MarkerHandleNumber *mhnToFree = mhn; mhn = mhn->next; delete mhnToFree; } root = 0; } int MarkerHandleSet::Length() const { int c = 0; MarkerHandleNumber *mhn = root; while (mhn) { c++; mhn = mhn->next; } return c; } int MarkerHandleSet::NumberFromHandle(int handle) const { MarkerHandleNumber *mhn = root; while (mhn) { if (mhn->handle == handle) { return mhn->number; } mhn = mhn->next; } return - 1; } int MarkerHandleSet::MarkValue() const { unsigned int m = 0; MarkerHandleNumber *mhn = root; while (mhn) { m |= (1 << mhn->number); mhn = mhn->next; } return m; } bool MarkerHandleSet::Contains(int handle) const { MarkerHandleNumber *mhn = root; while (mhn) { if (mhn->handle == handle) { return true; } mhn = mhn->next; } return false; } bool MarkerHandleSet::InsertHandle(int handle, int markerNum) { MarkerHandleNumber *mhn = new MarkerHandleNumber; if (!mhn) return false; mhn->handle = handle; mhn->number = markerNum; mhn->next = root; root = mhn; return true; } void MarkerHandleSet::RemoveHandle(int handle) { MarkerHandleNumber **pmhn = &root; while (*pmhn) { MarkerHandleNumber *mhn = *pmhn; if (mhn->handle == handle) { *pmhn = mhn->next; delete mhn; return; } pmhn = &((*pmhn)->next); } } bool MarkerHandleSet::RemoveNumber(int markerNum) { bool performedDeletion = false; MarkerHandleNumber **pmhn = &root; while (*pmhn) { MarkerHandleNumber *mhn = *pmhn; if (mhn->number == markerNum) { *pmhn = mhn->next; delete mhn; performedDeletion = true; } else { pmhn = &((*pmhn)->next); } } return performedDeletion; } void MarkerHandleSet::CombineWith(MarkerHandleSet *other) { MarkerHandleNumber **pmhn = &root; while (*pmhn) { pmhn = &((*pmhn)->next); } *pmhn = other->root; other->root = 0; } LineMarkers::~LineMarkers() { Init(); } void LineMarkers::Init() { for (int line = 0; line < markers.Length(); line++) { delete markers[line]; markers[line] = 0; } markers.DeleteAll(); } void LineMarkers::InsertLine(int line) { if (markers.Length()) { markers.Insert(line, 0); } } void LineMarkers::RemoveLine(int line) { // Retain the markers from the deleted line by oring them into the previous line if (markers.Length()) { if (line > 0) { MergeMarkers(line - 1); } markers.Delete(line); } } int LineMarkers::LineFromHandle(int markerHandle) { if (markers.Length()) { for (int line = 0; line < markers.Length(); line++) { if (markers[line]) { if (markers[line]->Contains(markerHandle)) { return line; } } } } return -1; } void LineMarkers::MergeMarkers(int pos) { if (markers[pos + 1] != NULL) { if (markers[pos] == NULL) markers[pos] = new MarkerHandleSet; markers[pos]->CombineWith(markers[pos + 1]); delete markers[pos + 1]; markers[pos + 1] = NULL; } } int LineMarkers::MarkValue(int line) { if (markers.Length() && (line >= 0) && (line < markers.Length()) && markers[line]) return markers[line]->MarkValue(); else return 0; } int LineMarkers::AddMark(int line, int markerNum, int lines) { handleCurrent++; if (!markers.Length()) { // No existing markers so allocate one element per line markers.InsertValue(0, lines, 0); } if (line >= markers.Length()) { return -1; } if (!markers[line]) { // Need new structure to hold marker handle markers[line] = new MarkerHandleSet(); if (!markers[line]) return -1; } markers[line]->InsertHandle(handleCurrent, markerNum); return handleCurrent; } bool LineMarkers::DeleteMark(int line, int markerNum, bool all) { bool someChanges = false; if (markers.Length() && (line >= 0) && (line < markers.Length()) && markers[line]) { if (markerNum == -1) { someChanges = true; delete markers[line]; markers[line] = NULL; } else { bool performedDeletion = markers[line]->RemoveNumber(markerNum); someChanges = someChanges || performedDeletion; while (all && performedDeletion) { performedDeletion = markers[line]->RemoveNumber(markerNum); someChanges = someChanges || performedDeletion; } if (markers[line]->Length() == 0) { delete markers[line]; markers[line] = NULL; } } } return someChanges; } void LineMarkers::DeleteMarkFromHandle(int markerHandle) { int line = LineFromHandle(markerHandle); if (line >= 0) { markers[line]->RemoveHandle(markerHandle); if (markers[line]->Length() == 0) { delete markers[line]; markers[line] = NULL; } } } LineLevels::~LineLevels() { } void LineLevels::Init() { levels.DeleteAll(); } void LineLevels::InsertLine(int line) { if (levels.Length()) { int level = SC_FOLDLEVELBASE; if ((line > 0) && (line < levels.Length())) { level = levels[line-1] & ~SC_FOLDLEVELWHITEFLAG; } levels.InsertValue(line, 1, level); } } void LineLevels::RemoveLine(int line) { if (levels.Length()) { // Move up following lines but merge header flag from this line // to line before to avoid a temporary disappearence causing expansion. int firstHeader = levels[line] & SC_FOLDLEVELHEADERFLAG; levels.Delete(line); if (line == levels.Length()-1) // Last line loses the header flag levels[line-1] &= ~SC_FOLDLEVELHEADERFLAG; else if (line > 0) levels[line-1] |= firstHeader; } } void LineLevels::ExpandLevels(int sizeNew) { levels.InsertValue(levels.Length(), sizeNew - levels.Length(), SC_FOLDLEVELBASE); } void LineLevels::ClearLevels() { levels.DeleteAll(); } int LineLevels::SetLevel(int line, int level, int lines) { int prev = 0; if ((line >= 0) && (line < lines)) { if (!levels.Length()) { ExpandLevels(lines + 1); } prev = levels[line]; if (prev != level) { levels[line] = level; } } return prev; } int LineLevels::GetLevel(int line) { if (levels.Length() && (line >= 0) && (line < levels.Length())) { return levels[line]; } else { return SC_FOLDLEVELBASE; } } LineState::~LineState() { } void LineState::Init() { lineStates.DeleteAll(); } void LineState::InsertLine(int line) { if (lineStates.Length()) { lineStates.EnsureLength(line); lineStates.Insert(line, 0); } } void LineState::RemoveLine(int line) { if (lineStates.Length() > line) { lineStates.Delete(line); } } int LineState::SetLineState(int line, int state) { lineStates.EnsureLength(line + 1); int stateOld = lineStates[line]; lineStates[line] = state; return stateOld; } int LineState::GetLineState(int line) { lineStates.EnsureLength(line + 1); return lineStates[line]; } int LineState::GetMaxLineState() { return lineStates.Length(); } static int NumberLines(const char *text) { if (text) { int newLines = 0; while (*text) { if (*text == '\n') newLines++; text++; } return newLines+1; } else { return 0; } } // Each allocated LineAnnotation is a char array which starts with an AnnotationHeader // and then has text and optional styles. static const int IndividualStyles = 0x100; struct AnnotationHeader { short style; // Style IndividualStyles implies array of styles short lines; int length; }; LineAnnotation::~LineAnnotation() { ClearAll(); } void LineAnnotation::Init() { ClearAll(); } void LineAnnotation::InsertLine(int line) { if (annotations.Length()) { annotations.EnsureLength(line); annotations.Insert(line, 0); } } void LineAnnotation::RemoveLine(int line) { if (annotations.Length() && (line < annotations.Length())) { delete []annotations[line]; annotations.Delete(line); } } bool LineAnnotation::AnySet() const { return annotations.Length() > 0; } bool LineAnnotation::MultipleStyles(int line) const { if (annotations.Length() && (line < annotations.Length()) && annotations[line]) return reinterpret_cast<AnnotationHeader *>(annotations[line])->style == IndividualStyles; else return 0; } int LineAnnotation::Style(int line) { if (annotations.Length() && (line < annotations.Length()) && annotations[line]) return reinterpret_cast<AnnotationHeader *>(annotations[line])->style; else return 0; } const char *LineAnnotation::Text(int line) const { if (annotations.Length() && (line < annotations.Length()) && annotations[line]) return annotations[line]+sizeof(AnnotationHeader); else return 0; } const unsigned char *LineAnnotation::Styles(int line) const { if (annotations.Length() && (line < annotations.Length()) && annotations[line] && MultipleStyles(line)) return reinterpret_cast<unsigned char *>(annotations[line] + sizeof(AnnotationHeader) + Length(line)); else return 0; } static char *AllocateAnnotation(int length, int style) { size_t len = sizeof(AnnotationHeader) + length + ((style == IndividualStyles) ? length : 0); char *ret = new char[len]; memset(ret, 0, len); return ret; } void LineAnnotation::SetText(int line, const char *text) { if (text) { annotations.EnsureLength(line+1); int style = Style(line); if (annotations[line]) { delete []annotations[line]; } annotations[line] = AllocateAnnotation(strlen(text), style); AnnotationHeader *pah = reinterpret_cast<AnnotationHeader *>(annotations[line]); pah->style = static_cast<short>(style); pah->length = strlen(text); pah->lines = static_cast<short>(NumberLines(text)); memcpy(annotations[line]+sizeof(AnnotationHeader), text, pah->length); } else { if (annotations.Length() && (line < annotations.Length()) && annotations[line]) { delete []annotations[line]; annotations[line] = 0; } } } void LineAnnotation::ClearAll() { for (int line = 0; line < annotations.Length(); line++) { delete []annotations[line]; annotations[line] = 0; } annotations.DeleteAll(); } void LineAnnotation::SetStyle(int line, int style) { annotations.EnsureLength(line+1); if (!annotations[line]) { annotations[line] = AllocateAnnotation(0, style); } reinterpret_cast<AnnotationHeader *>(annotations[line])->style = static_cast<short>(style); } void LineAnnotation::SetStyles(int line, const unsigned char *styles) { annotations.EnsureLength(line+1); if (!annotations[line]) { annotations[line] = AllocateAnnotation(0, IndividualStyles); } else { AnnotationHeader *pahSource = reinterpret_cast<AnnotationHeader *>(annotations[line]); if (pahSource->style != IndividualStyles) { char *allocation = AllocateAnnotation(pahSource->length, IndividualStyles); AnnotationHeader *pahAlloc = reinterpret_cast<AnnotationHeader *>(allocation); pahAlloc->length = pahSource->length; pahAlloc->lines = pahSource->lines; memcpy(allocation + sizeof(AnnotationHeader), annotations[line] + sizeof(AnnotationHeader), pahSource->length); delete []annotations[line]; annotations[line] = allocation; } } AnnotationHeader *pah = reinterpret_cast<AnnotationHeader *>(annotations[line]); pah->style = IndividualStyles; memcpy(annotations[line] + sizeof(AnnotationHeader) + pah->length, styles, pah->length); } int LineAnnotation::Length(int line) const { if (annotations.Length() && (line < annotations.Length()) && annotations[line]) return reinterpret_cast<AnnotationHeader *>(annotations[line])->length; else return 0; } int LineAnnotation::Lines(int line) const { if (annotations.Length() && (line < annotations.Length()) && annotations[line]) return reinterpret_cast<AnnotationHeader *>(annotations[line])->lines; else return 0; } <commit_msg>Fix problems with line state and fold level by duplicating value rather than inserting default.<commit_after>// Scintilla source code edit control /** @file PerLine.cxx ** Manages data associated with each line of the document **/ // Copyright 1998-2009 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <string.h> #include "Platform.h" #include "Scintilla.h" #include "SplitVector.h" #include "Partitioning.h" #include "CellBuffer.h" #include "PerLine.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif MarkerHandleSet::MarkerHandleSet() { root = 0; } MarkerHandleSet::~MarkerHandleSet() { MarkerHandleNumber *mhn = root; while (mhn) { MarkerHandleNumber *mhnToFree = mhn; mhn = mhn->next; delete mhnToFree; } root = 0; } int MarkerHandleSet::Length() const { int c = 0; MarkerHandleNumber *mhn = root; while (mhn) { c++; mhn = mhn->next; } return c; } int MarkerHandleSet::NumberFromHandle(int handle) const { MarkerHandleNumber *mhn = root; while (mhn) { if (mhn->handle == handle) { return mhn->number; } mhn = mhn->next; } return - 1; } int MarkerHandleSet::MarkValue() const { unsigned int m = 0; MarkerHandleNumber *mhn = root; while (mhn) { m |= (1 << mhn->number); mhn = mhn->next; } return m; } bool MarkerHandleSet::Contains(int handle) const { MarkerHandleNumber *mhn = root; while (mhn) { if (mhn->handle == handle) { return true; } mhn = mhn->next; } return false; } bool MarkerHandleSet::InsertHandle(int handle, int markerNum) { MarkerHandleNumber *mhn = new MarkerHandleNumber; if (!mhn) return false; mhn->handle = handle; mhn->number = markerNum; mhn->next = root; root = mhn; return true; } void MarkerHandleSet::RemoveHandle(int handle) { MarkerHandleNumber **pmhn = &root; while (*pmhn) { MarkerHandleNumber *mhn = *pmhn; if (mhn->handle == handle) { *pmhn = mhn->next; delete mhn; return; } pmhn = &((*pmhn)->next); } } bool MarkerHandleSet::RemoveNumber(int markerNum) { bool performedDeletion = false; MarkerHandleNumber **pmhn = &root; while (*pmhn) { MarkerHandleNumber *mhn = *pmhn; if (mhn->number == markerNum) { *pmhn = mhn->next; delete mhn; performedDeletion = true; } else { pmhn = &((*pmhn)->next); } } return performedDeletion; } void MarkerHandleSet::CombineWith(MarkerHandleSet *other) { MarkerHandleNumber **pmhn = &root; while (*pmhn) { pmhn = &((*pmhn)->next); } *pmhn = other->root; other->root = 0; } LineMarkers::~LineMarkers() { Init(); } void LineMarkers::Init() { for (int line = 0; line < markers.Length(); line++) { delete markers[line]; markers[line] = 0; } markers.DeleteAll(); } void LineMarkers::InsertLine(int line) { if (markers.Length()) { markers.Insert(line, 0); } } void LineMarkers::RemoveLine(int line) { // Retain the markers from the deleted line by oring them into the previous line if (markers.Length()) { if (line > 0) { MergeMarkers(line - 1); } markers.Delete(line); } } int LineMarkers::LineFromHandle(int markerHandle) { if (markers.Length()) { for (int line = 0; line < markers.Length(); line++) { if (markers[line]) { if (markers[line]->Contains(markerHandle)) { return line; } } } } return -1; } void LineMarkers::MergeMarkers(int pos) { if (markers[pos + 1] != NULL) { if (markers[pos] == NULL) markers[pos] = new MarkerHandleSet; markers[pos]->CombineWith(markers[pos + 1]); delete markers[pos + 1]; markers[pos + 1] = NULL; } } int LineMarkers::MarkValue(int line) { if (markers.Length() && (line >= 0) && (line < markers.Length()) && markers[line]) return markers[line]->MarkValue(); else return 0; } int LineMarkers::AddMark(int line, int markerNum, int lines) { handleCurrent++; if (!markers.Length()) { // No existing markers so allocate one element per line markers.InsertValue(0, lines, 0); } if (line >= markers.Length()) { return -1; } if (!markers[line]) { // Need new structure to hold marker handle markers[line] = new MarkerHandleSet(); if (!markers[line]) return -1; } markers[line]->InsertHandle(handleCurrent, markerNum); return handleCurrent; } bool LineMarkers::DeleteMark(int line, int markerNum, bool all) { bool someChanges = false; if (markers.Length() && (line >= 0) && (line < markers.Length()) && markers[line]) { if (markerNum == -1) { someChanges = true; delete markers[line]; markers[line] = NULL; } else { bool performedDeletion = markers[line]->RemoveNumber(markerNum); someChanges = someChanges || performedDeletion; while (all && performedDeletion) { performedDeletion = markers[line]->RemoveNumber(markerNum); someChanges = someChanges || performedDeletion; } if (markers[line]->Length() == 0) { delete markers[line]; markers[line] = NULL; } } } return someChanges; } void LineMarkers::DeleteMarkFromHandle(int markerHandle) { int line = LineFromHandle(markerHandle); if (line >= 0) { markers[line]->RemoveHandle(markerHandle); if (markers[line]->Length() == 0) { delete markers[line]; markers[line] = NULL; } } } LineLevels::~LineLevels() { } void LineLevels::Init() { levels.DeleteAll(); } void LineLevels::InsertLine(int line) { if (levels.Length()) { int level = (line < levels.Length()) ? levels[line] : SC_FOLDLEVELBASE; levels.InsertValue(line, 1, level); } } void LineLevels::RemoveLine(int line) { if (levels.Length()) { // Move up following lines but merge header flag from this line // to line before to avoid a temporary disappearence causing expansion. int firstHeader = levels[line] & SC_FOLDLEVELHEADERFLAG; levels.Delete(line); if (line == levels.Length()-1) // Last line loses the header flag levels[line-1] &= ~SC_FOLDLEVELHEADERFLAG; else if (line > 0) levels[line-1] |= firstHeader; } } void LineLevels::ExpandLevels(int sizeNew) { levels.InsertValue(levels.Length(), sizeNew - levels.Length(), SC_FOLDLEVELBASE); } void LineLevels::ClearLevels() { levels.DeleteAll(); } int LineLevels::SetLevel(int line, int level, int lines) { int prev = 0; if ((line >= 0) && (line < lines)) { if (!levels.Length()) { ExpandLevels(lines + 1); } prev = levels[line]; if (prev != level) { levels[line] = level; } } return prev; } int LineLevels::GetLevel(int line) { if (levels.Length() && (line >= 0) && (line < levels.Length())) { return levels[line]; } else { return SC_FOLDLEVELBASE; } } LineState::~LineState() { } void LineState::Init() { lineStates.DeleteAll(); } void LineState::InsertLine(int line) { if (lineStates.Length()) { lineStates.EnsureLength(line); int val = (line < lineStates.Length()) ? lineStates[line] : 0; lineStates.Insert(line, val); } } void LineState::RemoveLine(int line) { if (lineStates.Length() > line) { lineStates.Delete(line); } } int LineState::SetLineState(int line, int state) { lineStates.EnsureLength(line + 1); int stateOld = lineStates[line]; lineStates[line] = state; return stateOld; } int LineState::GetLineState(int line) { lineStates.EnsureLength(line + 1); return lineStates[line]; } int LineState::GetMaxLineState() { return lineStates.Length(); } static int NumberLines(const char *text) { if (text) { int newLines = 0; while (*text) { if (*text == '\n') newLines++; text++; } return newLines+1; } else { return 0; } } // Each allocated LineAnnotation is a char array which starts with an AnnotationHeader // and then has text and optional styles. static const int IndividualStyles = 0x100; struct AnnotationHeader { short style; // Style IndividualStyles implies array of styles short lines; int length; }; LineAnnotation::~LineAnnotation() { ClearAll(); } void LineAnnotation::Init() { ClearAll(); } void LineAnnotation::InsertLine(int line) { if (annotations.Length()) { annotations.EnsureLength(line); annotations.Insert(line, 0); } } void LineAnnotation::RemoveLine(int line) { if (annotations.Length() && (line < annotations.Length())) { delete []annotations[line]; annotations.Delete(line); } } bool LineAnnotation::AnySet() const { return annotations.Length() > 0; } bool LineAnnotation::MultipleStyles(int line) const { if (annotations.Length() && (line < annotations.Length()) && annotations[line]) return reinterpret_cast<AnnotationHeader *>(annotations[line])->style == IndividualStyles; else return 0; } int LineAnnotation::Style(int line) { if (annotations.Length() && (line < annotations.Length()) && annotations[line]) return reinterpret_cast<AnnotationHeader *>(annotations[line])->style; else return 0; } const char *LineAnnotation::Text(int line) const { if (annotations.Length() && (line < annotations.Length()) && annotations[line]) return annotations[line]+sizeof(AnnotationHeader); else return 0; } const unsigned char *LineAnnotation::Styles(int line) const { if (annotations.Length() && (line < annotations.Length()) && annotations[line] && MultipleStyles(line)) return reinterpret_cast<unsigned char *>(annotations[line] + sizeof(AnnotationHeader) + Length(line)); else return 0; } static char *AllocateAnnotation(int length, int style) { size_t len = sizeof(AnnotationHeader) + length + ((style == IndividualStyles) ? length : 0); char *ret = new char[len]; memset(ret, 0, len); return ret; } void LineAnnotation::SetText(int line, const char *text) { if (text) { annotations.EnsureLength(line+1); int style = Style(line); if (annotations[line]) { delete []annotations[line]; } annotations[line] = AllocateAnnotation(strlen(text), style); AnnotationHeader *pah = reinterpret_cast<AnnotationHeader *>(annotations[line]); pah->style = static_cast<short>(style); pah->length = strlen(text); pah->lines = static_cast<short>(NumberLines(text)); memcpy(annotations[line]+sizeof(AnnotationHeader), text, pah->length); } else { if (annotations.Length() && (line < annotations.Length()) && annotations[line]) { delete []annotations[line]; annotations[line] = 0; } } } void LineAnnotation::ClearAll() { for (int line = 0; line < annotations.Length(); line++) { delete []annotations[line]; annotations[line] = 0; } annotations.DeleteAll(); } void LineAnnotation::SetStyle(int line, int style) { annotations.EnsureLength(line+1); if (!annotations[line]) { annotations[line] = AllocateAnnotation(0, style); } reinterpret_cast<AnnotationHeader *>(annotations[line])->style = static_cast<short>(style); } void LineAnnotation::SetStyles(int line, const unsigned char *styles) { annotations.EnsureLength(line+1); if (!annotations[line]) { annotations[line] = AllocateAnnotation(0, IndividualStyles); } else { AnnotationHeader *pahSource = reinterpret_cast<AnnotationHeader *>(annotations[line]); if (pahSource->style != IndividualStyles) { char *allocation = AllocateAnnotation(pahSource->length, IndividualStyles); AnnotationHeader *pahAlloc = reinterpret_cast<AnnotationHeader *>(allocation); pahAlloc->length = pahSource->length; pahAlloc->lines = pahSource->lines; memcpy(allocation + sizeof(AnnotationHeader), annotations[line] + sizeof(AnnotationHeader), pahSource->length); delete []annotations[line]; annotations[line] = allocation; } } AnnotationHeader *pah = reinterpret_cast<AnnotationHeader *>(annotations[line]); pah->style = IndividualStyles; memcpy(annotations[line] + sizeof(AnnotationHeader) + pah->length, styles, pah->length); } int LineAnnotation::Length(int line) const { if (annotations.Length() && (line < annotations.Length()) && annotations[line]) return reinterpret_cast<AnnotationHeader *>(annotations[line])->length; else return 0; } int LineAnnotation::Lines(int line) const { if (annotations.Length() && (line < annotations.Length()) && annotations[line]) return reinterpret_cast<AnnotationHeader *>(annotations[line])->lines; else return 0; } <|endoftext|>
<commit_before>/// /// @file PhiTiny.cpp /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include "PhiTiny.hpp" #include <stdint.h> #include <vector> #include <cassert> namespace { /// Thread-safe singleton without locking /// @note Meyer's singleton (static const Singleton instance) causes a /// race condition with MSVC 2013 and OpenMP /// const primecount::PhiTiny phiTiny; } namespace primecount { int64_t phi_tiny(int64_t x, int64_t a) { return phiTiny.phi(x, a); } const int64_t PhiTiny::MAX_A = 6; const int32_t PhiTiny::primes_[7] = { 0, 2, 3, 5, 7, 11, 13 }; /// prime_products_[n] = \prod_{i=1}^{n} primes_[i] const int32_t PhiTiny::prime_products_[7] = { 1, 2, 6, 30, 210, 2310, 30030 }; /// totients_[n] = \prod_{i=1}^{n} (primes_[i] - 1) const int32_t PhiTiny::totients_[7] = { 1, 1, 2, 8, 48, 480, 5760 }; PhiTiny::PhiTiny() { phi_cache_[0].push_back(0); // Initialize the phi_cache_ lookup tables for (int a = 1; a <= MAX_A; a++) { int size = prime_products_[a]; std::vector<int16_t>& cache = phi_cache_[a]; cache.reserve(size); for (int x = 0; x < size; x++) { int16_t phixa = static_cast<int16_t>(phi(x, a - 1) - phi(x / primes_[a], a - 1)); cache.push_back(phixa); } } } /// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// @pre is_cached(a) == true. /// int64_t PhiTiny::phi(int64_t x, int64_t a) const { assert(x >= 0); assert(a <= MAX_A); return (x / prime_products_[a]) * totients_[a] + phi_cache_[a][x % prime_products_[a]]; } } // namespace primecount <commit_msg>Comment<commit_after>/// /// @file PhiTiny.cpp /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include "PhiTiny.hpp" #include <stdint.h> #include <vector> #include <cassert> namespace { const primecount::PhiTiny phiTiny; } namespace primecount { int64_t phi_tiny(int64_t x, int64_t a) { return phiTiny.phi(x, a); } const int64_t PhiTiny::MAX_A = 6; const int32_t PhiTiny::primes_[7] = { 0, 2, 3, 5, 7, 11, 13 }; /// prime_products_[n] = \prod_{i=1}^{n} primes_[i] const int32_t PhiTiny::prime_products_[7] = { 1, 2, 6, 30, 210, 2310, 30030 }; /// totients_[n] = \prod_{i=1}^{n} (primes_[i] - 1) const int32_t PhiTiny::totients_[7] = { 1, 1, 2, 8, 48, 480, 5760 }; PhiTiny::PhiTiny() { phi_cache_[0].push_back(0); // Initialize the phi_cache_ lookup tables for (int a = 1; a <= MAX_A; a++) { int size = prime_products_[a]; std::vector<int16_t>& cache = phi_cache_[a]; cache.reserve(size); for (int x = 0; x < size; x++) { int16_t phixa = static_cast<int16_t>(phi(x, a - 1) - phi(x / primes_[a], a - 1)); cache.push_back(phixa); } } } /// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// @pre is_cached(a) == true. /// int64_t PhiTiny::phi(int64_t x, int64_t a) const { assert(x >= 0); assert(a <= MAX_A); return (x / prime_products_[a]) * totients_[a] + phi_cache_[a][x % prime_products_[a]]; } } // namespace primecount <|endoftext|>
<commit_before>#ifndef QOR_NO_PHYSICS #include "Physics.h" #include <glm/glm.hpp> #include "Node.h" //#include "IMeshContainer.h" //#include "NodeAttributes.h" #include "Node.h" #include "Graphics.h" #include "PhysicsObject.h" #include "Mesh.h" #include <iostream> #include <memory> #include "kit/math/vectorops.h" using namespace std; Physics::Physics(Node* root, void* userdata): m_pRoot(root) { m_pCollisionConfig = kit::make_unique<btDefaultCollisionConfiguration>(); m_pDispatcher = kit::make_unique<btCollisionDispatcher>(m_pCollisionConfig.get()); //m_pBroadphase = kit::make_unique<btDbvtBroadphase>(); btVector3 worldMin(-1000,-1000,-1000); btVector3 worldMax(1000,1000,1000); m_pBroadphase = kit::make_unique<btAxisSweep3>(worldMin, worldMax); m_pSolver = kit::make_unique<btSequentialImpulseConstraintSolver>(); m_pWorld = kit::make_unique<btDiscreteDynamicsWorld>( m_pDispatcher.get(), m_pBroadphase.get(), m_pSolver.get(), m_pCollisionConfig.get() ); m_pWorld->setGravity(btVector3(0.0, -9.8, 0.0)); } Physics :: ~Physics() { if(m_pWorld) { //NewtonDestroyAllBodies(m_pWorld); //NewtonDestroy(m_pWorld); } } void Physics :: logic(Freq::Time advance) { static float accum = 0.0f; const float fixed_step = 1/60.0f; float timestep = advance.s(); m_pWorld->stepSimulation(timestep, NUM_SUBSTEPS, fixed_step); // accum += timestep; // while(accum >= fixed_step) // { // m_pWorld->stepSimulation(fixed_step, NUM_SUBSTEPS, fixed_step); // //NewtonUpdate(m_pWorld, fixed_step); // sync(m_pRoot, SYNC_RECURSIVE); ////#ifdef _NEWTON_VISUAL_DEBUGGER //// NewtonDebuggerServe(m_pDebugger, m_pWorld); ////#endif // accum -= fixed_step; // } } void Physics :: generate(Node* node, unsigned flags, std::unique_ptr<glm::mat4> transform) { if(!node) return; // TODO: If no transform is given, derive world space transform from node if(!transform) transform = kit::make_unique<glm::mat4>(); // apply transformation of node so the mesh vertices are correct *transform *= *node->matrix_c(); //assert(transform->isIdentity()); // Are there physics instructions? if(node->physics()) { if(not node->body()) { // Check if there's static geometry in this node, if so let's process it switch(node->physics()) { case Node::Physics::STATIC: generate_tree(node, flags, transform.get()); break; case Node::Physics::ACTOR: generate_actor(node, flags, transform.get()); break; case Node::Physics::DYNAMIC: generate_dynamic(node, flags, transform.get()); break; default: //assert(false); break; } } } // generate children if(node->has_children() && (flags & (unsigned)GenerateFlag::RECURSIVE)) { for(auto&& child: node->subnodes()) { // copy current node's transform so it can be modified by child std::unique_ptr<glm::mat4> transform_copy = kit::make_unique<glm::mat4>(*transform); generate(child.get(), flags, std::move(transform_copy)); } } // delete generated identity matrix for those who passed in null matrix pointers //if(created_transform) // delete transform; } void Physics :: generate_actor(Node* node, unsigned int flags, glm::mat4* transform) { assert(node); assert(transform); assert(node->physics()); //Actor* actor = dynamic_cast<Actor*>(node); // TODO: generate code } void Physics :: generate_tree(Node* node, unsigned int flags, glm::mat4* transform) { assert(node); assert(transform); if(node->physics() != Node::STATIC) return; assert(node->physics_shape() == Node::MESH); //assert(node->physics() == Node::STATIC); //assert(node->physics_shape() == Node::MESH); //std::vector<shared_ptr<Node>> meshes = node->children(); //for(auto&& c: meshes) //{ Mesh* mesh = dynamic_cast<Mesh*>(node); if(not mesh) return; //NewtonCollision* collision = NewtonCreateTreeCollision(m_pWorld, 0); //NewtonTreeCollisionBeginBuild(collision); //try{ if(not mesh->internals()) return; if(not mesh->internals()->geometry) return; //}catch(const exception& e){ // WARNING(e.what()); //} if(mesh->internals()->geometry->ordered_verts().empty()) return; auto triangles = kit::make_unique<btTriangleMesh>(); //mesh->each([&triangles](Node* n){ // Mesh* mesh = dynamic_cast<Mesh*>(node); auto verts = mesh->internals()->geometry->ordered_verts(); for(int i = 0; i < verts.size(); i += 3) { triangles->addTriangle( btVector3(verts[i].x, verts[i].y, verts[i].z), btVector3(verts[i+1].x, verts[i+1].y, verts[i+1].z), btVector3(verts[i+2].x, verts[i+2].y, verts[i+2].z) ); } //}, Node::Each::INCLUDE_SELF); node->reset_body(); auto physics_object = node->body(); assert(physics_object.get()); unique_ptr<btCollisionShape> shape = kit::make_unique<btBvhTriangleMeshShape>( triangles.get(), true, true ); btRigidBody::btRigidBodyConstructionInfo info( 0.0f, physics_object.get(), // inherits btMotionState shape.get() ); auto body = kit::make_unique<btRigidBody>(info); body->setUserPointer((void*)node); auto interface = unique_ptr<btStridingMeshInterface>(std::move(triangles)); physics_object->add_striding_mesh_interface(interface); physics_object->add_collision_shape(shape); physics_object->body(std::move(body)); physics_object->system(this); m_pWorld->addRigidBody((btRigidBody*)physics_object->body()); //NewtonTreeCollisionEndBuild(collision, 0); //add_body(collision, node, transform); //NewtonReleaseCollision(m_pWorld, collision); //} //if(meshes.empty()) // return; //Node* physics_object = dynamic_cast<Node*>(node); } void Physics :: generate_dynamic(Node* node, unsigned int flags, glm::mat4* transform) { assert(node); assert(transform); assert(node->physics()); assert(node->physics() == Node::DYNAMIC); Mesh* mesh = dynamic_cast<Mesh*>(node); if(not mesh) return; switch(node->physics_shape()) { case Node::HULL: break; case Node::BOX: { //std::vector<glm::vec3> verts; ////try{ //if(not mesh->internals()) // return; //if(not mesh->internals()->geometry) // return; //verts = mesh->internals()->geometry->ordered_verts(); ////}catch(const exception& e){ //// WARNING(e.what()); ////} //auto triangles = kit::make_unique<btTriangleMesh>(); //for(int i = 0; i < verts.size(); i += 3) //{ // //NewtonTreeCollisionAddFace( // // collision, 3, glm::value_ptr(verts[i]), // // sizeof(glm::vec3), 0 // //); // triangles->addTriangle( // btVector3(verts[0].x, verts[0].y, verts[0].z), // btVector3(verts[1].x, verts[1].y, verts[1].z), // btVector3(verts[2].x, verts[2].y, verts[2].z) // ); //} mesh->each([](Node* n){ auto m = std::dynamic_pointer_cast<Mesh>(n->as_node()); assert(m); m->set_physics(Node::NO_PHYSICS); }); node->reset_body(); auto physics_object = node->body(); assert(physics_object.get()); auto b = node->box(); //LOG(Vector::to_string(node->box().size())); unique_ptr<btCollisionShape> shape = kit::make_unique<btBoxShape>( //toBulletVector(node->box().size() / 2.0f) btVector3(0.5f, 0.5f, 0.5f) ); btRigidBody::btRigidBodyConstructionInfo info( mesh->mass(), physics_object.get(), // inherits btMotionState shape.get() ); auto body = kit::make_unique<btRigidBody>(info); //auto interface = unique_ptr<btStridingMeshInterface>(std::move(triangles)); //physics_object->add_striding_mesh_interface(interface); physics_object->add_collision_shape(shape); physics_object->body(std::move(body)); physics_object->system(this); m_pWorld->addRigidBody((btRigidBody*)physics_object->body()); return; //break; } default: assert(false); }; //std::vector<shared_ptr<Mesh>> meshes = node->children<Mesh>(); //if(meshes.empty()) // return; //Node* physics_object = dynamic_cast<Node*>(node); } // syncBody gets the data out of physics subsystem, reports it back to each node void Physics :: sync(Node* node, unsigned int flags) { if(!node) return; if(!node->physics()) return; if(node->physics() != Node::Physics::STATIC) { glm::mat4 body_matrix; //NewtonBodyGetMatrix((NewtonBody*)node->body(), glm::value_ptr(body_matrix)); node->sync(body_matrix); // NOTE: Remember to update the transform from the object side afterwards. } if(flags & SYNC_RECURSIVE) for(auto&& child: *node) sync(child.get(), flags); } //NewtonBody* Physics :: add_body(NewtonCollision* nc, Node* node, glm::mat4* transform) //{ // return nullptr; //} //btRigidBody* Physics :: add_body(btCollisionObject* obj, Node* node, glm::mat4* transform, btVector3* inertia) //{ //float mass = node->mass(); //glm::vec3 inertia, origin; //NewtonBody* body = NewtonCreateBody(m_pWorld, nc, glm::value_ptr(*transform)); //NewtonBodySetUserData(body, node); //btTransform btt; //btt.setFromOpenGLMatrix(glm::value_ptr(transform)); //btRigidBody* body = new bt //node->setPhysicsBody(this, (void*)body, (void*)motion); //m_pWorld->addRigidBody(body); //if(mass > EPSILON) //{ // NewtonConvexCollisionCalculateInertialMatrix(nc, glm::value_ptr(inertia), glm::value_ptr(origin)); // NewtonBodySetMassMatrix(body, mass, inertia.x * mass, inertia.y * mass, inertia.z * mass); // NewtonBodySetCentreOfMass(body, glm::value_ptr(origin)); // NewtonBodySetForceAndTorqueCallback(body, (NewtonApplyForceAndTorque)&cbForceTorque); // NewtonBodySetTransformCallback(body, (NewtonSetTransform)&cbTransform); //} // return nullptr; //} bool Physics :: delete_body(void* obj) { if(!obj) return false; m_pWorld->removeCollisionObject((btRigidBody*)obj); delete (btRigidBody*)obj; return true; } //void Physics :: cb_force_torque(const NewtonBody* body, float timestep, int threadIndex) //{ // float mass, ix, iy, iz; // //NewtonBodyGetMassMatrix(body, &mass, &ix, &iy, &iz); // glm::vec3 force(0.0f, mass * -9.8f, 0.0f); // glm::vec3 omega(0.0f); // glm::vec3 velocity(0.0f); // glm::vec3 torque(0.0f); // //NewtonBodyGetVelocity(body, glm::value_ptr(velocity)); // //Node* node = (Node*)NewtonBodyGetUserData(body); // unsigned int userflags = 0; // //node->on_physics_tick( // // Freq::Time::seconds(timestep), mass, force, omega, torque, velocity, &userflags // //); // //if(userflags & USER_FORCE) // // NewtonBodyAddForce(body, glm::value_ptr(force)); // //if(userflags & USER_OMEGA) // // NewtonBodySetOmega(body, glm::value_ptr(omega)); // //if(userflags & USER_TORQUE) // // NewtonBodySetTorque(body, glm::value_ptr(torque)); // //if(userflags & USER_VELOCITY) // // NewtonBodySetVelocity(body, glm::value_ptr(velocity)); //} //void Physics :: cb_transform(const NewtonBody* body) //{ // //Node* node = (Node*)NewtonBodyGetUserData(body); // //float marray[16]; // //NewtonBodyGetMatrix(body, &marray[0]); // //glm::mat4 m = Matrix::from_array(marray); // //node->sync(m); //} tuple<Node*, glm::vec3, glm::vec3> Physics :: first_hit(glm::vec3 start, glm::vec3 end) { auto s = toBulletVector(start); auto e = toBulletVector(end); btCollisionWorld::ClosestRayResultCallback ray(s,e); m_pWorld->rayTest(s,e,ray); return std::tuple<Node*,glm::vec3,glm::vec3>( ray.hasHit() ? (Node*)ray.m_collisionObject->getUserPointer() : nullptr, Physics::fromBulletVector(ray.m_hitPointWorld), Physics::fromBulletVector(ray.m_hitNormalWorld) ); } //std::tuple<Node*, glm::vec3, glm::vec3> Physics :: first_other_hit( // Node* me, glm::vec3 start, glm::vec3 end //){ // auto s = toBulletVector(start); // auto e = toBulletVector(end); // btCollisionWorld::btKinematicClosestNotMeRayResultCallback ray(s,e); // m_pWorld->rayTest(s,e,ray); //} #endif <commit_msg>make sure to return zero vectors if no hit<commit_after>#ifndef QOR_NO_PHYSICS #include "Physics.h" #include <glm/glm.hpp> #include "Node.h" //#include "IMeshContainer.h" //#include "NodeAttributes.h" #include "Node.h" #include "Graphics.h" #include "PhysicsObject.h" #include "Mesh.h" #include <iostream> #include <memory> #include "kit/math/vectorops.h" using namespace std; Physics::Physics(Node* root, void* userdata): m_pRoot(root) { m_pCollisionConfig = kit::make_unique<btDefaultCollisionConfiguration>(); m_pDispatcher = kit::make_unique<btCollisionDispatcher>(m_pCollisionConfig.get()); //m_pBroadphase = kit::make_unique<btDbvtBroadphase>(); btVector3 worldMin(-1000,-1000,-1000); btVector3 worldMax(1000,1000,1000); m_pBroadphase = kit::make_unique<btAxisSweep3>(worldMin, worldMax); m_pSolver = kit::make_unique<btSequentialImpulseConstraintSolver>(); m_pWorld = kit::make_unique<btDiscreteDynamicsWorld>( m_pDispatcher.get(), m_pBroadphase.get(), m_pSolver.get(), m_pCollisionConfig.get() ); m_pWorld->setGravity(btVector3(0.0, -9.8, 0.0)); } Physics :: ~Physics() { if(m_pWorld) { //NewtonDestroyAllBodies(m_pWorld); //NewtonDestroy(m_pWorld); } } void Physics :: logic(Freq::Time advance) { static float accum = 0.0f; const float fixed_step = 1/60.0f; float timestep = advance.s(); m_pWorld->stepSimulation(timestep, NUM_SUBSTEPS, fixed_step); // accum += timestep; // while(accum >= fixed_step) // { // m_pWorld->stepSimulation(fixed_step, NUM_SUBSTEPS, fixed_step); // //NewtonUpdate(m_pWorld, fixed_step); // sync(m_pRoot, SYNC_RECURSIVE); ////#ifdef _NEWTON_VISUAL_DEBUGGER //// NewtonDebuggerServe(m_pDebugger, m_pWorld); ////#endif // accum -= fixed_step; // } } void Physics :: generate(Node* node, unsigned flags, std::unique_ptr<glm::mat4> transform) { if(!node) return; // TODO: If no transform is given, derive world space transform from node if(!transform) transform = kit::make_unique<glm::mat4>(); // apply transformation of node so the mesh vertices are correct *transform *= *node->matrix_c(); //assert(transform->isIdentity()); // Are there physics instructions? if(node->physics()) { if(not node->body()) { // Check if there's static geometry in this node, if so let's process it switch(node->physics()) { case Node::Physics::STATIC: generate_tree(node, flags, transform.get()); break; case Node::Physics::ACTOR: generate_actor(node, flags, transform.get()); break; case Node::Physics::DYNAMIC: generate_dynamic(node, flags, transform.get()); break; default: //assert(false); break; } } } // generate children if(node->has_children() && (flags & (unsigned)GenerateFlag::RECURSIVE)) { for(auto&& child: node->subnodes()) { // copy current node's transform so it can be modified by child std::unique_ptr<glm::mat4> transform_copy = kit::make_unique<glm::mat4>(*transform); generate(child.get(), flags, std::move(transform_copy)); } } // delete generated identity matrix for those who passed in null matrix pointers //if(created_transform) // delete transform; } void Physics :: generate_actor(Node* node, unsigned int flags, glm::mat4* transform) { assert(node); assert(transform); assert(node->physics()); //Actor* actor = dynamic_cast<Actor*>(node); // TODO: generate code } void Physics :: generate_tree(Node* node, unsigned int flags, glm::mat4* transform) { assert(node); assert(transform); if(node->physics() != Node::STATIC) return; assert(node->physics_shape() == Node::MESH); //assert(node->physics() == Node::STATIC); //assert(node->physics_shape() == Node::MESH); //std::vector<shared_ptr<Node>> meshes = node->children(); //for(auto&& c: meshes) //{ Mesh* mesh = dynamic_cast<Mesh*>(node); if(not mesh) return; //NewtonCollision* collision = NewtonCreateTreeCollision(m_pWorld, 0); //NewtonTreeCollisionBeginBuild(collision); //try{ if(not mesh->internals()) return; if(not mesh->internals()->geometry) return; //}catch(const exception& e){ // WARNING(e.what()); //} if(mesh->internals()->geometry->ordered_verts().empty()) return; auto triangles = kit::make_unique<btTriangleMesh>(); //mesh->each([&triangles](Node* n){ // Mesh* mesh = dynamic_cast<Mesh*>(node); auto verts = mesh->internals()->geometry->ordered_verts(); for(int i = 0; i < verts.size(); i += 3) { triangles->addTriangle( btVector3(verts[i].x, verts[i].y, verts[i].z), btVector3(verts[i+1].x, verts[i+1].y, verts[i+1].z), btVector3(verts[i+2].x, verts[i+2].y, verts[i+2].z) ); } //}, Node::Each::INCLUDE_SELF); node->reset_body(); auto physics_object = node->body(); assert(physics_object.get()); unique_ptr<btCollisionShape> shape = kit::make_unique<btBvhTriangleMeshShape>( triangles.get(), true, true ); btRigidBody::btRigidBodyConstructionInfo info( 0.0f, physics_object.get(), // inherits btMotionState shape.get() ); auto body = kit::make_unique<btRigidBody>(info); body->setUserPointer((void*)node); auto interface = unique_ptr<btStridingMeshInterface>(std::move(triangles)); physics_object->add_striding_mesh_interface(interface); physics_object->add_collision_shape(shape); physics_object->body(std::move(body)); physics_object->system(this); m_pWorld->addRigidBody((btRigidBody*)physics_object->body()); //NewtonTreeCollisionEndBuild(collision, 0); //add_body(collision, node, transform); //NewtonReleaseCollision(m_pWorld, collision); //} //if(meshes.empty()) // return; //Node* physics_object = dynamic_cast<Node*>(node); } void Physics :: generate_dynamic(Node* node, unsigned int flags, glm::mat4* transform) { assert(node); assert(transform); assert(node->physics()); assert(node->physics() == Node::DYNAMIC); Mesh* mesh = dynamic_cast<Mesh*>(node); if(not mesh) return; switch(node->physics_shape()) { case Node::HULL: break; case Node::BOX: { //std::vector<glm::vec3> verts; ////try{ //if(not mesh->internals()) // return; //if(not mesh->internals()->geometry) // return; //verts = mesh->internals()->geometry->ordered_verts(); ////}catch(const exception& e){ //// WARNING(e.what()); ////} //auto triangles = kit::make_unique<btTriangleMesh>(); //for(int i = 0; i < verts.size(); i += 3) //{ // //NewtonTreeCollisionAddFace( // // collision, 3, glm::value_ptr(verts[i]), // // sizeof(glm::vec3), 0 // //); // triangles->addTriangle( // btVector3(verts[0].x, verts[0].y, verts[0].z), // btVector3(verts[1].x, verts[1].y, verts[1].z), // btVector3(verts[2].x, verts[2].y, verts[2].z) // ); //} mesh->each([](Node* n){ auto m = std::dynamic_pointer_cast<Mesh>(n->as_node()); assert(m); m->set_physics(Node::NO_PHYSICS); }); node->reset_body(); auto physics_object = node->body(); assert(physics_object.get()); auto b = node->box(); //LOG(Vector::to_string(node->box().size())); unique_ptr<btCollisionShape> shape = kit::make_unique<btBoxShape>( //toBulletVector(node->box().size() / 2.0f) btVector3(0.5f, 0.5f, 0.5f) ); btRigidBody::btRigidBodyConstructionInfo info( mesh->mass(), physics_object.get(), // inherits btMotionState shape.get() ); auto body = kit::make_unique<btRigidBody>(info); //auto interface = unique_ptr<btStridingMeshInterface>(std::move(triangles)); //physics_object->add_striding_mesh_interface(interface); physics_object->add_collision_shape(shape); physics_object->body(std::move(body)); physics_object->system(this); m_pWorld->addRigidBody((btRigidBody*)physics_object->body()); return; //break; } default: assert(false); }; //std::vector<shared_ptr<Mesh>> meshes = node->children<Mesh>(); //if(meshes.empty()) // return; //Node* physics_object = dynamic_cast<Node*>(node); } // syncBody gets the data out of physics subsystem, reports it back to each node void Physics :: sync(Node* node, unsigned int flags) { if(!node) return; if(!node->physics()) return; if(node->physics() != Node::Physics::STATIC) { glm::mat4 body_matrix; //NewtonBodyGetMatrix((NewtonBody*)node->body(), glm::value_ptr(body_matrix)); node->sync(body_matrix); // NOTE: Remember to update the transform from the object side afterwards. } if(flags & SYNC_RECURSIVE) for(auto&& child: *node) sync(child.get(), flags); } //NewtonBody* Physics :: add_body(NewtonCollision* nc, Node* node, glm::mat4* transform) //{ // return nullptr; //} //btRigidBody* Physics :: add_body(btCollisionObject* obj, Node* node, glm::mat4* transform, btVector3* inertia) //{ //float mass = node->mass(); //glm::vec3 inertia, origin; //NewtonBody* body = NewtonCreateBody(m_pWorld, nc, glm::value_ptr(*transform)); //NewtonBodySetUserData(body, node); //btTransform btt; //btt.setFromOpenGLMatrix(glm::value_ptr(transform)); //btRigidBody* body = new bt //node->setPhysicsBody(this, (void*)body, (void*)motion); //m_pWorld->addRigidBody(body); //if(mass > EPSILON) //{ // NewtonConvexCollisionCalculateInertialMatrix(nc, glm::value_ptr(inertia), glm::value_ptr(origin)); // NewtonBodySetMassMatrix(body, mass, inertia.x * mass, inertia.y * mass, inertia.z * mass); // NewtonBodySetCentreOfMass(body, glm::value_ptr(origin)); // NewtonBodySetForceAndTorqueCallback(body, (NewtonApplyForceAndTorque)&cbForceTorque); // NewtonBodySetTransformCallback(body, (NewtonSetTransform)&cbTransform); //} // return nullptr; //} bool Physics :: delete_body(void* obj) { if(!obj) return false; m_pWorld->removeCollisionObject((btRigidBody*)obj); delete (btRigidBody*)obj; return true; } //void Physics :: cb_force_torque(const NewtonBody* body, float timestep, int threadIndex) //{ // float mass, ix, iy, iz; // //NewtonBodyGetMassMatrix(body, &mass, &ix, &iy, &iz); // glm::vec3 force(0.0f, mass * -9.8f, 0.0f); // glm::vec3 omega(0.0f); // glm::vec3 velocity(0.0f); // glm::vec3 torque(0.0f); // //NewtonBodyGetVelocity(body, glm::value_ptr(velocity)); // //Node* node = (Node*)NewtonBodyGetUserData(body); // unsigned int userflags = 0; // //node->on_physics_tick( // // Freq::Time::seconds(timestep), mass, force, omega, torque, velocity, &userflags // //); // //if(userflags & USER_FORCE) // // NewtonBodyAddForce(body, glm::value_ptr(force)); // //if(userflags & USER_OMEGA) // // NewtonBodySetOmega(body, glm::value_ptr(omega)); // //if(userflags & USER_TORQUE) // // NewtonBodySetTorque(body, glm::value_ptr(torque)); // //if(userflags & USER_VELOCITY) // // NewtonBodySetVelocity(body, glm::value_ptr(velocity)); //} //void Physics :: cb_transform(const NewtonBody* body) //{ // //Node* node = (Node*)NewtonBodyGetUserData(body); // //float marray[16]; // //NewtonBodyGetMatrix(body, &marray[0]); // //glm::mat4 m = Matrix::from_array(marray); // //node->sync(m); //} tuple<Node*, glm::vec3, glm::vec3> Physics :: first_hit(glm::vec3 start, glm::vec3 end) { auto s = toBulletVector(start); auto e = toBulletVector(end); btCollisionWorld::ClosestRayResultCallback ray(s,e); m_pWorld->rayTest(s,e,ray); bool b = ray.hasHit(); return std::tuple<Node*,glm::vec3,glm::vec3>( b ? (Node*)ray.m_collisionObject->getUserPointer() : nullptr, b ? Physics::fromBulletVector(ray.m_hitPointWorld) : glm::vec3(0.0f), b ? Physics::fromBulletVector(ray.m_hitNormalWorld) : glm::vec3(0.0f) ); } //std::tuple<Node*, glm::vec3, glm::vec3> Physics :: first_other_hit( // Node* me, glm::vec3 start, glm::vec3 end //){ // auto s = toBulletVector(start); // auto e = toBulletVector(end); // btCollisionWorld::btKinematicClosestNotMeRayResultCallback ray(s,e); // m_pWorld->rayTest(s,e,ray); //} #endif <|endoftext|>
<commit_before>/* * TMC2130.cpp * * Created on: 03 nov 2019 * Author: Tim Evers */ #include "TMC2130.h" #if defined(FARMDUINO_EXP_V20) || defined(FARMDUINO_V30) || defined(FARMDUINO_V32) void loadTMC2130ParametersMotor(TMC2130_Basics *tb, int microsteps, int current, int sensitivity, bool stealth) { uint32_t data = 0; uint32_t value = 0; tb->init(); // Set the micro steps switch (microsteps) { case 1: data = 8; break; case 2: data = 7; break; case 4: data = 6; break; case 8: data = 5; break; case 16: data = 4; break; case 32: data = 3; break; case 64: data = 2; break; case 128: data = 1; break; } tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(data) << FB_TMC_CHOPCONF_MRES, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_MRES] << FB_TMC_CHOPCONF_MRES); // Set the current uint16_t mA = current; float multiplier = 0.5; float RS = 0.11; uint8_t CS = 32.0*1.41421*mA / 1000.0*(RS + 0.02) / 0.325 - 1; if (CS < 16) { CS = 32.0*1.41421*mA / 1000.0*(RS + 0.02) / 0.180 - 1; } data = ((uint32_t(CS)&FB_TMC_IHOLD_MASK) << FB_TMC_IHOLD); data |= ((uint32_t(CS)&FB_TMC_IRUN_MASK) << FB_TMC_IRUN); data |= ((uint32_t(16)&FB_TMC_IHOLDDELAY_MASK) << FB_TMC_IHOLDDELAY); tb->write_REG(FB_TMC_REG_IHOLD_IRUN, data); // Chop and cool conf if (!stealth) { tb->set_GCONF(FB_TMC_GCONF_I_SCALE_ANALOG, 1); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(3) << FB_TMC_CHOPCONF_TOFF, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_TOFF] << FB_TMC_CHOPCONF_TOFF); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(4) << FB_TMC_CHOPCONF_HSTRT, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_HSTRT] << FB_TMC_CHOPCONF_HSTRT); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(1) << FB_TMC_CHOPCONF_HEND, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_HEND] << FB_TMC_CHOPCONF_HEND); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(2) << FB_TMC_CHOPCONF_TBL, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_TBL] << FB_TMC_CHOPCONF_TBL); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0) << FB_TMC_CHOPCONF_CHM, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_CHM] << FB_TMC_CHOPCONF_CHM); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(1) << FB_TMC_COOLCONF_SEMIN, FB_TMC_CHOPCONF_MASKS[FB_TMC_COOLCONF_SEMIN] << FB_TMC_COOLCONF_SEMIN); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(2) << FB_TMC_COOLCONF_SEMAX, FB_TMC_CHOPCONF_MASKS[FB_TMC_COOLCONF_SEMAX] << FB_TMC_COOLCONF_SEMAX); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0b01) << FB_TMC_COOLCONF_SEDN, FB_TMC_CHOPCONF_MASKS[FB_TMC_COOLCONF_SEDN] << FB_TMC_COOLCONF_SEDN); tb->write_REG(FB_TMC_REG_TPWMTHRS, uint32_t(0xFFFFFFFF)); tb->write_REG(FB_TMC_REG_TCOOLTHRS, 0xFFFFF & FB_TMC_TCOOLTHRS_MASK); tb->write_REG(FB_TMC_REG_THIGH, 10000 & FB_TMC_THIGH_MASK); //dcStep settings tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0b01) << FB_TMC_CHOPCONF_VHIGHCHM, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_VHIGHCHM] << FB_TMC_CHOPCONF_VHIGHCHM); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0b01) << FB_TMC_CHOPCONF_VHIGHFS, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_VHIGHFS] << FB_TMC_CHOPCONF_VHIGHFS); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(8) << FB_TMC_CHOPCONF_TOFF, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_TOFF] << FB_TMC_CHOPCONF_TOFF); tb->alter_REG(FB_TMC_REG_DCCTRL, uint32_t(100) << FB_TMC_DCCTRL_DC_TIME, FB_TMC_DCCTRL_DC_TIME_MASK << FB_TMC_DCCTRL_DC_TIME); tb->alter_REG(FB_TMC_REG_DCCTRL, uint32_t(8) << FB_TMC_DCCTRL_DC_SG, FB_TMC_DCCTRL_DC_SG_MASK << FB_TMC_DCCTRL_DC_SG); tb->write_REG(FB_TMC_REG_THIGH, uint32_t(10000)); // Enable diagnostics tb->set_GCONF(FB_TMC_GCONF_DIAG0_ERROR, 1); tb->set_GCONF(FB_TMC_GCONF_DIAG1_STEPS_SKIPPED, 1); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(sensitivity) << FB_TMC_COOLCONF_SGT, FB_TMC_CHOPCONF_MASKS[FB_TMC_COOLCONF_SGT] << FB_TMC_COOLCONF_SGT); } if (stealth) { tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(3) << FB_TMC_CHOPCONF_TOFF, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_TOFF] << FB_TMC_CHOPCONF_TOFF); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(1) << FB_TMC_CHOPCONF_TBL, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_TBL] << FB_TMC_CHOPCONF_TBL); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0) << FB_TMC_CHOPCONF_HSTRT, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_HSTRT] << FB_TMC_CHOPCONF_HSTRT); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0) << FB_TMC_CHOPCONF_HEND, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_HEND] << FB_TMC_CHOPCONF_HEND); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0) << FB_TMC_CHOPCONF_CHM, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_CHM] << FB_TMC_CHOPCONF_CHM); // Disable settings from non-stealth mode tb->set_GCONF(FB_TMC_GCONF_I_SCALE_ANALOG, 0); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0b00) << FB_TMC_CHOPCONF_VHIGHCHM, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_VHIGHCHM] << FB_TMC_CHOPCONF_VHIGHCHM); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0b00) << FB_TMC_CHOPCONF_VHIGHFS, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_VHIGHFS] << FB_TMC_CHOPCONF_VHIGHFS); // Enbable stealth tb->alter_REG(FB_TMC_REG_PWMCONF, uint32_t(1) << FB_TMC_PWMCONF_PWM_AUTOSCALE, FB_TMC_PWMCONF_MASKS[FB_TMC_PWMCONF_PWM_AUTOSCALE] << FB_TMC_PWMCONF_PWM_AUTOSCALE); tb->alter_REG(FB_TMC_REG_PWMCONF, uint32_t(0) << FB_TMC_PWMCONF_PWM_FREQ, FB_TMC_PWMCONF_MASKS[FB_TMC_PWMCONF_PWM_FREQ] << FB_TMC_PWMCONF_PWM_FREQ); tb->alter_REG(FB_TMC_REG_PWMCONF, uint32_t(1) << FB_TMC_PWMCONF_PWM_GRAD, FB_TMC_PWMCONF_MASKS[FB_TMC_PWMCONF_PWM_GRAD] << FB_TMC_PWMCONF_PWM_GRAD); tb->alter_REG(FB_TMC_REG_PWMCONF, uint32_t(128) << FB_TMC_PWMCONF_PWM_AMPL, FB_TMC_PWMCONF_MASKS[FB_TMC_PWMCONF_PWM_AMPL] << FB_TMC_PWMCONF_PWM_AMPL); tb->set_GCONF(FB_TMC_GCONF_EN_PWM_MODE, uint32_t(1)); // Disable diagnostics tb->set_GCONF(FB_TMC_GCONF_DIAG0_ERROR, 0); tb->set_GCONF(FB_TMC_GCONF_DIAG1_STEPS_SKIPPED, 0); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0) << FB_TMC_COOLCONF_SGT, FB_TMC_CHOPCONF_MASKS[FB_TMC_COOLCONF_SGT] << FB_TMC_COOLCONF_SGT); } delay(100); } #endif <commit_msg>Adding IntPol<commit_after>/* * TMC2130.cpp * * Created on: 03 nov 2019 * Author: Tim Evers */ #include "TMC2130.h" #if defined(FARMDUINO_EXP_V20) || defined(FARMDUINO_V30) || defined(FARMDUINO_V32) void loadTMC2130ParametersMotor(TMC2130_Basics *tb, int microsteps, int current, int sensitivity, bool stealth) { uint32_t data = 0; uint32_t value = 0; tb->init(); // Set the micro steps switch (microsteps) { case 1: data = 8; break; case 2: data = 7; break; case 4: data = 6; break; case 8: data = 5; break; case 16: data = 4; break; case 32: data = 3; break; case 64: data = 2; break; case 128: data = 1; break; } tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(data) << FB_TMC_CHOPCONF_MRES, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_MRES] << FB_TMC_CHOPCONF_MRES); // Set the current uint16_t mA = current; float multiplier = 0.5; float RS = 0.11; uint8_t CS = 32.0*1.41421*mA / 1000.0*(RS + 0.02) / 0.325 - 1; if (CS < 16) { CS = 32.0*1.41421*mA / 1000.0*(RS + 0.02) / 0.180 - 1; } data = ((uint32_t(CS)&FB_TMC_IHOLD_MASK) << FB_TMC_IHOLD); data |= ((uint32_t(CS)&FB_TMC_IRUN_MASK) << FB_TMC_IRUN); data |= ((uint32_t(16)&FB_TMC_IHOLDDELAY_MASK) << FB_TMC_IHOLDDELAY); tb->write_REG(FB_TMC_REG_IHOLD_IRUN, data); // Chop and cool conf if (!stealth) { tb->set_GCONF(FB_TMC_GCONF_I_SCALE_ANALOG, 1); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(3) << FB_TMC_CHOPCONF_TOFF, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_TOFF] << FB_TMC_CHOPCONF_TOFF); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(4) << FB_TMC_CHOPCONF_HSTRT, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_HSTRT] << FB_TMC_CHOPCONF_HSTRT); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(1) << FB_TMC_CHOPCONF_HEND, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_HEND] << FB_TMC_CHOPCONF_HEND); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(2) << FB_TMC_CHOPCONF_TBL, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_TBL] << FB_TMC_CHOPCONF_TBL); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0) << FB_TMC_CHOPCONF_CHM, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_CHM] << FB_TMC_CHOPCONF_CHM); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(1) << FB_TMC_COOLCONF_SEMIN, FB_TMC_CHOPCONF_MASKS[FB_TMC_COOLCONF_SEMIN] << FB_TMC_COOLCONF_SEMIN); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(2) << FB_TMC_COOLCONF_SEMAX, FB_TMC_CHOPCONF_MASKS[FB_TMC_COOLCONF_SEMAX] << FB_TMC_COOLCONF_SEMAX); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0b01) << FB_TMC_COOLCONF_SEDN, FB_TMC_CHOPCONF_MASKS[FB_TMC_COOLCONF_SEDN] << FB_TMC_COOLCONF_SEDN); tb->write_REG(FB_TMC_REG_TPWMTHRS, uint32_t(0xFFFFFFFF)); tb->write_REG(FB_TMC_REG_TCOOLTHRS, 0xFFFFF & FB_TMC_TCOOLTHRS_MASK); tb->write_REG(FB_TMC_REG_THIGH, 10000 & FB_TMC_THIGH_MASK); //dcStep settings tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0b01) << FB_TMC_CHOPCONF_VHIGHCHM, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_VHIGHCHM] << FB_TMC_CHOPCONF_VHIGHCHM); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0b01) << FB_TMC_CHOPCONF_VHIGHFS, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_VHIGHFS] << FB_TMC_CHOPCONF_VHIGHFS); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(8) << FB_TMC_CHOPCONF_TOFF, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_TOFF] << FB_TMC_CHOPCONF_TOFF); tb->alter_REG(FB_TMC_REG_DCCTRL, uint32_t(100) << FB_TMC_DCCTRL_DC_TIME, FB_TMC_DCCTRL_DC_TIME_MASK << FB_TMC_DCCTRL_DC_TIME); tb->alter_REG(FB_TMC_REG_DCCTRL, uint32_t(8) << FB_TMC_DCCTRL_DC_SG, FB_TMC_DCCTRL_DC_SG_MASK << FB_TMC_DCCTRL_DC_SG); tb->write_REG(FB_TMC_REG_THIGH, uint32_t(10000)); // Enable diagnostics tb->set_GCONF(FB_TMC_GCONF_DIAG0_ERROR, 1); tb->set_GCONF(FB_TMC_GCONF_DIAG1_STEPS_SKIPPED, 1); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(sensitivity) << FB_TMC_COOLCONF_SGT, FB_TMC_CHOPCONF_MASKS[FB_TMC_COOLCONF_SGT] << FB_TMC_COOLCONF_SGT); } if (stealth) { tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(3) << FB_TMC_CHOPCONF_TOFF, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_TOFF] << FB_TMC_CHOPCONF_TOFF); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(1) << FB_TMC_CHOPCONF_TBL, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_TBL] << FB_TMC_CHOPCONF_TBL); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0) << FB_TMC_CHOPCONF_HSTRT, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_HSTRT] << FB_TMC_CHOPCONF_HSTRT); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0) << FB_TMC_CHOPCONF_HEND, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_HEND] << FB_TMC_CHOPCONF_HEND); /**/tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(1) << FB_TMC_CHOPCONF_INTPOL, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_INTPOL] << FB_TMC_CHOPCONF_INTPOL); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0) << FB_TMC_CHOPCONF_CHM, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_CHM] << FB_TMC_CHOPCONF_CHM); // Disable settings from non-stealth mode tb->set_GCONF(FB_TMC_GCONF_I_SCALE_ANALOG, 0); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0b00) << FB_TMC_CHOPCONF_VHIGHCHM, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_VHIGHCHM] << FB_TMC_CHOPCONF_VHIGHCHM); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0b00) << FB_TMC_CHOPCONF_VHIGHFS, FB_TMC_CHOPCONF_MASKS[FB_TMC_CHOPCONF_VHIGHFS] << FB_TMC_CHOPCONF_VHIGHFS); // Enbable stealth tb->alter_REG(FB_TMC_REG_PWMCONF, uint32_t(1) << FB_TMC_PWMCONF_PWM_AUTOSCALE, FB_TMC_PWMCONF_MASKS[FB_TMC_PWMCONF_PWM_AUTOSCALE] << FB_TMC_PWMCONF_PWM_AUTOSCALE); tb->alter_REG(FB_TMC_REG_PWMCONF, uint32_t(0) << FB_TMC_PWMCONF_PWM_FREQ, FB_TMC_PWMCONF_MASKS[FB_TMC_PWMCONF_PWM_FREQ] << FB_TMC_PWMCONF_PWM_FREQ); tb->alter_REG(FB_TMC_REG_PWMCONF, uint32_t(1) << FB_TMC_PWMCONF_PWM_GRAD, FB_TMC_PWMCONF_MASKS[FB_TMC_PWMCONF_PWM_GRAD] << FB_TMC_PWMCONF_PWM_GRAD); tb->alter_REG(FB_TMC_REG_PWMCONF, uint32_t(128) << FB_TMC_PWMCONF_PWM_AMPL, FB_TMC_PWMCONF_MASKS[FB_TMC_PWMCONF_PWM_AMPL] << FB_TMC_PWMCONF_PWM_AMPL); tb->set_GCONF(FB_TMC_GCONF_EN_PWM_MODE, uint32_t(1)); // Disable diagnostics tb->set_GCONF(FB_TMC_GCONF_DIAG0_ERROR, 0); tb->set_GCONF(FB_TMC_GCONF_DIAG1_STEPS_SKIPPED, 0); tb->alter_REG(FB_TMC_REG_CHOPCONF, uint32_t(0) << FB_TMC_COOLCONF_SGT, FB_TMC_CHOPCONF_MASKS[FB_TMC_COOLCONF_SGT] << FB_TMC_COOLCONF_SGT); } delay(100); } #endif <|endoftext|>
<commit_before>#include "Tracker.hpp" #include <stdexcept> #include <iostream> #include <stdlib.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <cvblob.h> #include <ros/console.h> #include <cmath> #include "profiling.hpp" // Use this to use the register keyword in some places. Might make things faster, but I didn't test it. //#define QC_REGISTER // Use this for debugging the object recognition. WARNING: Might lead to errors or strange behaviour when used with visualTracker == true. //#define QC_DEBUG_TRACKER Tracker::Tracker(ITrackerDataReceiver* dataReceiver, QuadcopterColor* color) { this->dataReceiver = dataReceiver; this->thread = 0; this->image = 0; this->qc = color; this->showCameraImage = false; this->showMaskedImage = false; } Tracker::Tracker(ITrackerDataReceiver* dataReceiver, QuadcopterColor* color, bool showCameraImage, bool showMaskedImage) { this->dataReceiver = dataReceiver; this->thread = 0; this->image = 0; this->qc = color; this->showCameraImage = showCameraImage; this->showMaskedImage = showMaskedImage; if (showMaskedImage) { std::stringstream ss; ss << "Tracker of id " << ((QuadcopterColor*) this->qc)->getId() << " showing masked image"; this->maskedWindowName = ss.str(); cv::startWindowThread(); } if (showCameraImage) { std::stringstream ss; ss << "Tracker of id " << ((QuadcopterColor*) this->qc)->getId() << " showing camera image"; this->cameraWindowName = ss.str(); cv::startWindowThread(); } } Tracker::~Tracker() { } void Tracker::start() { if (thread != 0) { throw new std::runtime_error("Already started. (Maybe you forgot to call join?)"); } if (showMaskedImage) { cv::namedWindow(maskedWindowName); } if (showCameraImage) { cv::namedWindow(cameraWindowName); } imageDirty = 0; stopFlag = false; thread = new boost::thread(boost::bind(&Tracker::executeTracker, this)); } void Tracker::stop() { if (thread == 0) { throw new std::runtime_error("Not started."); } stopFlag = true; } void Tracker::join() { if (thread != 0) { thread->join(); delete thread; thread = 0; } if (this->image != 0) { delete this->image; this->image = 0; } } bool Tracker::isStarted() { return thread != 0; } void Tracker::setNextImage(cv::Mat* image, long int time) { imageMutex.lock(); if (this->image != 0) { delete this->image; } this->image = new cv::Mat(*image); imageTime = time; imageDirty++; imageMutex.unlock(); } QuadcopterColor* Tracker::getQuadcopterColor() { return (QuadcopterColor*) qc; } void Tracker::drawCross(cv::Mat mat, const int x, const int y) { ROS_DEBUG("Drawing cross."); for (int i = x - 10; i <= x + 10; i++) { int j = y; // ROS_DEBUG("i/j: %d/%d", i, j); if (i >= 0 && i < mat.rows && j >= 0 && j < mat.cols) { unsigned char* element = mat.data + mat.step[0] * j + mat.step[1] * i; unsigned char color; if (i + j % 3 > 0) { color = 0xFF; } else { color = 0; } element[0] = color; element[1] = color; element[2] = color; } } for (int j = y - 10; j <= y + 10; j++) { int i = x; // ROS_DEBUG("i/j: %d/%d", i, j); if (i >= 0 && i < mat.rows && j >= 0 && j < mat.cols) { unsigned char* element = mat.data + mat.step[0] * j + mat.step[1] * i; unsigned char color; if (i + j % 3 > 0) { color = 0xFF; } else { color = 0; } element[0] = color; element[1] = color; element[2] = color; } } ROS_DEBUG("Cross drawed"); } void Tracker::executeTracker() { #define PI (3.1415926535897932384626433832795028841) // Kinect fow: 43° vertical, 57° horizontal double verticalScalingFactor = tan(43 * PI / 180) / 240; double horizontalScalingFactor = tan(57 * PI / 180) / 320; ROS_DEBUG("Scaling factors: %lf/%lf", horizontalScalingFactor, verticalScalingFactor); bool quadcopterTracked = false; // Images cv::Mat cameraImage(cv::Size(640, 480), CV_8UC3); cv::Mat maskedImage(cv::Size(640, 480), CV_8UC3); cv::Mat image(cv::Size(640, 480), CV_8UC3); cv::Mat mapImage(cv::Size(640, 480), CV_8UC1); cv::Mat hsvImage(cv::Size(640, 480), CV_8UC3); // CvBlob cvb::CvBlobs blobs; IplImage *labelImg = cvCreateImage(image.size(), IPL_DEPTH_LABEL, 1); cv::Mat morphKernel = cv::getStructuringElement(CV_SHAPE_RECT, cv::Size(5, 5)); cvb::CvTracks tracks; while (!stopFlag) { if (imageDirty == 0) { usleep(100); continue; } else if (imageDirty > 1) { ROS_WARN("Skipped %d frames!", imageDirty - 1); } START_CLOCK(trackerClock) imageMutex.lock(); ((cv::Mat*) this->image)->copyTo(image); long int time = this->imageTime; imageDirty = 0; imageMutex.unlock(); if (showCameraImage) { image.copyTo(cameraImage); } createColorMapImage(image, mapImage, hsvImage); if (showMaskedImage) { // Convert to 3 channel image. int target = 0; for (int i = 0; i < mapImage.total(); ++i) { maskedImage.data[target++] = mapImage.data[i]; maskedImage.data[target++] = mapImage.data[i]; maskedImage.data[target++] = mapImage.data[i]; } } cv::morphologyEx(mapImage, mapImage, cv::MORPH_OPEN, morphKernel); // Finding blobs // Only copies headers. IplImage iplMapImage = mapImage; unsigned int result = cvLabel(&iplMapImage, labelImg, blobs); // ROS_DEBUG("Blob result: %d", result); // Filter blobs cvFilterByArea(blobs, 10, 1000000); if (showCameraImage || showMaskedImage) { cvUpdateTracks(blobs, tracks, 200., 5); } if (showMaskedImage) { // Only copies headers. IplImage iplImage = maskedImage; cvRenderBlobs(labelImg, blobs, &iplImage, &iplImage, CV_BLOB_RENDER_BOUNDING_BOX); cvRenderTracks(tracks, &iplImage, &iplImage, CV_TRACK_RENDER_ID | CV_TRACK_RENDER_BOUNDING_BOX); ROS_DEBUG("Exiting visual masked block"); // TODO Tracking down issue #7 } if (showCameraImage) { // Only copies headers. IplImage iplImage = cameraImage; cvRenderBlobs(labelImg, blobs, &iplImage, &iplImage, CV_BLOB_RENDER_BOUNDING_BOX); cvRenderTracks(tracks, &iplImage, &iplImage, CV_TRACK_RENDER_ID | CV_TRACK_RENDER_BOUNDING_BOX); ROS_DEBUG("Exiting visual masked block"); // TODO Tracking down issue #7 } if (showCameraImage || showMaskedImage) { cvReleaseTracks(tracks); } if (blobs.size() != 0) { // Find biggest blob cvb::CvLabel largestBlob = cvLargestBlob(blobs); CvPoint2D64f center = blobs.find(largestBlob)->second->centroid; double x = center.x; double y = center.y; // Set (0, 0) to center. x -= 320; y -= 240; //ROS_DEBUG("Center: %lf/%lf", x, y); // Apply scaling x *= horizontalScalingFactor; y *= verticalScalingFactor; dataReceiver->receiveTrackingData(cv::Scalar(x, y, 1.0), ((QuadcopterColor*) qc)->getId(), time); if (showMaskedImage) { drawCross(maskedImage, center.x, center.y); } if (showCameraImage) { drawCross(cameraImage, center.x, center.y); } if (!quadcopterTracked) { quadcopterTracked = true; ROS_DEBUG("Quadcopter %d tracked", ((QuadcopterColor*) this->qc)->getId()); } } else if (quadcopterTracked) { quadcopterTracked = false; ROS_DEBUG("Quadcopter %d NOT tracked", ((QuadcopterColor*) this->qc)->getId()); } // Free cvb stuff. cvReleaseBlobs(blobs); // ROS_DEBUG("cvb stuff freed"); // TODO Tracking down issue #7 if (showMaskedImage) { cv::imshow(maskedWindowName, maskedImage); ROS_DEBUG("showed masked image"); // TODO Tracking down issue #7 } if (showCameraImage) { cv::imshow(cameraWindowName, cameraImage); ROS_DEBUG("showed camera image"); // TODO Tracking down issue #7 } STOP_CLOCK(trackerClock, "Calculation of quadcopter position took: ") } cvReleaseImage(&labelImg); if (showMaskedImage) { cv::destroyWindow(maskedWindowName); } if (showCameraImage) { cv::destroyWindow(cameraWindowName); } ROS_INFO("Tracker with id %d terminated", ((QuadcopterColor*) this->qc)->getId()); } cv::Mat Tracker::createColorMapImage(cv::Mat& image, cv::Mat& mapImage, cv::Mat& hsvImage) { START_CLOCK(convertColorClock) mapImage.reserve(480); // Debug HSV color range // unsigned char* element = image->data + image->step[0] * 240 + image->step[1] * 320; // ROS_DEBUG("R: %d G: %d B: %d", element[2], element[1], element[0]); cv::cvtColor(image, hsvImage, CV_BGR2HSV); // Debug HSV color range // ROS_DEBUG("H: %d S: %d V: %d", element[0], element[1], element[2]); STOP_CLOCK(convertColorClock, "Converting colors took: ") START_CLOCK(maskImageClock) // Trying to make this fast. #ifdef QC_REGISTER register uint8_t *current, *end, *source; register int minHue, maxHue, minSaturation, /*maxSaturation,*/ minValue/*, maxValue*/; #else uint8_t *current, *end, *source; int minHue, maxHue, minSaturation, /*maxSaturation,*/ minValue/*, maxValue*/; #endif QuadcopterColor* color = (QuadcopterColor*) qc; minHue = color->getMinColor().val[0]; maxHue = color->getMaxColor().val[0]; minSaturation = color->getMinColor().val[1]; //maxSaturation = color->getMaxColor().val[1]; // unused minValue = color->getMinColor().val[2]; //maxValue = color->getMaxColor().val[2]; // unused end = mapImage.data + mapImage.size().width * mapImage.size().height; source = hsvImage.data; if (minHue < maxHue) { for (current = mapImage.data; current < end; ++current, source += 3) { //if (*source > maxHue || *source < minHue || *(++source) > maxSaturation || *source < minSaturation || *(++source) > maxValue || *(source++) < minValue) { if (*source > maxHue || *source < minHue || *(source + 1) < minSaturation || *(source + 2) < minValue) { *current = 0; } else { *current = 255; } } } else { // Hue interval inverted here. for (current = mapImage.data; current < end; ++current, source += 3) { //if (*source < maxHue || *source > minHue || *(++source) > maxSaturation || *source < minSaturation || *(++source) > maxValue || *(source++) < minValue) { if ((*source > maxHue && *source < minHue) || *(source + 1) < minSaturation || *(source + 2) < minValue) { *current = 0; } else { *current = 255; } } } STOP_CLOCK(maskImageClock, "Image masking took: ") return mapImage; } <commit_msg>Less memory management<commit_after>#include "Tracker.hpp" #include <stdexcept> #include <iostream> #include <stdlib.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <cvblob.h> #include <ros/console.h> #include <cmath> #include "profiling.hpp" // Use this to use the register keyword in some places. Might make things faster, but I didn't test it. //#define QC_REGISTER // Use this for debugging the object recognition. WARNING: Might lead to errors or strange behaviour when used with visualTracker == true. //#define QC_DEBUG_TRACKER Tracker::Tracker(ITrackerDataReceiver* dataReceiver, QuadcopterColor* color) { this->dataReceiver = dataReceiver; this->thread = 0; this->image = 0; this->qc = color; this->showCameraImage = false; this->showMaskedImage = false; } Tracker::Tracker(ITrackerDataReceiver* dataReceiver, QuadcopterColor* color, bool showCameraImage, bool showMaskedImage) { this->dataReceiver = dataReceiver; this->thread = 0; this->image = 0; this->qc = color; this->showCameraImage = showCameraImage; this->showMaskedImage = showMaskedImage; if (showMaskedImage) { std::stringstream ss; ss << "Tracker of id " << ((QuadcopterColor*) this->qc)->getId() << " showing masked image"; this->maskedWindowName = ss.str(); cv::startWindowThread(); } if (showCameraImage) { std::stringstream ss; ss << "Tracker of id " << ((QuadcopterColor*) this->qc)->getId() << " showing camera image"; this->cameraWindowName = ss.str(); cv::startWindowThread(); } } Tracker::~Tracker() { } void Tracker::start() { if (thread != 0) { throw new std::runtime_error("Already started. (Maybe you forgot to call join?)"); } if (showMaskedImage) { cv::namedWindow(maskedWindowName); } if (showCameraImage) { cv::namedWindow(cameraWindowName); } imageDirty = 0; stopFlag = false; thread = new boost::thread(boost::bind(&Tracker::executeTracker, this)); } void Tracker::stop() { if (thread == 0) { throw new std::runtime_error("Not started."); } stopFlag = true; } void Tracker::join() { if (thread != 0) { thread->join(); delete thread; thread = 0; } if (this->image != 0) { delete this->image; this->image = 0; } } bool Tracker::isStarted() { return thread != 0; } void Tracker::setNextImage(cv::Mat* image, long int time) { imageMutex.lock(); if (this->image != 0) { delete this->image; } this->image = new cv::Mat(*image); imageTime = time; imageDirty++; imageMutex.unlock(); } QuadcopterColor* Tracker::getQuadcopterColor() { return (QuadcopterColor*) qc; } void Tracker::drawCross(cv::Mat mat, const int x, const int y) { ROS_DEBUG("Drawing cross."); for (int i = x - 10; i <= x + 10; i++) { int j = y; // ROS_DEBUG("i/j: %d/%d", i, j); if (i >= 0 && i < mat.rows && j >= 0 && j < mat.cols) { unsigned char* element = mat.data + mat.step[0] * j + mat.step[1] * i; unsigned char color; if (i + j % 3 > 0) { color = 0xFF; } else { color = 0; } element[0] = color; element[1] = color; element[2] = color; } } for (int j = y - 10; j <= y + 10; j++) { int i = x; // ROS_DEBUG("i/j: %d/%d", i, j); if (i >= 0 && i < mat.rows && j >= 0 && j < mat.cols) { unsigned char* element = mat.data + mat.step[0] * j + mat.step[1] * i; unsigned char color; if (i + j % 3 > 0) { color = 0xFF; } else { color = 0; } element[0] = color; element[1] = color; element[2] = color; } } ROS_DEBUG("Cross drawed"); } void Tracker::executeTracker() { #define PI (3.1415926535897932384626433832795028841) // Kinect fow: 43° vertical, 57° horizontal double verticalScalingFactor = tan(43 * PI / 180) / 240; double horizontalScalingFactor = tan(57 * PI / 180) / 320; ROS_DEBUG("Scaling factors: %lf/%lf", horizontalScalingFactor, verticalScalingFactor); bool quadcopterTracked = false; // Images cv::Mat cameraImage(cv::Size(640, 480), CV_8UC3); cv::Mat maskedImage(cv::Size(640, 480), CV_8UC3); cv::Mat image(cv::Size(640, 480), CV_8UC3); cv::Mat mapImage(cv::Size(640, 480), CV_8UC1); cv::Mat hsvImage(cv::Size(640, 480), CV_8UC3); // CvBlob cvb::CvBlobs blobs; IplImage *labelImg = cvCreateImage(image.size(), IPL_DEPTH_LABEL, 1); cv::Mat morphKernel = cv::getStructuringElement(CV_SHAPE_RECT, cv::Size(5, 5)); cvb::CvTracks tracks; IplImage iplMapImage; while (!stopFlag) { if (imageDirty == 0) { usleep(100); continue; } else if (imageDirty > 1) { ROS_WARN("Skipped %d frames!", imageDirty - 1); } START_CLOCK(trackerClock) imageMutex.lock(); ((cv::Mat*) this->image)->copyTo(image); long int time = this->imageTime; imageDirty = 0; imageMutex.unlock(); if (showCameraImage) { image.copyTo(cameraImage); } createColorMapImage(image, mapImage, hsvImage); if (showMaskedImage) { // Convert to 3 channel image. int target = 0; for (int i = 0; i < mapImage.total(); ++i) { maskedImage.data[target++] = mapImage.data[i]; maskedImage.data[target++] = mapImage.data[i]; maskedImage.data[target++] = mapImage.data[i]; } } cv::morphologyEx(mapImage, mapImage, cv::MORPH_OPEN, morphKernel); // Finding blobs // Only copies headers. iplMapImage = mapImage; unsigned int result = cvLabel(&iplMapImage, labelImg, blobs); // ROS_DEBUG("Blob result: %d", result); // Filter blobs cvFilterByArea(blobs, 10, 1000000); if (showCameraImage || showMaskedImage) { cvUpdateTracks(blobs, tracks, 200., 5); } if (showMaskedImage) { // Only copies headers. IplImage iplImage = maskedImage; cvRenderBlobs(labelImg, blobs, &iplImage, &iplImage, CV_BLOB_RENDER_BOUNDING_BOX); cvRenderTracks(tracks, &iplImage, &iplImage, CV_TRACK_RENDER_ID | CV_TRACK_RENDER_BOUNDING_BOX); ROS_DEBUG("Exiting visual masked block"); // TODO Tracking down issue #7 } if (showCameraImage) { // Only copies headers. IplImage iplImage = cameraImage; cvRenderBlobs(labelImg, blobs, &iplImage, &iplImage, CV_BLOB_RENDER_BOUNDING_BOX); cvRenderTracks(tracks, &iplImage, &iplImage, CV_TRACK_RENDER_ID | CV_TRACK_RENDER_BOUNDING_BOX); ROS_DEBUG("Exiting visual masked block"); // TODO Tracking down issue #7 } if (showCameraImage || showMaskedImage) { cvReleaseTracks(tracks); } if (blobs.size() != 0) { // Find biggest blob cvb::CvLabel largestBlob = cvLargestBlob(blobs); CvPoint2D64f center = blobs.find(largestBlob)->second->centroid; double x = center.x; double y = center.y; // Set (0, 0) to center. x -= 320; y -= 240; //ROS_DEBUG("Center: %lf/%lf", x, y); // Apply scaling x *= horizontalScalingFactor; y *= verticalScalingFactor; dataReceiver->receiveTrackingData(cv::Scalar(x, y, 1.0), ((QuadcopterColor*) qc)->getId(), time); if (showMaskedImage) { drawCross(maskedImage, center.x, center.y); } if (showCameraImage) { drawCross(cameraImage, center.x, center.y); } if (!quadcopterTracked) { quadcopterTracked = true; ROS_DEBUG("Quadcopter %d tracked", ((QuadcopterColor*) this->qc)->getId()); } } else if (quadcopterTracked) { quadcopterTracked = false; ROS_DEBUG("Quadcopter %d NOT tracked", ((QuadcopterColor*) this->qc)->getId()); } // Free cvb stuff. cvReleaseBlobs(blobs); // ROS_DEBUG("cvb stuff freed"); // TODO Tracking down issue #7 if (showMaskedImage) { cv::imshow(maskedWindowName, maskedImage); ROS_DEBUG("showed masked image"); // TODO Tracking down issue #7 } if (showCameraImage) { cv::imshow(cameraWindowName, cameraImage); ROS_DEBUG("showed camera image"); // TODO Tracking down issue #7 } STOP_CLOCK(trackerClock, "Calculation of quadcopter position took: ") } cvReleaseImage(&labelImg); if (showMaskedImage) { cv::destroyWindow(maskedWindowName); } if (showCameraImage) { cv::destroyWindow(cameraWindowName); } ROS_INFO("Tracker with id %d terminated", ((QuadcopterColor*) this->qc)->getId()); } cv::Mat Tracker::createColorMapImage(cv::Mat& image, cv::Mat& mapImage, cv::Mat& hsvImage) { START_CLOCK(convertColorClock) mapImage.reserve(480); // Debug HSV color range // unsigned char* element = image->data + image->step[0] * 240 + image->step[1] * 320; // ROS_DEBUG("R: %d G: %d B: %d", element[2], element[1], element[0]); cv::cvtColor(image, hsvImage, CV_BGR2HSV); // Debug HSV color range // ROS_DEBUG("H: %d S: %d V: %d", element[0], element[1], element[2]); STOP_CLOCK(convertColorClock, "Converting colors took: ") START_CLOCK(maskImageClock) // Trying to make this fast. #ifdef QC_REGISTER register uint8_t *current, *end, *source; register int minHue, maxHue, minSaturation, /*maxSaturation,*/ minValue/*, maxValue*/; #else uint8_t *current, *end, *source; int minHue, maxHue, minSaturation, /*maxSaturation,*/ minValue/*, maxValue*/; #endif QuadcopterColor* color = (QuadcopterColor*) qc; minHue = color->getMinColor().val[0]; maxHue = color->getMaxColor().val[0]; minSaturation = color->getMinColor().val[1]; //maxSaturation = color->getMaxColor().val[1]; // unused minValue = color->getMinColor().val[2]; //maxValue = color->getMaxColor().val[2]; // unused end = mapImage.data + mapImage.size().width * mapImage.size().height; source = hsvImage.data; if (minHue < maxHue) { for (current = mapImage.data; current < end; ++current, source += 3) { //if (*source > maxHue || *source < minHue || *(++source) > maxSaturation || *source < minSaturation || *(++source) > maxValue || *(source++) < minValue) { if (*source > maxHue || *source < minHue || *(source + 1) < minSaturation || *(source + 2) < minValue) { *current = 0; } else { *current = 255; } } } else { // Hue interval inverted here. for (current = mapImage.data; current < end; ++current, source += 3) { //if (*source < maxHue || *source > minHue || *(++source) > maxSaturation || *source < minSaturation || *(++source) > maxValue || *(source++) < minValue) { if ((*source > maxHue && *source < minHue) || *(source + 1) < minSaturation || *(source + 2) < minValue) { *current = 0; } else { *current = 255; } } } STOP_CLOCK(maskImageClock, "Image masking took: ") return mapImage; } <|endoftext|>
<commit_before>#include "Vertex4.h" Vertex4::Vertex4(TwoParticleGF &Chi, GreensFunction &g1, GreensFunction &g2, GreensFunction &g3, GreensFunction &g4) : Chi(Chi), g1(g1), g2(g2), g3(g3), g4(g4) { ChiBit1 = Chi.getBit(0); ChiBit2 = Chi.getBit(1); ChiBit3 = Chi.getBit(2); ChiBit4 = Chi.getBit(3); if((ChiBit1 != g1.getBit(0) || ChiBit1 != g1.getBit(1)) || (ChiBit2 != g2.getBit(0) || ChiBit1 != g2.getBit(1)) || (ChiBit3 != g3.getBit(0) || ChiBit1 != g3.getBit(1)) || (ChiBit4 != g4.getBit(0) || ChiBit1 != g4.getBit(1)) ) assert(0); } ComplexType Vertex4::operator()(long MatsubaraNumber1, long MatsubaraNumber2, long MatsubaraNumber3) { ComplexType Value = Chi(MatsubaraNumber1,MatsubaraNumber2,MatsubaraNumber3); if((ChiBit1 == ChiBit3 && MatsubaraNumber1 == MatsubaraNumber3) != (ChiBit2 == ChiBit3 && MatsubaraNumber2 == MatsubaraNumber3)){ ComplexType gg = g1(MatsubaraNumber1)*g2(MatsubaraNumber2); if(ChiBit1 == ChiBit3) Value -= Chi.getBeta() * gg; else Value += Chi.getBeta() * gg; } return Value; } ComplexType Vertex4::getAmputated(long MatsubaraNumber1, long MatsubaraNumber2, long MatsubaraNumber3) { ComplexType Value = Chi(MatsubaraNumber1,MatsubaraNumber2,MatsubaraNumber3); ComplexType g1Value = g1(MatsubaraNumber1); ComplexType g2Value = g2(MatsubaraNumber2); ComplexType g3Value = g3(MatsubaraNumber3); ComplexType g4Value = g4(MatsubaraNumber1+MatsubaraNumber2-MatsubaraNumber3); if((ChiBit1 == ChiBit3 && MatsubaraNumber1 == MatsubaraNumber3) != (ChiBit2 == ChiBit3 && MatsubaraNumber2 == MatsubaraNumber3)){ if(ChiBit1 == ChiBit3) Value += Chi.getBeta() * g1Value*g2Value; else Value -= Chi.getBeta() * g1Value*g2Value; } Value /= g1Value*g2Value*g3Value*g4Value; return Value; }<commit_msg>pomerol: one more try<commit_after>#include "Vertex4.h" Vertex4::Vertex4(TwoParticleGF &Chi, GreensFunction &g1, GreensFunction &g2, GreensFunction &g3, GreensFunction &g4) : Chi(Chi), g1(g1), g2(g2), g3(g3), g4(g4) { ChiBit1 = Chi.getBit(0); ChiBit2 = Chi.getBit(1); ChiBit3 = Chi.getBit(2); ChiBit4 = Chi.getBit(3); if((ChiBit1 != g1.getBit(0) || ChiBit1 != g1.getBit(1)) || (ChiBit2 != g2.getBit(0) || ChiBit1 != g2.getBit(1)) || (ChiBit3 != g3.getBit(0) || ChiBit1 != g3.getBit(1)) || (ChiBit4 != g4.getBit(0) || ChiBit1 != g4.getBit(1)) ) assert(0); } ComplexType Vertex4::operator()(long MatsubaraNumber1, long MatsubaraNumber2, long MatsubaraNumber3) { ComplexType Value = Chi(MatsubaraNumber1,MatsubaraNumber2,MatsubaraNumber3); if((ChiBit1 == ChiBit3 && MatsubaraNumber1 == MatsubaraNumber3) != (ChiBit2 == ChiBit3 && MatsubaraNumber2 == MatsubaraNumber3)){ ComplexType gg = g1(MatsubaraNumber1)*g2(MatsubaraNumber2); if(ChiBit1 == ChiBit3) Value -= Chi.getBeta() * gg; else Value += Chi.getBeta() * gg; } return Value; } ComplexType Vertex4::getAmputated(long MatsubaraNumber1, long MatsubaraNumber2, long MatsubaraNumber3) { ComplexType Value = Chi(MatsubaraNumber1,MatsubaraNumber2,MatsubaraNumber3); ComplexType g1Value = g1(MatsubaraNumber1); ComplexType g2Value = g2(MatsubaraNumber2); ComplexType g3Value = g3(MatsubaraNumber3); ComplexType g4Value = g4(MatsubaraNumber1+MatsubaraNumber2-MatsubaraNumber3); if((ChiBit1 == ChiBit3 && MatsubaraNumber1 == MatsubaraNumber3) != (ChiBit2 == ChiBit3 && MatsubaraNumber2 == MatsubaraNumber3)){ if(ChiBit1 == ChiBit3) Value -= Chi.getBeta() * g1Value*g2Value; else Value += Chi.getBeta() * g1Value*g2Value; } Value /= g1Value*g2Value*g3Value*g4Value; return Value; }<|endoftext|>
<commit_before>#include <stdio.h> #include <string> #include <boost/python.hpp> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <fcntl.h> #include <sys/mman.h> #include <string.h> #include <math.h> #include <vector> #include <boost/random.hpp> #include <boost/random/normal_distribution.hpp> using namespace std; using namespace boost; template<typename T> struct __attribute__((__packed__)) node { /* * We store a binary tree where each node has two things * - A vector associated with it * - Two children * All nodes occupy the same amount of memory * All nodes with n_descendants == 1 are leaf nodes. * A memory optimization is that for nodes with 2 <= n_descendants <= K, * we skip the vector. Instead we store a list of all descendants. K is * determined by the number of items that fits in the same space. * For nodes with n_descendants == 1 or > K, there is always a * corresponding vector. * Note that we can't really do sizeof(node<T>) because we cheat and allocate * more memory to be able to fit the vector outside */ int n_descendants; int children[2]; // Will possibly store more than 2 T v[0]; // Hack. We just allocate as much memory as we need and let this array overflow }; template<typename T> class AnnoyIndex { /* * We use random projection to build a forest of binary trees of all items. * Basically just split the hyperspace into two sides by a hyperplane, * then recursively split each of those subtrees etc. * We create a tree like this q times. The default q is determined automatically * in such a way that we at most use 2x as much memory as the vectors take. */ int _f; size_t _s; int _n_items; mt19937 _rng; normal_distribution<T> _nd; variate_generator<mt19937&, normal_distribution<T> > _var_nor; void* _nodes; // Could either be mmapped, or point to a memory buffer that we reallocate int _n_nodes; int _nodes_size; vector<int> _roots; int _K; bool _loaded; public: AnnoyIndex(int f) : _rng(), _nd(), _var_nor(_rng, _nd) { _f = f; _s = sizeof(node<T>) + sizeof(T) * f; // Size of each node _n_items = 0; _n_nodes = 0; _nodes_size = 0; _nodes = NULL; _loaded = false; _K = (sizeof(T) * f + sizeof(int) * 2) / sizeof(int); printf("K = %d\n", _K); } ~AnnoyIndex() { if (!_loaded && _nodes) { free(_nodes); } } void add_item(int item, const python::list& v) { _allocate_size(item+1); node<T>* n = _get(item); n->children[0] = 0; n->children[1] = 0; n->n_descendants = 1; for (int z = 0; z < _f; z++) n->v[z] = python::extract<T>(v[z]); if (item >= _n_items) _n_items = item + 1; } void build(int q) { _n_nodes = _n_items; while (1) { if (q == -1 && _n_nodes >= _n_items * 2) break; if (q != -1 && _roots.size() >= q) break; printf("pass %d...\n", _roots.size()); vector<int> indices; for (int i = 0; i < _n_items; i++) indices.push_back(i); _roots.push_back(_make_tree(indices)); } printf("has %d nodes\n", _n_nodes); } void save(const string& filename) { FILE *f = fopen(filename.c_str(), "w"); fwrite(_nodes, _s, _n_nodes, f); fclose(f); free(_nodes); _n_items = 0; _n_nodes = 0; _nodes_size = 0; _nodes = NULL; _roots.clear(); load(filename); } void load(const string& filename) { struct stat buf; stat(filename.c_str(), &buf); int size = buf.st_size; printf("size = %d\n", size); int fd = open(filename.c_str(), O_RDONLY, (mode_t)0400); printf("fd = %d\n", fd); _nodes = (node<T>*)mmap(0, size, PROT_READ, MAP_SHARED, fd, 0); int n = size / _s; printf("%d nodes\n", n); // Find the nodes with the largest number of descendants. These are the roots int m = 0; for (int i = 0; i < n; i++) { if (_get(i)->n_descendants > m) { _roots.clear(); m = _get(i)->n_descendants; } if (_get(i)->n_descendants == m) { _roots.push_back(i); } } _loaded = true; printf("found %lu roots with degree %d\n", _roots.size(), m); } inline T _cos(const T* x, const T* y) { T pp = 0, qq = 0, pq = 0; for (int z = 0; z < _f; z++) { pp += x[z] * x[z]; qq += y[z] * y[z]; pq += x[z] * y[z]; } T ppqq = pp * qq; if (ppqq > 0) return pq / sqrt(ppqq); else return 0.0; } inline T cos(int i, int j) { const T* x = _get(i)->v; const T* y = _get(j)->v; return _cos(x, y); } python::list get_nns_by_item(int item, int n) { const node<T>* m = _get(item); return _get_all_nns(m->v, n); } python::list get_nns_by_vector(python::list v, int n) { vector<T> w(_f); for (int z = 0; z < _f; z++) w[z] = python::extract<T>(v[z]); return _get_all_nns(&w[0], n); } private: void _allocate_size(int n) { if (n > _nodes_size) { int new_nodes_size = (_nodes_size + 1) * 2; if (n > new_nodes_size) new_nodes_size = n; printf("reallocating to %d nodes\n", new_nodes_size); _nodes = realloc(_nodes, _s * new_nodes_size); memset(_nodes + _nodes_size * _s, 0, (new_nodes_size - _nodes_size) * _s); _nodes_size = new_nodes_size; } } inline node<T>* _get(int i) { return (node<T>*)(_nodes + _s * i); } int _make_tree(const vector<int >& indices) { if (indices.size() == 1) return indices[0]; _allocate_size(_n_nodes + 1); int item = _n_nodes++; node<T>* m = _get(item); m->n_descendants = indices.size(); if (indices.size() <= _K) { for (int i = 0; i < indices.size(); i++) m->children[i] = indices[i]; return item; } vector<int> children_indices[2]; for (int attempt = 0; attempt < 20; attempt ++) { /* * Create a random hyperplane. * If all points end up on the same time, we try again. * We could in principle *construct* a plane so that we split * all items evenly, but I think that could violate the guarantees * given by just picking a hyperplane at random */ for (int z = 0; z < _f; z++) m->v[z] = _var_nor(); children_indices[0].clear(); children_indices[1].clear(); for (int i = 0; i < indices.size(); i++) { int j = indices[i]; node<T>* n = _get(j); if (!n) { printf("node %d undef...\n", j); continue; } T dot = 0; for (int z = 0; z < _f; z++) { dot += m->v[z] * n->v[z]; } while (dot == 0) dot = _var_nor(); children_indices[dot > 0].push_back(j); } if (children_indices[0].size() > 0 && children_indices[1].size() > 0) { if (indices.size() > 100000) printf("Split %lu items -> %lu, %lu (attempt %d)\n", indices.size(), children_indices[0].size(), children_indices[1].size(), attempt); break; } } while (children_indices[0].size() == 0 || children_indices[1].size() == 0) { // If we didn't find a hyperplane, just randomize sides as a last option if (indices.size() > 100000) printf("Failed splitting %lu items\n", indices.size()); children_indices[0].clear(); children_indices[1].clear(); // Set the vector to 0.0 for (int z = 0; z < _f; z++) m->v[z] = 0.0; for (int i = 0; i < indices.size(); i++) { int j = indices[i]; // Just randomize... children_indices[_var_nor() > 0].push_back(j); } } int children_0 = _make_tree(children_indices[0]); int children_1 = _make_tree(children_indices[1]); // We need to fetch m again because it might have been reallocated m = _get(item); m->children[0] = children_0; m->children[1] = children_1; return item; } void _get_nns(const T* v, int i, vector<int>* result, int limit) { const node<T>* n = _get(i); if (n->n_descendants == 0) { // unknown item, nothing to do... } else if (n->n_descendants == 1) { result->push_back(i); } else if (n->n_descendants <= _K) { for (int j = 0; j < n->n_descendants; j++) { result->push_back(n->children[j]); } } else { T dot = 0; for (int z = 0; z < _f; z++) dot += v[z] * n->v[z]; while (dot == 0) // Randomize side if the dot product is zero dot = _var_nor(); _get_nns(v, n->children[dot > 0], result, limit); if (result->size() < limit) _get_nns(v, n->children[dot < 0], result, limit); } } python::list _get_all_nns(const T* v, int n) { vector<pair<T, int> > nns_cos; for (int i = 0; i < _roots.size(); i++) { vector<int> nns; _get_nns(v, _roots[i], &nns, n); for (int j = 0; j < nns.size(); j++) { nns_cos.push_back(make_pair(_cos(v, _get(nns[j])->v), nns[j])); } } sort(nns_cos.begin(), nns_cos.end()); int last = -1, length=0; python::list l; for (int i = nns_cos.size() - 1; i >= 0 && length < n; i--) { if (nns_cos[i].second != last) { l.append(nns_cos[i].second); last = nns_cos[i].second; length++; } } return l; } }; BOOST_PYTHON_MODULE(annoylib) { python::class_<AnnoyIndex<float> >("AnnoyIndex", python::init<int>()) .def("add_item", &AnnoyIndex<float>::add_item) .def("build", &AnnoyIndex<float>::build) .def("save", &AnnoyIndex<float>::save) .def("load", &AnnoyIndex<float>::load) .def("cos", &AnnoyIndex<float>::cos) .def("get_nns_by_item", &AnnoyIndex<float>::get_nns_by_item) .def("get_nns_by_vector", &AnnoyIndex<float>::get_nns_by_vector); } <commit_msg>fixed some type issues, including one causing problems for files > 2GB<commit_after>#include <stdio.h> #include <string> #include <boost/python.hpp> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <fcntl.h> #include <sys/mman.h> #include <string.h> #include <math.h> #include <vector> #include <boost/random.hpp> #include <boost/random/normal_distribution.hpp> using namespace std; using namespace boost; template<typename T> struct __attribute__((__packed__)) node { /* * We store a binary tree where each node has two things * - A vector associated with it * - Two children * All nodes occupy the same amount of memory * All nodes with n_descendants == 1 are leaf nodes. * A memory optimization is that for nodes with 2 <= n_descendants <= K, * we skip the vector. Instead we store a list of all descendants. K is * determined by the number of items that fits in the same space. * For nodes with n_descendants == 1 or > K, there is always a * corresponding vector. * Note that we can't really do sizeof(node<T>) because we cheat and allocate * more memory to be able to fit the vector outside */ int n_descendants; int children[2]; // Will possibly store more than 2 T v[0]; // Hack. We just allocate as much memory as we need and let this array overflow }; template<typename T> class AnnoyIndex { /* * We use random projection to build a forest of binary trees of all items. * Basically just split the hyperspace into two sides by a hyperplane, * then recursively split each of those subtrees etc. * We create a tree like this q times. The default q is determined automatically * in such a way that we at most use 2x as much memory as the vectors take. */ int _f; size_t _s; int _n_items; mt19937 _rng; normal_distribution<T> _nd; variate_generator<mt19937&, normal_distribution<T> > _var_nor; void* _nodes; // Could either be mmapped, or point to a memory buffer that we reallocate int _n_nodes; int _nodes_size; vector<int> _roots; int _K; bool _loaded; public: AnnoyIndex(int f) : _rng(), _nd(), _var_nor(_rng, _nd) { _f = f; _s = sizeof(node<T>) + sizeof(T) * f; // Size of each node _n_items = 0; _n_nodes = 0; _nodes_size = 0; _nodes = NULL; _loaded = false; _K = (sizeof(T) * f + sizeof(int) * 2) / sizeof(int); } ~AnnoyIndex() { if (!_loaded && _nodes) { free(_nodes); } } void add_item(int item, const python::list& v) { _allocate_size(item+1); node<T>* n = _get(item); n->children[0] = 0; n->children[1] = 0; n->n_descendants = 1; for (int z = 0; z < _f; z++) n->v[z] = python::extract<T>(v[z]); if (item >= _n_items) _n_items = item + 1; } void build(int q) { _n_nodes = _n_items; while (1) { if (q == -1 && _n_nodes >= _n_items * 2) break; if (q != -1 && _roots.size() >= (size_t)q) break; printf("pass %zd...\n", _roots.size()); vector<int> indices; for (int i = 0; i < _n_items; i++) indices.push_back(i); _roots.push_back(_make_tree(indices)); } printf("has %d nodes\n", _n_nodes); } void save(const string& filename) { FILE *f = fopen(filename.c_str(), "w"); fwrite(_nodes, _s, _n_nodes, f); fclose(f); free(_nodes); _n_items = 0; _n_nodes = 0; _nodes_size = 0; _nodes = NULL; _roots.clear(); load(filename); } void load(const string& filename) { struct stat buf; stat(filename.c_str(), &buf); off_t size = buf.st_size; printf("size = %jd\n", (intmax_t)size); // http://stackoverflow.com/questions/586928/how-should-i-print-types-like-off-t-and-size-t int fd = open(filename.c_str(), O_RDONLY, (mode_t)0400); printf("fd = %d\n", fd); _nodes = (node<T>*)mmap(0, size, PROT_READ, MAP_SHARED, fd, 0); int n = size / _s; printf("%d nodes\n", n); // Find the nodes with the largest number of descendants. These are the roots int m = 0; for (int i = 0; i < n; i++) { if (_get(i)->n_descendants > m) { _roots.clear(); m = _get(i)->n_descendants; } if (_get(i)->n_descendants == m) { _roots.push_back(i); } } _loaded = true; printf("found %lu roots with degree %d\n", _roots.size(), m); } inline T _cos(const T* x, const T* y) { T pp = 0, qq = 0, pq = 0; for (int z = 0; z < _f; z++) { pp += x[z] * x[z]; qq += y[z] * y[z]; pq += x[z] * y[z]; } T ppqq = pp * qq; if (ppqq > 0) return pq / sqrt(ppqq); else return 0.0; } inline T cos(int i, int j) { const T* x = _get(i)->v; const T* y = _get(j)->v; return _cos(x, y); } python::list get_nns_by_item(int item, int n) { const node<T>* m = _get(item); return _get_all_nns(m->v, n); } python::list get_nns_by_vector(python::list v, int n) { vector<T> w(_f); for (int z = 0; z < _f; z++) w[z] = python::extract<T>(v[z]); return _get_all_nns(&w[0], n); } private: void _allocate_size(int n) { if (n > _nodes_size) { int new_nodes_size = (_nodes_size + 1) * 2; if (n > new_nodes_size) new_nodes_size = n; printf("reallocating to %d nodes\n", new_nodes_size); _nodes = realloc(_nodes, _s * new_nodes_size); memset((char *)_nodes + (_nodes_size * _s)/sizeof(char), 0, (new_nodes_size - _nodes_size) * _s); _nodes_size = new_nodes_size; } } inline node<T>* _get(int i) { return (node<T>*)((char *)_nodes + (_s * i)/sizeof(char)); } int _make_tree(const vector<int >& indices) { if (indices.size() == 1) return indices[0]; _allocate_size(_n_nodes + 1); int item = _n_nodes++; node<T>* m = _get(item); m->n_descendants = indices.size(); if (indices.size() <= (size_t)_K) { for (size_t i = 0; i < indices.size(); i++) m->children[i] = indices[i]; return item; } vector<int> children_indices[2]; for (int attempt = 0; attempt < 20; attempt ++) { /* * Create a random hyperplane. * If all points end up on the same time, we try again. * We could in principle *construct* a plane so that we split * all items evenly, but I think that could violate the guarantees * given by just picking a hyperplane at random */ for (int z = 0; z < _f; z++) m->v[z] = _var_nor(); children_indices[0].clear(); children_indices[1].clear(); for (size_t i = 0; i < indices.size(); i++) { int j = indices[i]; node<T>* n = _get(j); if (!n) { printf("node %d undef...\n", j); continue; } T dot = 0; for (int z = 0; z < _f; z++) { dot += m->v[z] * n->v[z]; } while (dot == 0) dot = _var_nor(); children_indices[dot > 0].push_back(j); } if (children_indices[0].size() > 0 && children_indices[1].size() > 0) { if (indices.size() > 100000) printf("Split %lu items -> %lu, %lu (attempt %d)\n", indices.size(), children_indices[0].size(), children_indices[1].size(), attempt); break; } } while (children_indices[0].size() == 0 || children_indices[1].size() == 0) { // If we didn't find a hyperplane, just randomize sides as a last option if (indices.size() > 100000) printf("Failed splitting %lu items\n", indices.size()); children_indices[0].clear(); children_indices[1].clear(); // Set the vector to 0.0 for (int z = 0; z < _f; z++) m->v[z] = 0.0; for (size_t i = 0; i < indices.size(); i++) { int j = indices[i]; // Just randomize... children_indices[_var_nor() > 0].push_back(j); } } int children_0 = _make_tree(children_indices[0]); int children_1 = _make_tree(children_indices[1]); // We need to fetch m again because it might have been reallocated m = _get(item); m->children[0] = children_0; m->children[1] = children_1; return item; } void _get_nns(const T* v, int i, vector<int>* result, int limit) { const node<T>* n = _get(i); if (n->n_descendants == 0) { // unknown item, nothing to do... } else if (n->n_descendants == 1) { result->push_back(i); } else if (n->n_descendants <= _K) { for (int j = 0; j < n->n_descendants; j++) { result->push_back(n->children[j]); } } else { T dot = 0; for (int z = 0; z < _f; z++) dot += v[z] * n->v[z]; while (dot == 0) // Randomize side if the dot product is zero dot = _var_nor(); _get_nns(v, n->children[dot > 0], result, limit); if (result->size() < (size_t)limit) _get_nns(v, n->children[dot < 0], result, limit); } } python::list _get_all_nns(const T* v, int n) { vector<pair<T, int> > nns_cos; for (size_t i = 0; i < _roots.size(); i++) { vector<int> nns; _get_nns(v, _roots[i], &nns, n); for (size_t j = 0; j < nns.size(); j++) { nns_cos.push_back(make_pair(_cos(v, _get(nns[j])->v), nns[j])); } } sort(nns_cos.begin(), nns_cos.end()); int last = -1, length=0; python::list l; for (size_t i = nns_cos.size() - 1; i >= 0 && length < n; i--) { if (nns_cos[i].second != last) { l.append(nns_cos[i].second); last = nns_cos[i].second; length++; } } return l; } }; BOOST_PYTHON_MODULE(annoylib) { python::class_<AnnoyIndex<float> >("AnnoyIndex", python::init<int>()) .def("add_item", &AnnoyIndex<float>::add_item) .def("build", &AnnoyIndex<float>::build) .def("save", &AnnoyIndex<float>::save) .def("load", &AnnoyIndex<float>::load) .def("cos", &AnnoyIndex<float>::cos) .def("get_nns_by_item", &AnnoyIndex<float>::get_nns_by_item) .def("get_nns_by_vector", &AnnoyIndex<float>::get_nns_by_vector); } <|endoftext|>
<commit_before>#include <thread> #include <iostream> #include "processor.h" #ifdef WINDOWS #include <windows.h> #else #include <unistd.h> #endif const uint MILLIS_IN_MICRO = 1000; void sleep_for_millis(uint period) { #ifdef WINDOWS Sleep(period); #else usleep(period * MILLIS_IN_MICRO); #endif } TRACE_DEFINE_BEGIN(Processor, kTraceProcessorTotal) TRACE_DEFINE("start processor") TRACE_DEFINE("stop processor") TRACE_DEFINE("chech that processor is running") TRACE_DEFINE_END(Processor, kTraceProcessorTotal); void Processor::run() { int popped = 0; while (true) { while (buffer_.pop()) { ++popped; } if (popped > 200) { if (!handler_.updateSigprofInterval()) { break; } popped = 0; } if (!isRunning_.load()) { break; } sleep_for_millis(interval_); } handler_.stopSigprof(); workerDone.clear(std::memory_order_relaxed); // no shared data access after this point, can be safely deleted } void callbackToRunProcessor(jvmtiEnv *jvmti_env, JNIEnv *jni_env, void *arg) { IMPLICITLY_USE(jvmti_env); IMPLICITLY_USE(jni_env); //Avoid having the processor thread also receive the PROF signals sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGPROF); if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) { logError("ERROR: failed to set processor thread signal mask\n"); } Processor *processor = (Processor *) arg; processor->run(); } void Processor::start(JNIEnv *jniEnv) { TRACE(Processor, kTraceProcessorStart); jvmtiError result; std::cout << "Starting sampling\n"; isRunning_.store(true); workerDone.test_and_set(std::memory_order_relaxed); // initial is true jthread thread = newThread(jniEnv, "Honest Profiler Processing Thread"); jvmtiStartFunction callback = callbackToRunProcessor; result = jvmti_->RunAgentThread(thread, callback, this, JVMTI_THREAD_NORM_PRIORITY); if (result != JVMTI_ERROR_NONE) { logError("ERROR: Running agent thread failed with: %d\n", result); } } void Processor::stop() { TRACE(Processor, kTraceProcessorStop); isRunning_.store(false); std::cout << "Stopping sampling\n"; while (workerDone.test_and_set(std::memory_order_relaxed)) sched_yield(); } bool Processor::isRunning() const { TRACE(Processor, kTraceProcessorRunning); return isRunning_.load(); } <commit_msg>Processor::isRunning flag reads/writes use relaxed memory order<commit_after>#include <thread> #include <iostream> #include "processor.h" #ifdef WINDOWS #include <windows.h> #else #include <unistd.h> #endif const uint MILLIS_IN_MICRO = 1000; void sleep_for_millis(uint period) { #ifdef WINDOWS Sleep(period); #else usleep(period * MILLIS_IN_MICRO); #endif } TRACE_DEFINE_BEGIN(Processor, kTraceProcessorTotal) TRACE_DEFINE("start processor") TRACE_DEFINE("stop processor") TRACE_DEFINE("chech that processor is running") TRACE_DEFINE_END(Processor, kTraceProcessorTotal); void Processor::run() { int popped = 0; while (true) { while (buffer_.pop()) { ++popped; } if (popped > 200) { if (!handler_.updateSigprofInterval()) { break; } popped = 0; } if (!isRunning_.load(std::memory_order_relaxed)) { break; } sleep_for_millis(interval_); } handler_.stopSigprof(); workerDone.clear(std::memory_order_relaxed); // no shared data access after this point, can be safely deleted } void callbackToRunProcessor(jvmtiEnv *jvmti_env, JNIEnv *jni_env, void *arg) { IMPLICITLY_USE(jvmti_env); IMPLICITLY_USE(jni_env); //Avoid having the processor thread also receive the PROF signals sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGPROF); if (pthread_sigmask(SIG_BLOCK, &mask, NULL) < 0) { logError("ERROR: failed to set processor thread signal mask\n"); } Processor *processor = (Processor *) arg; processor->run(); } void Processor::start(JNIEnv *jniEnv) { TRACE(Processor, kTraceProcessorStart); jvmtiError result; std::cout << "Starting sampling\n"; isRunning_.store(true, std::memory_order_relaxed); workerDone.test_and_set(std::memory_order_relaxed); // initial is true jthread thread = newThread(jniEnv, "Honest Profiler Processing Thread"); jvmtiStartFunction callback = callbackToRunProcessor; result = jvmti_->RunAgentThread(thread, callback, this, JVMTI_THREAD_NORM_PRIORITY); if (result != JVMTI_ERROR_NONE) { logError("ERROR: Running agent thread failed with: %d\n", result); } } void Processor::stop() { TRACE(Processor, kTraceProcessorStop); isRunning_.store(false, std::memory_order_relaxed); std::cout << "Stopping sampling\n"; while (workerDone.test_and_set(std::memory_order_relaxed)) sched_yield(); } bool Processor::isRunning() const { TRACE(Processor, kTraceProcessorRunning); return isRunning_.load(std::memory_order_relaxed); } <|endoftext|>
<commit_before>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * 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 * FOUNDATION 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 "direct.hxx" #include "bp_cmdline.hxx" #include "bp_instance.hxx" #include "bp_connection.hxx" #include "bp_worker.hxx" #include "bp_global.hxx" #include "crash.hxx" #include "pool.hxx" #include "fb_pool.hxx" #include "session_manager.hxx" #include "session_save.hxx" #include "tcp_stock.hxx" #include "translation/Stock.hxx" #include "translation/Cache.hxx" #include "tcp_balancer.hxx" #include "memcached/memcached_stock.hxx" #include "stock/MapStock.hxx" #include "http_cache.hxx" #include "lhttp_stock.hxx" #include "fcgi/Stock.hxx" #include "was/Stock.hxx" #include "delegate/Stock.hxx" #include "fcache.hxx" #include "thread_pool.hxx" #include "stopwatch.hxx" #include "failure.hxx" #include "bulldog.hxx" #include "balancer.hxx" #include "pipe_stock.hxx" #include "nfs/Stock.hxx" #include "nfs/Cache.hxx" #include "DirectResourceLoader.hxx" #include "CachedResourceLoader.hxx" #include "FilterResourceLoader.hxx" #include "bp_control.hxx" #include "access_log/Glue.hxx" #include "ua_classification.hxx" #include "ssl/ssl_init.hxx" #include "ssl/ssl_client.hxx" #include "system/SetupProcess.hxx" #include "system/ProcessName.hxx" #include "system/Error.hxx" #include "capabilities.hxx" #include "spawn/Local.hxx" #include "spawn/Glue.hxx" #include "spawn/Client.hxx" #include "event/Duration.hxx" #include "address_list.hxx" #include "net/SocketAddress.hxx" #include "net/StaticSocketAddress.hxx" #include "net/ServerSocket.hxx" #include "util/Macros.hxx" #include "util/PrintException.hxx" #include <daemon/log.h> #include <systemd/sd-daemon.h> #include <assert.h> #include <string.h> #include <unistd.h> #include <sys/signal.h> #include <stdlib.h> #include <stdio.h> #ifndef NDEBUG bool debug_mode = false; #endif static constexpr cap_value_t cap_keep_list[] = { /* allow libnfs to bind to privileged ports, which in turn allows disabling the "insecure" flag on the NFS server */ CAP_NET_BIND_SERVICE, }; void BpInstance::EnableListeners() { for (auto &listener : listeners) listener.AddEvent(); } void BpInstance::DisableListeners() { for (auto &listener : listeners) listener.RemoveEvent(); } void BpInstance::ShutdownCallback() { if (should_exit) return; should_exit = true; DisableSignals(); thread_pool_stop(); spawn->Shutdown(); listeners.clear(); connections.clear_and_dispose(BpConnection::Disposer()); pool_commit(); avahi_client.Close(); compress_timer.Cancel(); spawn_worker_event.Cancel(); child_process_registry.SetVolatile(); thread_pool_join(); KillAllWorkers(); background_manager.AbortAll(); session_save_timer.Cancel(); session_save_deinit(); session_manager_deinit(); FreeStocksAndCaches(); local_control_handler_deinit(this); global_control_handler_deinit(this); pool_commit(); } void BpInstance::ReloadEventCallback(int) { daemon_log(3, "caught SIGHUP, flushing all caches (pid=%d)\n", (int)getpid()); translate_cache_flush(*translate_cache); http_cache_flush(*http_cache); if (filter_cache != nullptr) filter_cache_flush(*filter_cache); Compress(); } void BpInstance::EnableSignals() { shutdown_listener.Enable(); sighup_event.Enable(); } void BpInstance::DisableSignals() { shutdown_listener.Disable(); sighup_event.Disable(); } void BpInstance::AddListener(const BpConfig::Listener &c) { listeners.emplace_front(*this, c.tag.empty() ? nullptr : c.tag.c_str()); auto &listener = listeners.front(); const char *const interface = c.GetInterface(); listener.Listen(c.bind_address, c.reuse_port, c.free_bind, interface); listener.SetTcpDeferAccept(10); if (!c.zeroconf_service.empty()) { /* ask the kernel for the effective address via getsockname(), because it may have changed, e.g. if the kernel has selected a port for us */ const auto local_address = listener.GetLocalAddress(); if (local_address.IsDefined()) avahi_client.AddService(c.zeroconf_service.c_str(), interface, local_address); } } void BpInstance::AddTcpListener(int port) { listeners.emplace_front(*this, nullptr); auto &listener = listeners.front(); listener.ListenTCP(port); listener.SetTcpDeferAccept(10); } int main(int argc, char **argv) try { InitProcessName(argc, argv); #ifndef NDEBUG if (geteuid() != 0) debug_mode = true; #endif const ScopeFbPoolInit fb_pool_init; BpInstance instance; /* configuration */ ParseCommandLine(instance.cmdline, instance.config, argc, argv); if (instance.cmdline.config_file != nullptr) LoadConfigFile(instance.config, instance.cmdline.config_file); if (instance.config.ports.empty() && instance.config.listen.empty()) instance.config.ports.push_back(debug_mode ? 8080 : 80); /* initialize */ if (instance.config.stopwatch) stopwatch_enable(); SetupProcess(); const ScopeSslGlobalInit ssl_init; ssl_client_init(); direct_global_init(); instance.EnableSignals(); for (auto i : instance.config.ports) instance.AddTcpListener(i); for (const auto &i : instance.config.listen) instance.AddListener(i); global_control_handler_init(&instance); if (instance.config.num_workers == 1) /* in single-worker mode with watchdog master process, let only the one worker handle control commands */ global_control_handler_disable(instance); /* note: this function call passes a temporary SpawnConfig copy, because the reference will be evaluated in the child process after ~BpInstance() has been called */ instance.spawn = StartSpawnServer(SpawnConfig(instance.config.spawn), instance.child_process_registry, nullptr, [&instance](){ instance.event_loop.Reinit(); global_control_handler_deinit(&instance); instance.listeners.clear(); instance.DisableSignals(); instance.~BpInstance(); }); instance.spawn_service = instance.spawn; if (!crash_global_init()) { fprintf(stderr, "crash_global_init() failed\n"); return EXIT_FAILURE; } session_manager_init(instance.event_loop, instance.config.session_idle_timeout, instance.config.cluster_size, instance.config.cluster_node); if (!instance.config.session_save_path.empty()) { session_save_init(instance.config.session_save_path.c_str()); instance.ScheduleSaveSessions(); } local_control_handler_init(&instance); try { local_control_handler_open(&instance); } catch (const std::exception &e) { PrintException(e); } instance.balancer = balancer_new(instance.event_loop); instance.tcp_stock = new TcpStock(instance.event_loop, instance.config.tcp_stock_limit); instance.tcp_balancer = tcp_balancer_new(*instance.tcp_stock, *instance.balancer); const AddressList memcached_server(ShallowCopy(), instance.config.memcached_server); if (!instance.config.memcached_server.empty()) instance.memcached_stock = memcached_stock_new(instance.event_loop, *instance.tcp_balancer, memcached_server); if (instance.config.translation_socket != nullptr) { instance.translate_stock = tstock_new(instance.event_loop, instance.config.translation_socket, instance.config.translate_stock_limit); instance.translate_cache = translate_cache_new(instance.root_pool, instance.event_loop, *instance.translate_stock, instance.config.translate_cache_size, false); } instance.lhttp_stock = lhttp_stock_new(0, 16, instance.event_loop, *instance.spawn_service); instance.fcgi_stock = fcgi_stock_new(instance.config.fcgi_stock_limit, instance.config.fcgi_stock_max_idle, instance.event_loop, *instance.spawn_service); instance.was_stock = was_stock_new(instance.config.was_stock_limit, instance.config.was_stock_max_idle, instance.event_loop, *instance.spawn_service); instance.delegate_stock = delegate_stock_new(instance.event_loop, *instance.spawn_service); instance.nfs_stock = nfs_stock_new(instance.event_loop, instance.root_pool); instance.nfs_cache = nfs_cache_new(instance.root_pool, instance.config.nfs_cache_size, *instance.nfs_stock, instance.event_loop); instance.direct_resource_loader = new DirectResourceLoader(instance.event_loop, instance.tcp_balancer, *instance.spawn_service, instance.lhttp_stock, instance.fcgi_stock, instance.was_stock, instance.delegate_stock, instance.nfs_cache); instance.http_cache = http_cache_new(instance.root_pool, instance.config.http_cache_size, instance.memcached_stock, instance.event_loop, *instance.direct_resource_loader); instance.cached_resource_loader = new CachedResourceLoader(*instance.http_cache); instance.pipe_stock = pipe_stock_new(instance.event_loop); if (instance.config.filter_cache_size > 0) { instance.filter_cache = filter_cache_new(instance.root_pool, instance.config.filter_cache_size, instance.event_loop, *instance.direct_resource_loader); instance.filter_resource_loader = new FilterResourceLoader(*instance.filter_cache); } else instance.filter_resource_loader = instance.direct_resource_loader; const ScopeFailureInit failure; bulldog_init(instance.config.bulldog_path); global_translate_cache = instance.translate_cache; global_pipe_stock = instance.pipe_stock; /* launch the access logger */ instance.access_log.reset(AccessLogGlue::Create(instance.config.access_log, &instance.cmdline.logger_user)); /* daemonize II */ if (!instance.cmdline.user.IsEmpty()) capabilities_pre_setuid(); instance.cmdline.user.Apply(); if (!instance.cmdline.user.IsEmpty()) capabilities_post_setuid(cap_keep_list, ARRAY_SIZE(cap_keep_list)); /* create worker processes */ if (instance.config.num_workers > 0) { /* the master process shouldn't work */ instance.DisableListeners(); /* spawn the first worker really soon */ instance.spawn_worker_event.Add(EventDuration<0, 10000>::value); } else { instance.InitWorker(); } /* tell systemd we're ready */ sd_notify(0, "READY=1"); /* main loop */ instance.event_loop.Dispatch(); /* cleanup */ bulldog_deinit(); delete instance.spawn; thread_pool_deinit(); ssl_client_deinit(); crash_global_deinit(); ua_classification_deinit(); } catch (const std::exception &e) { PrintException(e); return EXIT_FAILURE; } <commit_msg>bp_main: use the Logger library instead of libdaemon<commit_after>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * 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 * FOUNDATION 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 "direct.hxx" #include "bp_cmdline.hxx" #include "bp_instance.hxx" #include "bp_connection.hxx" #include "bp_worker.hxx" #include "bp_global.hxx" #include "crash.hxx" #include "pool.hxx" #include "fb_pool.hxx" #include "session_manager.hxx" #include "session_save.hxx" #include "tcp_stock.hxx" #include "translation/Stock.hxx" #include "translation/Cache.hxx" #include "tcp_balancer.hxx" #include "memcached/memcached_stock.hxx" #include "stock/MapStock.hxx" #include "http_cache.hxx" #include "lhttp_stock.hxx" #include "fcgi/Stock.hxx" #include "was/Stock.hxx" #include "delegate/Stock.hxx" #include "fcache.hxx" #include "thread_pool.hxx" #include "stopwatch.hxx" #include "failure.hxx" #include "bulldog.hxx" #include "balancer.hxx" #include "pipe_stock.hxx" #include "nfs/Stock.hxx" #include "nfs/Cache.hxx" #include "DirectResourceLoader.hxx" #include "CachedResourceLoader.hxx" #include "FilterResourceLoader.hxx" #include "bp_control.hxx" #include "access_log/Glue.hxx" #include "ua_classification.hxx" #include "ssl/ssl_init.hxx" #include "ssl/ssl_client.hxx" #include "system/SetupProcess.hxx" #include "system/ProcessName.hxx" #include "system/Error.hxx" #include "capabilities.hxx" #include "spawn/Local.hxx" #include "spawn/Glue.hxx" #include "spawn/Client.hxx" #include "event/Duration.hxx" #include "address_list.hxx" #include "net/SocketAddress.hxx" #include "net/StaticSocketAddress.hxx" #include "net/ServerSocket.hxx" #include "io/Logger.hxx" #include "util/Macros.hxx" #include "util/PrintException.hxx" #include <systemd/sd-daemon.h> #include <assert.h> #include <string.h> #include <unistd.h> #include <sys/signal.h> #include <stdlib.h> #include <stdio.h> #ifndef NDEBUG bool debug_mode = false; #endif static constexpr cap_value_t cap_keep_list[] = { /* allow libnfs to bind to privileged ports, which in turn allows disabling the "insecure" flag on the NFS server */ CAP_NET_BIND_SERVICE, }; void BpInstance::EnableListeners() { for (auto &listener : listeners) listener.AddEvent(); } void BpInstance::DisableListeners() { for (auto &listener : listeners) listener.RemoveEvent(); } void BpInstance::ShutdownCallback() { if (should_exit) return; should_exit = true; DisableSignals(); thread_pool_stop(); spawn->Shutdown(); listeners.clear(); connections.clear_and_dispose(BpConnection::Disposer()); pool_commit(); avahi_client.Close(); compress_timer.Cancel(); spawn_worker_event.Cancel(); child_process_registry.SetVolatile(); thread_pool_join(); KillAllWorkers(); background_manager.AbortAll(); session_save_timer.Cancel(); session_save_deinit(); session_manager_deinit(); FreeStocksAndCaches(); local_control_handler_deinit(this); global_control_handler_deinit(this); pool_commit(); } void BpInstance::ReloadEventCallback(int) { LogConcat(3, "main", "caught SIGHUP, flushing all caches (pid=", (int)getpid(), ")"); translate_cache_flush(*translate_cache); http_cache_flush(*http_cache); if (filter_cache != nullptr) filter_cache_flush(*filter_cache); Compress(); } void BpInstance::EnableSignals() { shutdown_listener.Enable(); sighup_event.Enable(); } void BpInstance::DisableSignals() { shutdown_listener.Disable(); sighup_event.Disable(); } void BpInstance::AddListener(const BpConfig::Listener &c) { listeners.emplace_front(*this, c.tag.empty() ? nullptr : c.tag.c_str()); auto &listener = listeners.front(); const char *const interface = c.GetInterface(); listener.Listen(c.bind_address, c.reuse_port, c.free_bind, interface); listener.SetTcpDeferAccept(10); if (!c.zeroconf_service.empty()) { /* ask the kernel for the effective address via getsockname(), because it may have changed, e.g. if the kernel has selected a port for us */ const auto local_address = listener.GetLocalAddress(); if (local_address.IsDefined()) avahi_client.AddService(c.zeroconf_service.c_str(), interface, local_address); } } void BpInstance::AddTcpListener(int port) { listeners.emplace_front(*this, nullptr); auto &listener = listeners.front(); listener.ListenTCP(port); listener.SetTcpDeferAccept(10); } int main(int argc, char **argv) try { InitProcessName(argc, argv); #ifndef NDEBUG if (geteuid() != 0) debug_mode = true; #endif const ScopeFbPoolInit fb_pool_init; BpInstance instance; /* configuration */ ParseCommandLine(instance.cmdline, instance.config, argc, argv); if (instance.cmdline.config_file != nullptr) LoadConfigFile(instance.config, instance.cmdline.config_file); if (instance.config.ports.empty() && instance.config.listen.empty()) instance.config.ports.push_back(debug_mode ? 8080 : 80); /* initialize */ if (instance.config.stopwatch) stopwatch_enable(); SetupProcess(); const ScopeSslGlobalInit ssl_init; ssl_client_init(); direct_global_init(); instance.EnableSignals(); for (auto i : instance.config.ports) instance.AddTcpListener(i); for (const auto &i : instance.config.listen) instance.AddListener(i); global_control_handler_init(&instance); if (instance.config.num_workers == 1) /* in single-worker mode with watchdog master process, let only the one worker handle control commands */ global_control_handler_disable(instance); /* note: this function call passes a temporary SpawnConfig copy, because the reference will be evaluated in the child process after ~BpInstance() has been called */ instance.spawn = StartSpawnServer(SpawnConfig(instance.config.spawn), instance.child_process_registry, nullptr, [&instance](){ instance.event_loop.Reinit(); global_control_handler_deinit(&instance); instance.listeners.clear(); instance.DisableSignals(); instance.~BpInstance(); }); instance.spawn_service = instance.spawn; if (!crash_global_init()) { fprintf(stderr, "crash_global_init() failed\n"); return EXIT_FAILURE; } session_manager_init(instance.event_loop, instance.config.session_idle_timeout, instance.config.cluster_size, instance.config.cluster_node); if (!instance.config.session_save_path.empty()) { session_save_init(instance.config.session_save_path.c_str()); instance.ScheduleSaveSessions(); } local_control_handler_init(&instance); try { local_control_handler_open(&instance); } catch (const std::exception &e) { PrintException(e); } instance.balancer = balancer_new(instance.event_loop); instance.tcp_stock = new TcpStock(instance.event_loop, instance.config.tcp_stock_limit); instance.tcp_balancer = tcp_balancer_new(*instance.tcp_stock, *instance.balancer); const AddressList memcached_server(ShallowCopy(), instance.config.memcached_server); if (!instance.config.memcached_server.empty()) instance.memcached_stock = memcached_stock_new(instance.event_loop, *instance.tcp_balancer, memcached_server); if (instance.config.translation_socket != nullptr) { instance.translate_stock = tstock_new(instance.event_loop, instance.config.translation_socket, instance.config.translate_stock_limit); instance.translate_cache = translate_cache_new(instance.root_pool, instance.event_loop, *instance.translate_stock, instance.config.translate_cache_size, false); } instance.lhttp_stock = lhttp_stock_new(0, 16, instance.event_loop, *instance.spawn_service); instance.fcgi_stock = fcgi_stock_new(instance.config.fcgi_stock_limit, instance.config.fcgi_stock_max_idle, instance.event_loop, *instance.spawn_service); instance.was_stock = was_stock_new(instance.config.was_stock_limit, instance.config.was_stock_max_idle, instance.event_loop, *instance.spawn_service); instance.delegate_stock = delegate_stock_new(instance.event_loop, *instance.spawn_service); instance.nfs_stock = nfs_stock_new(instance.event_loop, instance.root_pool); instance.nfs_cache = nfs_cache_new(instance.root_pool, instance.config.nfs_cache_size, *instance.nfs_stock, instance.event_loop); instance.direct_resource_loader = new DirectResourceLoader(instance.event_loop, instance.tcp_balancer, *instance.spawn_service, instance.lhttp_stock, instance.fcgi_stock, instance.was_stock, instance.delegate_stock, instance.nfs_cache); instance.http_cache = http_cache_new(instance.root_pool, instance.config.http_cache_size, instance.memcached_stock, instance.event_loop, *instance.direct_resource_loader); instance.cached_resource_loader = new CachedResourceLoader(*instance.http_cache); instance.pipe_stock = pipe_stock_new(instance.event_loop); if (instance.config.filter_cache_size > 0) { instance.filter_cache = filter_cache_new(instance.root_pool, instance.config.filter_cache_size, instance.event_loop, *instance.direct_resource_loader); instance.filter_resource_loader = new FilterResourceLoader(*instance.filter_cache); } else instance.filter_resource_loader = instance.direct_resource_loader; const ScopeFailureInit failure; bulldog_init(instance.config.bulldog_path); global_translate_cache = instance.translate_cache; global_pipe_stock = instance.pipe_stock; /* launch the access logger */ instance.access_log.reset(AccessLogGlue::Create(instance.config.access_log, &instance.cmdline.logger_user)); /* daemonize II */ if (!instance.cmdline.user.IsEmpty()) capabilities_pre_setuid(); instance.cmdline.user.Apply(); if (!instance.cmdline.user.IsEmpty()) capabilities_post_setuid(cap_keep_list, ARRAY_SIZE(cap_keep_list)); /* create worker processes */ if (instance.config.num_workers > 0) { /* the master process shouldn't work */ instance.DisableListeners(); /* spawn the first worker really soon */ instance.spawn_worker_event.Add(EventDuration<0, 10000>::value); } else { instance.InitWorker(); } /* tell systemd we're ready */ sd_notify(0, "READY=1"); /* main loop */ instance.event_loop.Dispatch(); /* cleanup */ bulldog_deinit(); delete instance.spawn; thread_pool_deinit(); ssl_client_deinit(); crash_global_deinit(); ua_classification_deinit(); } catch (const std::exception &e) { PrintException(e); return EXIT_FAILURE; } <|endoftext|>
<commit_before>CodeGen::CodeGen(){ Builder = new IRBuilder<>(getClobalContext()); Mod = NULL; } bool CodeGen::doCodeGen(TranslationUnitAST &tunit, std::string name){ return generateTranstationUnit(tunit, name); } Module &CodeGen::getModule(){ if(Mod){ return *Mod; } else{ return *(new Module("null", getGlobalContext())); } } bool CodeGen::generateTranslationUnit(Tra slationUnitAST &tunit, std::string name){ Mod = new Module(name, getClobalContext()); for(int i = 0; ; i++){ PrototypeAST *proto = trunit.getPrototype(i); if(!proto){ break; } else if(!generatePrototype(proto, Mod)){ SAFE_DELETE(Mod); return false; } } for(int i = 0; ; i++){ FunctionAST *func = trunit.getFunction(i); if(!func){ break; } else if(!generateDunctionDefinition(func, Mod)){ SAFE_DELETE(Mod); return false; } } return true; } Function *CodeGen::generatePrototype(PrototypeAST *proto, Module *mod){ Function *func = mod->getFunction(proto->getName()); if(func){ if(func->arg_size() == proto->getParamNum() && func->empty()){ return func; } else{ fprintf(stderr, "error::function %s id redefined", proto->getName().c_str()); return NULL; } } std::vector<Type*> int_types(proto->getParamNum(), Type::getInt32Ty(getGlobalContext())); FunctionType *func_type = FunctionType::get(Type::getInt32Ty(getGlobalContext()), int_type, false); func = Functin::Create(func_type, Function::ExternalLinkage, proto->getName(), mod); Function::arg_iterator arg_iter = func->arg_begin(); for(int i = 0; i< proto->getParamNum(); i++){ arg_iter->setName(proto->getParamName(i).append("_arg")); arg_iter++; } return func; } Function *CodeGen::generateFunctionDefinition(FucntionAST *func_ast, Module *mod){ Function *func = generatePrototype(func_ast->getPrototype(), mod); if(!func){ return NULL; } CurFunc = func; BasicBlock *bblock = BasicBlick::Create(getGlobalContext(), "entry", func); Builder->SetInsertPoint(bblock); generateFunctionStatement(func_ast->getBody()); return func; } <commit_msg>5.39 generateFunctionStatement<commit_after>CodeGen::CodeGen(){ Builder = new IRBuilder<>(getClobalContext()); Mod = NULL; } bool CodeGen::doCodeGen(TranslationUnitAST &tunit, std::string name){ return generateTranstationUnit(tunit, name); } Module &CodeGen::getModule(){ if(Mod){ return *Mod; } else{ return *(new Module("null", getGlobalContext())); } } bool CodeGen::generateTranslationUnit(Tra slationUnitAST &tunit, std::string name){ Mod = new Module(name, getClobalContext()); for(int i = 0; ; i++){ PrototypeAST *proto = trunit.getPrototype(i); if(!proto){ break; } else if(!generatePrototype(proto, Mod)){ SAFE_DELETE(Mod); return false; } } for(int i = 0; ; i++){ FunctionAST *func = trunit.getFunction(i); if(!func){ break; } else if(!generateDunctionDefinition(func, Mod)){ SAFE_DELETE(Mod); return false; } } return true; } Function *CodeGen::generatePrototype(PrototypeAST *proto, Module *mod){ Function *func = mod->getFunction(proto->getName()); if(func){ if(func->arg_size() == proto->getParamNum() && func->empty()){ return func; } else{ fprintf(stderr, "error::function %s id redefined", proto->getName().c_str()); return NULL; } } std::vector<Type*> int_types(proto->getParamNum(), Type::getInt32Ty(getGlobalContext())); FunctionType *func_type = FunctionType::get(Type::getInt32Ty(getGlobalContext()), int_type, false); func = Functin::Create(func_type, Function::ExternalLinkage, proto->getName(), mod); Function::arg_iterator arg_iter = func->arg_begin(); for(int i = 0; i< proto->getParamNum(); i++){ arg_iter->setName(proto->getParamName(i).append("_arg")); arg_iter++; } return func; } Function *CodeGen::generateFunctionDefinition(FucntionAST *func_ast, Module *mod){ Function *func = generatePrototype(func_ast->getPrototype(), mod); if(!func){ return NULL; } CurFunc = func; BasicBlock *bblock = BasicBlick::Create(getGlobalContext(), "entry", func); Builder->SetInsertPoint(bblock); generateFunctionStatement(func_ast->getBody()); return func; } Value *CodeGen::generateFunctionStatement(FunctionStmtAST *function_stmt){ VariableDeclAST *vdecl; Value *v = NULL; for(int i = 0; ; i++){ if(!func_stmt->getVariableDecl(i)){ break; } vdecl = dyn_cast<VariableDeclAST>(func_stmt->getVariableDecl(i)); v = generateVariableDeclaration(vdecl); } BaseAST *stmt; for(int i = 0; ; i++){ stmt = func->getStatement(i); if(!stmt){ break; } else if(!isa<NullExprAST>(stmt)){ v = generateStatement(stmt); } } return v; } <|endoftext|>
<commit_before>// codegen #include <iostream> #include "codegen.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Bitcode/BitstreamWriter.h" #include "llvm/Bitcode/ReaderWriter.h" llvm::Function *CodeUnit::buildFunctionHeader(const char *name, FunctionTypeHandle *type) { std::string myName(name); llvm::GlobalValue::LinkageTypes linkage = llvm::Function::ExternalLinkage; llvm::FunctionType *ft = (llvm::FunctionType *)type->getLLVMType(Context); llvm::Function *f = llvm::Function::Create(ft, linkage, myName, TheModule); if (f->getName() != myName) { f->eraseFromParent(); return 0; // TODO not this } return f; } bool CodeUnit::WriteToFile(const char *name) { std::error_code ec; llvm::raw_fd_ostream output(name, ec, (llvm::sys::fs::OpenFlags)1); // don't overwrite files if (ec.message() != "" && ec.message() != "Success") // brain dead { // TODO: not this std::cout << ec.value() << ": " << ec.message() << " [" << ec.category().name() << "]" << std::endl; return false; } output.SetUseAtomicWrites(true); llvm::WriteBitcodeToFile(TheModule, output); output.close(); return true; } FunctionBuilder *CodeUnit::MakeFunction(const char *name, FunctionTypeHandle *type) { llvm::Function *f = buildFunctionHeader(name, type); return new FunctionBuilder(name, type, Context, f); } FunctionValueHandle *CodeUnit::DeclareFunction(const char *name, FunctionTypeHandle *type) { llvm::Function *f = buildFunctionHeader(name, type); return new FunctionValueHandle(type, f); } ConstantValueHandle *CodeUnit::ConstantString(const std::string &value) { TypeHandle *type = new ArrayTypeHandle(value.size() + 1, new IntTypeHandle(8)); llvm::GlobalVariable *gv = new llvm::GlobalVariable( *TheModule, type->getLLVMType(Context), true, // constant llvm::GlobalValue::InternalLinkage, llvm::ConstantDataArray::getString(Context, value) ); return new ConstantValueHandle(type, gv); } <commit_msg>don't segfault on repeated function name<commit_after>// codegen #include <iostream> #include "codegen.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Bitcode/BitstreamWriter.h" #include "llvm/Bitcode/ReaderWriter.h" llvm::Function *CodeUnit::buildFunctionHeader(const char *name, FunctionTypeHandle *type) { std::string myName(name); llvm::GlobalValue::LinkageTypes linkage = llvm::Function::ExternalLinkage; llvm::FunctionType *ft = (llvm::FunctionType *)type->getLLVMType(Context); llvm::Function *f = llvm::Function::Create(ft, linkage, myName, TheModule); if (f->getName() != myName) { f->eraseFromParent(); return 0; // TODO not this } return f; } bool CodeUnit::WriteToFile(const char *name) { std::error_code ec; llvm::raw_fd_ostream output(name, ec, (llvm::sys::fs::OpenFlags)1); // don't overwrite files if (ec.message() != "" && ec.message() != "Success") // brain dead { // TODO: not this std::cout << ec.value() << ": " << ec.message() << " [" << ec.category().name() << "]" << std::endl; return false; } output.SetUseAtomicWrites(true); llvm::WriteBitcodeToFile(TheModule, output); output.close(); return true; } FunctionBuilder *CodeUnit::MakeFunction(const char *name, FunctionTypeHandle *type) { llvm::Function *f = buildFunctionHeader(name, type); if (!f) return 0; return new FunctionBuilder(name, type, Context, f); } FunctionValueHandle *CodeUnit::DeclareFunction(const char *name, FunctionTypeHandle *type) { llvm::Function *f = buildFunctionHeader(name, type); return new FunctionValueHandle(type, f); } ConstantValueHandle *CodeUnit::ConstantString(const std::string &value) { TypeHandle *type = new ArrayTypeHandle(value.size() + 1, new IntTypeHandle(8)); llvm::GlobalVariable *gv = new llvm::GlobalVariable( *TheModule, type->getLLVMType(Context), true, // constant llvm::GlobalValue::InternalLinkage, llvm::ConstantDataArray::getString(Context, value) ); return new ConstantValueHandle(type, gv); } <|endoftext|>
<commit_before>#include "Matrix.h" Matrix::Matrix(unsigned height, unsigned width) { n = height; m = width; data.reserve(n * m); } <commit_msg>Update Matrix.cpp<commit_after>#include "Matrix.h" Matrix::Matrix(const size_t height, const size_t width, const double initial_value) : n(height), m(width), data(n * m, initial_value) {} Matrix::Matrix(const Matrix & other) : n(other.n), m(other.m), data(other.data) {} Matrix & Matrix::operator=(const Matrix & other) { if (this != & other) { n = other.n; m = other.m; data = other.data; } return *this; } double Matrix::operator()(const size_t i, const size_t j) const { return data[i * n + j]; } double & Matrix::operator()(const size_t i, const size_t j) { return data[i * n + j]; } <|endoftext|>
<commit_before>#include "rtkTestConfiguration.h" #include "rtkProjectionsReader.h" #include "rtkMacro.h" #include "rtkDigisensGeometryReader.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include <itkRegularExpressionSeriesFileNames.h> typedef rtk::ThreeDCircularProjectionGeometry GeometryType; template<class TImage> #if FAST_TESTS_NO_CHECKS void CheckImageQuality(typename TImage::Pointer itkNotUsed(recon), typename TImage::Pointer itkNotUsed(ref)) { } #else void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref) { typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType; ImageIteratorType itTest( recon, recon->GetBufferedRegion() ); ImageIteratorType itRef( ref, ref->GetBufferedRegion() ); typedef double ErrorType; ErrorType TestError = 0.; ErrorType EnerError = 0.; itTest.GoToBegin(); itRef.GoToBegin(); while( !itRef.IsAtEnd() ) { typename TImage::PixelType TestVal = itTest.Get(); typename TImage::PixelType RefVal = itRef.Get(); if( TestVal != RefVal ) { TestError += vcl_abs(RefVal - TestVal); EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.); } ++itTest; ++itRef; } // Error per Pixel ErrorType ErrorPerPixel = TestError/recon->GetBufferedRegion().GetNumberOfPixels(); std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl; // MSE ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "MSE = " << MSE << std::endl; // PSNR ErrorType PSNR = 20*log10(255.0) - 10*log10(MSE); std::cout << "PSNR = " << PSNR << "dB" << std::endl; // QI ErrorType QI = (255.0-ErrorPerPixel)/255.0; std::cout << "QI = " << QI << std::endl; // Checking results if (ErrorPerPixel > 2.31e-7) { std::cerr << "Test Failed, Error per pixel not valid! " << ErrorPerPixel << " instead of 1.31e-7" << std::endl; exit( EXIT_FAILURE); } if (PSNR < 100.) { std::cerr << "Test Failed, PSNR not valid! " << PSNR << " instead of 100" << std::endl; exit( EXIT_FAILURE); } } #endif void CheckGeometries(GeometryType *g1, GeometryType *g2) { const double e = 1e-10; const unsigned int nproj = g1->GetGantryAngles().size(); if(g2->GetGantryAngles().size() != nproj) { std::cerr << "Unequal number of projections in the two geometries" << std::endl; exit(EXIT_FAILURE); } for(unsigned int i=0; i<nproj; i++) { if( e < rtk::ThreeDCircularProjectionGeometry::ConvertAngleBetween0And360Degrees( std::fabs(g1->GetGantryAngles()[i] - g2->GetGantryAngles()[i])) || e < rtk::ThreeDCircularProjectionGeometry::ConvertAngleBetween0And360Degrees( std::fabs(g1->GetOutOfPlaneAngles()[i] - g2->GetOutOfPlaneAngles()[i])) || e < rtk::ThreeDCircularProjectionGeometry::ConvertAngleBetween0And360Degrees( std::fabs(g1->GetInPlaneAngles()[i] - g2->GetInPlaneAngles()[i])) || e < std::fabs(g1->GetSourceToIsocenterDistances()[i] - g2->GetSourceToIsocenterDistances()[i]) || e < std::fabs(g1->GetSourceOffsetsX()[i] - g2->GetSourceOffsetsX()[i]) || e < std::fabs(g1->GetSourceOffsetsY()[i] - g2->GetSourceOffsetsY()[i]) || e < std::fabs(g1->GetSourceToDetectorDistances()[i] - g2->GetSourceToDetectorDistances()[i]) || e < std::fabs(g1->GetProjectionOffsetsX()[i] - g2->GetProjectionOffsetsX()[i]) || e < std::fabs(g1->GetProjectionOffsetsY()[i] - g2->GetProjectionOffsetsY()[i]) ) { std::cerr << "Geometry of projection #" << i << " is unvalid." << std::endl; exit(EXIT_FAILURE); } } } /** * \file rtkdigisenstest.cxx * * \brief Functional tests for classes managing Digisens data * * This test reads a projection and the geometry of an acquisition from a * Digisens acquisition and compares it to the expected results, which are * read from a baseline image in the MetaIO file format and a geometry file in * the RTK format, respectively. * * \author Simon Rit */ int main(int, char** ) { // Elekta geometry rtk::DigisensGeometryReader::Pointer geoTargReader; geoTargReader = rtk::DigisensGeometryReader::New(); geoTargReader->SetXMLFileName( std::string(RTK_DATA_ROOT) + std::string("/Input/Digisens/calibration.cal") ); TRY_AND_EXIT_ON_ITK_EXCEPTION( geoTargReader->UpdateOutputData() ); // Reference geometry rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geoRefReader; geoRefReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New(); geoRefReader->SetFilename( std::string(RTK_DATA_ROOT) + std::string("/Baseline/Digisens/geometry.xml") ); TRY_AND_EXIT_ON_ITK_EXCEPTION( geoRefReader->GenerateOutputInformation() ) // 1. Check geometries CheckGeometries(geoTargReader->GetGeometry(), geoRefReader->GetOutputObject() ); // ******* COMPARING projections ******* typedef float OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< OutputPixelType, Dimension > ImageType; // Tif projections reader typedef rtk::ProjectionsReader< ImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); std::vector<std::string> fileNames; fileNames.push_back( std::string(RTK_DATA_ROOT) + std::string("/Input/Digisens/ima0010.tif") ); reader->SetFileNames( fileNames ); TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() ); // Reference projections reader ReaderType::Pointer readerRef = ReaderType::New(); fileNames.clear(); fileNames.push_back( std::string(RTK_DATA_ROOT) + std::string("/Baseline/Digisens/attenuation.mha") ); readerRef->SetFileNames( fileNames ); TRY_AND_EXIT_ON_ITK_EXCEPTION(readerRef->Update()); // 2. Compare read projections CheckImageQuality< ImageType >(reader->GetOutput(), readerRef->GetOutput()); // If both succeed std::cout << "\n\nTest PASSED! " << std::endl; return EXIT_SUCCESS; } <commit_msg>COMP: Trying to fix UMR<commit_after>#include "rtkTestConfiguration.h" #include "rtkProjectionsReader.h" #include "rtkMacro.h" #include "rtkDigisensGeometryReader.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include <itkRegularExpressionSeriesFileNames.h> typedef rtk::ThreeDCircularProjectionGeometry GeometryType; template<class TImage> #if FAST_TESTS_NO_CHECKS void CheckImageQuality(typename TImage::Pointer itkNotUsed(recon), typename TImage::Pointer itkNotUsed(ref)) { } #else void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref) { typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType; ImageIteratorType itTest( recon, recon->GetBufferedRegion() ); ImageIteratorType itRef( ref, ref->GetBufferedRegion() ); typedef double ErrorType; ErrorType TestError = 0.; ErrorType EnerError = 0.; itTest.GoToBegin(); itRef.GoToBegin(); while( !itRef.IsAtEnd() ) { typename TImage::PixelType TestVal = itTest.Get(); typename TImage::PixelType RefVal = itRef.Get(); if( TestVal != RefVal ) { TestError += vcl_abs(RefVal - TestVal); EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.); } ++itTest; ++itRef; } // Error per Pixel ErrorType ErrorPerPixel = TestError/recon->GetBufferedRegion().GetNumberOfPixels(); std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl; // MSE ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "MSE = " << MSE << std::endl; // PSNR ErrorType PSNR = 20*log10(255.0) - 10*log10(MSE); std::cout << "PSNR = " << PSNR << "dB" << std::endl; // QI ErrorType QI = (255.0-ErrorPerPixel)/255.0; std::cout << "QI = " << QI << std::endl; // Checking results if (ErrorPerPixel > 2.31e-7) { std::cerr << "Test Failed, Error per pixel not valid! " << ErrorPerPixel << " instead of 1.31e-7" << std::endl; exit( EXIT_FAILURE); } if (PSNR < 100.) { std::cerr << "Test Failed, PSNR not valid! " << PSNR << " instead of 100" << std::endl; exit( EXIT_FAILURE); } } #endif void CheckGeometries(GeometryType *g1, GeometryType *g2) { const double e = 1e-10; const unsigned int nproj = g1->GetGantryAngles().size(); if(g2->GetGantryAngles().size() != nproj) { std::cerr << "Unequal number of projections in the two geometries" << std::endl; exit(EXIT_FAILURE); } for(unsigned int i=0; i<nproj; i++) { if( e < rtk::ThreeDCircularProjectionGeometry::ConvertAngleBetween0And360Degrees( std::fabs(g1->GetGantryAngles()[i] - g2->GetGantryAngles()[i])) || e < rtk::ThreeDCircularProjectionGeometry::ConvertAngleBetween0And360Degrees( std::fabs(g1->GetOutOfPlaneAngles()[i] - g2->GetOutOfPlaneAngles()[i])) || e < rtk::ThreeDCircularProjectionGeometry::ConvertAngleBetween0And360Degrees( std::fabs(g1->GetInPlaneAngles()[i] - g2->GetInPlaneAngles()[i])) || e < std::fabs(g1->GetSourceToIsocenterDistances()[i] - g2->GetSourceToIsocenterDistances()[i]) || e < std::fabs(g1->GetSourceOffsetsX()[i] - g2->GetSourceOffsetsX()[i]) || e < std::fabs(g1->GetSourceOffsetsY()[i] - g2->GetSourceOffsetsY()[i]) || e < std::fabs(g1->GetSourceToDetectorDistances()[i] - g2->GetSourceToDetectorDistances()[i]) || e < std::fabs(g1->GetProjectionOffsetsX()[i] - g2->GetProjectionOffsetsX()[i]) || e < std::fabs(g1->GetProjectionOffsetsY()[i] - g2->GetProjectionOffsetsY()[i]) ) { std::cerr << "Geometry of projection #" << i << " is unvalid." << std::endl; exit(EXIT_FAILURE); } } } /** * \file rtkdigisenstest.cxx * * \brief Functional tests for classes managing Digisens data * * This test reads a projection and the geometry of an acquisition from a * Digisens acquisition and compares it to the expected results, which are * read from a baseline image in the MetaIO file format and a geometry file in * the RTK format, respectively. * * \author Simon Rit */ int main(int, char** ) { // Elekta geometry rtk::DigisensGeometryReader::Pointer geoTargReader; geoTargReader = rtk::DigisensGeometryReader::New(); geoTargReader->SetXMLFileName( std::string(RTK_DATA_ROOT) + std::string("/Input/Digisens/calibration.cal") ); TRY_AND_EXIT_ON_ITK_EXCEPTION( geoTargReader->UpdateOutputData() ); // Reference geometry rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geoRefReader; geoRefReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New(); geoRefReader->SetFilename( std::string(RTK_DATA_ROOT) + std::string("/Baseline/Digisens/geometry.xml") ); TRY_AND_EXIT_ON_ITK_EXCEPTION( geoRefReader->GenerateOutputInformation() ) // 1. Check geometries CheckGeometries(geoTargReader->GetGeometry(), geoRefReader->GetOutputObject() ); // ******* COMPARING projections ******* typedef float OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< OutputPixelType, Dimension > ImageType; // Tif projections reader typedef rtk::ProjectionsReader< ImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); std::vector<std::string> fileNames; fileNames.push_back( std::string(RTK_DATA_ROOT) + std::string("/Input/Digisens/ima0010.tif") ); reader->SetFileNames( fileNames ); TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() ); // Reference projections reader ReaderType::Pointer readerRef = ReaderType::New(); std::vector<std::string> fileNamesRef; fileNamesRef.push_back( std::string(RTK_DATA_ROOT) + std::string("/Baseline/Digisens/attenuation.mha") ); readerRef->SetFileNames( fileNamesRef ); TRY_AND_EXIT_ON_ITK_EXCEPTION(readerRef->Update()); // 2. Compare read projections CheckImageQuality< ImageType >(reader->GetOutput(), readerRef->GetOutput()); // If both succeed std::cout << "\n\nTest PASSED! " << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#ifndef HEADER_GUARD_CLASS_CONTENTS_H #define HEADER_GUARD_CLASS_CONTENTS_H #include <vector> #include <string> #include "change.hh" #include "mode.hh" class contents { private: const mode* m; // not deleted in destructor public: std::vector<std::string> cont; unsigned long y = 0, x = 0, desired_x = 0, y_offset = 0, max_y,max_x; bool waiting_for_desired = false, refresh = true, delete_mode = false, is_inserting = false; std::vector<change> changes; contents(std::vector<std::string> cont = std::vector<std::string>(), mode* m = &mode::fundamental); contents(mode* m); contents(long y, long x, mode* m = &mode::fundamental); bool operator()(char) const; ~contents(); contents(const contents&); contents(contents&&); contents& operator=(const contents&); contents& operator=(contents&&); void refreshmaxyx(); void push_back(const std::string& str); }; #endif <commit_msg>Remove documentation that says contents::m isn't deleted because it might be<commit_after>#ifndef HEADER_GUARD_CLASS_CONTENTS_H #define HEADER_GUARD_CLASS_CONTENTS_H #include <vector> #include <string> #include "change.hh" #include "mode.hh" class contents { private: const mode* m; public: std::vector<std::string> cont; unsigned long y = 0, x = 0, desired_x = 0, y_offset = 0, max_y,max_x; bool waiting_for_desired = false, refresh = true, delete_mode = false, is_inserting = false; std::vector<change> changes; contents(std::vector<std::string> cont = std::vector<std::string>(), mode* m = &mode::fundamental); contents(mode* m); contents(long y, long x, mode* m = &mode::fundamental); bool operator()(char) const; ~contents(); contents(const contents&); contents(contents&&); contents& operator=(const contents&); contents& operator=(contents&&); void refreshmaxyx(); void push_back(const std::string& str); }; #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2017, Rauli Laine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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 <plorth/context.hpp> #include <plorth/value-word.hpp> #include "./utils.hpp" namespace plorth { context::context(const ref<class runtime>& runtime) : m_runtime(runtime) {} void context::error(enum error::code code, const unistring& message, const struct position* position) { m_error = new (m_runtime->memory_manager()) class error( code, message, position ); } void context::push_null() { push(ref<value>()); } void context::push_boolean(bool value) { push(m_runtime->boolean(value)); } void context::push_int(number::int_type value) { push(m_runtime->number(value)); } void context::push_real(number::real_type value) { push(m_runtime->number(value)); } void context::push_number(const unistring& value) { push(m_runtime->number(value)); } void context::push_string(const unistring& value) { push(m_runtime->string(value.c_str(), value.length())); } void context::push_string(string::const_pointer chars, string::size_type length) { push(m_runtime->string(chars, length)); } void context::push_array(array::const_pointer elements, array::size_type size) { push(m_runtime->array(elements, size)); } void context::push_object(const object::container_type& properties) { push(m_runtime->value<object>(properties)); } void context::push_symbol(const unistring& id) { push(m_runtime->symbol(id)); } void context::push_quote(const std::vector<ref<value>>& values) { push(m_runtime->compiled_quote(values)); } void context::push_word(const ref<class symbol>& symbol, const ref<class quote>& quote) { push(m_runtime->value<word>(symbol, quote)); } bool context::pop() { if (!m_data.empty()) { m_data.pop_back(); return true; } error(error::code_range, U"Stack underflow."); return false; } bool context::pop(enum value::type type) { if (!m_data.empty()) { const ref<class value>& value = m_data.back(); if ((!value && type != value::type_null) || (value && !value->is(type))) { error( error::code_type, U"Expected " + value::type_description(type) + U", got " + (value ? value->type_description().c_str() : U"null") + U" instead." ); return false; } m_data.pop_back(); return true; } error(error::code_range, U"Stack underflow."); return false; } bool context::pop(ref<value>& slot) { if (!m_data.empty()) { slot = m_data.back(); m_data.pop_back(); return true; } error(error::code_range, U"Stack underflow."); return false; } bool context::pop(ref<value>& slot, enum value::type type) { if (!m_data.empty()) { slot = m_data.back(); if ((!slot && type != value::type_null) || (slot && !slot->is(type))) { error( error::code_type, U"Expected " + value::type_description(type) + U", got " + (slot ? slot->type_description().c_str() : U"null") + U" instead." ); return false; } m_data.pop_back(); return true; } error(error::code_range, U"Stack underflow."); return false; } bool context::pop_boolean(bool& slot) { ref<class value> value; if (!pop(value, value::type_boolean)) { return false; } slot = value.cast<boolean>()->value(); return true; } bool context::pop_number(ref<number>& slot) { ref<class value> value; if (!pop(value, value::type_number)) { return false; } slot = value.cast<number>(); return true; } bool context::pop_string(ref<string>& slot) { ref<class value> value; if (!pop(value, value::type_string)) { return false; } slot = value.cast<string>(); return true; } bool context::pop_array(ref<array>& slot) { ref<class value> value; if (!pop(value, value::type_array)) { return false; } slot = value.cast<array>(); return true; } bool context::pop_object(ref<object>& slot) { ref<class value> value; if (!pop(value, value::type_object)) { return false; } slot = value.cast<object>(); return true; } bool context::pop_quote(ref<quote>& slot) { ref<class value> value; if (!pop(value, value::type_quote)) { return false; } slot = value.cast<quote>(); return true; } bool context::pop_symbol(ref<symbol>& slot) { ref<class value> value; if (!pop(value, value::type_symbol)) { return false; } slot = value.cast<symbol>(); return true; } bool context::pop_word(ref<word>& slot) { ref<class value> value; if (!pop(value, value::type_word)) { return false; } slot = value.cast<word>(); return true; } } <commit_msg>Use context's position as default position<commit_after>/* * Copyright (c) 2017, Rauli Laine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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 <plorth/context.hpp> #include <plorth/value-word.hpp> #include "./utils.hpp" namespace plorth { context::context(const ref<class runtime>& runtime) : m_runtime(runtime) {} void context::error(enum error::code code, const unistring& message, const struct position* position) { if (!position && (m_position.filename.empty() || m_position.line > 0)) { position = &m_position; } m_error = new (m_runtime->memory_manager()) class error( code, message, position ); } void context::push_null() { push(ref<value>()); } void context::push_boolean(bool value) { push(m_runtime->boolean(value)); } void context::push_int(number::int_type value) { push(m_runtime->number(value)); } void context::push_real(number::real_type value) { push(m_runtime->number(value)); } void context::push_number(const unistring& value) { push(m_runtime->number(value)); } void context::push_string(const unistring& value) { push(m_runtime->string(value.c_str(), value.length())); } void context::push_string(string::const_pointer chars, string::size_type length) { push(m_runtime->string(chars, length)); } void context::push_array(array::const_pointer elements, array::size_type size) { push(m_runtime->array(elements, size)); } void context::push_object(const object::container_type& properties) { push(m_runtime->value<object>(properties)); } void context::push_symbol(const unistring& id) { push(m_runtime->symbol(id)); } void context::push_quote(const std::vector<ref<value>>& values) { push(m_runtime->compiled_quote(values)); } void context::push_word(const ref<class symbol>& symbol, const ref<class quote>& quote) { push(m_runtime->value<word>(symbol, quote)); } bool context::pop() { if (!m_data.empty()) { m_data.pop_back(); return true; } error(error::code_range, U"Stack underflow."); return false; } bool context::pop(enum value::type type) { if (!m_data.empty()) { const ref<class value>& value = m_data.back(); if ((!value && type != value::type_null) || (value && !value->is(type))) { error( error::code_type, U"Expected " + value::type_description(type) + U", got " + (value ? value->type_description().c_str() : U"null") + U" instead." ); return false; } m_data.pop_back(); return true; } error(error::code_range, U"Stack underflow."); return false; } bool context::pop(ref<value>& slot) { if (!m_data.empty()) { slot = m_data.back(); m_data.pop_back(); return true; } error(error::code_range, U"Stack underflow."); return false; } bool context::pop(ref<value>& slot, enum value::type type) { if (!m_data.empty()) { slot = m_data.back(); if ((!slot && type != value::type_null) || (slot && !slot->is(type))) { error( error::code_type, U"Expected " + value::type_description(type) + U", got " + (slot ? slot->type_description().c_str() : U"null") + U" instead." ); return false; } m_data.pop_back(); return true; } error(error::code_range, U"Stack underflow."); return false; } bool context::pop_boolean(bool& slot) { ref<class value> value; if (!pop(value, value::type_boolean)) { return false; } slot = value.cast<boolean>()->value(); return true; } bool context::pop_number(ref<number>& slot) { ref<class value> value; if (!pop(value, value::type_number)) { return false; } slot = value.cast<number>(); return true; } bool context::pop_string(ref<string>& slot) { ref<class value> value; if (!pop(value, value::type_string)) { return false; } slot = value.cast<string>(); return true; } bool context::pop_array(ref<array>& slot) { ref<class value> value; if (!pop(value, value::type_array)) { return false; } slot = value.cast<array>(); return true; } bool context::pop_object(ref<object>& slot) { ref<class value> value; if (!pop(value, value::type_object)) { return false; } slot = value.cast<object>(); return true; } bool context::pop_quote(ref<quote>& slot) { ref<class value> value; if (!pop(value, value::type_quote)) { return false; } slot = value.cast<quote>(); return true; } bool context::pop_symbol(ref<symbol>& slot) { ref<class value> value; if (!pop(value, value::type_symbol)) { return false; } slot = value.cast<symbol>(); return true; } bool context::pop_word(ref<word>& slot) { ref<class value> value; if (!pop(value, value::type_word)) { return false; } slot = value.cast<word>(); return true; } } <|endoftext|>
<commit_before>// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "public/fpdf_ppo.h" #include <map> #include <memory> #include <vector> #include "core/fpdfapi/parser/cpdf_array.h" #include "core/fpdfapi/parser/cpdf_document.h" #include "core/fpdfapi/parser/cpdf_name.h" #include "core/fpdfapi/parser/cpdf_number.h" #include "core/fpdfapi/parser/cpdf_reference.h" #include "core/fpdfapi/parser/cpdf_stream.h" #include "core/fpdfapi/parser/cpdf_string.h" #include "fpdfsdk/fsdk_define.h" #include "third_party/base/stl_util.h" class CPDF_PageOrganizer { public: using ObjectNumberMap = std::map<uint32_t, uint32_t>; CPDF_PageOrganizer(); ~CPDF_PageOrganizer(); bool PDFDocInit(CPDF_Document* pDestPDFDoc, CPDF_Document* pSrcPDFDoc); bool ExportPage(CPDF_Document* pSrcPDFDoc, std::vector<uint16_t>* pPageNums, CPDF_Document* pDestPDFDoc, int nIndex); CPDF_Object* PageDictGetInheritableTag(CPDF_Dictionary* pDict, const CFX_ByteString& bsSrctag); bool UpdateReference(CPDF_Object* pObj, CPDF_Document* pDoc, ObjectNumberMap* pObjNumberMap); uint32_t GetNewObjId(CPDF_Document* pDoc, ObjectNumberMap* pObjNumberMap, CPDF_Reference* pRef); }; CPDF_PageOrganizer::CPDF_PageOrganizer() {} CPDF_PageOrganizer::~CPDF_PageOrganizer() {} bool CPDF_PageOrganizer::PDFDocInit(CPDF_Document* pDestPDFDoc, CPDF_Document* pSrcPDFDoc) { if (!pDestPDFDoc || !pSrcPDFDoc) return false; CPDF_Dictionary* pNewRoot = pDestPDFDoc->GetRoot(); if (!pNewRoot) return false; CPDF_Dictionary* DInfoDict = pDestPDFDoc->GetInfo(); if (!DInfoDict) return false; CFX_ByteString producerstr; producerstr.Format("PDFium"); DInfoDict->SetFor("Producer", new CPDF_String(producerstr, false)); CFX_ByteString cbRootType = pNewRoot->GetStringFor("Type", ""); if (cbRootType.IsEmpty()) pNewRoot->SetFor("Type", new CPDF_Name("Catalog")); CPDF_Object* pElement = pNewRoot->GetObjectFor("Pages"); CPDF_Dictionary* pNewPages = pElement ? ToDictionary(pElement->GetDirect()) : nullptr; if (!pNewPages) { pNewPages = new CPDF_Dictionary(pDestPDFDoc->GetByteStringPool()); pNewRoot->SetReferenceFor("Pages", pDestPDFDoc, pDestPDFDoc->AddIndirectObject(pNewPages)); } CFX_ByteString cbPageType = pNewPages->GetStringFor("Type", ""); if (cbPageType == "") { pNewPages->SetFor("Type", new CPDF_Name("Pages")); } if (!pNewPages->GetArrayFor("Kids")) { pNewPages->SetIntegerFor("Count", 0); pNewPages->SetReferenceFor("Kids", pDestPDFDoc, pDestPDFDoc->AddIndirectObject(new CPDF_Array)); } return true; } bool CPDF_PageOrganizer::ExportPage(CPDF_Document* pSrcPDFDoc, std::vector<uint16_t>* pPageNums, CPDF_Document* pDestPDFDoc, int nIndex) { int curpage = nIndex; std::unique_ptr<ObjectNumberMap> pObjNumberMap(new ObjectNumberMap); int nSize = pdfium::CollectionSize<int>(*pPageNums); for (int i = 0; i < nSize; ++i) { CPDF_Dictionary* pCurPageDict = pDestPDFDoc->CreateNewPage(curpage); CPDF_Dictionary* pSrcPageDict = pSrcPDFDoc->GetPage(pPageNums->at(i) - 1); if (!pSrcPageDict || !pCurPageDict) return false; // Clone the page dictionary for (const auto& it : *pSrcPageDict) { const CFX_ByteString& cbSrcKeyStr = it.first; CPDF_Object* pObj = it.second; if (cbSrcKeyStr.Compare(("Type")) && cbSrcKeyStr.Compare(("Parent"))) { if (pCurPageDict->KeyExist(cbSrcKeyStr)) pCurPageDict->RemoveFor(cbSrcKeyStr); pCurPageDict->SetFor(cbSrcKeyStr, pObj->Clone().release()); } } // inheritable item CPDF_Object* pInheritable = nullptr; // 1 MediaBox //required if (!pCurPageDict->KeyExist("MediaBox")) { pInheritable = PageDictGetInheritableTag(pSrcPageDict, "MediaBox"); if (!pInheritable) { // Search the "CropBox" from source page dictionary, // if not exists,we take the letter size. pInheritable = PageDictGetInheritableTag(pSrcPageDict, "CropBox"); if (pInheritable) { pCurPageDict->SetFor("MediaBox", pInheritable->Clone().release()); } else { // Make the default size to be letter size (8.5'x11') CPDF_Array* pArray = new CPDF_Array; pArray->AddNumber(0); pArray->AddNumber(0); pArray->AddNumber(612); pArray->AddNumber(792); pCurPageDict->SetFor("MediaBox", pArray); } } else { pCurPageDict->SetFor("MediaBox", pInheritable->Clone().release()); } } // 2 Resources //required if (!pCurPageDict->KeyExist("Resources")) { pInheritable = PageDictGetInheritableTag(pSrcPageDict, "Resources"); if (!pInheritable) return false; pCurPageDict->SetFor("Resources", pInheritable->Clone().release()); } // 3 CropBox //Optional if (!pCurPageDict->KeyExist("CropBox")) { pInheritable = PageDictGetInheritableTag(pSrcPageDict, "CropBox"); if (pInheritable) pCurPageDict->SetFor("CropBox", pInheritable->Clone().release()); } // 4 Rotate //Optional if (!pCurPageDict->KeyExist("Rotate")) { pInheritable = PageDictGetInheritableTag(pSrcPageDict, "Rotate"); if (pInheritable) pCurPageDict->SetFor("Rotate", pInheritable->Clone().release()); } // Update the reference uint32_t dwOldPageObj = pSrcPageDict->GetObjNum(); uint32_t dwNewPageObj = pCurPageDict->GetObjNum(); (*pObjNumberMap)[dwOldPageObj] = dwNewPageObj; UpdateReference(pCurPageDict, pDestPDFDoc, pObjNumberMap.get()); ++curpage; } return true; } CPDF_Object* CPDF_PageOrganizer::PageDictGetInheritableTag( CPDF_Dictionary* pDict, const CFX_ByteString& bsSrcTag) { if (!pDict || bsSrcTag.IsEmpty()) return nullptr; if (!pDict->KeyExist("Parent") || !pDict->KeyExist("Type")) return nullptr; CPDF_Object* pType = pDict->GetObjectFor("Type")->GetDirect(); if (!ToName(pType)) return nullptr; if (pType->GetString().Compare("Page")) return nullptr; CPDF_Dictionary* pp = ToDictionary(pDict->GetObjectFor("Parent")->GetDirect()); if (!pp) return nullptr; if (pDict->KeyExist(bsSrcTag)) return pDict->GetObjectFor(bsSrcTag); while (pp) { if (pp->KeyExist(bsSrcTag)) return pp->GetObjectFor(bsSrcTag); if (!pp->KeyExist("Parent")) break; pp = ToDictionary(pp->GetObjectFor("Parent")->GetDirect()); } return nullptr; } bool CPDF_PageOrganizer::UpdateReference(CPDF_Object* pObj, CPDF_Document* pDoc, ObjectNumberMap* pObjNumberMap) { switch (pObj->GetType()) { case CPDF_Object::REFERENCE: { CPDF_Reference* pReference = pObj->AsReference(); uint32_t newobjnum = GetNewObjId(pDoc, pObjNumberMap, pReference); if (newobjnum == 0) return false; pReference->SetRef(pDoc, newobjnum); break; } case CPDF_Object::DICTIONARY: { CPDF_Dictionary* pDict = pObj->AsDictionary(); auto it = pDict->begin(); while (it != pDict->end()) { const CFX_ByteString& key = it->first; CPDF_Object* pNextObj = it->second; ++it; if (key == "Parent" || key == "Prev" || key == "First") continue; if (!pNextObj) return false; if (!UpdateReference(pNextObj, pDoc, pObjNumberMap)) pDict->RemoveFor(key); } break; } case CPDF_Object::ARRAY: { CPDF_Array* pArray = pObj->AsArray(); for (size_t i = 0; i < pArray->GetCount(); ++i) { CPDF_Object* pNextObj = pArray->GetObjectAt(i); if (!pNextObj) return false; if (!UpdateReference(pNextObj, pDoc, pObjNumberMap)) return false; } break; } case CPDF_Object::STREAM: { CPDF_Stream* pStream = pObj->AsStream(); CPDF_Dictionary* pDict = pStream->GetDict(); if (pDict) { if (!UpdateReference(pDict, pDoc, pObjNumberMap)) return false; } else { return false; } break; } default: break; } return true; } uint32_t CPDF_PageOrganizer::GetNewObjId(CPDF_Document* pDoc, ObjectNumberMap* pObjNumberMap, CPDF_Reference* pRef) { if (!pRef) return 0; uint32_t dwObjnum = pRef->GetRefObjNum(); uint32_t dwNewObjNum = 0; const auto it = pObjNumberMap->find(dwObjnum); if (it != pObjNumberMap->end()) dwNewObjNum = it->second; if (dwNewObjNum) return dwNewObjNum; CPDF_Object* pDirect = pRef->GetDirect(); if (!pDirect) return 0; std::unique_ptr<CPDF_Object> pClone = pDirect->Clone(); if (CPDF_Dictionary* pDictClone = pClone->AsDictionary()) { if (pDictClone->KeyExist("Type")) { CFX_ByteString strType = pDictClone->GetStringFor("Type"); if (!FXSYS_stricmp(strType.c_str(), "Pages")) return 4; if (!FXSYS_stricmp(strType.c_str(), "Page")) return 0; } } CPDF_Object* pUnownedClone = pClone.get(); dwNewObjNum = pDoc->AddIndirectObject(pClone.release()); (*pObjNumberMap)[dwObjnum] = dwNewObjNum; if (!UpdateReference(pUnownedClone, pDoc, pObjNumberMap)) return 0; return dwNewObjNum; } FPDF_BOOL ParserPageRangeString(CFX_ByteString rangstring, std::vector<uint16_t>* pageArray, int nCount) { if (rangstring.GetLength() != 0) { rangstring.Remove(' '); int nLength = rangstring.GetLength(); CFX_ByteString cbCompareString("0123456789-,"); for (int i = 0; i < nLength; ++i) { if (cbCompareString.Find(rangstring[i]) == -1) return false; } CFX_ByteString cbMidRange; int nStringFrom = 0; int nStringTo = 0; while (nStringTo < nLength) { nStringTo = rangstring.Find(',', nStringFrom); if (nStringTo == -1) nStringTo = nLength; cbMidRange = rangstring.Mid(nStringFrom, nStringTo - nStringFrom); int nMid = cbMidRange.Find('-'); if (nMid == -1) { long lPageNum = atol(cbMidRange.c_str()); if (lPageNum <= 0 || lPageNum > nCount) return false; pageArray->push_back((uint16_t)lPageNum); } else { int nStartPageNum = atol(cbMidRange.Mid(0, nMid).c_str()); if (nStartPageNum == 0) return false; ++nMid; int nEnd = cbMidRange.GetLength() - nMid; if (nEnd == 0) return false; int nEndPageNum = atol(cbMidRange.Mid(nMid, nEnd).c_str()); if (nStartPageNum < 0 || nStartPageNum > nEndPageNum || nEndPageNum > nCount) { return false; } for (int i = nStartPageNum; i <= nEndPageNum; ++i) { pageArray->push_back(i); } } nStringFrom = nStringTo + 1; } } return true; } DLLEXPORT FPDF_BOOL STDCALL FPDF_ImportPages(FPDF_DOCUMENT dest_doc, FPDF_DOCUMENT src_doc, FPDF_BYTESTRING pagerange, int index) { CPDF_Document* pDestDoc = CPDFDocumentFromFPDFDocument(dest_doc); if (!dest_doc) return false; CPDF_Document* pSrcDoc = CPDFDocumentFromFPDFDocument(src_doc); if (!pSrcDoc) return false; std::vector<uint16_t> pageArray; int nCount = pSrcDoc->GetPageCount(); if (pagerange) { if (!ParserPageRangeString(pagerange, &pageArray, nCount)) return false; } else { for (int i = 1; i <= nCount; ++i) { pageArray.push_back(i); } } CPDF_PageOrganizer pageOrg; pageOrg.PDFDocInit(pDestDoc, pSrcDoc); return pageOrg.ExportPage(pSrcDoc, &pageArray, pDestDoc, index); } DLLEXPORT FPDF_BOOL STDCALL FPDF_CopyViewerPreferences(FPDF_DOCUMENT dest_doc, FPDF_DOCUMENT src_doc) { CPDF_Document* pDstDoc = CPDFDocumentFromFPDFDocument(dest_doc); if (!pDstDoc) return false; CPDF_Document* pSrcDoc = CPDFDocumentFromFPDFDocument(src_doc); if (!pSrcDoc) return false; CPDF_Dictionary* pSrcDict = pSrcDoc->GetRoot(); pSrcDict = pSrcDict->GetDictFor("ViewerPreferences"); if (!pSrcDict) return false; CPDF_Dictionary* pDstDict = pDstDoc->GetRoot(); if (!pDstDict) return false; pDstDict->SetFor("ViewerPreferences", pSrcDict->CloneDirectObject().release()); return true; } <commit_msg>Fix nits in CPDF_PageOrganizer.<commit_after>// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "public/fpdf_ppo.h" #include <map> #include <memory> #include <vector> #include "core/fpdfapi/parser/cpdf_array.h" #include "core/fpdfapi/parser/cpdf_document.h" #include "core/fpdfapi/parser/cpdf_name.h" #include "core/fpdfapi/parser/cpdf_number.h" #include "core/fpdfapi/parser/cpdf_reference.h" #include "core/fpdfapi/parser/cpdf_stream.h" #include "core/fpdfapi/parser/cpdf_string.h" #include "fpdfsdk/fsdk_define.h" #include "third_party/base/ptr_util.h" #include "third_party/base/stl_util.h" namespace { CPDF_Object* PageDictGetInheritableTag(CPDF_Dictionary* pDict, const CFX_ByteString& bsSrcTag) { if (!pDict || bsSrcTag.IsEmpty()) return nullptr; if (!pDict->KeyExist("Parent") || !pDict->KeyExist("Type")) return nullptr; CPDF_Object* pType = pDict->GetObjectFor("Type")->GetDirect(); if (!ToName(pType)) return nullptr; if (pType->GetString().Compare("Page")) return nullptr; CPDF_Dictionary* pp = ToDictionary(pDict->GetObjectFor("Parent")->GetDirect()); if (!pp) return nullptr; if (pDict->KeyExist(bsSrcTag)) return pDict->GetObjectFor(bsSrcTag); while (pp) { if (pp->KeyExist(bsSrcTag)) return pp->GetObjectFor(bsSrcTag); if (!pp->KeyExist("Parent")) break; pp = ToDictionary(pp->GetObjectFor("Parent")->GetDirect()); } return nullptr; } bool CopyInheritable(CPDF_Dictionary* pCurPageDict, CPDF_Dictionary* pSrcPageDict, const CFX_ByteString& key) { if (pCurPageDict->KeyExist(key)) return true; CPDF_Object* pInheritable = PageDictGetInheritableTag(pSrcPageDict, key); if (!pInheritable) return false; pCurPageDict->SetFor(key, pInheritable->Clone().release()); return true; } bool ParserPageRangeString(CFX_ByteString rangstring, std::vector<uint16_t>* pageArray, int nCount) { if (rangstring.IsEmpty()) return true; rangstring.Remove(' '); int nLength = rangstring.GetLength(); CFX_ByteString cbCompareString("0123456789-,"); for (int i = 0; i < nLength; ++i) { if (cbCompareString.Find(rangstring[i]) == -1) return false; } CFX_ByteString cbMidRange; int nStringFrom = 0; int nStringTo = 0; while (nStringTo < nLength) { nStringTo = rangstring.Find(',', nStringFrom); if (nStringTo == -1) nStringTo = nLength; cbMidRange = rangstring.Mid(nStringFrom, nStringTo - nStringFrom); int nMid = cbMidRange.Find('-'); if (nMid == -1) { long lPageNum = atol(cbMidRange.c_str()); if (lPageNum <= 0 || lPageNum > nCount) return false; pageArray->push_back((uint16_t)lPageNum); } else { int nStartPageNum = atol(cbMidRange.Mid(0, nMid).c_str()); if (nStartPageNum == 0) return false; ++nMid; int nEnd = cbMidRange.GetLength() - nMid; if (nEnd == 0) return false; int nEndPageNum = atol(cbMidRange.Mid(nMid, nEnd).c_str()); if (nStartPageNum < 0 || nStartPageNum > nEndPageNum || nEndPageNum > nCount) { return false; } for (int i = nStartPageNum; i <= nEndPageNum; ++i) { pageArray->push_back(i); } } nStringFrom = nStringTo + 1; } return true; } } // namespace class CPDF_PageOrganizer { public: CPDF_PageOrganizer(CPDF_Document* pDestPDFDoc, CPDF_Document* pSrcPDFDoc); ~CPDF_PageOrganizer(); bool PDFDocInit(); bool ExportPage(const std::vector<uint16_t>& pageNums, int nIndex); private: using ObjectNumberMap = std::map<uint32_t, uint32_t>; bool UpdateReference(CPDF_Object* pObj, ObjectNumberMap* pObjNumberMap); uint32_t GetNewObjId(ObjectNumberMap* pObjNumberMap, CPDF_Reference* pRef); CPDF_Document* m_pDestPDFDoc; CPDF_Document* m_pSrcPDFDoc; }; CPDF_PageOrganizer::CPDF_PageOrganizer(CPDF_Document* pDestPDFDoc, CPDF_Document* pSrcPDFDoc) : m_pDestPDFDoc(pDestPDFDoc), m_pSrcPDFDoc(pSrcPDFDoc) {} CPDF_PageOrganizer::~CPDF_PageOrganizer() {} bool CPDF_PageOrganizer::PDFDocInit() { ASSERT(m_pDestPDFDoc); ASSERT(m_pSrcPDFDoc); CPDF_Dictionary* pNewRoot = m_pDestPDFDoc->GetRoot(); if (!pNewRoot) return false; CPDF_Dictionary* pDocInfoDict = m_pDestPDFDoc->GetInfo(); if (!pDocInfoDict) return false; CFX_ByteString producerstr; producerstr.Format("PDFium"); pDocInfoDict->SetFor("Producer", new CPDF_String(producerstr, false)); CFX_ByteString cbRootType = pNewRoot->GetStringFor("Type", ""); if (cbRootType.IsEmpty()) pNewRoot->SetFor("Type", new CPDF_Name("Catalog")); CPDF_Object* pElement = pNewRoot->GetObjectFor("Pages"); CPDF_Dictionary* pNewPages = pElement ? ToDictionary(pElement->GetDirect()) : nullptr; if (!pNewPages) { pNewPages = new CPDF_Dictionary(m_pDestPDFDoc->GetByteStringPool()); pNewRoot->SetReferenceFor("Pages", m_pDestPDFDoc, m_pDestPDFDoc->AddIndirectObject(pNewPages)); } CFX_ByteString cbPageType = pNewPages->GetStringFor("Type", ""); if (cbPageType.IsEmpty()) pNewPages->SetFor("Type", new CPDF_Name("Pages")); if (!pNewPages->GetArrayFor("Kids")) { pNewPages->SetIntegerFor("Count", 0); pNewPages->SetReferenceFor( "Kids", m_pDestPDFDoc, m_pDestPDFDoc->AddIndirectObject(new CPDF_Array)); } return true; } bool CPDF_PageOrganizer::ExportPage(const std::vector<uint16_t>& pageNums, int nIndex) { int curpage = nIndex; auto pObjNumberMap = pdfium::MakeUnique<ObjectNumberMap>(); int nSize = pdfium::CollectionSize<int>(pageNums); for (int i = 0; i < nSize; ++i) { CPDF_Dictionary* pCurPageDict = m_pDestPDFDoc->CreateNewPage(curpage); CPDF_Dictionary* pSrcPageDict = m_pSrcPDFDoc->GetPage(pageNums[i] - 1); if (!pSrcPageDict || !pCurPageDict) return false; // Clone the page dictionary for (const auto& it : *pSrcPageDict) { const CFX_ByteString& cbSrcKeyStr = it.first; CPDF_Object* pObj = it.second; if (cbSrcKeyStr == "Type" || cbSrcKeyStr == "Parent") continue; pCurPageDict->SetFor(cbSrcKeyStr, pObj->Clone().release()); } // inheritable item // 1 MediaBox - required if (!CopyInheritable(pCurPageDict, pSrcPageDict, "MediaBox")) { // Search for "CropBox" in the source page dictionary, // if it does not exists, use the default letter size. CPDF_Object* pInheritable = PageDictGetInheritableTag(pSrcPageDict, "CropBox"); if (pInheritable) { pCurPageDict->SetFor("MediaBox", pInheritable->Clone().release()); } else { // Make the default size to be letter size (8.5'x11') CPDF_Array* pArray = new CPDF_Array; pArray->AddNumber(0); pArray->AddNumber(0); pArray->AddNumber(612); pArray->AddNumber(792); pCurPageDict->SetFor("MediaBox", pArray); } } // 2 Resources - required if (!CopyInheritable(pCurPageDict, pSrcPageDict, "Resources")) return false; // 3 CropBox - optional CopyInheritable(pCurPageDict, pSrcPageDict, "CropBox"); // 4 Rotate - optional CopyInheritable(pCurPageDict, pSrcPageDict, "Rotate"); // Update the reference uint32_t dwOldPageObj = pSrcPageDict->GetObjNum(); uint32_t dwNewPageObj = pCurPageDict->GetObjNum(); (*pObjNumberMap)[dwOldPageObj] = dwNewPageObj; UpdateReference(pCurPageDict, pObjNumberMap.get()); ++curpage; } return true; } bool CPDF_PageOrganizer::UpdateReference(CPDF_Object* pObj, ObjectNumberMap* pObjNumberMap) { switch (pObj->GetType()) { case CPDF_Object::REFERENCE: { CPDF_Reference* pReference = pObj->AsReference(); uint32_t newobjnum = GetNewObjId(pObjNumberMap, pReference); if (newobjnum == 0) return false; pReference->SetRef(m_pDestPDFDoc, newobjnum); break; } case CPDF_Object::DICTIONARY: { CPDF_Dictionary* pDict = pObj->AsDictionary(); auto it = pDict->begin(); while (it != pDict->end()) { const CFX_ByteString& key = it->first; CPDF_Object* pNextObj = it->second; ++it; if (key == "Parent" || key == "Prev" || key == "First") continue; if (!pNextObj) return false; if (!UpdateReference(pNextObj, pObjNumberMap)) pDict->RemoveFor(key); } break; } case CPDF_Object::ARRAY: { CPDF_Array* pArray = pObj->AsArray(); for (size_t i = 0; i < pArray->GetCount(); ++i) { CPDF_Object* pNextObj = pArray->GetObjectAt(i); if (!pNextObj) return false; if (!UpdateReference(pNextObj, pObjNumberMap)) return false; } break; } case CPDF_Object::STREAM: { CPDF_Stream* pStream = pObj->AsStream(); CPDF_Dictionary* pDict = pStream->GetDict(); if (!pDict) return false; if (!UpdateReference(pDict, pObjNumberMap)) return false; break; } default: break; } return true; } uint32_t CPDF_PageOrganizer::GetNewObjId(ObjectNumberMap* pObjNumberMap, CPDF_Reference* pRef) { if (!pRef) return 0; uint32_t dwObjnum = pRef->GetRefObjNum(); uint32_t dwNewObjNum = 0; const auto it = pObjNumberMap->find(dwObjnum); if (it != pObjNumberMap->end()) dwNewObjNum = it->second; if (dwNewObjNum) return dwNewObjNum; CPDF_Object* pDirect = pRef->GetDirect(); if (!pDirect) return 0; std::unique_ptr<CPDF_Object> pClone = pDirect->Clone(); if (CPDF_Dictionary* pDictClone = pClone->AsDictionary()) { if (pDictClone->KeyExist("Type")) { CFX_ByteString strType = pDictClone->GetStringFor("Type"); if (!FXSYS_stricmp(strType.c_str(), "Pages")) return 4; if (!FXSYS_stricmp(strType.c_str(), "Page")) return 0; } } CPDF_Object* pUnownedClone = pClone.get(); dwNewObjNum = m_pDestPDFDoc->AddIndirectObject(pClone.release()); (*pObjNumberMap)[dwObjnum] = dwNewObjNum; if (!UpdateReference(pUnownedClone, pObjNumberMap)) return 0; return dwNewObjNum; } DLLEXPORT FPDF_BOOL STDCALL FPDF_ImportPages(FPDF_DOCUMENT dest_doc, FPDF_DOCUMENT src_doc, FPDF_BYTESTRING pagerange, int index) { CPDF_Document* pDestDoc = CPDFDocumentFromFPDFDocument(dest_doc); if (!dest_doc) return false; CPDF_Document* pSrcDoc = CPDFDocumentFromFPDFDocument(src_doc); if (!pSrcDoc) return false; std::vector<uint16_t> pageArray; int nCount = pSrcDoc->GetPageCount(); if (pagerange) { if (!ParserPageRangeString(pagerange, &pageArray, nCount)) return false; } else { for (int i = 1; i <= nCount; ++i) { pageArray.push_back(i); } } CPDF_PageOrganizer pageOrg(pDestDoc, pSrcDoc); return pageOrg.PDFDocInit() && pageOrg.ExportPage(pageArray, index); } DLLEXPORT FPDF_BOOL STDCALL FPDF_CopyViewerPreferences(FPDF_DOCUMENT dest_doc, FPDF_DOCUMENT src_doc) { CPDF_Document* pDstDoc = CPDFDocumentFromFPDFDocument(dest_doc); if (!pDstDoc) return false; CPDF_Document* pSrcDoc = CPDFDocumentFromFPDFDocument(src_doc); if (!pSrcDoc) return false; CPDF_Dictionary* pSrcDict = pSrcDoc->GetRoot(); pSrcDict = pSrcDict->GetDictFor("ViewerPreferences"); if (!pSrcDict) return false; CPDF_Dictionary* pDstDict = pDstDoc->GetRoot(); if (!pDstDict) return false; pDstDict->SetFor("ViewerPreferences", pSrcDict->CloneDirectObject().release()); return true; } <|endoftext|>
<commit_before>#include "scene.hpp" Scene loadSDF(std::string const& filename) { Scene scene; std::map<std::string,std::shared_ptr<Shape>> tmp_shapes; std::ifstream file; file.open(filename); std::string line; if(file.is_open()) { while(std::getline(file, line)) { Material mat; std::stringstream ss; std::string keyword; ss<<line; ss>>keyword; if (keyword == "define") { ss>>keyword; if (keyword == "material") { ss>>mat.name_; ss>>mat.ka_.r; ss>>mat.ka_.g; ss>>mat.ka_.b; ss>>mat.kd_.r; ss>>mat.kd_.g; ss>>mat.kd_.b; ss>>mat.ks_.r; ss>>mat.ks_.g; ss>>mat.ks_.b; ss>>mat.m_; scene.materials[mat.name_]= mat; std::cout << "another material added to scene...\n"; } if (keyword == "shape") { ss>>keyword; if (keyword =="box") { std::string name,color; glm::vec3 min, max; ss>>name; ss>>min.x; ss>>min.y; ss>>min.z; ss>>max.x; ss>>max.y; ss>>max.z; ss>>color; //std::cout << box << std::endl; std::shared_ptr<Shape> box0 = std::make_shared<Box> (scene.materials[color],name,min,max); tmp_shapes[name] = box0; std::cout << "another box added to scene...\n"; } if (keyword == "sphere") { std::string name, color; glm::vec3 middlpt; float r; ss>>name; ss>>middlpt.x; ss>>middlpt.y; ss>>middlpt.z; ss>>r; ss>>color; std::shared_ptr<Shape> sphere0 = std::make_shared<Sphere> (scene.materials[color],name, middlpt,r); tmp_shapes[name] = sphere0; std::cout << "another sphere added to scene...\n"; } if (keyword == "composite") { std::string name, shape1, shape2; ss>>name; ss>>shape1; ss>>shape2; std::shared_ptr<Composite> comp0 = std::make_shared<Composite> (name); comp0->add_shape(tmp_shapes[shape1]); comp0->add_shape(tmp_shapes[shape2]); scene.shapes.push_back(comp0); } } if (keyword == "camera") { ss>>scene.camera.name_; ss>>scene.camera.fov_x_; ss>>scene.camera.origin_.x; ss>>scene.camera.origin_.y; ss>>scene.camera.origin_.z; ss>>scene.camera.dir_.x; ss>>scene.camera.dir_.y; ss>>scene.camera.dir_.z; ss>>scene.camera.up_.x; ss>>scene.camera.up_.y; ss>>scene.camera.up_.z; std::cout << "another camera added to scene...\n"; } if (keyword == "light") { std::string name; glm::vec3 pos; Color ambient; Color diffuse; ss>>name; ss>>pos.x; ss>>pos.y; ss>>pos.z; ss>>ambient.r; ss>>ambient.g; ss>>ambient.b; ss>>diffuse.r; ss>>diffuse.g; ss>>diffuse.b; std::shared_ptr<Light> light = std::make_shared<Light> (name,pos,ambient,diffuse); scene.lights.push_back(light); std::cout << "another light added to scene...\n"; } } else if (keyword == "render") { ss>>keyword; ss>>scene.filename; ss>>scene.width; ss>>scene.height; std::cout << "rendering taking place...\n" ; } } } return scene; } <commit_msg>in scene wird jetzt die box zu composite hinzugefuegt<commit_after>#include "scene.hpp" Scene loadSDF(std::string const& filename) { Scene scene; std::map<std::string,std::shared_ptr<Shape>> tmp_shapes; std::ifstream file; file.open(filename); std::string line; if(file.is_open()) { while(std::getline(file, line)) { Material mat; std::stringstream ss; std::string keyword; ss<<line; ss>>keyword; if (keyword == "define") { ss>>keyword; if (keyword == "material") { ss>>mat.name_; ss>>mat.ka_.r; ss>>mat.ka_.g; ss>>mat.ka_.b; ss>>mat.kd_.r; ss>>mat.kd_.g; ss>>mat.kd_.b; ss>>mat.ks_.r; ss>>mat.ks_.g; ss>>mat.ks_.b; ss>>mat.m_; scene.materials[mat.name_]= mat; std::cout << "another material added to scene...\n"; } if (keyword == "shape") { ss>>keyword; if (keyword =="box") { std::string name,color; glm::vec3 min, max; ss>>name; ss>>min.x; ss>>min.y; ss>>min.z; ss>>max.x; ss>>max.y; ss>>max.z; ss>>color; //std::cout << box << std::endl; std::shared_ptr<Shape> box0 = std::make_shared<Box> (scene.materials[color],name,min,max); tmp_shapes[name] = box0; std::cout << "another box added to scene...\n"; } if (keyword == "sphere") { std::string name, color; glm::vec3 middlpt; float r; ss>>name; ss>>middlpt.x; ss>>middlpt.y; ss>>middlpt.z; ss>>r; ss>>color; std::shared_ptr<Shape> sphere0 = std::make_shared<Sphere> (scene.materials[color],name, middlpt,r); tmp_shapes[name] = sphere0; std::cout << "another sphere added to scene...\n"; } if (keyword == "composite") { std::string name, shape1, shape2, box0; ss>>name; ss>>shape1; ss>>shape2; ss>>box0; std::shared_ptr<Composite> comp0 = std::make_shared<Composite> (name); comp0->add_shape(tmp_shapes[shape1]); comp0->add_shape(tmp_shapes[shape2]); comp0->add_shape(tmp_shapes[box0]); scene.shapes.push_back(comp0); } } if (keyword == "camera") { ss>>scene.camera.name_; ss>>scene.camera.fov_x_; ss>>scene.camera.origin_.x; ss>>scene.camera.origin_.y; ss>>scene.camera.origin_.z; ss>>scene.camera.dir_.x; ss>>scene.camera.dir_.y; ss>>scene.camera.dir_.z; ss>>scene.camera.up_.x; ss>>scene.camera.up_.y; ss>>scene.camera.up_.z; std::cout << "another camera added to scene...\n"; } if (keyword == "light") { std::string name; glm::vec3 pos; Color ambient; Color diffuse; ss>>name; ss>>pos.x; ss>>pos.y; ss>>pos.z; ss>>ambient.r; ss>>ambient.g; ss>>ambient.b; ss>>diffuse.r; ss>>diffuse.g; ss>>diffuse.b; std::shared_ptr<Light> light = std::make_shared<Light> (name,pos,ambient,diffuse); scene.lights.push_back(light); std::cout << "another light added to scene...\n"; } } else if (keyword == "render") { ss>>keyword; ss>>scene.filename; ss>>scene.width; ss>>scene.height; std::cout << "rendering taking place...\n" ; } } } return scene; } <|endoftext|>
<commit_before>#include "List.hpp" #include "../App.hpp" using namespace morda; namespace{ class StaticProvider : public List::ItemsProvider{ std::vector<std::unique_ptr<stob::Node>> widgets; public: size_t count() const noexcept override{ return this->widgets.size(); } std::shared_ptr<Widget> getWidget(size_t index)const override{ // TRACE(<< "StaticProvider::getWidget(): index = " << index << std::endl) return morda::App::Inst().inflater.Inflate(*(this->widgets[index])); } void recycle(size_t index, std::shared_ptr<Widget> w)const override{ // TRACE(<< "StaticProvider::recycle(): index = " << index << std::endl) } void add(std::unique_ptr<stob::Node> w){ this->widgets.push_back(std::move(w)); } }; } List::List(bool isVertical, const stob::Node* chain): Widget(chain), isVertical(isVertical) { if(!chain){ return; } const stob::Node* n = chain->ThisOrNextNonProperty().node(); if(!n){ return; } std::shared_ptr<StaticProvider> p = ting::New<StaticProvider>(); for(; n; n = n->NextNonProperty().node()){ p->add(n->Clone()); } this->setItemsProvider(std::move(p)); } void List::layOut() { TRACE(<< "List::layOut(): invoked" << std::endl) this->numTailItems = 0;//means that it needs to be recomputed this->updateChildrenList(); } void List::setItemsProvider(std::shared_ptr<ItemsProvider> provider){ if(this->provider){ this->provider->list = nullptr; } this->provider = std::move(provider); if(this->provider){ this->provider->list = this; } this->notifyDataSetChanged(); } real List::scrollFactor()const noexcept{ if(!this->provider || this->provider->count() == 0){ return 0; } return real(this->posIndex) / real(this->provider->count() - this->visibleCount()); } void List::setScrollPosAsFactor(real factor){ if(!this->provider || this->provider->count() == 0){ return; } if(this->numTailItems == 0){ this->updateTailItemsInfo(); } this->posIndex = size_t(factor * real(this->provider->count() - this->numTailItems)); // TRACE(<< "List::setScrollPosAsFactor(): this->posIndex = " << this->posIndex << std::endl) if(this->provider->count() != this->numTailItems){ real intFactor = real(this->posIndex) / real(this->provider->count() - this->numTailItems); if(this->Children().size() != 0){ real d; if(this->isVertical){ d = this->Children().front()->rect().d.y; }else{ d = this->Children().front()->rect().d.x; } this->posOffset = ting::math::Round(d * (factor - intFactor) * real(this->provider->count() - this->numTailItems) + factor * this->firstTailItemOffset); }else{ this->posOffset = 0; } }else{ ASSERT(this->posIndex == 0) this->posOffset = ting::math::Round(factor * this->firstTailItemOffset); } this->updateChildrenList(); } bool List::arrangeWidget(std::shared_ptr<Widget>& w, real& pos, bool added, size_t index, T_ChildrenList::const_iterator insertBefore){ auto& lp = this->getLayoutParamsAs<LayoutParams>(*w); Vec2r dim = this->dimForWidget(*w, lp); w->resize(dim); if(this->isVertical){ pos -= w->rect().d.y; w->moveTo(Vec2r(0, pos)); if(pos < this->rect().d.y){ if(!added){ this->Add(w, insertBefore); } if(this->addedIndex > index){ this->addedIndex = index; } }else{ ++this->posIndex; this->posOffset -= w->rect().d.y; if(added){ auto widget = this->Remove(*w); if(this->provider){ this->provider->recycle(index, widget); } ++this->addedIndex; }else{ if(this->provider){ this->provider->recycle(index, w); } } } if(w->rect().p.y <= 0){ return true; } }else{ w->moveTo(Vec2r(pos, 0)); pos += w->rect().d.x; if(pos > 0){ if(!added){ this->Add(w, insertBefore); } if(this->addedIndex > index){ this->addedIndex = index; } }else{ ++this->posIndex; this->posOffset -= w->rect().d.x; if(added){ auto widget = this->Remove(*w); if(this->provider){ this->provider->recycle(index, widget); } ++this->addedIndex; }else{ if(this->provider){ this->provider->recycle(index, w); } } } if(w->rect().Right() >= this->rect().d.x){ return true; } } return false; } void List::updateChildrenList(){ if(!this->provider){ this->posIndex = 0; this->posOffset = 0; this->removeAll(); this->addedIndex = size_t(-1); return; } if(this->numTailItems == 0){ this->updateTailItemsInfo(); } if(this->posIndex == this->firstTailItemIndex){ if(this->posOffset > this->firstTailItemOffset){ this->posOffset = this->firstTailItemOffset; } }else if(this->posIndex > this->firstTailItemIndex){ this->posIndex = this->firstTailItemIndex; this->posOffset = this->firstTailItemOffset; } real pos; if(this->isVertical){ pos = this->rect().d.y + this->posOffset; }else{ pos = -this->posOffset; } // TRACE(<< "List::updateChildrenList(): this->addedIndex = " << this->addedIndex << " this->posIndex = " << this->posIndex << std::endl) //remove widgets from top for(; this->Children().size() != 0 && this->addedIndex < this->posIndex; ++this->addedIndex){ auto w = (*this->Children().begin())->removeFromParent(); if(this->provider){ this->provider->recycle(this->addedIndex, w); } } auto iter = this->Children().begin(); size_t iterIndex = this->addedIndex; size_t iterEndIndex = iterIndex + this->Children().size(); size_t index = this->posIndex; for(; index < this->provider->count();){ std::shared_ptr<Widget> w; bool isAdded; if(iterIndex <= index && index < iterEndIndex && iter != this->Children().end()){ w = *iter; ++iter; ++iterIndex; isAdded = true; }else{ w = this->provider->getWidget(index); isAdded = false; } if(this->arrangeWidget(w, pos, isAdded, index, iter)){ ++index; break; } ++index; } //remove rest if(iterIndex < iterEndIndex){ size_t oldIterIndex = iterIndex; for(;;){ auto i = iter; ++i; ++iterIndex; if(i == this->Children().end()){ break; } auto w = this->Remove(i); if(this->provider){ this->provider->recycle(iterIndex, w); } } auto w = this->Remove(iter); if(this->provider){ this->provider->recycle(oldIterIndex, w); } } } void List::updateTailItemsInfo(){ this->numTailItems = 0; if(!this->provider || this->provider->count() == 0){ return; } real dim; if(this->isVertical){ dim = this->rect().d.y; }else{ dim = this->rect().d.x; } ASSERT(this->provider) ASSERT(this->provider->count() > 0) for(size_t i = this->provider->count(); i != 0 && dim > 0; --i){ ++this->numTailItems; auto w = this->provider->getWidget(i - 1); auto& lp = this->getLayoutParamsAs<LayoutParams>(*w); Vec2r d = this->dimForWidget(*w, lp); if(this->isVertical){ dim -= d.y; }else{ dim -= d.x; } } this->firstTailItemIndex = this->provider->count() - this->numTailItems; if(dim > 0){ this->firstTailItemOffset = -1; }else{ this->firstTailItemOffset = -dim; } } morda::Vec2r List::measure(const morda::Vec2r& quotum) const { unsigned longIndex, transIndex; if(this->isVertical){ longIndex = 1; transIndex = 0; }else{ longIndex = 0; transIndex = 1; } Vec2r ret(quotum); ting::util::ClampBottom(ret[longIndex], real(0)); if(ret[transIndex] > 0){ return ret; } ret[transIndex] = 0; for(auto i = this->Children().begin(); i != this->Children().end(); ++i){ ting::util::ClampBottom(ret[transIndex], (*i)->rect().d[transIndex]); } return ret; } <commit_msg>stuff<commit_after>#include "List.hpp" #include "../App.hpp" using namespace morda; namespace{ class StaticProvider : public List::ItemsProvider{ std::vector<std::unique_ptr<stob::Node>> widgets; public: size_t count() const noexcept override{ return this->widgets.size(); } std::shared_ptr<Widget> getWidget(size_t index)const override{ // TRACE(<< "StaticProvider::getWidget(): index = " << index << std::endl) return morda::App::Inst().inflater.Inflate(*(this->widgets[index])); } void recycle(size_t index, std::shared_ptr<Widget> w)const override{ // TRACE(<< "StaticProvider::recycle(): index = " << index << std::endl) } void add(std::unique_ptr<stob::Node> w){ this->widgets.push_back(std::move(w)); } }; } List::List(bool isVertical, const stob::Node* chain): Widget(chain), isVertical(isVertical) { if(!chain){ return; } const stob::Node* n = chain->ThisOrNextNonProperty().node(); if(!n){ return; } std::shared_ptr<StaticProvider> p = ting::New<StaticProvider>(); for(; n; n = n->NextNonProperty().node()){ p->add(n->Clone()); } this->setItemsProvider(std::move(p)); } void List::layOut() { // TRACE(<< "List::layOut(): invoked" << std::endl) this->numTailItems = 0;//means that it needs to be recomputed this->updateChildrenList(); } void List::setItemsProvider(std::shared_ptr<ItemsProvider> provider){ if(this->provider){ this->provider->list = nullptr; } this->provider = std::move(provider); if(this->provider){ this->provider->list = this; } this->notifyDataSetChanged(); } real List::scrollFactor()const noexcept{ if(!this->provider || this->provider->count() == 0){ return 0; } return real(this->posIndex) / real(this->provider->count() - this->visibleCount()); } void List::setScrollPosAsFactor(real factor){ if(!this->provider || this->provider->count() == 0){ return; } if(this->numTailItems == 0){ this->updateTailItemsInfo(); } this->posIndex = size_t(factor * real(this->provider->count() - this->numTailItems)); // TRACE(<< "List::setScrollPosAsFactor(): this->posIndex = " << this->posIndex << std::endl) if(this->provider->count() != this->numTailItems){ real intFactor = real(this->posIndex) / real(this->provider->count() - this->numTailItems); if(this->Children().size() != 0){ real d; if(this->isVertical){ d = this->Children().front()->rect().d.y; }else{ d = this->Children().front()->rect().d.x; } this->posOffset = ting::math::Round(d * (factor - intFactor) * real(this->provider->count() - this->numTailItems) + factor * this->firstTailItemOffset); }else{ this->posOffset = 0; } }else{ ASSERT(this->posIndex == 0) this->posOffset = ting::math::Round(factor * this->firstTailItemOffset); } this->updateChildrenList(); } bool List::arrangeWidget(std::shared_ptr<Widget>& w, real& pos, bool added, size_t index, T_ChildrenList::const_iterator insertBefore){ auto& lp = this->getLayoutParamsAs<LayoutParams>(*w); Vec2r dim = this->dimForWidget(*w, lp); w->resize(dim); if(this->isVertical){ pos -= w->rect().d.y; w->moveTo(Vec2r(0, pos)); if(pos < this->rect().d.y){ if(!added){ this->Add(w, insertBefore); } if(this->addedIndex > index){ this->addedIndex = index; } }else{ ++this->posIndex; this->posOffset -= w->rect().d.y; if(added){ auto widget = this->Remove(*w); if(this->provider){ this->provider->recycle(index, widget); } ++this->addedIndex; }else{ if(this->provider){ this->provider->recycle(index, w); } } } if(w->rect().p.y <= 0){ return true; } }else{ w->moveTo(Vec2r(pos, 0)); pos += w->rect().d.x; if(pos > 0){ if(!added){ this->Add(w, insertBefore); } if(this->addedIndex > index){ this->addedIndex = index; } }else{ ++this->posIndex; this->posOffset -= w->rect().d.x; if(added){ auto widget = this->Remove(*w); if(this->provider){ this->provider->recycle(index, widget); } ++this->addedIndex; }else{ if(this->provider){ this->provider->recycle(index, w); } } } if(w->rect().Right() >= this->rect().d.x){ return true; } } return false; } void List::updateChildrenList(){ if(!this->provider){ this->posIndex = 0; this->posOffset = 0; this->removeAll(); this->addedIndex = size_t(-1); return; } if(this->numTailItems == 0){ this->updateTailItemsInfo(); } if(this->posIndex == this->firstTailItemIndex){ if(this->posOffset > this->firstTailItemOffset){ this->posOffset = this->firstTailItemOffset; } }else if(this->posIndex > this->firstTailItemIndex){ this->posIndex = this->firstTailItemIndex; this->posOffset = this->firstTailItemOffset; } real pos; if(this->isVertical){ pos = this->rect().d.y + this->posOffset; }else{ pos = -this->posOffset; } // TRACE(<< "List::updateChildrenList(): this->addedIndex = " << this->addedIndex << " this->posIndex = " << this->posIndex << std::endl) //remove widgets from top for(; this->Children().size() != 0 && this->addedIndex < this->posIndex; ++this->addedIndex){ auto w = (*this->Children().begin())->removeFromParent(); if(this->provider){ this->provider->recycle(this->addedIndex, w); } } auto iter = this->Children().begin(); size_t iterIndex = this->addedIndex; size_t iterEndIndex = iterIndex + this->Children().size(); size_t index = this->posIndex; for(; index < this->provider->count();){ std::shared_ptr<Widget> w; bool isAdded; if(iterIndex <= index && index < iterEndIndex && iter != this->Children().end()){ w = *iter; ++iter; ++iterIndex; isAdded = true; }else{ w = this->provider->getWidget(index); isAdded = false; } if(this->arrangeWidget(w, pos, isAdded, index, iter)){ ++index; break; } ++index; } //remove rest if(iterIndex < iterEndIndex){ size_t oldIterIndex = iterIndex; for(;;){ auto i = iter; ++i; ++iterIndex; if(i == this->Children().end()){ break; } auto w = this->Remove(i); if(this->provider){ this->provider->recycle(iterIndex, w); } } auto w = this->Remove(iter); if(this->provider){ this->provider->recycle(oldIterIndex, w); } } } void List::updateTailItemsInfo(){ this->numTailItems = 0; if(!this->provider || this->provider->count() == 0){ return; } real dim; if(this->isVertical){ dim = this->rect().d.y; }else{ dim = this->rect().d.x; } ASSERT(this->provider) ASSERT(this->provider->count() > 0) for(size_t i = this->provider->count(); i != 0 && dim > 0; --i){ ++this->numTailItems; auto w = this->provider->getWidget(i - 1); auto& lp = this->getLayoutParamsAs<LayoutParams>(*w); Vec2r d = this->dimForWidget(*w, lp); if(this->isVertical){ dim -= d.y; }else{ dim -= d.x; } } this->firstTailItemIndex = this->provider->count() - this->numTailItems; if(dim > 0){ this->firstTailItemOffset = -1; }else{ this->firstTailItemOffset = -dim; } } morda::Vec2r List::measure(const morda::Vec2r& quotum) const { unsigned longIndex, transIndex; if(this->isVertical){ longIndex = 1; transIndex = 0; }else{ longIndex = 0; transIndex = 1; } Vec2r ret(quotum); ting::util::ClampBottom(ret[longIndex], real(0)); if(ret[transIndex] > 0){ return ret; } ret[transIndex] = 0; for(auto i = this->Children().begin(); i != this->Children().end(); ++i){ ting::util::ClampBottom(ret[transIndex], (*i)->rect().d[transIndex]); } return ret; } <|endoftext|>
<commit_before>#pragma once #include <memory> namespace beat { template <class BV> struct IGetBV { virtual BV operator()(const void* p) const = 0; }; template <class BV> using GetBV_SP = std::shared_ptr<IGetBV<BV>>; } <commit_msg>IGetBV: virtual-dtor fix<commit_after>#pragma once #include <memory> namespace beat { template <class BV> struct IGetBV { virtual BV operator()(const void* p) const = 0; virtual ~IGetBV() {} }; template <class BV> using GetBV_SP = std::shared_ptr<IGetBV<BV>>; } <|endoftext|>
<commit_before>/*========================================================================= Library : Image Registration Toolkit (IRTK) Module : $Id$ Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2008 onwards Date : $Date$ Version : $Revision$ Changes : $Author$ =========================================================================*/ #include <irtkImage.h> #include <irtkTransformation.h> // Default filenames char *input_name = NULL, *input_name_x = NULL, *input_name_y = NULL, *input_name_z = NULL, *output_name = NULL; void usage() { cerr << "Usage: image2dof [image] [dx] [dy] [dz] [dof] <options> \n" << endl; cerr << "where <options> is one or more of the following:\n" << endl; cerr << "<-bspline spacing> Fit an approximation using a BSpline FFD with the specified spacing in mm" << endl; exit(1); } int main(int argc, char **argv) { int i, j, k, ok, bspline; double x, y, z, x1, y1, z1, x2, y2, z2, xsize, ysize, zsize, xaxis[3], yaxis[3], zaxis[3], spacing; if (argc < 3) { usage(); } // Parse file names input_name = argv[1]; argc--; argv++; input_name_x = argv[1]; argc--; argv++; input_name_y = argv[1]; argc--; argv++; input_name_z = argv[1]; argc--; argv++; output_name = argv[1]; argc--; argv++; bspline = false; while (argc > 1) { ok = false; if ((ok == false) && (strcmp(argv[1], "-bspline") == 0)) { argc--; argv++; spacing = atof(argv[1]); argc--; argv++; bspline = true; ok = true; } if (ok == false) { cerr << "Can not parse argument " << argv[1] << endl; usage(); } } // Read image irtkGreyImage image; image.Read(input_name); // Read images with displacements irtkRealImage dx; irtkRealImage dy; irtkRealImage dz; dx.Read(input_name_x); dy.Read(input_name_y); dz.Read(input_name_z); // Compute bounding box of data x1 = 0; y1 = 0; z1 = 0; x2 = dx.GetX()-1; y2 = dx.GetY()-1; z2 = dx.GetZ()-1; dx.ImageToWorld(x1, y1, z1); dx.ImageToWorld(x2, y2, z2); dx.GetOrientation(xaxis, yaxis, zaxis); dx.GetPixelSize(&xsize, &ysize, &zsize); // Create transformation irtkMultiLevelFreeFormTransformation *transformation = new irtkMultiLevelFreeFormTransformation; irtkFreeFormTransformation3D *ffd; if (bspline) { int no = dx.GetX() * dx.GetY() * dx.GetZ(); int index; double dispX, dispY, dispZ, point2X, point2Y, point2Z; double *pointsX = new double[no]; double *pointsY = new double[no]; double *pointsZ = new double[no]; double *displacementsX = new double[no]; double *displacementsY = new double[no]; double *displacementsZ = new double[no]; //Create deformation ffd = new irtkBSplineFreeFormTransformation(x1, y1, z1, x2, y2, z2, spacing, spacing, spacing, xaxis, yaxis, zaxis); index = 0; for (k = 0; k < image.GetZ(); k++) { for (j = 0; j < image.GetY(); j++) { for (i = 0; i < image.GetX(); i++) { x = i; y = j; z = k; image.ImageToWorld(x, y, z); pointsX[index] = x; pointsY[index] = y; pointsZ[index] = z; point2X = i + dx.Get(i, j, k); point2Y = j + dy.Get(i, j, k); point2Z = k + dz.Get(i, j, k); image.ImageToWorld(point2X, point2Y, point2Z); dispX = point2X - x; dispY = point2Y - y; dispZ = point2Z - z; displacementsX[index] = dispX; displacementsY[index] = dispY; displacementsZ[index] = dispZ; index++; } } } ffd->Approximate(pointsX, pointsY, pointsZ, displacementsX, displacementsY, displacementsZ, no); } else { // Create deformation ffd = new irtkLinearFreeFormTransformation(x1, y1, z1, x2, y2, z2, xsize, ysize, zsize, xaxis, yaxis, zaxis); // Initialize point structure with transformed point positions for (k = 0; k < dx.GetZ(); k++) { for (j = 0; j < dx.GetY(); j++) { for (i = 0; i < dx.GetX(); i++) { ffd->Put(i, j, k, dx(i, j, k), dy(i, j, k), dz(i, j, k)); } } } } // Add deformation transformation->PushLocalTransformation(ffd); // Write transformation transformation->irtkTransformation::Write(output_name); } <commit_msg>The bspline case of Image2dof now expects displacements images with values in world coordinates (milimeters) as it should be<commit_after>/*========================================================================= Library : Image Registration Toolkit (IRTK) Module : $Id$ Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2008 onwards Date : $Date$ Version : $Revision$ Changes : $Author$ =========================================================================*/ #include <irtkImage.h> #include <irtkTransformation.h> // Default filenames char *input_name = NULL, *input_name_x = NULL, *input_name_y = NULL, *input_name_z = NULL, *output_name = NULL; void usage() { cerr << "Usage: image2dof [image] [dx] [dy] [dz] [dof] <options> \n" << endl; cerr << "where <options> is one or more of the following:\n" << endl; cerr << "<-bspline spacing> Fit an approximation using a BSpline FFD with the specified spacing in mm" << endl; exit(1); } int main(int argc, char **argv) { int i, j, k, ok, bspline; double x, y, z, x1, y1, z1, x2, y2, z2, xsize, ysize, zsize, xaxis[3], yaxis[3], zaxis[3], spacing; if (argc < 3) { usage(); } // Parse file names input_name = argv[1]; argc--; argv++; input_name_x = argv[1]; argc--; argv++; input_name_y = argv[1]; argc--; argv++; input_name_z = argv[1]; argc--; argv++; output_name = argv[1]; argc--; argv++; bspline = false; while (argc > 1) { ok = false; if ((ok == false) && (strcmp(argv[1], "-bspline") == 0)) { argc--; argv++; spacing = atof(argv[1]); argc--; argv++; bspline = true; ok = true; } if (ok == false) { cerr << "Can not parse argument " << argv[1] << endl; usage(); } } // Read image irtkGreyImage image; image.Read(input_name); // Read images with displacements irtkRealImage dx; irtkRealImage dy; irtkRealImage dz; dx.Read(input_name_x); dy.Read(input_name_y); dz.Read(input_name_z); // Compute bounding box of data x1 = 0; y1 = 0; z1 = 0; x2 = dx.GetX()-1; y2 = dx.GetY()-1; z2 = dx.GetZ()-1; dx.ImageToWorld(x1, y1, z1); dx.ImageToWorld(x2, y2, z2); dx.GetOrientation(xaxis, yaxis, zaxis); dx.GetPixelSize(&xsize, &ysize, &zsize); // Create transformation irtkMultiLevelFreeFormTransformation *transformation = new irtkMultiLevelFreeFormTransformation; irtkFreeFormTransformation3D *ffd; if (bspline) { int no = dx.GetX() * dx.GetY() * dx.GetZ(); int index; double *pointsX = new double[no]; double *pointsY = new double[no]; double *pointsZ = new double[no]; double *displacementsX = new double[no]; double *displacementsY = new double[no]; double *displacementsZ = new double[no]; //Create deformation ffd = new irtkBSplineFreeFormTransformation(x1, y1, z1, x2, y2, z2, spacing, spacing, spacing, xaxis, yaxis, zaxis); index = 0; for (k = 0; k < image.GetZ(); k++) { for (j = 0; j < image.GetY(); j++) { for (i = 0; i < image.GetX(); i++) { x = i; y = j; z = k; image.ImageToWorld(x, y, z); pointsX[index] = x; pointsY[index] = y; pointsZ[index] = z; displacementsX[index] = dx.Get(i, j, k); displacementsY[index] = dy.Get(i, j, k); displacementsZ[index] = dz.Get(i, j, k); index++; } } } ffd->Approximate(pointsX, pointsY, pointsZ, displacementsX, displacementsY, displacementsZ, no); } else { // Create deformation ffd = new irtkLinearFreeFormTransformation(x1, y1, z1, x2, y2, z2, xsize, ysize, zsize, xaxis, yaxis, zaxis); // Initialize point structure with transformed point positions for (k = 0; k < dx.GetZ(); k++) { for (j = 0; j < dx.GetY(); j++) { for (i = 0; i < dx.GetX(); i++) { ffd->Put(i, j, k, dx(i, j, k), dy(i, j, k), dz(i, j, k)); } } } } // Add deformation transformation->PushLocalTransformation(ffd); // Write transformation transformation->irtkTransformation::Write(output_name); } <|endoftext|>
<commit_before>#include <cstdlib> #include <sqlite3.h> #include <nan.h> #include "macros.h" #include "database.h" namespace NODE_SQLITE3_PLUS_DATABASE { int WRITE_MODE = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX; int READ_MODE = SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX; v8::PropertyAttribute FROZEN = static_cast<v8::PropertyAttribute>(v8::DontDelete | v8::ReadOnly); bool CONSTRUCTING_STATEMENT = false; class Database : public Nan::ObjectWrap { public: Database(char*); ~Database(); static NAN_MODULE_INIT(Init); friend class OpenWorker; friend class CloseWorker; private: static CONSTRUCTOR(constructor); static NAN_METHOD(New); static NAN_GETTER(OpenGetter); static NAN_METHOD(Close); static NAN_METHOD(Prepare); char* filename; sqlite3* readHandle; sqlite3* writeHandle; bool open; bool closed; }; class Statement : public Nan::ObjectWrap { public: Statement(); ~Statement(); static void Init(); friend class Database; private: static CONSTRUCTOR(constructor); static NAN_METHOD(New); sqlite3_stmt* handle; bool dead; }; class OpenWorker : public Nan::AsyncWorker { public: OpenWorker(Database*); ~OpenWorker(); void Execute(); void HandleOKCallback(); void HandleErrorCallback(); private: Database* db; }; class CloseWorker : public Nan::AsyncWorker { public: CloseWorker(Database*, bool); ~CloseWorker(); void Execute(); void HandleOKCallback(); void HandleErrorCallback(); private: Database* db; bool actuallyClose; }; Database::Database(char* filename) : Nan::ObjectWrap(), filename(filename), readHandle(NULL), writeHandle(NULL), open(false), closed(false) {} Database::~Database() { open = false; sqlite3_close(readHandle); sqlite3_close(writeHandle); readHandle = NULL; writeHandle = NULL; free(filename); filename = NULL; } NAN_MODULE_INIT(Database::Init) { Nan::HandleScope scope; v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(New); t->InstanceTemplate()->SetInternalFieldCount(1); t->SetClassName(Nan::New("Database").ToLocalChecked()); Nan::SetPrototypeMethod(t, "disconnect", Close); Nan::SetPrototypeMethod(t, "prepare", Prepare); Nan::SetAccessor(t->InstanceTemplate(), Nan::New("connected").ToLocalChecked(), OpenGetter); constructor.Reset(Nan::GetFunction(t).ToLocalChecked()); Nan::Set(target, Nan::New("Database").ToLocalChecked(), Nan::GetFunction(t).ToLocalChecked()); } CONSTRUCTOR(Database::constructor); NAN_METHOD(Database::New) { REQUIRE_ARGUMENTS(1); if (!info.IsConstructCall()) { v8::Local<v8::Value> args[1] = {info[0]}; v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor); info.GetReturnValue().Set(cons->NewInstance(1, args)); } else { REQUIRE_ARGUMENT_STRING(0, filename); Database* db = new Database(RAW_STRING(filename)); db->Wrap(info.This()); db->Ref(); AsyncQueueWorker(new OpenWorker(db)); info.GetReturnValue().Set(info.This()); } } NAN_GETTER(Database::OpenGetter) { Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); info.GetReturnValue().Set(db->open); } NAN_METHOD(Database::Close) { Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); if (!db->closed) { db->closed = true; // -- // This should wait in queue for all pending transactions to finish. (writes AND reads) db->Ref(); AsyncQueueWorker(new CloseWorker(db, db->open)); // -- db->open = false; } info.GetReturnValue().Set(info.This()); } NAN_METHOD(Database::Prepare) { REQUIRE_ARGUMENT_STRING(0, source); v8::Local<v8::Function> cons = Nan::New<v8::Function>(Statement::constructor); CONSTRUCTING_STATEMENT = true; v8::Local<v8::Object> statement = cons->NewInstance(0, NULL); CONSTRUCTING_STATEMENT = false; Nan::ForceSet(statement, Nan::New("database").ToLocalChecked(), info.This(), FROZEN); Nan::ForceSet(statement, Nan::New("source").ToLocalChecked(), source, FROZEN); info.GetReturnValue().Set(statement); } Statement::Statement() : Nan::ObjectWrap(), handle(NULL), dead(false) {} Statement::~Statement() { dead = true; sqlite3_finalize(handle); handle = NULL; } void Statement::Init() { Nan::HandleScope scope; v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(New); t->InstanceTemplate()->SetInternalFieldCount(1); t->SetClassName(Nan::New("Statement").ToLocalChecked()); constructor.Reset(Nan::GetFunction(t).ToLocalChecked()); } CONSTRUCTOR(Statement::constructor); NAN_METHOD(Statement::New) { if (!CONSTRUCTING_STATEMENT) { return Nan::ThrowSyntaxError("Statements can only be constructed by the db.prepare() method."); } Statement* stmt = new Statement(); stmt->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } OpenWorker::OpenWorker(Database* db) : Nan::AsyncWorker(NULL), db(db) {} OpenWorker::~OpenWorker() {} void OpenWorker::Execute() { int status; status = sqlite3_open_v2(db->filename, &db->writeHandle, WRITE_MODE, NULL); if (status != SQLITE_OK) { SetErrorMessage(sqlite3_errmsg(db->writeHandle)); sqlite3_close(db->writeHandle); db->writeHandle = NULL; return; } status = sqlite3_open_v2(db->filename, &db->readHandle, READ_MODE, NULL); if (status != SQLITE_OK) { SetErrorMessage(sqlite3_errmsg(db->readHandle)); sqlite3_close(db->writeHandle); sqlite3_close(db->readHandle); db->writeHandle = NULL; db->readHandle = NULL; return; } sqlite3_busy_timeout(db->writeHandle, 30000); sqlite3_busy_timeout(db->readHandle, 30000); } void OpenWorker::HandleOKCallback() { Nan::HandleScope scope; if (db->closed) { sqlite3_close(db->writeHandle); sqlite3_close(db->readHandle); db->writeHandle = NULL; db->readHandle = NULL; } else { db->open = true; v8::Local<v8::Value> args[1] = {Nan::New("connect").ToLocalChecked()}; EMIT_EVENT(db->handle(), 1, args); } db->Unref(); } void OpenWorker::HandleErrorCallback() { Nan::HandleScope scope; if (!db->closed) { db->closed = true; v8::Local<v8::Value> args[2] = { Nan::New("disconnect").ToLocalChecked(), v8::Exception::Error(Nan::New<v8::String>(ErrorMessage()).ToLocalChecked()) }; EMIT_EVENT(db->handle(), 2, args); } db->Unref(); } CloseWorker::CloseWorker(Database* db, bool actuallyClose) : Nan::AsyncWorker(NULL), db(db), actuallyClose(actuallyClose) {} CloseWorker::~CloseWorker() {} void CloseWorker::Execute() { if (actuallyClose) { int status1 = sqlite3_close(db->writeHandle); int status2 = sqlite3_close(db->readHandle); db->writeHandle = NULL; db->readHandle = NULL; if (status1 != SQLITE_OK) { SetErrorMessage(sqlite3_errmsg(db->writeHandle)); } else if (status2 != SQLITE_OK) { SetErrorMessage(sqlite3_errmsg(db->readHandle)); } } } void CloseWorker::HandleOKCallback() { Nan::HandleScope scope; v8::Local<v8::Value> args[2] = {Nan::New("disconnect").ToLocalChecked(), Nan::Null()}; EMIT_EVENT(db->handle(), 2, args); db->Unref(); } void CloseWorker::HandleErrorCallback() { Nan::HandleScope scope; v8::Local<v8::Value> args[2] = { Nan::New("disconnect").ToLocalChecked(), v8::Exception::Error(Nan::New<v8::String>(ErrorMessage()).ToLocalChecked()) }; EMIT_EVENT(db->handle(), 2, args); db->Unref(); } NAN_MODULE_INIT(InitDatabase) { Database::Init(target); Statement::Init(); } } <commit_msg>simplified database state<commit_after>#include <cstdlib> #include <sqlite3.h> #include <nan.h> #include "macros.h" #include "database.h" namespace NODE_SQLITE3_PLUS_DATABASE { int WRITE_MODE = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX; int READ_MODE = SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX; v8::PropertyAttribute FROZEN = static_cast<v8::PropertyAttribute>(v8::DontDelete | v8::ReadOnly); bool CONSTRUCTING_STATEMENT = false; enum STATE {CONNECTING, READY, DONE}; class Database : public Nan::ObjectWrap { public: Database(char*); ~Database(); static NAN_MODULE_INIT(Init); friend class OpenWorker; friend class CloseWorker; private: static CONSTRUCTOR(constructor); static NAN_METHOD(New); static NAN_GETTER(OpenGetter); static NAN_METHOD(Close); static NAN_METHOD(Prepare); char* filename; sqlite3* readHandle; sqlite3* writeHandle; STATE state; }; class Statement : public Nan::ObjectWrap { public: Statement(); ~Statement(); static void Init(); friend class Database; private: static CONSTRUCTOR(constructor); static NAN_METHOD(New); sqlite3_stmt* handle; bool dead; }; class OpenWorker : public Nan::AsyncWorker { public: OpenWorker(Database*); ~OpenWorker(); void Execute(); void HandleOKCallback(); void HandleErrorCallback(); private: Database* db; }; class CloseWorker : public Nan::AsyncWorker { public: CloseWorker(Database*, bool); ~CloseWorker(); void Execute(); void HandleOKCallback(); void HandleErrorCallback(); private: Database* db; bool doNothing; }; Database::Database(char* filename) : Nan::ObjectWrap(), filename(filename), readHandle(NULL), writeHandle(NULL), state(CONNECTING) {} Database::~Database() { state = DONE; sqlite3_close(readHandle); sqlite3_close(writeHandle); readHandle = NULL; writeHandle = NULL; free(filename); filename = NULL; } NAN_MODULE_INIT(Database::Init) { Nan::HandleScope scope; v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(New); t->InstanceTemplate()->SetInternalFieldCount(1); t->SetClassName(Nan::New("Database").ToLocalChecked()); Nan::SetPrototypeMethod(t, "disconnect", Close); Nan::SetPrototypeMethod(t, "prepare", Prepare); Nan::SetAccessor(t->InstanceTemplate(), Nan::New("connected").ToLocalChecked(), OpenGetter); constructor.Reset(Nan::GetFunction(t).ToLocalChecked()); Nan::Set(target, Nan::New("Database").ToLocalChecked(), Nan::GetFunction(t).ToLocalChecked()); } CONSTRUCTOR(Database::constructor); NAN_METHOD(Database::New) { REQUIRE_ARGUMENTS(1); if (!info.IsConstructCall()) { v8::Local<v8::Value> args[1] = {info[0]}; v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor); info.GetReturnValue().Set(cons->NewInstance(1, args)); } else { REQUIRE_ARGUMENT_STRING(0, filename); Database* db = new Database(RAW_STRING(filename)); db->Wrap(info.This()); db->Ref(); AsyncQueueWorker(new OpenWorker(db)); info.GetReturnValue().Set(info.This()); } } NAN_GETTER(Database::OpenGetter) { Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); info.GetReturnValue().Set(db->state == READY); } NAN_METHOD(Database::Close) { Database* db = Nan::ObjectWrap::Unwrap<Database>(info.This()); if (db->state != DONE) { db->Ref(); // -- // This should wait in queue for all pending transactions to finish. (writes AND reads). // This should be invoked right away if there are no pending transactions (which will) // always be the case if it's still connecting. db->state == DONE simply means that it // was READY when Close was invoked, and therefore should be treated equally, as shown // below. AsyncQueueWorker(new CloseWorker(db, db->state == CONNECTING)); // -- db->state = DONE; } info.GetReturnValue().Set(info.This()); } NAN_METHOD(Database::Prepare) { REQUIRE_ARGUMENT_STRING(0, source); v8::Local<v8::Function> cons = Nan::New<v8::Function>(Statement::constructor); CONSTRUCTING_STATEMENT = true; v8::Local<v8::Object> statement = cons->NewInstance(0, NULL); CONSTRUCTING_STATEMENT = false; Nan::ForceSet(statement, Nan::New("database").ToLocalChecked(), info.This(), FROZEN); Nan::ForceSet(statement, Nan::New("source").ToLocalChecked(), source, FROZEN); info.GetReturnValue().Set(statement); } Statement::Statement() : Nan::ObjectWrap(), handle(NULL), dead(false) {} Statement::~Statement() { dead = true; sqlite3_finalize(handle); handle = NULL; } void Statement::Init() { Nan::HandleScope scope; v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(New); t->InstanceTemplate()->SetInternalFieldCount(1); t->SetClassName(Nan::New("Statement").ToLocalChecked()); constructor.Reset(Nan::GetFunction(t).ToLocalChecked()); } CONSTRUCTOR(Statement::constructor); NAN_METHOD(Statement::New) { if (!CONSTRUCTING_STATEMENT) { return Nan::ThrowSyntaxError("Statements can only be constructed by the db.prepare() method."); } Statement* stmt = new Statement(); stmt->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } OpenWorker::OpenWorker(Database* db) : Nan::AsyncWorker(NULL), db(db) {} OpenWorker::~OpenWorker() {} void OpenWorker::Execute() { int status; status = sqlite3_open_v2(db->filename, &db->writeHandle, WRITE_MODE, NULL); if (status != SQLITE_OK) { SetErrorMessage(sqlite3_errmsg(db->writeHandle)); sqlite3_close(db->writeHandle); db->writeHandle = NULL; return; } status = sqlite3_open_v2(db->filename, &db->readHandle, READ_MODE, NULL); if (status != SQLITE_OK) { SetErrorMessage(sqlite3_errmsg(db->readHandle)); sqlite3_close(db->writeHandle); sqlite3_close(db->readHandle); db->writeHandle = NULL; db->readHandle = NULL; return; } sqlite3_busy_timeout(db->writeHandle, 30000); sqlite3_busy_timeout(db->readHandle, 30000); } void OpenWorker::HandleOKCallback() { Nan::HandleScope scope; if (db->state == DONE) { sqlite3_close(db->writeHandle); sqlite3_close(db->readHandle); db->writeHandle = NULL; db->readHandle = NULL; } else { db->state = READY; v8::Local<v8::Value> args[1] = {Nan::New("connect").ToLocalChecked()}; EMIT_EVENT(db->handle(), 1, args); } db->Unref(); } void OpenWorker::HandleErrorCallback() { Nan::HandleScope scope; if (db->state != DONE) { db->state = DONE; v8::Local<v8::Value> args[2] = { Nan::New("disconnect").ToLocalChecked(), v8::Exception::Error(Nan::New<v8::String>(ErrorMessage()).ToLocalChecked()) }; EMIT_EVENT(db->handle(), 2, args); } db->Unref(); } CloseWorker::CloseWorker(Database* db, bool doNothing) : Nan::AsyncWorker(NULL), db(db), doNothing(doNothing) {} CloseWorker::~CloseWorker() {} void CloseWorker::Execute() { if (!doNothing) { int status1 = sqlite3_close(db->writeHandle); int status2 = sqlite3_close(db->readHandle); db->writeHandle = NULL; db->readHandle = NULL; if (status1 != SQLITE_OK) { SetErrorMessage(sqlite3_errmsg(db->writeHandle)); } else if (status2 != SQLITE_OK) { SetErrorMessage(sqlite3_errmsg(db->readHandle)); } } } void CloseWorker::HandleOKCallback() { Nan::HandleScope scope; v8::Local<v8::Value> args[2] = {Nan::New("disconnect").ToLocalChecked(), Nan::Null()}; EMIT_EVENT(db->handle(), 2, args); db->Unref(); } void CloseWorker::HandleErrorCallback() { Nan::HandleScope scope; v8::Local<v8::Value> args[2] = { Nan::New("disconnect").ToLocalChecked(), v8::Exception::Error(Nan::New<v8::String>(ErrorMessage()).ToLocalChecked()) }; EMIT_EVENT(db->handle(), 2, args); db->Unref(); } NAN_MODULE_INIT(InitDatabase) { Database::Init(target); Statement::Init(); } } <|endoftext|>
<commit_before>// Copyright 2013 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // The GYP based build ends up defining USING_V8_SHARED when compiling this // file. #undef USING_V8_SHARED #include "../include/v8-defaults.h" #include "platform.h" #include "globals.h" #include "v8.h" namespace v8 { #if V8_OS_ANDROID const bool kOsHasSwap = false; #else const bool kOsHasSwap = true; #endif bool ConfigureResourceConstraintsForCurrentPlatform( ResourceConstraints* constraints) { if (constraints == NULL) { return false; } uint64_t physical_memory = i::OS::TotalPhysicalMemory(); int lump_of_memory = (i::kPointerSize / 4) * i::MB; // The young_space_size should be a power of 2 and old_generation_size should // be a multiple of Page::kPageSize. if (physical_memory <= 512ul * i::MB) { constraints->set_max_young_space_size(2 * lump_of_memory); constraints->set_max_old_space_size(128 * lump_of_memory); constraints->set_max_executable_size(96 * lump_of_memory); } else if (physical_memory <= (kOsHasSwap ? 768ul * i::MB : 1ul * i::GB)) { constraints->set_max_young_space_size(8 * lump_of_memory); constraints->set_max_old_space_size(256 * lump_of_memory); constraints->set_max_executable_size(192 * lump_of_memory); } else if (physical_memory <= (kOsHasSwap ? 1ul * i::GB : 2ul * i::GB)) { constraints->set_max_young_space_size(16 * lump_of_memory); constraints->set_max_old_space_size(512 * lump_of_memory); constraints->set_max_executable_size(256 * lump_of_memory); } else { constraints->set_max_young_space_size(16 * lump_of_memory); constraints->set_max_old_space_size(700 * lump_of_memory); constraints->set_max_executable_size(256 * lump_of_memory); } return true; } bool SetDefaultResourceConstraintsForCurrentPlatform() { ResourceConstraints constraints; if (!ConfigureResourceConstraintsForCurrentPlatform(&constraints)) return false; return SetResourceConstraints(&constraints); } } // namespace v8 <commit_msg>Temporarily disable calls to OS::TotalPhysicalMemory to avoid ASSERT when running under the Chrome Sandbox.<commit_after>// Copyright 2013 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // The GYP based build ends up defining USING_V8_SHARED when compiling this // file. #undef USING_V8_SHARED #include "../include/v8-defaults.h" #include "platform.h" #include "globals.h" #include "v8.h" namespace v8 { bool ConfigureResourceConstraintsForCurrentPlatform( ResourceConstraints* constraints) { if (constraints == NULL) { return false; } int lump_of_memory = (i::kPointerSize / 4) * i::MB; // The young_space_size should be a power of 2 and old_generation_size should // be a multiple of Page::kPageSize. #if V8_OS_ANDROID constraints->set_max_young_space_size(8 * lump_of_memory); constraints->set_max_old_space_size(256 * lump_of_memory); constraints->set_max_executable_size(192 * lump_of_memory); #else constraints->set_max_young_space_size(16 * lump_of_memory); constraints->set_max_old_space_size(700 * lump_of_memory); constraints->set_max_executable_size(256 * lump_of_memory); #endif return true; } bool SetDefaultResourceConstraintsForCurrentPlatform() { ResourceConstraints constraints; if (!ConfigureResourceConstraintsForCurrentPlatform(&constraints)) return false; return SetResourceConstraints(&constraints); } } // namespace v8 <|endoftext|>
<commit_before> #include "display.h" namespace ssnake { Display::Display(const coordType size_x, const coordType size_y) { initCurses(); setTextures(); initScreen(size_x * 2, size_y); #ifdef _WIN32 system("title SlicerSnake"); #endif } Display::~Display() { if (snakeWin != nullptr) { delwin(snakeWin); } if (gameWin != nullptr) { delwin(gameWin); } if (messageWin != nullptr) { delwin(messageWin); } clear(); refresh(); endwin(); if (gameTextures != nullptr) { if (gameTextures[0] != nullptr) { delete gameTextures[0]; } delete gameTextures; } } void Display::clearGameMessage() { std::size_t lengthLabelSize = std::strlen(lengthLabel) + windowPadding + 3; std::size_t maxLengthLabelSize = std::strlen(maxLengthLabel) + windowPadding + 3; unsigned int endPos = ScreenSize.x - maxLengthLabelSize - 1; wmove(gameWin, 0, lengthLabelSize); for (unsigned int i = lengthLabelSize; i < endPos; ++i) { waddch(gameWin, ' '); } gameWinModified = true; } void Display::clearScreen() { wclear(snakeWin); wclear(gameWin); wclear(messageWin); wattron(snakeWin, COLOR_PAIR(BORDER_TEXTURE)); box(snakeWin, 0, 0); wattroff(snakeWin, COLOR_PAIR(BORDER_TEXTURE)); snakeWinModified = true; gameWinModified = true; messageWinModified = true; // Clear screen immediately update(); } void Display::drawTexture(Texture_t texture, const Vec2& pos) { mvwaddchnstr(snakeWin, pos.y, pos.x * 2, gameTextures[texture], 2); snakeWinModified = true; } coordType Display::getSize_x() const { return getmaxx(snakeWin) / 2; } coordType Display::getSize_y() const { return getmaxy(snakeWin); } void Display::initCurses() { /* if (curscr != NULL) { initscr(); refresh(); } */ initscr(); start_color(); leaveok(stdscr, TRUE); refresh(); curs_set(0); } void Display::initScreen(coordType size_x, coordType size_y) { ScreenSize.x = size_x; ScreenSize.y = size_y; #ifdef _WIN32 // Ensure window is large enough for requested display size on windows // Since window users generally want things to work more than to have control if (ScreenSize.y > getmaxy(stdscr) || ScreenSize.x > getmaxx(stdscr)) { int err = resize_term(ScreenSize.y, ScreenSize.x); assert(err == OK); refresh(); } #endif if (ScreenSize.y > getmaxy(stdscr) || ScreenSize.x > getmaxx(stdscr)) { // probably warning or exit here, but for now do nothing } if (snakeWin != nullptr) { wclear(snakeWin); } else { snakeWin = newpad(ScreenSize.y - (gameTextLines + windowPadding * 2), ScreenSize.x - (windowPadding * 2)); } if (gameWin != nullptr) { wclear(gameWin); } else { gameWin = newpad(gameTextLines, ScreenSize.x - (windowPadding * 2)); } if (messageWin != nullptr) { wclear(messageWin); } else { // We have to make it slightly smaller here for Windows builds with pdcurses, because pdcurses doesn't allow it to be the same size messageWin = subpad(snakeWin, ScreenSize.y - (gameTextLines + windowPadding * 2) - 1, ScreenSize.x - (windowPadding * 2) - 2, 0, 0); } // gameWin and messageWin always uses the same color for now wattron(gameWin, COLOR_PAIR(GAME_TEXT_TEXTURE)); wattron(messageWin, COLOR_PAIR(GAME_TEXT_TEXTURE)); wattron(snakeWin, COLOR_PAIR(BORDER_TEXTURE)); box(snakeWin, 0, 0); wattroff(snakeWin, COLOR_PAIR(BORDER_TEXTURE)); snakeWinModified = true; gameWinModified = true; messageWinModified = true; update(); return; } void Display::moveSnakeHead(const Vec2& oldPos, const Vec2& newPos, const SnakeTextureList& snakeTextures) { drawTexture(snakeTextures.body, oldPos); drawTexture(snakeTextures.head, newPos); } void Display::moveSnakeBody(const Vec2& oldPos, const Vec2& newPos, const SnakeTextureList& snakeTextures) { // unused in curses implementation } void Display::moveSnakeTail(const Vec2& oldPos, const Vec2& newPos, const SnakeTextureList& snakeTextures) { drawTexture(snakeTextures.tail, newPos); // Don't overwrite anything else when clearing old tail chtype prevChar = mvwinch(snakeWin, oldPos.y, oldPos.x * 2); if (prevChar == gameTextures[snakeTextures.tail][0]) { drawTexture(BACKGROUND_TEXTURE, oldPos); } } void Display::printTextLine(unsigned int lineNumber, const char* message) { std::size_t size = std::strlen(message); std::size_t maxTextLength = getmaxx(messageWin) - (windowPadding * 2) - 2; mvwaddnstr(messageWin, lineNumber, (getmaxx(messageWin) / 2) - (size / 2) + 1, message, static_cast<int>(maxTextLength)); messageWinModified = true; } void Display::printGameMessage(const char* message) { clearGameMessage(); std::size_t size = std::strlen(message); std::size_t maxGameTextLength = 2 * ((getmaxx(gameWin) / 2) - (std::strlen(maxLengthLabel) + windowPadding + 2) - 1); if (size > maxGameTextLength) { size = maxGameTextLength; } mvwaddnstr(gameWin, 0, (getmaxx(gameWin) / 2) - (size / 2), message, static_cast<int>(maxGameTextLength)); gameWinModified = true; // Game messages should be printed immediately update(); } void Display::setTextures() { init_pair(SNAKE_TEXTURE, COLOR_GREEN, COLOR_BLACK); init_pair(SS_SNAKE_TEXTURE, COLOR_MAGENTA, COLOR_BLACK); init_pair(FOOD_TEXTURE, COLOR_YELLOW, COLOR_BLACK); init_pair(BORDER_TEXTURE, COLOR_CYAN, COLOR_BLACK); init_pair(GAME_TEXT_TEXTURE, COLOR_RED, COLOR_BLACK); init_pair(COLLISION_TEXTURE, COLOR_RED, COLOR_BLACK); init_pair(BACKGROUND_TEXTURE, COLOR_BLACK, COLOR_BLACK); if (can_change_color() && COLORS>=256) { init_color(9, 40, 1000, 90); init_color(10, 900, 70, 1000); init_pair(SNAKE_HEAD_TEXTURE, 9, COLOR_BLACK); init_pair(SS_SNAKE_HEAD_TEXTURE, 10, COLOR_BLACK); } else { init_pair(SNAKE_HEAD_TEXTURE, COLOR_GREEN, COLOR_BLACK); init_pair(SS_SNAKE_HEAD_TEXTURE, COLOR_MAGENTA, COLOR_BLACK); } const chtype missingTexture = '?'; gameTextures = new chtype*[TEXTURE_COUNT]; gameTextures[0] = new chtype[TEXTURE_COUNT*2]; for (int i=1; i < TEXTURE_COUNT; ++i) { gameTextures[i] = *gameTextures + (2*i); gameTextures[i][1] = gameTextures[i][0] = missingTexture; } gameTextures[SNAKE_TEXTURE][0] = '(' | COLOR_PAIR(SNAKE_TEXTURE); gameTextures[SNAKE_TEXTURE][1] = ')' | COLOR_PAIR(SNAKE_TEXTURE); gameTextures[SNAKE_HEAD_TEXTURE][0] = '<' | COLOR_PAIR(SNAKE_HEAD_TEXTURE); gameTextures[SNAKE_HEAD_TEXTURE][1] = '>' | COLOR_PAIR(SNAKE_HEAD_TEXTURE); gameTextures[SS_SNAKE_TEXTURE][0] = '(' | COLOR_PAIR(SS_SNAKE_TEXTURE); gameTextures[SS_SNAKE_TEXTURE][1] = ')' | COLOR_PAIR(SS_SNAKE_TEXTURE); gameTextures[SS_SNAKE_HEAD_TEXTURE][0] = '<' | COLOR_PAIR(SS_SNAKE_HEAD_TEXTURE); gameTextures[SS_SNAKE_HEAD_TEXTURE][1] = '>' | COLOR_PAIR(SS_SNAKE_HEAD_TEXTURE); gameTextures[FOOD_TEXTURE][0] = '{' | COLOR_PAIR(FOOD_TEXTURE); gameTextures[FOOD_TEXTURE][1] = '}' | COLOR_PAIR(FOOD_TEXTURE); gameTextures[COLLISION_TEXTURE][0] = '*' | COLOR_PAIR(COLLISION_TEXTURE); gameTextures[COLLISION_TEXTURE][1] = '*' | COLOR_PAIR(COLLISION_TEXTURE); gameTextures[BACKGROUND_TEXTURE][0] = ' ' | COLOR_PAIR(BACKGROUND_TEXTURE); gameTextures[BACKGROUND_TEXTURE][1] = ' ' | COLOR_PAIR(BACKGROUND_TEXTURE); } void Display::updateLengthCounter(std::size_t length) { mvwaddstr(gameWin, 0, windowPadding, lengthLabel); std::size_t lengthLabelSize = std::strlen(lengthLabel); mvwaddstr(gameWin, 0, lengthLabelSize + windowPadding, " "); mvwprintw(gameWin, 0, lengthLabelSize + windowPadding, "%d", length); gameWinModified = true; } void Display::updateMaxLengthCounter(std::size_t maxLength) { std::size_t lengthLabelSize = std::strlen(maxLengthLabel); mvwaddstr(gameWin, 0, getmaxx(gameWin) - (lengthLabelSize + windowPadding + 2), maxLengthLabel); mvwaddstr(gameWin, 0, getmaxx(gameWin) - (windowPadding + 2), " "); mvwprintw(gameWin, 0, getmaxx(gameWin) - (windowPadding + 2), "%d", maxLength); gameWinModified = true; } void Display::update() { if ( !(snakeWinModified || gameWinModified || messageWinModified) ) { return; } if (snakeWinModified) { pnoutrefresh(snakeWin, 0, 0, windowPadding, windowPadding, ScreenSize.y - (gameTextLines + windowPadding), ScreenSize.x - windowPadding); } if (messageWinModified) { pnoutrefresh(messageWin, 0, 0, windowPadding, windowPadding, ScreenSize.y - (gameTextLines + windowPadding), ScreenSize.x - windowPadding); } if (gameWinModified) { pnoutrefresh(gameWin, 0, 0, ScreenSize.y - (gameTextLines + windowPadding), windowPadding, ScreenSize.y - windowPadding, ScreenSize.x - windowPadding); } doupdate(); snakeWinModified = false; gameWinModified = false; messageWinModified = false; } }<commit_msg>Delete sub-pad first<commit_after> #include "display.h" namespace ssnake { Display::Display(const coordType size_x, const coordType size_y) { initCurses(); setTextures(); initScreen(size_x * 2, size_y); #ifdef _WIN32 system("title SlicerSnake"); #endif } Display::~Display() { if (messageWin != nullptr) { delwin(messageWin); } if (snakeWin != nullptr) { delwin(snakeWin); } if (gameWin != nullptr) { delwin(gameWin); } clear(); refresh(); endwin(); if (gameTextures != nullptr) { if (gameTextures[0] != nullptr) { delete gameTextures[0]; } delete gameTextures; } } void Display::clearGameMessage() { std::size_t lengthLabelSize = std::strlen(lengthLabel) + windowPadding + 3; std::size_t maxLengthLabelSize = std::strlen(maxLengthLabel) + windowPadding + 3; unsigned int endPos = ScreenSize.x - maxLengthLabelSize - 1; wmove(gameWin, 0, lengthLabelSize); for (unsigned int i = lengthLabelSize; i < endPos; ++i) { waddch(gameWin, ' '); } gameWinModified = true; } void Display::clearScreen() { wclear(snakeWin); wclear(gameWin); wclear(messageWin); wattron(snakeWin, COLOR_PAIR(BORDER_TEXTURE)); box(snakeWin, 0, 0); wattroff(snakeWin, COLOR_PAIR(BORDER_TEXTURE)); snakeWinModified = true; gameWinModified = true; messageWinModified = true; // Clear screen immediately update(); } void Display::drawTexture(Texture_t texture, const Vec2& pos) { mvwaddchnstr(snakeWin, pos.y, pos.x * 2, gameTextures[texture], 2); snakeWinModified = true; } coordType Display::getSize_x() const { return getmaxx(snakeWin) / 2; } coordType Display::getSize_y() const { return getmaxy(snakeWin); } void Display::initCurses() { /* if (curscr != NULL) { initscr(); refresh(); } */ initscr(); start_color(); leaveok(stdscr, TRUE); refresh(); curs_set(0); } void Display::initScreen(coordType size_x, coordType size_y) { ScreenSize.x = size_x; ScreenSize.y = size_y; #ifdef _WIN32 // Ensure window is large enough for requested display size on windows // Since window users generally want things to work more than to have control if (ScreenSize.y > getmaxy(stdscr) || ScreenSize.x > getmaxx(stdscr)) { int err = resize_term(ScreenSize.y, ScreenSize.x); assert(err == OK); refresh(); } #endif if (ScreenSize.y > getmaxy(stdscr) || ScreenSize.x > getmaxx(stdscr)) { // probably warning or exit here, but for now do nothing } if (snakeWin != nullptr) { wclear(snakeWin); } else { snakeWin = newpad(ScreenSize.y - (gameTextLines + windowPadding * 2), ScreenSize.x - (windowPadding * 2)); } if (gameWin != nullptr) { wclear(gameWin); } else { gameWin = newpad(gameTextLines, ScreenSize.x - (windowPadding * 2)); } if (messageWin != nullptr) { wclear(messageWin); } else { // We have to make it slightly smaller here for Windows builds with pdcurses, because pdcurses doesn't allow it to be the same size messageWin = subpad(snakeWin, ScreenSize.y - (gameTextLines + windowPadding * 2) - 1, ScreenSize.x - (windowPadding * 2) - 2, 0, 0); } // gameWin and messageWin always uses the same color for now wattron(gameWin, COLOR_PAIR(GAME_TEXT_TEXTURE)); wattron(messageWin, COLOR_PAIR(GAME_TEXT_TEXTURE)); wattron(snakeWin, COLOR_PAIR(BORDER_TEXTURE)); box(snakeWin, 0, 0); wattroff(snakeWin, COLOR_PAIR(BORDER_TEXTURE)); snakeWinModified = true; gameWinModified = true; messageWinModified = true; update(); return; } void Display::moveSnakeHead(const Vec2& oldPos, const Vec2& newPos, const SnakeTextureList& snakeTextures) { drawTexture(snakeTextures.body, oldPos); drawTexture(snakeTextures.head, newPos); } void Display::moveSnakeBody(const Vec2& oldPos, const Vec2& newPos, const SnakeTextureList& snakeTextures) { // unused in curses implementation } void Display::moveSnakeTail(const Vec2& oldPos, const Vec2& newPos, const SnakeTextureList& snakeTextures) { drawTexture(snakeTextures.tail, newPos); // Don't overwrite anything else when clearing old tail chtype prevChar = mvwinch(snakeWin, oldPos.y, oldPos.x * 2); if (prevChar == gameTextures[snakeTextures.tail][0]) { drawTexture(BACKGROUND_TEXTURE, oldPos); } } void Display::printTextLine(unsigned int lineNumber, const char* message) { std::size_t size = std::strlen(message); std::size_t maxTextLength = getmaxx(messageWin) - (windowPadding * 2) - 2; mvwaddnstr(messageWin, lineNumber, (getmaxx(messageWin) / 2) - (size / 2) + 1, message, static_cast<int>(maxTextLength)); messageWinModified = true; } void Display::printGameMessage(const char* message) { clearGameMessage(); std::size_t size = std::strlen(message); std::size_t maxGameTextLength = 2 * ((getmaxx(gameWin) / 2) - (std::strlen(maxLengthLabel) + windowPadding + 2) - 1); if (size > maxGameTextLength) { size = maxGameTextLength; } mvwaddnstr(gameWin, 0, (getmaxx(gameWin) / 2) - (size / 2), message, static_cast<int>(maxGameTextLength)); gameWinModified = true; // Game messages should be printed immediately update(); } void Display::setTextures() { init_pair(SNAKE_TEXTURE, COLOR_GREEN, COLOR_BLACK); init_pair(SS_SNAKE_TEXTURE, COLOR_MAGENTA, COLOR_BLACK); init_pair(FOOD_TEXTURE, COLOR_YELLOW, COLOR_BLACK); init_pair(BORDER_TEXTURE, COLOR_CYAN, COLOR_BLACK); init_pair(GAME_TEXT_TEXTURE, COLOR_RED, COLOR_BLACK); init_pair(COLLISION_TEXTURE, COLOR_RED, COLOR_BLACK); init_pair(BACKGROUND_TEXTURE, COLOR_BLACK, COLOR_BLACK); if (can_change_color() && COLORS>=256) { init_color(9, 40, 1000, 90); init_color(10, 900, 70, 1000); init_pair(SNAKE_HEAD_TEXTURE, 9, COLOR_BLACK); init_pair(SS_SNAKE_HEAD_TEXTURE, 10, COLOR_BLACK); } else { init_pair(SNAKE_HEAD_TEXTURE, COLOR_GREEN, COLOR_BLACK); init_pair(SS_SNAKE_HEAD_TEXTURE, COLOR_MAGENTA, COLOR_BLACK); } const chtype missingTexture = '?'; gameTextures = new chtype*[TEXTURE_COUNT]; gameTextures[0] = new chtype[TEXTURE_COUNT*2]; for (int i=1; i < TEXTURE_COUNT; ++i) { gameTextures[i] = *gameTextures + (2*i); gameTextures[i][1] = gameTextures[i][0] = missingTexture; } gameTextures[SNAKE_TEXTURE][0] = '(' | COLOR_PAIR(SNAKE_TEXTURE); gameTextures[SNAKE_TEXTURE][1] = ')' | COLOR_PAIR(SNAKE_TEXTURE); gameTextures[SNAKE_HEAD_TEXTURE][0] = '<' | COLOR_PAIR(SNAKE_HEAD_TEXTURE); gameTextures[SNAKE_HEAD_TEXTURE][1] = '>' | COLOR_PAIR(SNAKE_HEAD_TEXTURE); gameTextures[SS_SNAKE_TEXTURE][0] = '(' | COLOR_PAIR(SS_SNAKE_TEXTURE); gameTextures[SS_SNAKE_TEXTURE][1] = ')' | COLOR_PAIR(SS_SNAKE_TEXTURE); gameTextures[SS_SNAKE_HEAD_TEXTURE][0] = '<' | COLOR_PAIR(SS_SNAKE_HEAD_TEXTURE); gameTextures[SS_SNAKE_HEAD_TEXTURE][1] = '>' | COLOR_PAIR(SS_SNAKE_HEAD_TEXTURE); gameTextures[FOOD_TEXTURE][0] = '{' | COLOR_PAIR(FOOD_TEXTURE); gameTextures[FOOD_TEXTURE][1] = '}' | COLOR_PAIR(FOOD_TEXTURE); gameTextures[COLLISION_TEXTURE][0] = '*' | COLOR_PAIR(COLLISION_TEXTURE); gameTextures[COLLISION_TEXTURE][1] = '*' | COLOR_PAIR(COLLISION_TEXTURE); gameTextures[BACKGROUND_TEXTURE][0] = ' ' | COLOR_PAIR(BACKGROUND_TEXTURE); gameTextures[BACKGROUND_TEXTURE][1] = ' ' | COLOR_PAIR(BACKGROUND_TEXTURE); } void Display::updateLengthCounter(std::size_t length) { mvwaddstr(gameWin, 0, windowPadding, lengthLabel); std::size_t lengthLabelSize = std::strlen(lengthLabel); mvwaddstr(gameWin, 0, lengthLabelSize + windowPadding, " "); mvwprintw(gameWin, 0, lengthLabelSize + windowPadding, "%d", length); gameWinModified = true; } void Display::updateMaxLengthCounter(std::size_t maxLength) { std::size_t lengthLabelSize = std::strlen(maxLengthLabel); mvwaddstr(gameWin, 0, getmaxx(gameWin) - (lengthLabelSize + windowPadding + 2), maxLengthLabel); mvwaddstr(gameWin, 0, getmaxx(gameWin) - (windowPadding + 2), " "); mvwprintw(gameWin, 0, getmaxx(gameWin) - (windowPadding + 2), "%d", maxLength); gameWinModified = true; } void Display::update() { if ( !(snakeWinModified || gameWinModified || messageWinModified) ) { return; } if (snakeWinModified) { pnoutrefresh(snakeWin, 0, 0, windowPadding, windowPadding, ScreenSize.y - (gameTextLines + windowPadding), ScreenSize.x - windowPadding); } if (messageWinModified) { pnoutrefresh(messageWin, 0, 0, windowPadding, windowPadding, ScreenSize.y - (gameTextLines + windowPadding), ScreenSize.x - windowPadding); } if (gameWinModified) { pnoutrefresh(gameWin, 0, 0, ScreenSize.y - (gameTextLines + windowPadding), windowPadding, ScreenSize.y - windowPadding, ScreenSize.x - windowPadding); } doupdate(); snakeWinModified = false; gameWinModified = false; messageWinModified = false; } }<|endoftext|>
<commit_before>/* Calf DSP Library utility application. * DSSI GUI application. * Copyright (C) 2007 Krzysztof Foltman * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. */ #include <getopt.h> #include <stdint.h> #include <stdlib.h> #include <config.h> #include <calf/giface.h> #include <calf/gui.h> #include <calf/modules.h> #include <calf/modules_dev.h> #include <calf/benchmark.h> #include <calf/main_win.h> #include <calf/osctl.h> #include <calf/osctlnet.h> using namespace std; using namespace dsp; using namespace synth; using namespace osctl; #define debug_printf(...) #if 0 void osctl_test() { string sdata = string("\000\000\000\003123\000test\000\000\000\000\000\000\000\001\000\000\000\002", 24); osc_stream is(sdata); vector<osc_data> data; is.read("bsii", data); assert(is.pos == sdata.length()); assert(data.size() == 4); assert(data[0].type == osc_blob); assert(data[1].type == osc_string); assert(data[2].type == osc_i32); assert(data[3].type == osc_i32); assert(data[0].strval == "123"); assert(data[1].strval == "test"); assert(data[2].i32val == 1); assert(data[3].i32val == 2); osc_stream os(""); os.write(data); assert(os.buffer == sdata); osc_server srv; srv.bind("0.0.0.0", 4541); osc_client cli; cli.bind("0.0.0.0", 0); cli.set_addr("0.0.0.0", 4541); if (!cli.send("/blah", data)) g_error("Could not send the OSC message"); g_main_loop_run(g_main_loop_new(NULL, FALSE)); } #endif struct plugin_proxy_base: public plugin_ctl_iface { osc_client *client; bool send_osc; plugin_gui *gui; map<string, string> cfg_vars; plugin_proxy_base() { client = NULL; send_osc = false; gui = NULL; } }; template<class Module> struct plugin_proxy: public plugin_proxy_base, public line_graph_iface { float params[Module::param_count]; plugin_proxy() { for (unsigned int i = 0; i < Module::param_count; i++) params[i] = get_param_props(i)->def_value; } virtual parameter_properties *get_param_props(int param_no) { return Module::param_props + param_no; } virtual float get_param_value(int param_no) { if (param_no < 0 || param_no >= Module::param_count) return 0; return params[param_no]; } virtual void set_param_value(int param_no, float value) { if (param_no < 0 || param_no >= Module::param_count) return; params[param_no] = value; if (send_osc) { osc_inline_typed_strstream str; str << (uint32_t)(param_no + get_param_port_offset()) << value; client->send("/control", str); } } virtual int get_param_count() { return Module::param_count; } virtual int get_param_port_offset() { return Module::in_count + Module::out_count; } virtual const char *get_gui_xml() { return Module::get_gui_xml(); } virtual line_graph_iface *get_line_graph_iface() { return this; } virtual bool activate_preset(int bank, int program) { if (send_osc) { osc_inline_typed_strstream str; str << (uint32_t)(bank) << (uint32_t)(program); client->send("/program", str); return false; } return false; } virtual bool get_graph(int index, int subindex, float *data, int points, cairo_t *context) { return Module::get_static_graph(index, subindex, params[index], data, points, context); } virtual const char *get_name() { return Module::get_name(); } virtual const char *get_id() { return Module::get_id(); } virtual const char *get_label() { return Module::get_label(); } virtual int get_input_count() { return Module::in_count; } virtual int get_output_count() { return Module::out_count; } virtual bool get_midi() { return Module::support_midi; } virtual float get_level(unsigned int port) { return 0.f; } virtual plugin_command_info *get_commands() { return Module::get_commands(); } virtual void execute(int command_no) { if (send_osc) { stringstream ss; ss << command_no; osc_inline_typed_strstream str; str << "ExecCommand" << ss.str(); client->send("/configure", str); str.clear(); str << "ExecCommand" << ""; client->send("/configure", str); } } char *configure(const char *key, const char *value) { cfg_vars[key] = value; osc_inline_typed_strstream str; str << key << value; client->send("/configure", str); return NULL; } void send_configures(send_configure_iface *sci) { for (map<string, string>::iterator i = cfg_vars.begin(); i != cfg_vars.end(); i++) sci->send_configure(i->first.c_str(), i->second.c_str()); } void clear_preset() { const char **p = Module::get_default_configure_vars(); if (p) { for(; p[0]; p += 2) configure(p[0], p[1]); } } }; plugin_proxy_base *create_plugin_proxy(const char *effect_name) { if (!strcmp(effect_name, "reverb")) return new plugin_proxy<reverb_audio_module>(); else if (!strcmp(effect_name, "flanger")) return new plugin_proxy<flanger_audio_module>(); else if (!strcmp(effect_name, "filter")) return new plugin_proxy<filter_audio_module>(); else if (!strcmp(effect_name, "monosynth")) return new plugin_proxy<monosynth_audio_module>(); else if (!strcmp(effect_name, "vintagedelay")) return new plugin_proxy<vintage_delay_audio_module>(); else if (!strcmp(effect_name, "organ")) return new plugin_proxy<organ_audio_module>(); else if (!strcmp(effect_name, "rotaryspeaker")) return new plugin_proxy<rotary_speaker_audio_module>(); #ifdef ENABLE_EXPERIMENTAL #endif else return NULL; } void help(char *argv[]) { printf("GTK+ user interface for Calf DSSI plugins\nSyntax: %s [--help] [--version] <osc-url> <so-file> <plugin-label> <instance-name>\n", argv[0]); } static struct option long_options[] = { {"help", 0, 0, 'h'}, {"version", 0, 0, 'v'}, {"debug", 0, 0, 'd'}, {0,0,0,0}, }; GMainLoop *mainloop; static bool osc_debug = false; struct dssi_osc_server: public osc_server, public osc_message_sink<osc_strstream> { plugin_proxy_base *plugin; main_window *main_win; plugin_gui_window *window; string effect_name, title; osc_client cli; bool in_program, enable_dump; vector<plugin_preset> presets; dssi_osc_server() : plugin(NULL) , main_win(new main_window) , window(new plugin_gui_window(main_win)) { sink = this; } static void on_destroy(GtkWindow *window, dssi_osc_server *self) { debug_printf("on_destroy, have to send \"exiting\"\n"); bool result = self->cli.send("/exiting"); debug_printf("result = %d\n", result ? 1 : 0); g_main_loop_quit(mainloop); // eliminate a warning with empty debug_printf result = false; } void create_window() { plugin = create_plugin_proxy(effect_name.c_str()); if (!plugin) { fprintf(stderr, "Unknown plugin: %s\n", effect_name.c_str()); exit(1); } plugin->client = &cli; plugin->send_osc = true; ((main_window *)window->main)->conditions.insert("dssi"); window->create(plugin, title.c_str(), effect_name.c_str()); plugin->gui = window->gui; gtk_signal_connect(GTK_OBJECT(window->toplevel), "destroy", G_CALLBACK(on_destroy), this); vector<plugin_preset> tmp_presets; get_builtin_presets().get_for_plugin(presets, effect_name.c_str()); get_user_presets().get_for_plugin(tmp_presets, effect_name.c_str()); presets.insert(presets.end(), tmp_presets.begin(), tmp_presets.end()); } virtual void receive_osc_message(std::string address, std::string args, osc_strstream &buffer) { if (osc_debug) dump.receive_osc_message(address, args, buffer); if (address == prefix + "/update" && args == "s") { string str; buffer >> str; debug_printf("UPDATE: %s\n", str.c_str()); return; } if (address == prefix + "/quit") { debug_printf("QUIT\n"); g_main_loop_quit(mainloop); return; } if (address == prefix + "/configure"&& args == "ss") { string key, value; buffer >> key >> value; plugin->cfg_vars[key] = value; // XXXKF perhaps this should be queued ! window->gui->refresh(); return; } if (address == prefix + "/program"&& args == "ii") { uint32_t bank, program; buffer >> bank >> program; unsigned int nr = bank * 128 + program; debug_printf("PROGRAM %d\n", nr); if (nr == 0) { bool sosc = plugin->send_osc; plugin->send_osc = false; int count = plugin->get_param_count(); for (int i =0 ; i < count; i++) plugin->set_param_value(i, plugin->get_param_props(i)->def_value); plugin->send_osc = sosc; window->gui->refresh(); // special handling for default preset return; } nr--; if (nr >= presets.size()) return; bool sosc = plugin->send_osc; plugin->send_osc = false; presets[nr].activate(plugin); plugin->send_osc = sosc; window->gui->refresh(); // cli.send("/update", data); return; } if (address == prefix + "/control" && args == "if") { uint32_t port; float val; buffer >> port >> val; int idx = port - plugin->get_param_port_offset(); debug_printf("CONTROL %d %f\n", idx, val); bool sosc = plugin->send_osc; plugin->send_osc = false; window->gui->set_param_value(idx, val); plugin->send_osc = sosc; return; } if (address == prefix + "/show") { gtk_widget_show_all(GTK_WIDGET(window->toplevel)); return; } if (address == prefix + "/hide") { gtk_widget_hide(GTK_WIDGET(window->toplevel)); return; } } }; int main(int argc, char *argv[]) { char *debug_var = getenv("OSC_DEBUG"); if (debug_var && atoi(debug_var)) osc_debug = true; gtk_init(&argc, &argv); while(1) { int option_index; int c = getopt_long(argc, argv, "dhv", long_options, &option_index); if (c == -1) break; switch(c) { case 'd': osc_debug = true; break; case 'h': help(argv); return 0; case 'v': printf("%s\n", PACKAGE_STRING); return 0; } } if (argc - optind != 4) { help(argv); exit(0); } try { get_builtin_presets().load_defaults(true); get_user_presets().load_defaults(false); } catch(synth::preset_exception &e) { fprintf(stderr, "Error while loading presets: %s\n", e.what()); exit(1); } dssi_osc_server srv; srv.prefix = "/dssi/"+string(argv[optind + 1]) + "/" + string(argv[optind + 2]); for (char *p = argv[optind + 2]; *p; p++) *p = tolower(*p); srv.effect_name = argv[optind + 2]; srv.title = argv[optind + 3]; srv.bind(); srv.create_window(); mainloop = g_main_loop_new(NULL, FALSE); srv.cli.bind(); srv.cli.set_url(argv[optind]); debug_printf("URI = %s\n", srv.get_uri().c_str()); string data_buf, type_buf; osc_inline_typed_strstream data; data << srv.get_uri(); if (!srv.cli.send("/update", data)) { g_error("Could not send the initial update message via OSC to %s", argv[optind]); return 1; } g_main_loop_run(mainloop); debug_printf("exited\n"); return 0; } <commit_msg>+ MultiChorus: fix DSSI GUI too<commit_after>/* Calf DSP Library utility application. * DSSI GUI application. * Copyright (C) 2007 Krzysztof Foltman * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. */ #include <getopt.h> #include <stdint.h> #include <stdlib.h> #include <config.h> #include <calf/giface.h> #include <calf/gui.h> #include <calf/modules.h> #include <calf/modules_dev.h> #include <calf/benchmark.h> #include <calf/main_win.h> #include <calf/osctl.h> #include <calf/osctlnet.h> using namespace std; using namespace dsp; using namespace synth; using namespace osctl; #define debug_printf(...) #if 0 void osctl_test() { string sdata = string("\000\000\000\003123\000test\000\000\000\000\000\000\000\001\000\000\000\002", 24); osc_stream is(sdata); vector<osc_data> data; is.read("bsii", data); assert(is.pos == sdata.length()); assert(data.size() == 4); assert(data[0].type == osc_blob); assert(data[1].type == osc_string); assert(data[2].type == osc_i32); assert(data[3].type == osc_i32); assert(data[0].strval == "123"); assert(data[1].strval == "test"); assert(data[2].i32val == 1); assert(data[3].i32val == 2); osc_stream os(""); os.write(data); assert(os.buffer == sdata); osc_server srv; srv.bind("0.0.0.0", 4541); osc_client cli; cli.bind("0.0.0.0", 0); cli.set_addr("0.0.0.0", 4541); if (!cli.send("/blah", data)) g_error("Could not send the OSC message"); g_main_loop_run(g_main_loop_new(NULL, FALSE)); } #endif struct plugin_proxy_base: public plugin_ctl_iface { osc_client *client; bool send_osc; plugin_gui *gui; map<string, string> cfg_vars; plugin_proxy_base() { client = NULL; send_osc = false; gui = NULL; } }; template<class Module> struct plugin_proxy: public plugin_proxy_base, public line_graph_iface { float params[Module::param_count]; plugin_proxy() { for (unsigned int i = 0; i < Module::param_count; i++) params[i] = get_param_props(i)->def_value; } virtual parameter_properties *get_param_props(int param_no) { return Module::param_props + param_no; } virtual float get_param_value(int param_no) { if (param_no < 0 || param_no >= Module::param_count) return 0; return params[param_no]; } virtual void set_param_value(int param_no, float value) { if (param_no < 0 || param_no >= Module::param_count) return; params[param_no] = value; if (send_osc) { osc_inline_typed_strstream str; str << (uint32_t)(param_no + get_param_port_offset()) << value; client->send("/control", str); } } virtual int get_param_count() { return Module::param_count; } virtual int get_param_port_offset() { return Module::in_count + Module::out_count; } virtual const char *get_gui_xml() { return Module::get_gui_xml(); } virtual line_graph_iface *get_line_graph_iface() { return this; } virtual bool activate_preset(int bank, int program) { if (send_osc) { osc_inline_typed_strstream str; str << (uint32_t)(bank) << (uint32_t)(program); client->send("/program", str); return false; } return false; } virtual bool get_graph(int index, int subindex, float *data, int points, cairo_t *context) { return Module::get_static_graph(index, subindex, params[index], data, points, context); } virtual const char *get_name() { return Module::get_name(); } virtual const char *get_id() { return Module::get_id(); } virtual const char *get_label() { return Module::get_label(); } virtual int get_input_count() { return Module::in_count; } virtual int get_output_count() { return Module::out_count; } virtual bool get_midi() { return Module::support_midi; } virtual float get_level(unsigned int port) { return 0.f; } virtual plugin_command_info *get_commands() { return Module::get_commands(); } virtual void execute(int command_no) { if (send_osc) { stringstream ss; ss << command_no; osc_inline_typed_strstream str; str << "ExecCommand" << ss.str(); client->send("/configure", str); str.clear(); str << "ExecCommand" << ""; client->send("/configure", str); } } char *configure(const char *key, const char *value) { cfg_vars[key] = value; osc_inline_typed_strstream str; str << key << value; client->send("/configure", str); return NULL; } void send_configures(send_configure_iface *sci) { for (map<string, string>::iterator i = cfg_vars.begin(); i != cfg_vars.end(); i++) sci->send_configure(i->first.c_str(), i->second.c_str()); } void clear_preset() { const char **p = Module::get_default_configure_vars(); if (p) { for(; p[0]; p += 2) configure(p[0], p[1]); } } }; plugin_proxy_base *create_plugin_proxy(const char *effect_name) { if (!strcmp(effect_name, "reverb")) return new plugin_proxy<reverb_audio_module>(); else if (!strcmp(effect_name, "flanger")) return new plugin_proxy<flanger_audio_module>(); else if (!strcmp(effect_name, "filter")) return new plugin_proxy<filter_audio_module>(); else if (!strcmp(effect_name, "monosynth")) return new plugin_proxy<monosynth_audio_module>(); else if (!strcmp(effect_name, "vintagedelay")) return new plugin_proxy<vintage_delay_audio_module>(); else if (!strcmp(effect_name, "organ")) return new plugin_proxy<organ_audio_module>(); else if (!strcmp(effect_name, "rotaryspeaker")) return new plugin_proxy<rotary_speaker_audio_module>(); else if (!strcmp(effect_name, "multichorus")) return new plugin_proxy<multichorus_audio_module>(); #ifdef ENABLE_EXPERIMENTAL #endif else return NULL; } void help(char *argv[]) { printf("GTK+ user interface for Calf DSSI plugins\nSyntax: %s [--help] [--version] <osc-url> <so-file> <plugin-label> <instance-name>\n", argv[0]); } static struct option long_options[] = { {"help", 0, 0, 'h'}, {"version", 0, 0, 'v'}, {"debug", 0, 0, 'd'}, {0,0,0,0}, }; GMainLoop *mainloop; static bool osc_debug = false; struct dssi_osc_server: public osc_server, public osc_message_sink<osc_strstream> { plugin_proxy_base *plugin; main_window *main_win; plugin_gui_window *window; string effect_name, title; osc_client cli; bool in_program, enable_dump; vector<plugin_preset> presets; dssi_osc_server() : plugin(NULL) , main_win(new main_window) , window(new plugin_gui_window(main_win)) { sink = this; } static void on_destroy(GtkWindow *window, dssi_osc_server *self) { debug_printf("on_destroy, have to send \"exiting\"\n"); bool result = self->cli.send("/exiting"); debug_printf("result = %d\n", result ? 1 : 0); g_main_loop_quit(mainloop); // eliminate a warning with empty debug_printf result = false; } void create_window() { plugin = create_plugin_proxy(effect_name.c_str()); if (!plugin) { fprintf(stderr, "Unknown plugin: %s\n", effect_name.c_str()); exit(1); } plugin->client = &cli; plugin->send_osc = true; ((main_window *)window->main)->conditions.insert("dssi"); window->create(plugin, title.c_str(), effect_name.c_str()); plugin->gui = window->gui; gtk_signal_connect(GTK_OBJECT(window->toplevel), "destroy", G_CALLBACK(on_destroy), this); vector<plugin_preset> tmp_presets; get_builtin_presets().get_for_plugin(presets, effect_name.c_str()); get_user_presets().get_for_plugin(tmp_presets, effect_name.c_str()); presets.insert(presets.end(), tmp_presets.begin(), tmp_presets.end()); } virtual void receive_osc_message(std::string address, std::string args, osc_strstream &buffer) { if (osc_debug) dump.receive_osc_message(address, args, buffer); if (address == prefix + "/update" && args == "s") { string str; buffer >> str; debug_printf("UPDATE: %s\n", str.c_str()); return; } if (address == prefix + "/quit") { debug_printf("QUIT\n"); g_main_loop_quit(mainloop); return; } if (address == prefix + "/configure"&& args == "ss") { string key, value; buffer >> key >> value; plugin->cfg_vars[key] = value; // XXXKF perhaps this should be queued ! window->gui->refresh(); return; } if (address == prefix + "/program"&& args == "ii") { uint32_t bank, program; buffer >> bank >> program; unsigned int nr = bank * 128 + program; debug_printf("PROGRAM %d\n", nr); if (nr == 0) { bool sosc = plugin->send_osc; plugin->send_osc = false; int count = plugin->get_param_count(); for (int i =0 ; i < count; i++) plugin->set_param_value(i, plugin->get_param_props(i)->def_value); plugin->send_osc = sosc; window->gui->refresh(); // special handling for default preset return; } nr--; if (nr >= presets.size()) return; bool sosc = plugin->send_osc; plugin->send_osc = false; presets[nr].activate(plugin); plugin->send_osc = sosc; window->gui->refresh(); // cli.send("/update", data); return; } if (address == prefix + "/control" && args == "if") { uint32_t port; float val; buffer >> port >> val; int idx = port - plugin->get_param_port_offset(); debug_printf("CONTROL %d %f\n", idx, val); bool sosc = plugin->send_osc; plugin->send_osc = false; window->gui->set_param_value(idx, val); plugin->send_osc = sosc; return; } if (address == prefix + "/show") { gtk_widget_show_all(GTK_WIDGET(window->toplevel)); return; } if (address == prefix + "/hide") { gtk_widget_hide(GTK_WIDGET(window->toplevel)); return; } } }; int main(int argc, char *argv[]) { char *debug_var = getenv("OSC_DEBUG"); if (debug_var && atoi(debug_var)) osc_debug = true; gtk_init(&argc, &argv); while(1) { int option_index; int c = getopt_long(argc, argv, "dhv", long_options, &option_index); if (c == -1) break; switch(c) { case 'd': osc_debug = true; break; case 'h': help(argv); return 0; case 'v': printf("%s\n", PACKAGE_STRING); return 0; } } if (argc - optind != 4) { help(argv); exit(0); } try { get_builtin_presets().load_defaults(true); get_user_presets().load_defaults(false); } catch(synth::preset_exception &e) { fprintf(stderr, "Error while loading presets: %s\n", e.what()); exit(1); } dssi_osc_server srv; srv.prefix = "/dssi/"+string(argv[optind + 1]) + "/" + string(argv[optind + 2]); for (char *p = argv[optind + 2]; *p; p++) *p = tolower(*p); srv.effect_name = argv[optind + 2]; srv.title = argv[optind + 3]; srv.bind(); srv.create_window(); mainloop = g_main_loop_new(NULL, FALSE); srv.cli.bind(); srv.cli.set_url(argv[optind]); debug_printf("URI = %s\n", srv.get_uri().c_str()); string data_buf, type_buf; osc_inline_typed_strstream data; data << srv.get_uri(); if (!srv.cli.send("/update", data)) { g_error("Could not send the initial update message via OSC to %s", argv[optind]); return 1; } g_main_loop_run(mainloop); debug_printf("exited\n"); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2015-2018 Dubalu LLC. All rights reserved. * * 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 "endpoint.h" #include "config.h" // for XAPIAND_BINARY_SERVERPORT #include <xapian.h> // for SerialisationError #include "fs.hh" // for normalize_path #include "opts.h" // for opts #include "serialise.h" // for UUIDRepr, Serialise #include "string.hh" // for string::Number static inline std::string normalize(const void *p, size_t size) { auto repr = static_cast<UUIDRepr>(opts.uuid_repr); std::string serialised_uuid; std::string normalized; std::string unserialised(static_cast<const char*>(p), size); if (Serialise::possiblyUUID(unserialised)) { try { serialised_uuid = Serialise::uuid(unserialised); normalized = Unserialise::uuid(serialised_uuid, repr); } catch (const SerialisationError&) { } } return normalized; } static inline std::string normalize_and_partition(const void *p, size_t size) { auto repr = static_cast<UUIDRepr>(opts.uuid_repr); std::string serialised_uuid; std::string normalized; std::string unserialised(static_cast<const char*>(p), size); if (Serialise::possiblyUUID(unserialised)) { try { serialised_uuid = Serialise::uuid(unserialised); normalized = Unserialise::uuid(serialised_uuid, repr); } catch (const SerialisationError& exc) { return normalized; } } else { return normalized; } std::string result; switch (repr) { #ifdef XAPIAND_UUID_GUID case UUIDRepr::guid: // {00000000-0000-1000-8000-010000000000} result.reserve(2 + 8 + normalized.size()); result.append(&normalized[1 + 14], &normalized[1 + 18]); result.push_back('/'); result.append(&normalized[1 + 9], &normalized[1 + 13]); result.push_back('/'); result.append(normalized); break; #endif #ifdef XAPIAND_UUID_URN case UUIDRepr::urn: // urn:uuid:00000000-0000-1000-8000-010000000000 result.reserve(2 + 8 + normalized.size()); result.append(&normalized[9 + 14], &normalized[9 + 18]); result.push_back('/'); result.append(&normalized[9 + 9], &normalized[9 + 13]); result.push_back('/'); result.append(normalized); break; #endif #ifdef XAPIAND_UUID_ENCODED case UUIDRepr::encoded: if (serialised_uuid.front() != 1 && (((serialised_uuid.back() & 1) != 0) || (serialised_uuid.size() > 5 && ((*(serialised_uuid.rbegin() + 5) & 2) != 0)))) { auto cit = normalized.cbegin(); auto cit_e = normalized.cend(); result.reserve(4 + normalized.size()); if (cit == cit_e) { return result; } result.push_back(*cit++); if (cit == cit_e) { return result; } result.push_back('/'); result.push_back(*cit++); if (cit == cit_e) { return result; } result.push_back(*cit++); if (cit == cit_e) { return result; } result.push_back('/'); result.push_back(*cit++); if (cit == cit_e) { return result; } result.push_back(*cit++); if (cit == cit_e) { return result; } result.push_back('/'); result.push_back(*cit++); if (cit == cit_e) { return result; } result.push_back(*cit++); if (cit == cit_e) { return result; } result.push_back('/'); result.append(cit, cit_e); break; } /* FALLTHROUGH */ #endif default: case UUIDRepr::simple: // 00000000-0000-1000-8000-010000000000 result.reserve(2 + 8 + normalized.size()); result.append(&normalized[14], &normalized[18]); result.push_back('/'); result.append(&normalized[9], &normalized[13]); result.push_back('/'); result.append(normalized); break; } return result; } using normalizer_t = std::string (*)(const void *, size_t); template<normalizer_t normalize> static inline std::string normalizer(const void *p, size_t size) { std::string buf; buf.reserve(size); auto q = static_cast<const char *>(p); auto p_end = q + size; auto oq = q; while (q != p_end) { char c = *q++; switch (c) { case '.': case '/': { auto sz = q - oq - 1; if (sz) { auto normalized = normalize(oq, sz); if (!normalized.empty()) { buf.resize(buf.size() - sz); buf.append(normalized); } } buf.push_back(c); oq = q; break; } default: buf.push_back(c); } } auto sz = q - oq; if (sz) { auto normalized = normalize(oq, sz); if (!normalized.empty()) { buf.resize(buf.size() - sz); buf.append(normalized); } } return buf; } std::string Endpoint::cwd("/"); Endpoint::Endpoint() : port(-1) { } Endpoint::Endpoint(std::string_view uri, const Node* node_, std::string_view node_name_) : node_name(node_name_) { auto protocol = slice_before(uri, "://"); if (protocol.empty()) { protocol = "file"; } auto _search = slice_after(uri, "?"); auto _path = slice_after(uri, "/"); auto _user = slice_before(uri, "@"); auto _password = slice_after(_user, ":"); auto _port = slice_after(uri, ":"); if (protocol == "file") { if (_path.empty()) { _path = uri; } else { _path = path = std::string(uri) + "/" + std::string(_path); } port = 0; } else { host = uri; port = strict_stoi(nullptr, _port); if (port == 0) { port = XAPIAND_BINARY_SERVERPORT; } search = _search; password = _password; user = _user; } if (!string::startswith(_path, '/')) { _path = path = Endpoint::cwd + std::string(_path); } path = normalize_path(_path); _path = path; if (string::startswith(_path, Endpoint::cwd)) { _path.remove_prefix(Endpoint::cwd.size()); } if (_path.size() != 1 && string::endswith(_path, '/')) { _path.remove_suffix(1); } if (opts.uuid_partition) { path = normalizer<normalize_and_partition>(_path.data(), _path.size()); } else { path = normalizer<normalize>(_path.data(), _path.size()); } if (protocol == "file") { auto local_node = Node::local_node(); if (node_ == nullptr) { node_ = local_node.get(); } host = node_->host(); port = node_->binary_port; if (port == 0) { port = XAPIAND_BINARY_SERVERPORT; } } } inline std::string_view Endpoint::slice_after(std::string_view& subject, std::string_view delimiter) const { size_t delimiter_location = subject.find(delimiter); std::string_view output; if (delimiter_location != std::string_view::npos) { size_t start = delimiter_location + delimiter.size(); output = subject.substr(start, subject.size() - start); if (!output.empty()) { subject = subject.substr(0, delimiter_location); } } return output; } inline std::string_view Endpoint::slice_before(std::string_view& subject, std::string_view delimiter) const { size_t delimiter_location = subject.find(delimiter); std::string_view output; if (delimiter_location != std::string::npos) { size_t start = delimiter_location + delimiter.length(); output = subject.substr(0, delimiter_location); subject = subject.substr(start, subject.length() - start); } return output; } std::string Endpoint::to_string() const { std::string ret; if (path.empty()) { return ret; } ret += "xapian://"; if (!user.empty() || !password.empty()) { ret += user; if (!password.empty()) { ret += ":" + password; } ret += "@"; } ret += host; if (port > 0) { ret += ":"; ret += string::Number(port); } if (!host.empty() || port > 0) { ret += "/"; } ret += path; if (!search.empty()) { ret += "?" + search; } return ret; } bool Endpoint::operator<(const Endpoint& other) const { return hash() < other.hash(); } bool Endpoint::is_local() const { auto local_node = Node::local_node(); int binary_port = local_node->binary_port; if (!binary_port) binary_port = XAPIAND_BINARY_SERVERPORT; return (host == local_node->host() || host == "127.0.0.1" || host == "localhost") && port == binary_port; } size_t Endpoint::hash() const { std::hash<std::string> hash_fn_string; std::hash<int> hash_fn_int; return ( hash_fn_string(path) ^ hash_fn_string(user) ^ hash_fn_string(password) ^ hash_fn_string(host) ^ hash_fn_int(port) ^ hash_fn_string(search) ); } std::string Endpoints::to_string() const { std::string ret; auto j = endpoints.cbegin(); for (int i = 0; j != endpoints.cend(); ++j, ++i) { if (i != 0) { ret += ";"; } ret += (*j).to_string(); } return ret; } size_t Endpoints::hash() const { size_t hash = 0; std::hash<Endpoint> hash_fn; auto j = endpoints.cbegin(); for (int i = 0; j != endpoints.cend(); ++j, ++i) { hash ^= hash_fn(*j); } return hash; } bool operator==(const Endpoint& le, const Endpoint& re) { std::hash<Endpoint> hash_fn; return hash_fn(le) == hash_fn(re); } bool operator==(const Endpoints& le, const Endpoints& re) { std::hash<Endpoints> hash_fn; return hash_fn(le) == hash_fn(re); } bool operator!=(const Endpoint& le, const Endpoint& re) { return !(le == re); } bool operator!=(const Endpoints& le, const Endpoints& re) { return !(le == re); } size_t std::hash<Endpoint>::operator()(const Endpoint& e) const { return e.hash(); } size_t std::hash<Endpoints>::operator()(const Endpoints& e) const { return e.hash(); } <commit_msg>Endpoint: Save node name<commit_after>/* * Copyright (C) 2015-2018 Dubalu LLC. All rights reserved. * * 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 "endpoint.h" #include "config.h" // for XAPIAND_BINARY_SERVERPORT #include <xapian.h> // for SerialisationError #include "fs.hh" // for normalize_path #include "opts.h" // for opts #include "serialise.h" // for UUIDRepr, Serialise #include "string.hh" // for string::Number static inline std::string normalize(const void *p, size_t size) { auto repr = static_cast<UUIDRepr>(opts.uuid_repr); std::string serialised_uuid; std::string normalized; std::string unserialised(static_cast<const char*>(p), size); if (Serialise::possiblyUUID(unserialised)) { try { serialised_uuid = Serialise::uuid(unserialised); normalized = Unserialise::uuid(serialised_uuid, repr); } catch (const SerialisationError&) { } } return normalized; } static inline std::string normalize_and_partition(const void *p, size_t size) { auto repr = static_cast<UUIDRepr>(opts.uuid_repr); std::string serialised_uuid; std::string normalized; std::string unserialised(static_cast<const char*>(p), size); if (Serialise::possiblyUUID(unserialised)) { try { serialised_uuid = Serialise::uuid(unserialised); normalized = Unserialise::uuid(serialised_uuid, repr); } catch (const SerialisationError& exc) { return normalized; } } else { return normalized; } std::string result; switch (repr) { #ifdef XAPIAND_UUID_GUID case UUIDRepr::guid: // {00000000-0000-1000-8000-010000000000} result.reserve(2 + 8 + normalized.size()); result.append(&normalized[1 + 14], &normalized[1 + 18]); result.push_back('/'); result.append(&normalized[1 + 9], &normalized[1 + 13]); result.push_back('/'); result.append(normalized); break; #endif #ifdef XAPIAND_UUID_URN case UUIDRepr::urn: // urn:uuid:00000000-0000-1000-8000-010000000000 result.reserve(2 + 8 + normalized.size()); result.append(&normalized[9 + 14], &normalized[9 + 18]); result.push_back('/'); result.append(&normalized[9 + 9], &normalized[9 + 13]); result.push_back('/'); result.append(normalized); break; #endif #ifdef XAPIAND_UUID_ENCODED case UUIDRepr::encoded: if (serialised_uuid.front() != 1 && (((serialised_uuid.back() & 1) != 0) || (serialised_uuid.size() > 5 && ((*(serialised_uuid.rbegin() + 5) & 2) != 0)))) { auto cit = normalized.cbegin(); auto cit_e = normalized.cend(); result.reserve(4 + normalized.size()); if (cit == cit_e) { return result; } result.push_back(*cit++); if (cit == cit_e) { return result; } result.push_back('/'); result.push_back(*cit++); if (cit == cit_e) { return result; } result.push_back(*cit++); if (cit == cit_e) { return result; } result.push_back('/'); result.push_back(*cit++); if (cit == cit_e) { return result; } result.push_back(*cit++); if (cit == cit_e) { return result; } result.push_back('/'); result.push_back(*cit++); if (cit == cit_e) { return result; } result.push_back(*cit++); if (cit == cit_e) { return result; } result.push_back('/'); result.append(cit, cit_e); break; } /* FALLTHROUGH */ #endif default: case UUIDRepr::simple: // 00000000-0000-1000-8000-010000000000 result.reserve(2 + 8 + normalized.size()); result.append(&normalized[14], &normalized[18]); result.push_back('/'); result.append(&normalized[9], &normalized[13]); result.push_back('/'); result.append(normalized); break; } return result; } using normalizer_t = std::string (*)(const void *, size_t); template<normalizer_t normalize> static inline std::string normalizer(const void *p, size_t size) { std::string buf; buf.reserve(size); auto q = static_cast<const char *>(p); auto p_end = q + size; auto oq = q; while (q != p_end) { char c = *q++; switch (c) { case '.': case '/': { auto sz = q - oq - 1; if (sz) { auto normalized = normalize(oq, sz); if (!normalized.empty()) { buf.resize(buf.size() - sz); buf.append(normalized); } } buf.push_back(c); oq = q; break; } default: buf.push_back(c); } } auto sz = q - oq; if (sz) { auto normalized = normalize(oq, sz); if (!normalized.empty()) { buf.resize(buf.size() - sz); buf.append(normalized); } } return buf; } std::string Endpoint::cwd("/"); Endpoint::Endpoint() : port(-1) { } Endpoint::Endpoint(std::string_view uri, const Node* node_, std::string_view node_name_) : node_name(node_name_) { auto protocol = slice_before(uri, "://"); if (protocol.empty()) { protocol = "file"; } auto _search = slice_after(uri, "?"); auto _path = slice_after(uri, "/"); auto _user = slice_before(uri, "@"); auto _password = slice_after(_user, ":"); auto _port = slice_after(uri, ":"); if (protocol == "file") { if (_path.empty()) { _path = uri; } else { _path = path = std::string(uri) + "/" + std::string(_path); } port = 0; } else { host = uri; port = strict_stoi(nullptr, _port); if (port == 0) { port = XAPIAND_BINARY_SERVERPORT; } search = _search; password = _password; user = _user; } if (!string::startswith(_path, '/')) { _path = path = Endpoint::cwd + std::string(_path); } path = normalize_path(_path); _path = path; if (string::startswith(_path, Endpoint::cwd)) { _path.remove_prefix(Endpoint::cwd.size()); } if (_path.size() != 1 && string::endswith(_path, '/')) { _path.remove_suffix(1); } if (opts.uuid_partition) { path = normalizer<normalize_and_partition>(_path.data(), _path.size()); } else { path = normalizer<normalize>(_path.data(), _path.size()); } if (protocol == "file") { auto local_node = Node::local_node(); if (node_ == nullptr) { node_ = local_node.get(); } node_name = node_->name(); host = node_->host(); port = node_->binary_port; if (port == 0) { port = XAPIAND_BINARY_SERVERPORT; } } } inline std::string_view Endpoint::slice_after(std::string_view& subject, std::string_view delimiter) const { size_t delimiter_location = subject.find(delimiter); std::string_view output; if (delimiter_location != std::string_view::npos) { size_t start = delimiter_location + delimiter.size(); output = subject.substr(start, subject.size() - start); if (!output.empty()) { subject = subject.substr(0, delimiter_location); } } return output; } inline std::string_view Endpoint::slice_before(std::string_view& subject, std::string_view delimiter) const { size_t delimiter_location = subject.find(delimiter); std::string_view output; if (delimiter_location != std::string::npos) { size_t start = delimiter_location + delimiter.length(); output = subject.substr(0, delimiter_location); subject = subject.substr(start, subject.length() - start); } return output; } std::string Endpoint::to_string() const { std::string ret; if (path.empty()) { return ret; } ret += "xapian://"; if (!user.empty() || !password.empty()) { ret += user; if (!password.empty()) { ret += ":" + password; } ret += "@"; } ret += host; if (port > 0) { ret += ":"; ret += string::Number(port); } if (!host.empty() || port > 0) { ret += "/"; } ret += path; if (!search.empty()) { ret += "?" + search; } return ret; } bool Endpoint::operator<(const Endpoint& other) const { return hash() < other.hash(); } bool Endpoint::is_local() const { auto local_node = Node::local_node(); int binary_port = local_node->binary_port; if (!binary_port) binary_port = XAPIAND_BINARY_SERVERPORT; return (host == local_node->host() || host == "127.0.0.1" || host == "localhost") && port == binary_port; } size_t Endpoint::hash() const { std::hash<std::string> hash_fn_string; std::hash<int> hash_fn_int; return ( hash_fn_string(path) ^ hash_fn_string(user) ^ hash_fn_string(password) ^ hash_fn_string(host) ^ hash_fn_int(port) ^ hash_fn_string(search) ); } std::string Endpoints::to_string() const { std::string ret; auto j = endpoints.cbegin(); for (int i = 0; j != endpoints.cend(); ++j, ++i) { if (i != 0) { ret += ";"; } ret += (*j).to_string(); } return ret; } size_t Endpoints::hash() const { size_t hash = 0; std::hash<Endpoint> hash_fn; auto j = endpoints.cbegin(); for (int i = 0; j != endpoints.cend(); ++j, ++i) { hash ^= hash_fn(*j); } return hash; } bool operator==(const Endpoint& le, const Endpoint& re) { std::hash<Endpoint> hash_fn; return hash_fn(le) == hash_fn(re); } bool operator==(const Endpoints& le, const Endpoints& re) { std::hash<Endpoints> hash_fn; return hash_fn(le) == hash_fn(re); } bool operator!=(const Endpoint& le, const Endpoint& re) { return !(le == re); } bool operator!=(const Endpoints& le, const Endpoints& re) { return !(le == re); } size_t std::hash<Endpoint>::operator()(const Endpoint& e) const { return e.hash(); } size_t std::hash<Endpoints>::operator()(const Endpoints& e) const { return e.hash(); } <|endoftext|>
<commit_before>// Copyright (c) 2011 Zeex // // 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 <sampgdk/config.h> #include <sampgdk/amx/amx.h> #include "fakeamx.h" #include <cstddef> #include <cstring> #include <limits> FakeAmx::FakeAmx() : heap_(new cell[INITIAL_HEAP_SIZE]) , heapSize_(INITIAL_HEAP_SIZE) { std::memset(&hdr_, 0, sizeof(hdr_)); std::memset(&amx_, 0, sizeof(amx_)); hdr_.magic = AMX_MAGIC; hdr_.file_version = MIN_FILE_VERSION; hdr_.amx_version = MIN_AMX_VERSION; hdr_.dat = reinterpret_cast<int32_t>(heap_) - reinterpret_cast<int32_t>(&hdr_); amx_.base = reinterpret_cast<unsigned char*>(&hdr_); amx_.data = reinterpret_cast<unsigned char*>(heap_); amx_.callback = amx_Callback; amx_.stp = std::numeric_limits<cell>::max(); amx_.error = AMX_ERR_NONE; } FakeAmx::~FakeAmx() { delete[] heap_; } FakeAmx &FakeAmx::GetInstance() { static FakeAmx instance; return instance; } cell FakeAmx::Push(size_t cells) { cell address = amx_.hea; amx_.hea += cells * sizeof(cell); if (amx_.hea >= heapSize_) { ResizeHeap(amx_.hea); } return address; } cell FakeAmx::Push(const char *s) { std::size_t size = std::strlen(s) + 1; cell address = Push(size); amx_SetString(heap_ + address/sizeof(cell), s, 0, 0, size); return address; } void FakeAmx::Get(cell address, cell &value) const { value = heap_[address/sizeof(cell)]; } void FakeAmx::Get(cell address, char *value, size_t size) const { cell *ptr = heap_ + address/sizeof(cell); amx_GetString(value, ptr, 0, size); } void FakeAmx::Pop(cell address) { if (amx_.hea > address) { amx_.hea = address; } } cell FakeAmx::CallNative(AMX_NATIVE native, cell *params) { return native(&amx_, params); } bool FakeAmx::CallBooleanNative(AMX_NATIVE native, cell *params) { return CallNative(native, params) != 0; } void FakeAmx::ResizeHeap(std::size_t newSize) { cell *newHeap = new cell[newSize]; if (newHeap != 0) { std::memcpy(newHeap, heap_, heapSize_); delete[] heap_; heap_ = newHeap; heapSize_ = newSize; } } FakeAmxHeapObject::FakeAmxHeapObject() : size_(1), address_(FakeAmx::GetInstance().Push(1)) {} FakeAmxHeapObject::FakeAmxHeapObject(size_t cells) : size_(cells), address_(FakeAmx::GetInstance().Push(cells)) {} FakeAmxHeapObject::FakeAmxHeapObject(const char *s) : size_(std::strlen(s) + 1), address_(FakeAmx::GetInstance().Push(s)) {} FakeAmxHeapObject::~FakeAmxHeapObject() { FakeAmx::GetInstance().Pop(address_); } cell FakeAmxHeapObject::address() const { return address_; } size_t FakeAmxHeapObject::size() const { return size_; } cell FakeAmxHeapObject::Get() const { cell value; FakeAmx::GetInstance().Get(address_, value); return value; } float FakeAmxHeapObject::GetAsFloat() const { cell value = this->Get(); return amx_ctof(value); } void FakeAmxHeapObject::GetAsString(char *s, size_t size) const { FakeAmx::GetInstance().Get(address_, s, size); } <commit_msg>Fix MSVC warning C4018: '>=' : signed/unsigned mismatch<commit_after>// Copyright (c) 2011 Zeex // // 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 <sampgdk/config.h> #include <sampgdk/amx/amx.h> #include "fakeamx.h" #include <cstddef> #include <cstring> #include <limits> FakeAmx::FakeAmx() : heap_(new cell[INITIAL_HEAP_SIZE]) , heapSize_(INITIAL_HEAP_SIZE) { std::memset(&hdr_, 0, sizeof(hdr_)); std::memset(&amx_, 0, sizeof(amx_)); hdr_.magic = AMX_MAGIC; hdr_.file_version = MIN_FILE_VERSION; hdr_.amx_version = MIN_AMX_VERSION; hdr_.dat = reinterpret_cast<int32_t>(heap_) - reinterpret_cast<int32_t>(&hdr_); amx_.base = reinterpret_cast<unsigned char*>(&hdr_); amx_.data = reinterpret_cast<unsigned char*>(heap_); amx_.callback = amx_Callback; amx_.stp = std::numeric_limits<cell>::max(); amx_.error = AMX_ERR_NONE; } FakeAmx::~FakeAmx() { delete[] heap_; } FakeAmx &FakeAmx::GetInstance() { static FakeAmx instance; return instance; } cell FakeAmx::Push(size_t cells) { cell address = amx_.hea; amx_.hea += cells * sizeof(cell); if (amx_.hea >= static_cast<cell>(heapSize_)) { ResizeHeap(amx_.hea); } return address; } cell FakeAmx::Push(const char *s) { std::size_t size = std::strlen(s) + 1; cell address = Push(size); amx_SetString(heap_ + address/sizeof(cell), s, 0, 0, size); return address; } void FakeAmx::Get(cell address, cell &value) const { value = heap_[address/sizeof(cell)]; } void FakeAmx::Get(cell address, char *value, size_t size) const { cell *ptr = heap_ + address/sizeof(cell); amx_GetString(value, ptr, 0, size); } void FakeAmx::Pop(cell address) { if (amx_.hea > address) { amx_.hea = address; } } cell FakeAmx::CallNative(AMX_NATIVE native, cell *params) { return native(&amx_, params); } bool FakeAmx::CallBooleanNative(AMX_NATIVE native, cell *params) { return CallNative(native, params) != 0; } void FakeAmx::ResizeHeap(std::size_t newSize) { cell *newHeap = new cell[newSize]; if (newHeap != 0) { std::memcpy(newHeap, heap_, heapSize_); delete[] heap_; heap_ = newHeap; heapSize_ = newSize; } } FakeAmxHeapObject::FakeAmxHeapObject() : size_(1), address_(FakeAmx::GetInstance().Push(1)) {} FakeAmxHeapObject::FakeAmxHeapObject(size_t cells) : size_(cells), address_(FakeAmx::GetInstance().Push(cells)) {} FakeAmxHeapObject::FakeAmxHeapObject(const char *s) : size_(std::strlen(s) + 1), address_(FakeAmx::GetInstance().Push(s)) {} FakeAmxHeapObject::~FakeAmxHeapObject() { FakeAmx::GetInstance().Pop(address_); } cell FakeAmxHeapObject::address() const { return address_; } size_t FakeAmxHeapObject::size() const { return size_; } cell FakeAmxHeapObject::Get() const { cell value; FakeAmx::GetInstance().Get(address_, value); return value; } float FakeAmxHeapObject::GetAsFloat() const { cell value = this->Get(); return amx_ctof(value); } void FakeAmxHeapObject::GetAsString(char *s, size_t size) const { FakeAmx::GetInstance().Get(address_, s, size); } <|endoftext|>
<commit_before>#include "feClass.h" feClass::feClass() { } feClass::feClass(std::string baseClassData) { initializeNameStats(baseClassData); } void feClass::initializeNameStats(std::string baseClassData) { } std::vector<std::string> feClass::getWeaponTypes() const { return (weaponTypes); } std::vector<std::string> feClass::getPromotions() const { return (promotions); }<commit_msg>return function for skill map<commit_after>#include "feClass.h" feClass::feClass() { } feClass::feClass(std::string baseClassData) { initializeNameStats(baseClassData); } void feClass::initializeNameStats(std::string baseClassData) { } std::vector<std::string> feClass::getWeaponTypes() const { return (weaponTypes); } std::vector<std::string> feClass::getPromotions() const { return (promotions); } std::unordered_map<int, feSkill> feClass::getSkills() const { return (classSkills); }<|endoftext|>
<commit_before>/* Copyright (c) 2011, The Mineserver Project 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 The Mineserver Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 <iostream> #include "constants.h" #include "furnace.h" #include "mineserver.h" #include "map.h" #include "tools.h" #include "config.h" #include "protocol.h" Creation createList[2258]; bool configIsRead = false; Creation::Creation() { output = -1; meta = 0; count = 0; } Furnace::Furnace(furnaceDataPtr data) : m_data(data) { uint8_t block; uint8_t meta; ServerInstance->map(m_data->map)->getBlock(m_data->x, m_data->y, m_data->z, &block, &meta); if (!configIsRead) { readConfig(); configIsRead = true; } // Check if this is a burning block if (block == BLOCK_BURNING_FURNACE) { m_burning = true; } else { m_burning = false; } // Make sure we're the right kind of block based on our current status updateBlock(); } void Furnace::updateItems() { if (!hasValidIngredient()) { m_data->cookTime = 0; } else { } } void Furnace::updateBlock() { // Get a pointer to this furnace's current block uint8_t block; uint8_t meta; // Now make sure that it's got the correct block type based on it's current status if (isBurningFuel() && !m_burning) { ServerInstance->map(m_data->map)->getBlock(m_data->x, m_data->y, m_data->z, &block, &meta); // Switch to burning furnace ServerInstance->map(m_data->map)->setBlock(m_data->x, m_data->y, m_data->z, BLOCK_BURNING_FURNACE, meta); ServerInstance->map(m_data->map)->sendBlockChange(m_data->x, m_data->y, m_data->z, BLOCK_BURNING_FURNACE, meta); sendToAllUsers(); m_burning = true; } else if (!isBurningFuel() && m_burning) { ServerInstance->map(m_data->map)->getBlock(m_data->x, m_data->y, m_data->z, &block, &meta); // Switch to regular furnace ServerInstance->map(m_data->map)->setBlock(m_data->x, m_data->y, m_data->z, BLOCK_FURNACE, meta); ServerInstance->map(m_data->map)->sendBlockChange(m_data->x, m_data->y, m_data->z, BLOCK_FURNACE, meta); sendToAllUsers(); m_burning = false; } } void Furnace::smelt() { // Check if we're cooking if (isCooking()) { // Convert where applicable Item* inputSlot = &slots()[SLOT_INPUT]; Item* fuelSlot = &slots()[SLOT_FUEL]; Item* outputSlot = &slots()[SLOT_OUTPUT]; int32_t creationID = createList[inputSlot->getType()].output; // Update other params if we actually converted if (creationID != -1 && outputSlot->getCount() != 64) { // Check if the outputSlot is empty if (outputSlot->getType() == -1) { outputSlot->setType(creationID); outputSlot->setCount(1); outputSlot->setHealth(createList[inputSlot->getType()].meta); inputSlot->setCount(inputSlot->getCount() - 1); m_data->cookTime = 0; } // Ok - now check if the current output slot contains the same stuff if (outputSlot->getType() == creationID && m_data->cookTime != 0) { // Increment output and decrememnt the input source outputSlot->setCount(outputSlot->getCount() + createList[inputSlot->getType()].count); inputSlot->setCount(inputSlot->getCount() - 1); outputSlot->setHealth(createList[inputSlot->getType()].meta); m_data->cookTime = 0; if (inputSlot->getCount() == 0) { *inputSlot = Item(); } } } } } bool Furnace::isBurningFuel() { // Check if this furnace is currently burning if (m_data->burnTime > 0) { return true; } else { return false; } } bool Furnace::isCooking() { // If we're burning fuel and have valid ingredients, we're cooking! if (isBurningFuel() && hasValidIngredient()) { return true; } else { return false; } } bool Furnace::hasValidIngredient() { // Check that we have a valid input type Item* slot = &slots()[SLOT_INPUT]; if (slot->getType() < 0) { return false; } if (createList[slot->getType()].output != -1) { return true; } return false; } void Furnace::consumeFuel() { // Check that we have fuel if (slots()[SLOT_FUEL].getCount() == 0) { return; } // Increment the fuel burning time based on fuel type // http://www.minecraftwiki.net/wiki/Furnace#Fuel_efficiency Item* fuelSlot = &slots()[SLOT_FUEL]; uint16_t fuelTime = 0; switch (fuelSlot->getType()) { case ITEM_COAL: fuelTime = 80; break; case BLOCK_PLANK: fuelTime = 15; break; case ITEM_STICK: fuelTime = 5; break; case BLOCK_LOG: fuelTime = 15; break; case BLOCK_WORKBENCH: fuelTime = 15; break; case BLOCK_CHEST: fuelTime = 15; break; case BLOCK_BOOKSHELF: fuelTime = 15; break; case BLOCK_JUKEBOX: fuelTime = 15; break; case BLOCK_FENCE_OAK: case BLOCK_FENCE_BIRCH: case BLOCK_FENCE_JUNGLE: case BLOCK_FENCE_DARK_OAK: case BLOCK_FENCE_ACACIA: fuelTime = 15; break; case BLOCK_WOODEN_STAIRS: fuelTime = 15; break; case ITEM_LAVA_BUCKET: fuelTime = 1000; break; default: break; } if (fuelTime > 0) { m_data->burnTime += fuelTime; // Now decrement the fuel & reset fuelSlot->setCount(fuelSlot->getCount() - 1); if (fuelSlot->getCount() == 0) { *fuelSlot = Item(); } } // Update our block type if need be updateBlock(); } int16_t Furnace::burnTime() { return m_data->burnTime; } int16_t Furnace::cookTime() { return 10; } void Furnace::sendToAllUsers() { enum { PROGRESS_ARROW = 0, PROGRESS_FIRE = 1 }; //ToDo: send changes to all with this furnace opened std::vector<OpenInvPtr>& inv = ServerInstance->inventory()->openFurnaces; for (size_t openinv = 0; openinv < inv.size(); ++openinv) { if (inv[openinv]->x == m_data->x && inv[openinv]->y == m_data->y && inv[openinv]->z == m_data->z) { for (size_t user = 0; user < inv[openinv]->users.size(); ++user) { for (size_t j = 0; j < 3; ++j) { if (m_data->items[j].getType() != -1) { Item& item = m_data->items[j]; inv[openinv]->users[user]->writePacket(Protocol::setSlot(WINDOW_FURNACE, j, item)); } } inv[openinv]->users[user]->writePacket(Protocol::windowProperty(WINDOW_FURNACE, PROGRESS_ARROW, (m_data->cookTime * 18))); inv[openinv]->users[user]->writePacket(Protocol::windowProperty(WINDOW_FURNACE, PROGRESS_FIRE, (m_data->burnTime * 3))); } break; } } } void readConfig() { const std::string key = "furnace.items"; if (ServerInstance->config()->has(key) && ServerInstance->config()->type(key) == CONFIG_NODE_LIST) { std::list<std::string> tmp = ServerInstance->config()->mData(key)->keys(); for (std::list<std::string>::const_iterator it = tmp.begin(); it != tmp.end(); ++it) { int input = ServerInstance->config()->iData(key + "." + *it + ".in"); createList[input].output = ServerInstance->config()->iData(key + "." + *it + ".out"); createList[input].meta = ServerInstance->config()->iData(key + "." + *it + ".meta"); createList[input].count = ServerInstance->config()->iData(key + "." + *it + ".count"); } } } <commit_msg>Fix furnace progress arrow<commit_after>/* Copyright (c) 2011, The Mineserver Project 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 The Mineserver Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 <iostream> #include "constants.h" #include "furnace.h" #include "mineserver.h" #include "map.h" #include "tools.h" #include "config.h" #include "protocol.h" Creation createList[2258]; bool configIsRead = false; Creation::Creation() { output = -1; meta = 0; count = 0; } Furnace::Furnace(furnaceDataPtr data) : m_data(data) { uint8_t block; uint8_t meta; ServerInstance->map(m_data->map)->getBlock(m_data->x, m_data->y, m_data->z, &block, &meta); if (!configIsRead) { readConfig(); configIsRead = true; } // Check if this is a burning block if (block == BLOCK_BURNING_FURNACE) { m_burning = true; } else { m_burning = false; } // Make sure we're the right kind of block based on our current status updateBlock(); } void Furnace::updateItems() { if (!hasValidIngredient()) { m_data->cookTime = 0; } else { } } void Furnace::updateBlock() { // Get a pointer to this furnace's current block uint8_t block; uint8_t meta; // Now make sure that it's got the correct block type based on it's current status if (isBurningFuel() && !m_burning) { ServerInstance->map(m_data->map)->getBlock(m_data->x, m_data->y, m_data->z, &block, &meta); // Switch to burning furnace ServerInstance->map(m_data->map)->setBlock(m_data->x, m_data->y, m_data->z, BLOCK_BURNING_FURNACE, meta); ServerInstance->map(m_data->map)->sendBlockChange(m_data->x, m_data->y, m_data->z, BLOCK_BURNING_FURNACE, meta); sendToAllUsers(); m_burning = true; } else if (!isBurningFuel() && m_burning) { ServerInstance->map(m_data->map)->getBlock(m_data->x, m_data->y, m_data->z, &block, &meta); // Switch to regular furnace ServerInstance->map(m_data->map)->setBlock(m_data->x, m_data->y, m_data->z, BLOCK_FURNACE, meta); ServerInstance->map(m_data->map)->sendBlockChange(m_data->x, m_data->y, m_data->z, BLOCK_FURNACE, meta); sendToAllUsers(); m_burning = false; } } void Furnace::smelt() { // Check if we're cooking if (isCooking()) { // Convert where applicable Item* inputSlot = &slots()[SLOT_INPUT]; Item* fuelSlot = &slots()[SLOT_FUEL]; Item* outputSlot = &slots()[SLOT_OUTPUT]; int32_t creationID = createList[inputSlot->getType()].output; // Update other params if we actually converted if (creationID != -1 && outputSlot->getCount() != 64) { // Check if the outputSlot is empty if (outputSlot->getType() == -1) { outputSlot->setType(creationID); outputSlot->setCount(1); outputSlot->setHealth(createList[inputSlot->getType()].meta); inputSlot->setCount(inputSlot->getCount() - 1); m_data->cookTime = 0; } // Ok - now check if the current output slot contains the same stuff if (outputSlot->getType() == creationID && m_data->cookTime != 0) { // Increment output and decrememnt the input source outputSlot->setCount(outputSlot->getCount() + createList[inputSlot->getType()].count); inputSlot->setCount(inputSlot->getCount() - 1); outputSlot->setHealth(createList[inputSlot->getType()].meta); m_data->cookTime = 0; if (inputSlot->getCount() == 0) { *inputSlot = Item(); } } } } } bool Furnace::isBurningFuel() { // Check if this furnace is currently burning if (m_data->burnTime > 0) { return true; } else { return false; } } bool Furnace::isCooking() { // If we're burning fuel and have valid ingredients, we're cooking! if (isBurningFuel() && hasValidIngredient()) { return true; } else { return false; } } bool Furnace::hasValidIngredient() { // Check that we have a valid input type Item* slot = &slots()[SLOT_INPUT]; if (slot->getType() < 0) { return false; } if (createList[slot->getType()].output != -1) { return true; } return false; } void Furnace::consumeFuel() { // Check that we have fuel if (slots()[SLOT_FUEL].getCount() == 0) { return; } // Increment the fuel burning time based on fuel type // http://www.minecraftwiki.net/wiki/Furnace#Fuel_efficiency Item* fuelSlot = &slots()[SLOT_FUEL]; uint16_t fuelTime = 0; switch (fuelSlot->getType()) { case ITEM_COAL: fuelTime = 80; break; case BLOCK_PLANK: fuelTime = 15; break; case ITEM_STICK: fuelTime = 5; break; case BLOCK_LOG: fuelTime = 15; break; case BLOCK_WORKBENCH: fuelTime = 15; break; case BLOCK_CHEST: fuelTime = 15; break; case BLOCK_BOOKSHELF: fuelTime = 15; break; case BLOCK_JUKEBOX: fuelTime = 15; break; case BLOCK_FENCE_OAK: case BLOCK_FENCE_BIRCH: case BLOCK_FENCE_JUNGLE: case BLOCK_FENCE_DARK_OAK: case BLOCK_FENCE_ACACIA: fuelTime = 15; break; case BLOCK_WOODEN_STAIRS: fuelTime = 15; break; case ITEM_LAVA_BUCKET: fuelTime = 1000; break; default: break; } if (fuelTime > 0) { m_data->burnTime += fuelTime; // Now decrement the fuel & reset fuelSlot->setCount(fuelSlot->getCount() - 1); if (fuelSlot->getCount() == 0) { *fuelSlot = Item(); } } // Update our block type if need be updateBlock(); } int16_t Furnace::burnTime() { return m_data->burnTime; } int16_t Furnace::cookTime() { return 10; } void Furnace::sendToAllUsers() { enum { PROGRESS_FIRE = 0, PROGRESS_ARROW = 2 }; //ToDo: send changes to all with this furnace opened std::vector<OpenInvPtr>& inv = ServerInstance->inventory()->openFurnaces; for (size_t openinv = 0; openinv < inv.size(); ++openinv) { if (inv[openinv]->x == m_data->x && inv[openinv]->y == m_data->y && inv[openinv]->z == m_data->z) { for (size_t user = 0; user < inv[openinv]->users.size(); ++user) { for (size_t j = 0; j < 3; ++j) { Item& item = m_data->items[j]; inv[openinv]->users[user]->writePacket(Protocol::setSlot(WINDOW_FURNACE, j, item)); } inv[openinv]->users[user]->writePacket(Protocol::windowProperty(WINDOW_FURNACE, PROGRESS_FIRE, m_data->burnTime>10?200: (m_data->burnTime * 20))); inv[openinv]->users[user]->writePacket(Protocol::windowProperty(WINDOW_FURNACE, 3, 200)); inv[openinv]->users[user]->writePacket(Protocol::windowProperty(WINDOW_FURNACE, PROGRESS_ARROW, (m_data->cookTime * 20))); } break; } } } void readConfig() { const std::string key = "furnace.items"; if (ServerInstance->config()->has(key) && ServerInstance->config()->type(key) == CONFIG_NODE_LIST) { std::list<std::string> tmp = ServerInstance->config()->mData(key)->keys(); for (std::list<std::string>::const_iterator it = tmp.begin(); it != tmp.end(); ++it) { int input = ServerInstance->config()->iData(key + "." + *it + ".in"); createList[input].output = ServerInstance->config()->iData(key + "." + *it + ".out"); createList[input].meta = ServerInstance->config()->iData(key + "." + *it + ".meta"); createList[input].count = ServerInstance->config()->iData(key + "." + *it + ".count"); } } } <|endoftext|>
<commit_before>/** * @file LLSidepanelInventory.cpp * @brief Side Bar "Inventory" panel * * $LicenseInfo:firstyear=2009&license=viewergpl$ * * Copyright (c) 2004-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llsidepanelinventory.h" #include "llagent.h" #include "llbutton.h" #include "llinventorybridge.h" #include "llinventorypanel.h" #include "llpanelmaininventory.h" #include "llsidepaneliteminfo.h" #include "llsidepaneltaskinfo.h" #include "lltabcontainer.h" #include "llselectmgr.h" static LLRegisterPanelClassWrapper<LLSidepanelInventory> t_inventory("sidepanel_inventory"); LLSidepanelInventory::LLSidepanelInventory() : LLPanel(), mItemPanel(NULL), mPanelMainInventory(NULL) { //LLUICtrlFactory::getInstance()->buildPanel(this, "panel_inventory.xml"); // Called from LLRegisterPanelClass::defaultPanelClassBuilder() } LLSidepanelInventory::~LLSidepanelInventory() { } BOOL LLSidepanelInventory::postBuild() { // UI elements from inventory panel { mInventoryPanel = getChild<LLPanel>("sidepanel__inventory_panel"); mInfoBtn = mInventoryPanel->getChild<LLButton>("info_btn"); mInfoBtn->setClickedCallback(boost::bind(&LLSidepanelInventory::onInfoButtonClicked, this)); mShareBtn = mInventoryPanel->getChild<LLButton>("share_btn"); mShareBtn->setClickedCallback(boost::bind(&LLSidepanelInventory::onShareButtonClicked, this)); mWearBtn = mInventoryPanel->getChild<LLButton>("wear_btn"); mWearBtn->setClickedCallback(boost::bind(&LLSidepanelInventory::onWearButtonClicked, this)); mPlayBtn = mInventoryPanel->getChild<LLButton>("play_btn"); mPlayBtn->setClickedCallback(boost::bind(&LLSidepanelInventory::onPlayButtonClicked, this)); mTeleportBtn = mInventoryPanel->getChild<LLButton>("teleport_btn"); mTeleportBtn->setClickedCallback(boost::bind(&LLSidepanelInventory::onTeleportButtonClicked, this)); mOverflowBtn = mInventoryPanel->getChild<LLButton>("overflow_btn"); mOverflowBtn->setClickedCallback(boost::bind(&LLSidepanelInventory::onOverflowButtonClicked, this)); mPanelMainInventory = mInventoryPanel->getChild<LLPanelMainInventory>("panel_main_inventory"); mPanelMainInventory->setSelectCallback(boost::bind(&LLSidepanelInventory::onSelectionChange, this, _1, _2)); } // UI elements from item panel { mItemPanel = getChild<LLSidepanelItemInfo>("sidepanel__item_panel"); LLButton* back_btn = mItemPanel->getChild<LLButton>("back_btn"); back_btn->setClickedCallback(boost::bind(&LLSidepanelInventory::onBackButtonClicked, this)); } // UI elements from task panel { mTaskPanel = getChild<LLSidepanelTaskInfo>("sidepanel__task_panel"); if (mTaskPanel) { LLButton* back_btn = mTaskPanel->getChild<LLButton>("back_btn"); back_btn->setClickedCallback(boost::bind(&LLSidepanelInventory::onBackButtonClicked, this)); } } return TRUE; } void LLSidepanelInventory::onOpen(const LLSD& key) { if(key.size() == 0) return; mItemPanel->reset(); if (key.has("id")) { mItemPanel->setItemID(key["id"].asUUID()); if (key.has("object")) { mItemPanel->setObjectID(key["object"].asUUID()); } showItemInfoPanel(); } if (key.has("task")) { if (mTaskPanel) mTaskPanel->setObjectSelection(LLSelectMgr::getInstance()->getSelection()); showTaskInfoPanel(); } } void LLSidepanelInventory::onInfoButtonClicked() { LLInventoryItem *item = getSelectedItem(); if (item) { mItemPanel->reset(); mItemPanel->setItemID(item->getUUID()); showItemInfoPanel(); } } void LLSidepanelInventory::onShareButtonClicked() { } void LLSidepanelInventory::performActionOnSelection(const std::string &action) { LLPanelMainInventory *panel_main_inventory = mInventoryPanel->getChild<LLPanelMainInventory>("panel_main_inventory"); LLFolderViewItem* current_item = panel_main_inventory->getActivePanel()->getRootFolder()->getCurSelectedItem(); if (!current_item) { return; } current_item->getListener()->performAction(panel_main_inventory->getActivePanel()->getRootFolder(), panel_main_inventory->getActivePanel()->getModel(), action); } void LLSidepanelInventory::onWearButtonClicked() { performActionOnSelection("wear"); performActionOnSelection("attach"); } void LLSidepanelInventory::onPlayButtonClicked() { performActionOnSelection("activate"); } void LLSidepanelInventory::onTeleportButtonClicked() { performActionOnSelection("teleport"); } void LLSidepanelInventory::onOverflowButtonClicked() { } void LLSidepanelInventory::onBackButtonClicked() { showInventoryPanel(); } void LLSidepanelInventory::onSelectionChange(const std::deque<LLFolderViewItem*> &items, BOOL user_action) { updateVerbs(); } void LLSidepanelInventory::showItemInfoPanel() { mItemPanel->setVisible(TRUE); if (mTaskPanel) mTaskPanel->setVisible(FALSE); mInventoryPanel->setVisible(FALSE); mItemPanel->dirty(); mItemPanel->setIsEditing(FALSE); } void LLSidepanelInventory::showTaskInfoPanel() { mItemPanel->setVisible(FALSE); mInventoryPanel->setVisible(FALSE); if (mTaskPanel) { mTaskPanel->setVisible(TRUE); mTaskPanel->dirty(); mTaskPanel->setIsEditing(FALSE); } } void LLSidepanelInventory::showInventoryPanel() { mItemPanel->setVisible(FALSE); if (mTaskPanel) mTaskPanel->setVisible(FALSE); mInventoryPanel->setVisible(TRUE); updateVerbs(); } void LLSidepanelInventory::updateVerbs() { mInfoBtn->setEnabled(FALSE); mShareBtn->setEnabled(FALSE); mWearBtn->setVisible(FALSE); mWearBtn->setEnabled(FALSE); mPlayBtn->setVisible(FALSE); mPlayBtn->setEnabled(FALSE); mTeleportBtn->setVisible(FALSE); mTeleportBtn->setEnabled(FALSE); const LLInventoryItem *item = getSelectedItem(); if (!item) return; bool is_single_selection = getSelectedCount() == 1; mInfoBtn->setEnabled(is_single_selection); mShareBtn->setEnabled(is_single_selection); switch(item->getInventoryType()) { case LLInventoryType::IT_WEARABLE: case LLInventoryType::IT_OBJECT: case LLInventoryType::IT_ATTACHMENT: mWearBtn->setVisible(TRUE); mWearBtn->setEnabled(TRUE); break; case LLInventoryType::IT_SOUND: case LLInventoryType::IT_GESTURE: case LLInventoryType::IT_ANIMATION: mPlayBtn->setVisible(TRUE); mPlayBtn->setEnabled(TRUE); break; case LLInventoryType::IT_LANDMARK: mTeleportBtn->setVisible(TRUE); mTeleportBtn->setEnabled(TRUE); break; default: break; } } LLInventoryItem *LLSidepanelInventory::getSelectedItem() { LLPanelMainInventory *panel_main_inventory = mInventoryPanel->getChild<LLPanelMainInventory>("panel_main_inventory"); LLFolderViewItem* current_item = panel_main_inventory->getActivePanel()->getRootFolder()->getCurSelectedItem(); if (!current_item) { return NULL; } const LLUUID &item_id = current_item->getListener()->getUUID(); LLInventoryItem *item = gInventory.getItem(item_id); return item; } U32 LLSidepanelInventory::getSelectedCount() { LLPanelMainInventory *panel_main_inventory = mInventoryPanel->getChild<LLPanelMainInventory>("panel_main_inventory"); std::set<LLUUID> selection_list; panel_main_inventory->getActivePanel()->getRootFolder()->getSelectionList(selection_list); return selection_list.size(); } LLInventoryPanel *LLSidepanelInventory::getActivePanel() { if (!getVisible()) { return NULL; } if (mInventoryPanel->getVisible()) { return mPanelMainInventory->getActivePanel(); } return NULL; } BOOL LLSidepanelInventory::isMainInventoryPanelActive() const { return mInventoryPanel->getVisible(); } <commit_msg>EXT-4603 Right-clicking a sound and choosing "Play" doesn't actually play it<commit_after>/** * @file LLSidepanelInventory.cpp * @brief Side Bar "Inventory" panel * * $LicenseInfo:firstyear=2009&license=viewergpl$ * * Copyright (c) 2004-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llsidepanelinventory.h" #include "llagent.h" #include "llbutton.h" #include "llinventorybridge.h" #include "llinventorypanel.h" #include "llpanelmaininventory.h" #include "llsidepaneliteminfo.h" #include "llsidepaneltaskinfo.h" #include "lltabcontainer.h" #include "llselectmgr.h" static LLRegisterPanelClassWrapper<LLSidepanelInventory> t_inventory("sidepanel_inventory"); LLSidepanelInventory::LLSidepanelInventory() : LLPanel(), mItemPanel(NULL), mPanelMainInventory(NULL) { //LLUICtrlFactory::getInstance()->buildPanel(this, "panel_inventory.xml"); // Called from LLRegisterPanelClass::defaultPanelClassBuilder() } LLSidepanelInventory::~LLSidepanelInventory() { } BOOL LLSidepanelInventory::postBuild() { // UI elements from inventory panel { mInventoryPanel = getChild<LLPanel>("sidepanel__inventory_panel"); mInfoBtn = mInventoryPanel->getChild<LLButton>("info_btn"); mInfoBtn->setClickedCallback(boost::bind(&LLSidepanelInventory::onInfoButtonClicked, this)); mShareBtn = mInventoryPanel->getChild<LLButton>("share_btn"); mShareBtn->setClickedCallback(boost::bind(&LLSidepanelInventory::onShareButtonClicked, this)); mWearBtn = mInventoryPanel->getChild<LLButton>("wear_btn"); mWearBtn->setClickedCallback(boost::bind(&LLSidepanelInventory::onWearButtonClicked, this)); mPlayBtn = mInventoryPanel->getChild<LLButton>("play_btn"); mPlayBtn->setClickedCallback(boost::bind(&LLSidepanelInventory::onPlayButtonClicked, this)); mTeleportBtn = mInventoryPanel->getChild<LLButton>("teleport_btn"); mTeleportBtn->setClickedCallback(boost::bind(&LLSidepanelInventory::onTeleportButtonClicked, this)); mOverflowBtn = mInventoryPanel->getChild<LLButton>("overflow_btn"); mOverflowBtn->setClickedCallback(boost::bind(&LLSidepanelInventory::onOverflowButtonClicked, this)); mPanelMainInventory = mInventoryPanel->getChild<LLPanelMainInventory>("panel_main_inventory"); mPanelMainInventory->setSelectCallback(boost::bind(&LLSidepanelInventory::onSelectionChange, this, _1, _2)); } // UI elements from item panel { mItemPanel = getChild<LLSidepanelItemInfo>("sidepanel__item_panel"); LLButton* back_btn = mItemPanel->getChild<LLButton>("back_btn"); back_btn->setClickedCallback(boost::bind(&LLSidepanelInventory::onBackButtonClicked, this)); } // UI elements from task panel { mTaskPanel = getChild<LLSidepanelTaskInfo>("sidepanel__task_panel"); if (mTaskPanel) { LLButton* back_btn = mTaskPanel->getChild<LLButton>("back_btn"); back_btn->setClickedCallback(boost::bind(&LLSidepanelInventory::onBackButtonClicked, this)); } } return TRUE; } void LLSidepanelInventory::onOpen(const LLSD& key) { if(key.size() == 0) return; mItemPanel->reset(); if (key.has("id")) { mItemPanel->setItemID(key["id"].asUUID()); if (key.has("object")) { mItemPanel->setObjectID(key["object"].asUUID()); } showItemInfoPanel(); } if (key.has("task")) { if (mTaskPanel) mTaskPanel->setObjectSelection(LLSelectMgr::getInstance()->getSelection()); showTaskInfoPanel(); } } void LLSidepanelInventory::onInfoButtonClicked() { LLInventoryItem *item = getSelectedItem(); if (item) { mItemPanel->reset(); mItemPanel->setItemID(item->getUUID()); showItemInfoPanel(); } } void LLSidepanelInventory::onShareButtonClicked() { } void LLSidepanelInventory::performActionOnSelection(const std::string &action) { LLPanelMainInventory *panel_main_inventory = mInventoryPanel->getChild<LLPanelMainInventory>("panel_main_inventory"); LLFolderViewItem* current_item = panel_main_inventory->getActivePanel()->getRootFolder()->getCurSelectedItem(); if (!current_item) { return; } current_item->getListener()->performAction(panel_main_inventory->getActivePanel()->getRootFolder(), panel_main_inventory->getActivePanel()->getModel(), action); } void LLSidepanelInventory::onWearButtonClicked() { performActionOnSelection("wear"); performActionOnSelection("attach"); } void LLSidepanelInventory::onPlayButtonClicked() { performActionOnSelection("open"); } void LLSidepanelInventory::onTeleportButtonClicked() { performActionOnSelection("teleport"); } void LLSidepanelInventory::onOverflowButtonClicked() { } void LLSidepanelInventory::onBackButtonClicked() { showInventoryPanel(); } void LLSidepanelInventory::onSelectionChange(const std::deque<LLFolderViewItem*> &items, BOOL user_action) { updateVerbs(); } void LLSidepanelInventory::showItemInfoPanel() { mItemPanel->setVisible(TRUE); if (mTaskPanel) mTaskPanel->setVisible(FALSE); mInventoryPanel->setVisible(FALSE); mItemPanel->dirty(); mItemPanel->setIsEditing(FALSE); } void LLSidepanelInventory::showTaskInfoPanel() { mItemPanel->setVisible(FALSE); mInventoryPanel->setVisible(FALSE); if (mTaskPanel) { mTaskPanel->setVisible(TRUE); mTaskPanel->dirty(); mTaskPanel->setIsEditing(FALSE); } } void LLSidepanelInventory::showInventoryPanel() { mItemPanel->setVisible(FALSE); if (mTaskPanel) mTaskPanel->setVisible(FALSE); mInventoryPanel->setVisible(TRUE); updateVerbs(); } void LLSidepanelInventory::updateVerbs() { mInfoBtn->setEnabled(FALSE); mShareBtn->setEnabled(FALSE); mWearBtn->setVisible(FALSE); mWearBtn->setEnabled(FALSE); mPlayBtn->setVisible(FALSE); mPlayBtn->setEnabled(FALSE); mTeleportBtn->setVisible(FALSE); mTeleportBtn->setEnabled(FALSE); const LLInventoryItem *item = getSelectedItem(); if (!item) return; bool is_single_selection = getSelectedCount() == 1; mInfoBtn->setEnabled(is_single_selection); mShareBtn->setEnabled(is_single_selection); switch(item->getInventoryType()) { case LLInventoryType::IT_WEARABLE: case LLInventoryType::IT_OBJECT: case LLInventoryType::IT_ATTACHMENT: mWearBtn->setVisible(TRUE); mWearBtn->setEnabled(TRUE); break; case LLInventoryType::IT_SOUND: case LLInventoryType::IT_GESTURE: case LLInventoryType::IT_ANIMATION: mPlayBtn->setVisible(TRUE); mPlayBtn->setEnabled(TRUE); break; case LLInventoryType::IT_LANDMARK: mTeleportBtn->setVisible(TRUE); mTeleportBtn->setEnabled(TRUE); break; default: break; } } LLInventoryItem *LLSidepanelInventory::getSelectedItem() { LLPanelMainInventory *panel_main_inventory = mInventoryPanel->getChild<LLPanelMainInventory>("panel_main_inventory"); LLFolderViewItem* current_item = panel_main_inventory->getActivePanel()->getRootFolder()->getCurSelectedItem(); if (!current_item) { return NULL; } const LLUUID &item_id = current_item->getListener()->getUUID(); LLInventoryItem *item = gInventory.getItem(item_id); return item; } U32 LLSidepanelInventory::getSelectedCount() { LLPanelMainInventory *panel_main_inventory = mInventoryPanel->getChild<LLPanelMainInventory>("panel_main_inventory"); std::set<LLUUID> selection_list; panel_main_inventory->getActivePanel()->getRootFolder()->getSelectionList(selection_list); return selection_list.size(); } LLInventoryPanel *LLSidepanelInventory::getActivePanel() { if (!getVisible()) { return NULL; } if (mInventoryPanel->getVisible()) { return mPanelMainInventory->getActivePanel(); } return NULL; } BOOL LLSidepanelInventory::isMainInventoryPanelActive() const { return mInventoryPanel->getVisible(); } <|endoftext|>
<commit_before>/* * LCALayer.cpp * * Created on: Sep 27, 2012 * Author: pschultz */ #include "LCALayer.hpp" namespace PV { LCALayer::LCALayer(const char * name, HyPerCol * hc, int num_channels) { initialize_base(); initialize(name, hc, num_channels); } LCALayer::LCALayer() { initialize_base(); } LCALayer::~LCALayer() { free(stimulus); stimulus = NULL; } int LCALayer::initialize_base() { stimulus = NULL; return PV_SUCCESS; } int LCALayer::initialize(const char * name, HyPerCol * hc, int num_channels) { int status = HyPerLayer::initialize(name, hc, num_channels); threshold = readThreshold(); thresholdSoftness = readThresholdSoftness(); timeConstantTau = readTimeConstantTau(); stimulus = (pvdata_t *) calloc(getNumNeurons(), sizeof(pvdata_t)); if (stimulus == NULL) { fprintf(stderr, "LCALayer::initialize error allocating memory for stimulus: %s", strerror(errno)); abort(); } return status; } int LCALayer::updateState(float timef, float dt) { #define LCALAYER_FEEDBACK_LENGTH 3 #define LCALAYER_START_STEP 2 int step = parent->getCurrentStep(); if (step <= LCALAYER_START_STEP || step % LCALAYER_FEEDBACK_LENGTH != 0) return PV_SUCCESS; const pvdata_t * gSynExc = getChannel(CHANNEL_EXC); const pvdata_t * gSynInh = getChannel(CHANNEL_INH); pvdata_t * V = getV(); pvdata_t * A = getActivity(); const float dt_tau = LCALAYER_FEEDBACK_LENGTH*dt/timeConstantTau; const float threshdrop = thresholdSoftness * threshold; const PVLayerLoc * loc = getLayerLoc(); const int nx = loc->nx; const int ny = loc->ny; const int nf = loc->nf; const int nb = loc->nb; for (int k=0; k<getNumNeurons(); k++) { stimulus[k] = gSynExc[k] - gSynInh[k]; int kex = kIndexExtended(k, nx, ny, nf, nb); pvdata_t Vk = V[k]; Vk = Vk + dt_tau*(stimulus[k] - V[k] + A[kex]); A[kex] = Vk >= threshold ? Vk - threshdrop : 0.0; V[k] = Vk; } resetGSynBuffers_HyPerLayer(getNumNeurons(), getNumChannels(), GSyn[0]); return PV_SUCCESS; } int LCALayer::checkpointWrite(const char * cpDir) { int status = HyPerLayer::checkpointWrite(cpDir); char filename[PV_PATH_MAX]; int chars_needed = snprintf(filename, PV_PATH_MAX, "%s/%s_stimulus.pvp", cpDir, name); assert(chars_needed < PV_PATH_MAX); status = writeBufferFile(filename, getParent()->icCommunicator(), getParent()->simulationTime(), stimulus, 1, /*extended*/false, /*contiguous*/false) == PV_SUCCESS ? status : PV_FAILURE; return status; } } /* namespace PV */ <commit_msg>Update to LCALayer since checkpointWrite has an additional argument (the pointer to PVLayerLoc)<commit_after>/* * LCALayer.cpp * * Created on: Sep 27, 2012 * Author: pschultz */ #include "LCALayer.hpp" namespace PV { LCALayer::LCALayer(const char * name, HyPerCol * hc, int num_channels) { initialize_base(); initialize(name, hc, num_channels); } LCALayer::LCALayer() { initialize_base(); } LCALayer::~LCALayer() { free(stimulus); stimulus = NULL; } int LCALayer::initialize_base() { stimulus = NULL; return PV_SUCCESS; } int LCALayer::initialize(const char * name, HyPerCol * hc, int num_channels) { int status = HyPerLayer::initialize(name, hc, num_channels); threshold = readThreshold(); thresholdSoftness = readThresholdSoftness(); timeConstantTau = readTimeConstantTau(); stimulus = (pvdata_t *) calloc(getNumNeurons(), sizeof(pvdata_t)); if (stimulus == NULL) { fprintf(stderr, "LCALayer::initialize error allocating memory for stimulus: %s", strerror(errno)); abort(); } return status; } int LCALayer::updateState(float timef, float dt) { #define LCALAYER_FEEDBACK_LENGTH 3 #define LCALAYER_START_STEP 2 int step = parent->getCurrentStep(); if (step <= LCALAYER_START_STEP || step % LCALAYER_FEEDBACK_LENGTH != 0) return PV_SUCCESS; const pvdata_t * gSynExc = getChannel(CHANNEL_EXC); const pvdata_t * gSynInh = getChannel(CHANNEL_INH); pvdata_t * V = getV(); pvdata_t * A = getActivity(); const float dt_tau = LCALAYER_FEEDBACK_LENGTH*dt/timeConstantTau; const float threshdrop = thresholdSoftness * threshold; const PVLayerLoc * loc = getLayerLoc(); const int nx = loc->nx; const int ny = loc->ny; const int nf = loc->nf; const int nb = loc->nb; for (int k=0; k<getNumNeurons(); k++) { stimulus[k] = gSynExc[k] - gSynInh[k]; int kex = kIndexExtended(k, nx, ny, nf, nb); pvdata_t Vk = V[k]; Vk = Vk + dt_tau*(stimulus[k] - V[k] + A[kex]); A[kex] = Vk >= threshold ? Vk - threshdrop : 0.0; V[k] = Vk; } resetGSynBuffers_HyPerLayer(getNumNeurons(), getNumChannels(), GSyn[0]); return PV_SUCCESS; } int LCALayer::checkpointWrite(const char * cpDir) { int status = HyPerLayer::checkpointWrite(cpDir); char filename[PV_PATH_MAX]; int chars_needed = snprintf(filename, PV_PATH_MAX, "%s/%s_stimulus.pvp", cpDir, name); assert(chars_needed < PV_PATH_MAX); status = writeBufferFile(filename, getParent()->icCommunicator(), getParent()->simulationTime(), stimulus, 1, /*extended*/false, /*contiguous*/false, getLayerLoc()) == PV_SUCCESS ? status : PV_FAILURE; return status; } } /* namespace PV */ <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/indexed_db_key.h" #include "base/logging.h" #include "third_party/WebKit/WebKit/chromium/public/WebString.h" using WebKit::WebIDBKey; IndexedDBKey::IndexedDBKey() : type_(WebIDBKey::InvalidType), number_(0) { } IndexedDBKey::IndexedDBKey(const WebIDBKey& key) { Set(key); } IndexedDBKey::~IndexedDBKey() { } void IndexedDBKey::SetNull() { type_ = WebIDBKey::NullType; } void IndexedDBKey::SetInvalid() { type_ = WebIDBKey::InvalidType; } void IndexedDBKey::Set(const string16& string) { type_ = WebIDBKey::StringType; string_ = string; } void IndexedDBKey::Set(int32_t number) { type_ = WebIDBKey::NumberType; number_ = number; } void IndexedDBKey::Set(const WebIDBKey& key) { type_ = key.type(); string_ = key.type() == WebIDBKey::StringType ? static_cast<string16>(key.string()) : string16(); number_ = key.type() == WebIDBKey::NumberType ? key.number() : 0; } IndexedDBKey::operator WebIDBKey() const { switch (type_) { case WebIDBKey::NullType: return WebIDBKey::createNull(); case WebIDBKey::StringType: return WebIDBKey(string_); case WebIDBKey::NumberType: return WebIDBKey(number_); case WebIDBKey::InvalidType: return WebIDBKey::createInvalid(); } NOTREACHED(); return WebIDBKey::createInvalid(); } <commit_msg>IndexedDB: Preparatory patch for https://bugs.webkit.org/show_bug.cgi?id=50674<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/indexed_db_key.h" #include "base/logging.h" #include "third_party/WebKit/WebKit/chromium/public/WebString.h" using WebKit::WebIDBKey; IndexedDBKey::IndexedDBKey() : type_(WebIDBKey::InvalidType), number_(0) { } IndexedDBKey::IndexedDBKey(const WebIDBKey& key) { Set(key); } IndexedDBKey::~IndexedDBKey() { } void IndexedDBKey::SetNull() { type_ = WebIDBKey::NullType; } void IndexedDBKey::SetInvalid() { type_ = WebIDBKey::InvalidType; } void IndexedDBKey::Set(const string16& string) { type_ = WebIDBKey::StringType; string_ = string; } void IndexedDBKey::Set(int32_t number) { type_ = WebIDBKey::NumberType; number_ = number; } void IndexedDBKey::Set(const WebIDBKey& key) { type_ = key.type(); string_ = key.type() == WebIDBKey::StringType ? static_cast<string16>(key.string()) : string16(); number_ = key.type() == WebIDBKey::NumberType ? static_cast<int32_t>(key.number()) : 0; } IndexedDBKey::operator WebIDBKey() const { switch (type_) { case WebIDBKey::NullType: return WebIDBKey::createNull(); case WebIDBKey::StringType: return WebIDBKey(string_); case WebIDBKey::NumberType: return WebIDBKey(number_); case WebIDBKey::InvalidType: return WebIDBKey::createInvalid(); } NOTREACHED(); return WebIDBKey::createInvalid(); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/gpu/gpu_video_decoder.h" #include "chrome/common/child_thread.h" #include "chrome/common/gpu_messages.h" #include "chrome/gpu/gpu_channel.h" #include "chrome/gpu/media/fake_gl_video_decode_engine.h" #include "chrome/gpu/media/fake_gl_video_device.h" #include "media/base/data_buffer.h" #include "media/base/video_frame.h" #if defined(OS_WIN) #include "chrome/gpu/media/mft_angle_video_device.h" #include "media/video/mft_h264_decode_engine.h" #include <d3d9.h> #endif void GpuVideoDecoder::OnChannelConnected(int32 peer_pid) { } void GpuVideoDecoder::OnChannelError() { } void GpuVideoDecoder::OnMessageReceived(const IPC::Message& msg) { IPC_BEGIN_MESSAGE_MAP(GpuVideoDecoder, msg) IPC_MESSAGE_HANDLER(GpuVideoDecoderMsg_Initialize, OnInitialize) IPC_MESSAGE_HANDLER(GpuVideoDecoderMsg_Destroy, OnUninitialize) IPC_MESSAGE_HANDLER(GpuVideoDecoderMsg_Flush, OnFlush) IPC_MESSAGE_HANDLER(GpuVideoDecoderMsg_Preroll, OnPreroll) IPC_MESSAGE_HANDLER(GpuVideoDecoderMsg_EmptyThisBuffer, OnEmptyThisBuffer) IPC_MESSAGE_HANDLER(GpuVideoDecoderMsg_ProduceVideoFrame, OnProduceVideoFrame) IPC_MESSAGE_HANDLER(GpuVideoDecoderMsg_VideoFrameAllocated, OnVideoFrameAllocated) IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() } bool GpuVideoDecoder::CreateInputTransferBuffer( uint32 size, base::SharedMemoryHandle* handle) { input_transfer_buffer_.reset(new base::SharedMemory); if (!input_transfer_buffer_.get()) return false; if (!input_transfer_buffer_->Create(std::string(), false, false, size)) return false; if (!input_transfer_buffer_->Map(size)) return false; if (!input_transfer_buffer_->ShareToProcess(renderer_handle_, handle)) return false; return true; } void GpuVideoDecoder::OnInitializeComplete(const VideoCodecInfo& info) { info_ = info; GpuVideoDecoderInitDoneParam param; param.success = false; param.input_buffer_handle = base::SharedMemory::NULLHandle(); if (!info.success) { SendInitializeDone(param); return; } // TODO(jiesun): Check the assumption of input size < original size. param.input_buffer_size = config_.width * config_.height * 3 / 2; if (!CreateInputTransferBuffer(param.input_buffer_size, &param.input_buffer_handle)) { SendInitializeDone(param); return; } param.success = true; SendInitializeDone(param); } void GpuVideoDecoder::OnUninitializeComplete() { SendUninitializeDone(); } void GpuVideoDecoder::OnFlushComplete() { SendFlushDone(); } void GpuVideoDecoder::OnSeekComplete() { SendPrerollDone(); } void GpuVideoDecoder::OnError() { NOTIMPLEMENTED(); } void GpuVideoDecoder::OnFormatChange(VideoStreamInfo stream_info) { NOTIMPLEMENTED(); } void GpuVideoDecoder::ProduceVideoSample(scoped_refptr<Buffer> buffer) { SendEmptyBufferDone(); } void GpuVideoDecoder::ConsumeVideoFrame(scoped_refptr<VideoFrame> frame) { if (frame->IsEndOfStream()) { SendConsumeVideoFrame(kGpuVideoInvalidFrameId, 0, 0, kGpuVideoEndOfStream); return; } int32 frame_id = kGpuVideoInvalidFrameId; for (VideoFrameMap::iterator i = video_frame_map_.begin(); i != video_frame_map_.end(); ++i) { if (i->second == frame) { frame_id = i->first; break; } } DCHECK_NE(-1, frame_id) << "VideoFrame not recognized"; SendConsumeVideoFrame(frame_id, frame->GetTimestamp().InMicroseconds(), frame->GetDuration().InMicroseconds(), 0); } void* GpuVideoDecoder::GetDevice() { bool ret = gles2_decoder_->MakeCurrent(); DCHECK(ret) << "Failed to switch context"; // Simply delegate the method call to GpuVideoDevice. return video_device_->GetDevice(); } void GpuVideoDecoder::AllocateVideoFrames( int n, size_t width, size_t height, media::VideoFrame::Format format, std::vector<scoped_refptr<media::VideoFrame> >* frames, Task* task) { // Since the communication between Renderer and GPU process is by GL textures. // We need to obtain a set of GL textures by sending IPC commands to the // Renderer process. The recipient of these commands will be IpcVideoDecoder. // // After IpcVideoDecoder replied with a set of textures. We'll assign these // textures to GpuVideoDevice. They will be used to generate platform // specific VideoFrames objects that are used by VideoDecodeEngine. // // After GL textures are assigned we'll proceed with allocation the // VideoFrames. GpuVideoDevice::CreateVideoFramesFromGlTextures() will be // called. // // When GpuVideoDevice replied with a set of VideoFrames we'll give // that to VideoDecodeEngine and the cycle of video frame allocation is done. // // Note that this method is called when there's no video frames allocated or // they were all released. DCHECK(video_frame_map_.empty()); // Save the parameters for allocation. pending_allocation_.reset(new PendingAllocation()); pending_allocation_->n = n; pending_allocation_->width = width; pending_allocation_->height = height; pending_allocation_->format = format; pending_allocation_->frames = frames; pending_allocation_->task = task; SendAllocateVideoFrames(n, width, height, format); } void GpuVideoDecoder::ReleaseAllVideoFrames() { // This method will first call to GpuVideoDevice to release all the resource // associated with a VideoFrame. // // And then we'll call GpuVideoDevice::ReleaseVideoFrame() to remove the set // of Gl textures associated with the context. // // And finally we'll send IPC commands to IpcVideoDecoder to destroy all // GL textures generated. bool ret = gles2_decoder_->MakeCurrent(); DCHECK(ret) << "Failed to switch context"; for (VideoFrameMap::iterator i = video_frame_map_.begin(); i != video_frame_map_.end(); ++i) { video_device_->ReleaseVideoFrame(i->second); } video_frame_map_.clear(); SendReleaseAllVideoFrames(); } void GpuVideoDecoder::UploadToVideoFrame(void* buffer, scoped_refptr<media::VideoFrame> frame, Task* task) { // This method is called by VideoDecodeEngine to upload a buffer to a // VideoFrame. We should just delegate this to GpuVideoDevice which contains // the actual implementation. bool ret = gles2_decoder_->MakeCurrent(); DCHECK(ret) << "Failed to switch context"; // Actually doing the upload on the main thread. ret = video_device_->UploadToVideoFrame(buffer, frame); DCHECK(ret) << "Failed to upload video content to a VideoFrame."; task->Run(); delete task; } void GpuVideoDecoder::Destroy(Task* task) { // TODO(hclam): I still need to think what I should do here. } void GpuVideoDecoder::SetVideoDecodeEngine(media::VideoDecodeEngine* engine) { decode_engine_.reset(engine); } void GpuVideoDecoder::SetGpuVideoDevice(GpuVideoDevice* device) { video_device_.reset(device); } GpuVideoDecoder::GpuVideoDecoder( MessageLoop* message_loop, int32 decoder_host_id, IPC::Message::Sender* sender, base::ProcessHandle handle, gpu::gles2::GLES2Decoder* decoder) : message_loop_(message_loop), decoder_host_id_(decoder_host_id), sender_(sender), renderer_handle_(handle), gles2_decoder_(decoder) { memset(&config_, 0, sizeof(config_)); memset(&info_, 0, sizeof(info_)); // TODO(jiesun): find a better way to determine which VideoDecodeEngine // to return on current platform. #if defined(OS_WIN) decode_engine_.reset(new media::MftH264DecodeEngine(true)); video_device_.reset(new MftAngleVideoDevice()); #else decode_engine_.reset(new FakeGlVideoDecodeEngine()); video_device_.reset(new FakeGlVideoDevice()); #endif } void GpuVideoDecoder::OnInitialize(const GpuVideoDecoderInitParam& param) { // TODO(jiesun): codec id should come from |param|. config_.codec = media::kCodecH264; config_.width = param.width; config_.height = param.height; config_.opaque_context = NULL; decode_engine_->Initialize(message_loop_, this, this, config_); } void GpuVideoDecoder::OnUninitialize() { decode_engine_->Uninitialize(); } void GpuVideoDecoder::OnFlush() { decode_engine_->Flush(); } void GpuVideoDecoder::OnPreroll() { decode_engine_->Seek(); } void GpuVideoDecoder::OnEmptyThisBuffer( const GpuVideoDecoderInputBufferParam& buffer) { DCHECK(input_transfer_buffer_->memory()); uint8* src = static_cast<uint8*>(input_transfer_buffer_->memory()); scoped_refptr<Buffer> input_buffer; uint8* dst = buffer.size ? new uint8[buffer.size] : NULL; input_buffer = new media::DataBuffer(dst, buffer.size); memcpy(dst, src, buffer.size); SendEmptyBufferACK(); // Delegate the method call to VideoDecodeEngine. decode_engine_->ConsumeVideoSample(input_buffer); } void GpuVideoDecoder::OnProduceVideoFrame(int32 frame_id) { VideoFrameMap::iterator i = video_frame_map_.find(frame_id); if (i == video_frame_map_.end()) { NOTREACHED() << "Received a request of unknown frame ID."; } // Delegate the method call to VideoDecodeEngine. decode_engine_->ProduceVideoFrame(i->second); } void GpuVideoDecoder::OnVideoFrameAllocated(int32 frame_id, std::vector<uint32> textures) { bool ret = gles2_decoder_->MakeCurrent(); DCHECK(ret) << "Failed to switch context"; // This method is called in response to a video frame allocation request sent // to the Renderer process. // We should use the textures to generate a VideoFrame by using // GpuVideoDevice. The VideoFrame created is added to the internal map. // If we have generated enough VideoFrame, we call |allocation_callack_| to // complete the allocation process. for (size_t i = 0; i < textures.size(); ++i) { media::VideoFrame::GlTexture gl_texture; // Translate the client texture id to service texture id. ret = gles2_decoder_->GetServiceTextureId(textures[i], &gl_texture); DCHECK(ret) << "Cannot translate client texture ID to service ID"; textures[i] = gl_texture; } // Use GpuVideoDevice to allocate VideoFrame objects. scoped_refptr<media::VideoFrame> frame; ret = video_device_->CreateVideoFrameFromGlTextures( pending_allocation_->width, pending_allocation_->height, pending_allocation_->format, textures, &frame); DCHECK(ret) << "Failed to allocation VideoFrame from GL textures)"; pending_allocation_->frames->push_back(frame); video_frame_map_.insert(std::make_pair(frame_id, frame)); if (video_frame_map_.size() == pending_allocation_->n) { pending_allocation_->task->Run(); delete pending_allocation_->task; pending_allocation_.reset(); } } void GpuVideoDecoder::SendInitializeDone( const GpuVideoDecoderInitDoneParam& param) { if (!sender_->Send( new GpuVideoDecoderHostMsg_InitializeACK(decoder_host_id(), param))) { LOG(ERROR) << "GpuVideoDecoderMsg_InitializeACK failed"; } } void GpuVideoDecoder::SendUninitializeDone() { if (!sender_->Send( new GpuVideoDecoderHostMsg_DestroyACK(decoder_host_id()))) { LOG(ERROR) << "GpuVideoDecoderMsg_DestroyACK failed"; } } void GpuVideoDecoder::SendFlushDone() { if (!sender_->Send(new GpuVideoDecoderHostMsg_FlushACK(decoder_host_id()))) { LOG(ERROR) << "GpuVideoDecoderMsg_FlushACK failed"; } } void GpuVideoDecoder::SendPrerollDone() { if (!sender_->Send(new GpuVideoDecoderHostMsg_PrerollDone( decoder_host_id()))) { LOG(ERROR) << "GpuVideoDecoderMsg_PrerollDone failed"; } } void GpuVideoDecoder::SendEmptyBufferDone() { if (!sender_->Send( new GpuVideoDecoderHostMsg_EmptyThisBufferDone(decoder_host_id()))) { LOG(ERROR) << "GpuVideoDecoderMsg_EmptyThisBufferDone failed"; } } void GpuVideoDecoder::SendEmptyBufferACK() { if (!sender_->Send( new GpuVideoDecoderHostMsg_EmptyThisBufferACK(decoder_host_id()))) { LOG(ERROR) << "GpuVideoDecoderMsg_EmptyThisBufferACK failed"; } } void GpuVideoDecoder::SendConsumeVideoFrame( int32 frame_id, int64 timestamp, int64 duration, int32 flags) { if (!sender_->Send( new GpuVideoDecoderHostMsg_ConsumeVideoFrame( decoder_host_id(), frame_id, timestamp, duration, flags))) { LOG(ERROR) << "GpuVideoDecodeHostMsg_ConsumeVideoFrame failed."; } } void GpuVideoDecoder::SendAllocateVideoFrames( int n, size_t width, size_t height, media::VideoFrame::Format format) { if (!sender_->Send( new GpuVideoDecoderHostMsg_AllocateVideoFrames( decoder_host_id(), n, width, height, static_cast<int32>(format)))) { LOG(ERROR) << "GpuVideoDecoderMsg_AllocateVideoFrames failed"; } } void GpuVideoDecoder::SendReleaseAllVideoFrames() { if (!sender_->Send( new GpuVideoDecoderHostMsg_ReleaseAllVideoFrames( decoder_host_id()))) { LOG(ERROR) << "GpuVideoDecoderMsg_ReleaseAllVideoFrames failed"; } } <commit_msg>Fix build failure.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/gpu/gpu_video_decoder.h" #include "base/command_line.h" #include "chrome/common/child_thread.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/gpu_messages.h" #include "chrome/gpu/gpu_channel.h" #include "chrome/gpu/media/fake_gl_video_decode_engine.h" #include "chrome/gpu/media/fake_gl_video_device.h" #include "media/base/data_buffer.h" #include "media/base/video_frame.h" #if defined(OS_WIN) #include "chrome/gpu/media/mft_angle_video_device.h" #include "media/video/mft_h264_decode_engine.h" #include <d3d9.h> #endif void GpuVideoDecoder::OnChannelConnected(int32 peer_pid) { } void GpuVideoDecoder::OnChannelError() { } void GpuVideoDecoder::OnMessageReceived(const IPC::Message& msg) { IPC_BEGIN_MESSAGE_MAP(GpuVideoDecoder, msg) IPC_MESSAGE_HANDLER(GpuVideoDecoderMsg_Initialize, OnInitialize) IPC_MESSAGE_HANDLER(GpuVideoDecoderMsg_Destroy, OnUninitialize) IPC_MESSAGE_HANDLER(GpuVideoDecoderMsg_Flush, OnFlush) IPC_MESSAGE_HANDLER(GpuVideoDecoderMsg_Preroll, OnPreroll) IPC_MESSAGE_HANDLER(GpuVideoDecoderMsg_EmptyThisBuffer, OnEmptyThisBuffer) IPC_MESSAGE_HANDLER(GpuVideoDecoderMsg_ProduceVideoFrame, OnProduceVideoFrame) IPC_MESSAGE_HANDLER(GpuVideoDecoderMsg_VideoFrameAllocated, OnVideoFrameAllocated) IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() } bool GpuVideoDecoder::CreateInputTransferBuffer( uint32 size, base::SharedMemoryHandle* handle) { input_transfer_buffer_.reset(new base::SharedMemory); if (!input_transfer_buffer_.get()) return false; if (!input_transfer_buffer_->Create(std::string(), false, false, size)) return false; if (!input_transfer_buffer_->Map(size)) return false; if (!input_transfer_buffer_->ShareToProcess(renderer_handle_, handle)) return false; return true; } void GpuVideoDecoder::OnInitializeComplete(const VideoCodecInfo& info) { info_ = info; GpuVideoDecoderInitDoneParam param; param.success = false; param.input_buffer_handle = base::SharedMemory::NULLHandle(); if (!info.success) { SendInitializeDone(param); return; } // TODO(jiesun): Check the assumption of input size < original size. param.input_buffer_size = config_.width * config_.height * 3 / 2; if (!CreateInputTransferBuffer(param.input_buffer_size, &param.input_buffer_handle)) { SendInitializeDone(param); return; } param.success = true; SendInitializeDone(param); } void GpuVideoDecoder::OnUninitializeComplete() { SendUninitializeDone(); } void GpuVideoDecoder::OnFlushComplete() { SendFlushDone(); } void GpuVideoDecoder::OnSeekComplete() { SendPrerollDone(); } void GpuVideoDecoder::OnError() { NOTIMPLEMENTED(); } void GpuVideoDecoder::OnFormatChange(VideoStreamInfo stream_info) { NOTIMPLEMENTED(); } void GpuVideoDecoder::ProduceVideoSample(scoped_refptr<Buffer> buffer) { SendEmptyBufferDone(); } void GpuVideoDecoder::ConsumeVideoFrame(scoped_refptr<VideoFrame> frame) { if (frame->IsEndOfStream()) { SendConsumeVideoFrame(kGpuVideoInvalidFrameId, 0, 0, kGpuVideoEndOfStream); return; } int32 frame_id = kGpuVideoInvalidFrameId; for (VideoFrameMap::iterator i = video_frame_map_.begin(); i != video_frame_map_.end(); ++i) { if (i->second == frame) { frame_id = i->first; break; } } DCHECK_NE(-1, frame_id) << "VideoFrame not recognized"; SendConsumeVideoFrame(frame_id, frame->GetTimestamp().InMicroseconds(), frame->GetDuration().InMicroseconds(), 0); } void* GpuVideoDecoder::GetDevice() { bool ret = gles2_decoder_->MakeCurrent(); DCHECK(ret) << "Failed to switch context"; // Simply delegate the method call to GpuVideoDevice. return video_device_->GetDevice(); } void GpuVideoDecoder::AllocateVideoFrames( int n, size_t width, size_t height, media::VideoFrame::Format format, std::vector<scoped_refptr<media::VideoFrame> >* frames, Task* task) { // Since the communication between Renderer and GPU process is by GL textures. // We need to obtain a set of GL textures by sending IPC commands to the // Renderer process. The recipient of these commands will be IpcVideoDecoder. // // After IpcVideoDecoder replied with a set of textures. We'll assign these // textures to GpuVideoDevice. They will be used to generate platform // specific VideoFrames objects that are used by VideoDecodeEngine. // // After GL textures are assigned we'll proceed with allocation the // VideoFrames. GpuVideoDevice::CreateVideoFramesFromGlTextures() will be // called. // // When GpuVideoDevice replied with a set of VideoFrames we'll give // that to VideoDecodeEngine and the cycle of video frame allocation is done. // // Note that this method is called when there's no video frames allocated or // they were all released. DCHECK(video_frame_map_.empty()); // Save the parameters for allocation. pending_allocation_.reset(new PendingAllocation()); pending_allocation_->n = n; pending_allocation_->width = width; pending_allocation_->height = height; pending_allocation_->format = format; pending_allocation_->frames = frames; pending_allocation_->task = task; SendAllocateVideoFrames(n, width, height, format); } void GpuVideoDecoder::ReleaseAllVideoFrames() { // This method will first call to GpuVideoDevice to release all the resource // associated with a VideoFrame. // // And then we'll call GpuVideoDevice::ReleaseVideoFrame() to remove the set // of Gl textures associated with the context. // // And finally we'll send IPC commands to IpcVideoDecoder to destroy all // GL textures generated. bool ret = gles2_decoder_->MakeCurrent(); DCHECK(ret) << "Failed to switch context"; for (VideoFrameMap::iterator i = video_frame_map_.begin(); i != video_frame_map_.end(); ++i) { video_device_->ReleaseVideoFrame(i->second); } video_frame_map_.clear(); SendReleaseAllVideoFrames(); } void GpuVideoDecoder::UploadToVideoFrame(void* buffer, scoped_refptr<media::VideoFrame> frame, Task* task) { // This method is called by VideoDecodeEngine to upload a buffer to a // VideoFrame. We should just delegate this to GpuVideoDevice which contains // the actual implementation. bool ret = gles2_decoder_->MakeCurrent(); DCHECK(ret) << "Failed to switch context"; // Actually doing the upload on the main thread. ret = video_device_->UploadToVideoFrame(buffer, frame); DCHECK(ret) << "Failed to upload video content to a VideoFrame."; task->Run(); delete task; } void GpuVideoDecoder::Destroy(Task* task) { // TODO(hclam): I still need to think what I should do here. } void GpuVideoDecoder::SetVideoDecodeEngine(media::VideoDecodeEngine* engine) { decode_engine_.reset(engine); } void GpuVideoDecoder::SetGpuVideoDevice(GpuVideoDevice* device) { video_device_.reset(device); } GpuVideoDecoder::GpuVideoDecoder( MessageLoop* message_loop, int32 decoder_host_id, IPC::Message::Sender* sender, base::ProcessHandle handle, gpu::gles2::GLES2Decoder* decoder) : message_loop_(message_loop), decoder_host_id_(decoder_host_id), sender_(sender), renderer_handle_(handle), gles2_decoder_(decoder) { memset(&config_, 0, sizeof(config_)); memset(&info_, 0, sizeof(info_)); // TODO(jiesun): find a better way to determine which VideoDecodeEngine // to return on current platform. #if defined(OS_WIN) const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kEnableAcceleratedDecoding)) { decode_engine_.reset(new media::MftH264DecodeEngine(true)); video_device_.reset(new MftAngleVideoDevice()); } #else decode_engine_.reset(new FakeGlVideoDecodeEngine()); video_device_.reset(new FakeGlVideoDevice()); #endif } void GpuVideoDecoder::OnInitialize(const GpuVideoDecoderInitParam& param) { // TODO(jiesun): codec id should come from |param|. config_.codec = media::kCodecH264; config_.width = param.width; config_.height = param.height; config_.opaque_context = NULL; decode_engine_->Initialize(message_loop_, this, this, config_); } void GpuVideoDecoder::OnUninitialize() { decode_engine_->Uninitialize(); } void GpuVideoDecoder::OnFlush() { decode_engine_->Flush(); } void GpuVideoDecoder::OnPreroll() { decode_engine_->Seek(); } void GpuVideoDecoder::OnEmptyThisBuffer( const GpuVideoDecoderInputBufferParam& buffer) { DCHECK(input_transfer_buffer_->memory()); uint8* src = static_cast<uint8*>(input_transfer_buffer_->memory()); scoped_refptr<Buffer> input_buffer; uint8* dst = buffer.size ? new uint8[buffer.size] : NULL; input_buffer = new media::DataBuffer(dst, buffer.size); memcpy(dst, src, buffer.size); SendEmptyBufferACK(); // Delegate the method call to VideoDecodeEngine. decode_engine_->ConsumeVideoSample(input_buffer); } void GpuVideoDecoder::OnProduceVideoFrame(int32 frame_id) { VideoFrameMap::iterator i = video_frame_map_.find(frame_id); if (i == video_frame_map_.end()) { NOTREACHED() << "Received a request of unknown frame ID."; } // Delegate the method call to VideoDecodeEngine. decode_engine_->ProduceVideoFrame(i->second); } void GpuVideoDecoder::OnVideoFrameAllocated(int32 frame_id, std::vector<uint32> textures) { bool ret = gles2_decoder_->MakeCurrent(); DCHECK(ret) << "Failed to switch context"; // This method is called in response to a video frame allocation request sent // to the Renderer process. // We should use the textures to generate a VideoFrame by using // GpuVideoDevice. The VideoFrame created is added to the internal map. // If we have generated enough VideoFrame, we call |allocation_callack_| to // complete the allocation process. for (size_t i = 0; i < textures.size(); ++i) { media::VideoFrame::GlTexture gl_texture; // Translate the client texture id to service texture id. ret = gles2_decoder_->GetServiceTextureId(textures[i], &gl_texture); DCHECK(ret) << "Cannot translate client texture ID to service ID"; textures[i] = gl_texture; } // Use GpuVideoDevice to allocate VideoFrame objects. scoped_refptr<media::VideoFrame> frame; ret = video_device_->CreateVideoFrameFromGlTextures( pending_allocation_->width, pending_allocation_->height, pending_allocation_->format, textures, &frame); DCHECK(ret) << "Failed to allocation VideoFrame from GL textures)"; pending_allocation_->frames->push_back(frame); video_frame_map_.insert(std::make_pair(frame_id, frame)); if (video_frame_map_.size() == pending_allocation_->n) { pending_allocation_->task->Run(); delete pending_allocation_->task; pending_allocation_.reset(); } } void GpuVideoDecoder::SendInitializeDone( const GpuVideoDecoderInitDoneParam& param) { if (!sender_->Send( new GpuVideoDecoderHostMsg_InitializeACK(decoder_host_id(), param))) { LOG(ERROR) << "GpuVideoDecoderMsg_InitializeACK failed"; } } void GpuVideoDecoder::SendUninitializeDone() { if (!sender_->Send( new GpuVideoDecoderHostMsg_DestroyACK(decoder_host_id()))) { LOG(ERROR) << "GpuVideoDecoderMsg_DestroyACK failed"; } } void GpuVideoDecoder::SendFlushDone() { if (!sender_->Send(new GpuVideoDecoderHostMsg_FlushACK(decoder_host_id()))) { LOG(ERROR) << "GpuVideoDecoderMsg_FlushACK failed"; } } void GpuVideoDecoder::SendPrerollDone() { if (!sender_->Send(new GpuVideoDecoderHostMsg_PrerollDone( decoder_host_id()))) { LOG(ERROR) << "GpuVideoDecoderMsg_PrerollDone failed"; } } void GpuVideoDecoder::SendEmptyBufferDone() { if (!sender_->Send( new GpuVideoDecoderHostMsg_EmptyThisBufferDone(decoder_host_id()))) { LOG(ERROR) << "GpuVideoDecoderMsg_EmptyThisBufferDone failed"; } } void GpuVideoDecoder::SendEmptyBufferACK() { if (!sender_->Send( new GpuVideoDecoderHostMsg_EmptyThisBufferACK(decoder_host_id()))) { LOG(ERROR) << "GpuVideoDecoderMsg_EmptyThisBufferACK failed"; } } void GpuVideoDecoder::SendConsumeVideoFrame( int32 frame_id, int64 timestamp, int64 duration, int32 flags) { if (!sender_->Send( new GpuVideoDecoderHostMsg_ConsumeVideoFrame( decoder_host_id(), frame_id, timestamp, duration, flags))) { LOG(ERROR) << "GpuVideoDecodeHostMsg_ConsumeVideoFrame failed."; } } void GpuVideoDecoder::SendAllocateVideoFrames( int n, size_t width, size_t height, media::VideoFrame::Format format) { if (!sender_->Send( new GpuVideoDecoderHostMsg_AllocateVideoFrames( decoder_host_id(), n, width, height, static_cast<int32>(format)))) { LOG(ERROR) << "GpuVideoDecoderMsg_AllocateVideoFrames failed"; } } void GpuVideoDecoder::SendReleaseAllVideoFrames() { if (!sender_->Send( new GpuVideoDecoderHostMsg_ReleaseAllVideoFrames( decoder_host_id()))) { LOG(ERROR) << "GpuVideoDecoderMsg_ReleaseAllVideoFrames failed"; } } <|endoftext|>
<commit_before>#pragma once #include "terminalpp/rectangle.hpp" #include <type_traits> #include <utility> namespace terminalpp { //* ========================================================================= /// \brief Iterate a 2D array in row-major order, providing indexed access /// to each element therein. /// /// \tparam TwoDimensionalContainer A container where @c container[x][y] is /// a valid expression that yields an element. /// \tparam IndexedElementFunction A function of the form @c /// void(element &, x_coordinate, y_coordinate) or @c /// void(element const &, x_coordinate, y_coordinate) where @c element /// is a type inside the container and x_coordinate and y_coordinate /// are index types for accessing that element. The constness of /// the element must be convertible from the elements in the /// container (i.e. a function taking non-const will not be callable) /// when passed a const canvas). //* ========================================================================= template < typename TwoDimensionalContainer, typename IndexedElementFunction > void for_each_in_region( TwoDimensionalContainer &&container, rectangle const &region, IndexedElementFunction &&callable) { using x_coordinate = typename std::remove_cv< typename std::remove_reference<TwoDimensionalContainer>::type >::type::size_type; using y_coordinate = typename std::remove_cv< typename std::remove_reference< decltype(container[std::declval<x_coordinate>()]) >::type >::type::size_type; static_assert(std::is_same< terminalpp::element, typename std::remove_cv< typename std::remove_reference< decltype(container[std::declval<x_coordinate>()][std::declval<y_coordinate>()]) >::type >::type>::value, "container[x][y] must yield an element"); for (auto row = region.origin.y; row < region.origin.y + region.size.height; ++row) { for (auto column = region.origin.x; column < region.origin.x + region.size.width; ++column) { callable(container[column][row], column, row); } } } }<commit_msg>Added missing include to for_each_in_region.hpp.<commit_after>#pragma once #include "terminalpp/element.hpp" #include "terminalpp/rectangle.hpp" #include <type_traits> #include <utility> namespace terminalpp { //* ========================================================================= /// \brief Iterate a 2D array in row-major order, providing indexed access /// to each element therein. /// /// \tparam TwoDimensionalContainer A container where @c container[x][y] is /// a valid expression that yields an element. /// \tparam IndexedElementFunction A function of the form @c /// void(element &, x_coordinate, y_coordinate) or @c /// void(element const &, x_coordinate, y_coordinate) where @c element /// is a type inside the container and x_coordinate and y_coordinate /// are index types for accessing that element. The constness of /// the element must be convertible from the elements in the /// container (i.e. a function taking non-const will not be callable) /// when passed a const canvas). //* ========================================================================= template < typename TwoDimensionalContainer, typename IndexedElementFunction > void for_each_in_region( TwoDimensionalContainer &&container, rectangle const &region, IndexedElementFunction &&callable) { using x_coordinate = typename std::remove_cv< typename std::remove_reference<TwoDimensionalContainer>::type >::type::size_type; using y_coordinate = typename std::remove_cv< typename std::remove_reference< decltype(container[std::declval<x_coordinate>()]) >::type >::type::size_type; static_assert(std::is_same< terminalpp::element, typename std::remove_cv< typename std::remove_reference< decltype(container[std::declval<x_coordinate>()][std::declval<y_coordinate>()]) >::type >::type>::value, "container[x][y] must yield an element"); for (auto row = region.origin.y; row < region.origin.y + region.size.height; ++row) { for (auto column = region.origin.x; column < region.origin.x + region.size.width; ++column) { callable(container[column][row], column, row); } } } }<|endoftext|>
<commit_before>#ifndef YAMAIL_RESOURCE_POOL_ASYNC_DETAIL_QUEUE_HPP #define YAMAIL_RESOURCE_POOL_ASYNC_DETAIL_QUEUE_HPP #include <yamail/resource_pool/error.hpp> #include <yamail/resource_pool/time_traits.hpp> #include <boost/asio/executor.hpp> #include <boost/asio/post.hpp> #include <algorithm> #include <list> #include <map> #include <mutex> #include <unordered_map> namespace yamail { namespace resource_pool { namespace async { namespace asio = boost::asio; namespace detail { using clock = std::chrono::steady_clock; class expired_handler { public: using executor_type = asio::executor; expired_handler() = default; template <class Handler> explicit expired_handler(Handler&& handler) : executor(asio::get_associated_executor(handler)), handler(std::forward<Handler>(handler)) {} void operator ()() { handler(); } auto get_executor() const noexcept { return executor; } private: asio::executor executor; std::function<void ()> handler; }; template <class Value, class Mutex, class IoContext, class Timer> class queue : public std::enable_shared_from_this<queue<Value, Mutex, IoContext, Timer>>, boost::noncopyable { public: using value_type = Value; using io_context_t = IoContext; using timer_t = Timer; queue(std::size_t capacity) : _capacity(capacity) {} std::size_t capacity() const { return _capacity; } std::size_t size() const; bool empty() const; const timer_t& timer(io_context_t& io_context); template <class Handler> bool push(io_context_t& io_context, const value_type& req, Handler&& req_expired, time_traits::duration wait_duration); bool pop(io_context_t*& io_context, value_type& req); private: using mutex_t = Mutex; using lock_guard = std::lock_guard<mutex_t>; struct expiring_request { using list = std::list<expiring_request>; using list_it = typename list::iterator; using multimap = std::multimap<time_traits::time_point, const expiring_request*>; using multimap_it = typename multimap::iterator; io_context_t* io_context; queue::value_type request; expired_handler expired; list_it order_it; multimap_it expires_at_it; expiring_request(io_context_t& io_context, const queue::value_type& request, expired_handler expired) : io_context(&io_context), request(request), expired(std::move(expired)) {} }; using request_multimap_value = typename expiring_request::multimap::value_type; using timers_map = typename std::unordered_map<const io_context_t*, std::unique_ptr<timer_t>>; mutable mutex_t _mutex; typename expiring_request::list _ordered_requests; typename expiring_request::multimap _expires_at_requests; const std::size_t _capacity; timers_map _timers; time_traits::time_point _min_expires_at = time_traits::time_point::max(); bool fit_capacity() const { return _expires_at_requests.size() < _capacity; } void cancel(const boost::system::error_code& ec, time_traits::time_point expires_at); void cancel_one(const request_multimap_value& pair); void update_timer(); timer_t& get_timer(io_context_t& io_context); }; template <class V, class M, class I, class T> std::size_t queue<V, M, I, T>::size() const { const lock_guard lock(_mutex); return _expires_at_requests.size(); } template <class V, class M, class I, class T> bool queue<V, M, I, T>::empty() const { const lock_guard lock(_mutex); return _ordered_requests.empty(); } template <class V, class M, class I, class T> const typename queue<V, M, I, T>::timer_t& queue<V, M, I, T>::timer(io_context_t& io_context) { const lock_guard lock(_mutex); return get_timer(io_context); } template <class V, class M, class I, class T> template <class Handler> bool queue<V, M, I, T>::push(io_context_t& io_context, const value_type& req_data, Handler&& req_expired, time_traits::duration wait_duration) { const lock_guard lock(_mutex); if (!fit_capacity()) { return false; } auto order_it = _ordered_requests.insert( _ordered_requests.end(), expiring_request(io_context, req_data, expired_handler(std::forward<Handler>(req_expired))) ); expiring_request& req = *order_it; req.order_it = order_it; const auto expires_at = time_traits::add(time_traits::now(), wait_duration); req.expires_at_it = _expires_at_requests.insert(std::make_pair(expires_at, &req)); update_timer(); return true; } template <class V, class M, class I, class T> bool queue<V, M, I, T>::pop(io_context_t*& io_context, value_type& value) { const lock_guard lock(_mutex); if (_ordered_requests.empty()) { return false; } const expiring_request& req = _ordered_requests.front(); io_context = req.io_context; value = req.request; _expires_at_requests.erase(req.expires_at_it); _ordered_requests.pop_front(); update_timer(); return true; } template <class V, class M, class I, class T> void queue<V, M, I, T>::cancel(const boost::system::error_code& ec, time_traits::time_point expires_at) { if (ec) { return; } const lock_guard lock(_mutex); const auto begin = _expires_at_requests.begin(); const auto end = _expires_at_requests.upper_bound(expires_at); std::for_each(begin, end, [&] (const request_multimap_value& v) { this->cancel_one(v); }); _expires_at_requests.erase(_expires_at_requests.begin(), end); update_timer(); } template <class V, class M, class I, class T> void queue<V, M, I, T>::cancel_one(const request_multimap_value &pair) { const expiring_request* req = pair.second; asio::post(*req->io_context, std::move(req->expired)); _ordered_requests.erase(req->order_it); } template <class V, class M, class I, class T> void queue<V, M, I, T>::update_timer() { using timers_map_value = typename timers_map::value_type; if (_expires_at_requests.empty()) { std::for_each(_timers.begin(), _timers.end(), [] (timers_map_value& v) { v.second->cancel(); }); _timers.clear(); return; } const auto earliest_expire = _expires_at_requests.begin(); const auto expires_at = earliest_expire->first; auto& timer = get_timer(*earliest_expire->second->io_context); timer.expires_at(expires_at); std::weak_ptr<queue> weak(this->shared_from_this()); timer.async_wait([weak, expires_at] (const boost::system::error_code& ec) { if (const auto locked = weak.lock()) { locked->cancel(ec, expires_at); } }); } template <class V, class M, class I, class T> typename queue<V, M, I, T>::timer_t& queue<V, M, I, T>::get_timer(io_context_t& io_context) { auto it = _timers.find(&io_context); if (it != _timers.end()) { return *it->second; } return *_timers.insert(std::make_pair(&io_context, std::make_unique<timer_t>(io_context))).first->second; } } // namespace detail } // namespace async } // namespace resource_pool } // namespace yamail #endif // YAMAIL_RESOURCE_POOL_ASYNC_DETAIL_QUEUE_HPP <commit_msg>Reuse queue ordered requests iterators<commit_after>#ifndef YAMAIL_RESOURCE_POOL_ASYNC_DETAIL_QUEUE_HPP #define YAMAIL_RESOURCE_POOL_ASYNC_DETAIL_QUEUE_HPP #include <yamail/resource_pool/error.hpp> #include <yamail/resource_pool/time_traits.hpp> #include <boost/asio/executor.hpp> #include <boost/asio/post.hpp> #include <algorithm> #include <list> #include <map> #include <mutex> #include <unordered_map> namespace yamail { namespace resource_pool { namespace async { namespace asio = boost::asio; namespace detail { using clock = std::chrono::steady_clock; class expired_handler { public: using executor_type = asio::executor; expired_handler() = default; template <class Handler> explicit expired_handler(Handler&& handler) : executor(asio::get_associated_executor(handler)), handler(std::forward<Handler>(handler)) {} void operator ()() { handler(); } auto get_executor() const noexcept { return executor; } private: asio::executor executor; std::function<void ()> handler; }; template <class Value, class Mutex, class IoContext, class Timer> class queue : public std::enable_shared_from_this<queue<Value, Mutex, IoContext, Timer>>, boost::noncopyable { public: using value_type = Value; using io_context_t = IoContext; using timer_t = Timer; queue(std::size_t capacity) : _capacity(capacity) {} std::size_t capacity() const { return _capacity; } std::size_t size() const; bool empty() const; const timer_t& timer(io_context_t& io_context); template <class Handler> bool push(io_context_t& io_context, const value_type& req, Handler&& req_expired, time_traits::duration wait_duration); bool pop(io_context_t*& io_context, value_type& req); private: using mutex_t = Mutex; using lock_guard = std::lock_guard<mutex_t>; struct expiring_request { using list = std::list<expiring_request>; using list_it = typename list::iterator; using multimap = std::multimap<time_traits::time_point, const expiring_request*>; using multimap_it = typename multimap::iterator; io_context_t* io_context; queue::value_type request; expired_handler expired; list_it order_it; multimap_it expires_at_it; expiring_request() = default; }; using request_multimap_value = typename expiring_request::multimap::value_type; using timers_map = typename std::unordered_map<const io_context_t*, std::unique_ptr<timer_t>>; const std::size_t _capacity; mutable mutex_t _mutex; typename expiring_request::list _ordered_requests_pool; typename expiring_request::list _ordered_requests; typename expiring_request::multimap _expires_at_requests; timers_map _timers; time_traits::time_point _min_expires_at = time_traits::time_point::max(); bool fit_capacity() const { return _expires_at_requests.size() < _capacity; } void cancel(const boost::system::error_code& ec, time_traits::time_point expires_at); void cancel_one(const request_multimap_value& pair); void update_timer(); timer_t& get_timer(io_context_t& io_context); }; template <class V, class M, class I, class T> std::size_t queue<V, M, I, T>::size() const { const lock_guard lock(_mutex); return _expires_at_requests.size(); } template <class V, class M, class I, class T> bool queue<V, M, I, T>::empty() const { const lock_guard lock(_mutex); return _ordered_requests.empty(); } template <class V, class M, class I, class T> const typename queue<V, M, I, T>::timer_t& queue<V, M, I, T>::timer(io_context_t& io_context) { const lock_guard lock(_mutex); return get_timer(io_context); } template <class V, class M, class I, class T> template <class Handler> bool queue<V, M, I, T>::push(io_context_t& io_context, const value_type& req_data, Handler&& req_expired, time_traits::duration wait_duration) { const lock_guard lock(_mutex); if (!fit_capacity()) { return false; } if (_ordered_requests_pool.empty()) { _ordered_requests_pool.emplace_back(); } const auto order_it = _ordered_requests_pool.begin(); _ordered_requests.splice(_ordered_requests.end(), _ordered_requests_pool, order_it); expiring_request& req = *order_it; req.io_context = std::addressof(io_context); req.request = req_data; req.expired = expired_handler(std::forward<Handler>(req_expired)); req.order_it = order_it; const auto expires_at = time_traits::add(time_traits::now(), wait_duration); req.expires_at_it = _expires_at_requests.insert(std::make_pair(expires_at, &req)); update_timer(); return true; } template <class V, class M, class I, class T> bool queue<V, M, I, T>::pop(io_context_t*& io_context, value_type& value) { const lock_guard lock(_mutex); if (_ordered_requests.empty()) { return false; } const auto ordered_it = _ordered_requests.begin(); const expiring_request& req = *ordered_it; io_context = req.io_context; value = req.request; _expires_at_requests.erase(req.expires_at_it); _ordered_requests_pool.splice(_ordered_requests_pool.begin(), _ordered_requests, ordered_it); update_timer(); return true; } template <class V, class M, class I, class T> void queue<V, M, I, T>::cancel(const boost::system::error_code& ec, time_traits::time_point expires_at) { if (ec) { return; } const lock_guard lock(_mutex); const auto begin = _expires_at_requests.begin(); const auto end = _expires_at_requests.upper_bound(expires_at); std::for_each(begin, end, [&] (const request_multimap_value& v) { this->cancel_one(v); }); _expires_at_requests.erase(_expires_at_requests.begin(), end); update_timer(); } template <class V, class M, class I, class T> void queue<V, M, I, T>::cancel_one(const request_multimap_value &pair) { const expiring_request* req = pair.second; asio::post(*req->io_context, std::move(req->expired)); _ordered_requests_pool.splice(_ordered_requests_pool.begin(), _ordered_requests, req->order_it); } template <class V, class M, class I, class T> void queue<V, M, I, T>::update_timer() { using timers_map_value = typename timers_map::value_type; if (_expires_at_requests.empty()) { std::for_each(_timers.begin(), _timers.end(), [] (timers_map_value& v) { v.second->cancel(); }); _timers.clear(); return; } const auto earliest_expire = _expires_at_requests.begin(); const auto expires_at = earliest_expire->first; auto& timer = get_timer(*earliest_expire->second->io_context); timer.expires_at(expires_at); std::weak_ptr<queue> weak(this->shared_from_this()); timer.async_wait([weak, expires_at] (const boost::system::error_code& ec) { if (const auto locked = weak.lock()) { locked->cancel(ec, expires_at); } }); } template <class V, class M, class I, class T> typename queue<V, M, I, T>::timer_t& queue<V, M, I, T>::get_timer(io_context_t& io_context) { auto it = _timers.find(&io_context); if (it != _timers.end()) { return *it->second; } return *_timers.insert(std::make_pair(&io_context, std::make_unique<timer_t>(io_context))).first->second; } } // namespace detail } // namespace async } // namespace resource_pool } // namespace yamail #endif // YAMAIL_RESOURCE_POOL_ASYNC_DETAIL_QUEUE_HPP <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // taskd - Task Server // // Copyright 2010 - 2013, Göteborg Bit Factory. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <iostream> #include <cstring> #include <stdlib.h> #include <Date.h> #include <Color.h> #include <Timer.h> #include <text.h> #include <util.h> #include <taskd.h> //////////////////////////////////////////////////////////////////////////////// int status_statistics (Config& config) { int status = 0; // Request statistics, but do not spool request, in the event of failure. Msg request; request.set ("type", "statistics"); request.set ("time", Date ().toISO ()); Msg response; if (taskd_sendMessage (config, "server", request, response)) { std::vector <std::string> names; response.all (names); std::map <std::string, std::string> data; data["Uptime"] = formatTime (strtol (response.get ("uptime").c_str (), NULL, 10)); data["Transactions"] = commify (response.get ("transactions")); data["TPS"] = format (strtod (response.get ("tps").c_str (), NULL), 4, 5); data["Errors"] = commify (response.get ("errors")); data["Idle"] = format (100.0 * strtod (response.get ("idle").c_str (), NULL), 3, 5) + "%"; data["Total In"] = formatBytes (strtol (response.get ("total bytes in").c_str (), NULL, 10)); data["Total Out"] = formatBytes (strtol (response.get ("total bytes out").c_str (), NULL, 10)); data["Average Request"] = formatBytes (strtol (response.get ("average request bytes").c_str (), NULL, 10)); data["Average Response"] = formatBytes (strtol (response.get ("average response bytes").c_str (), NULL, 10)); data["Average Response Time"] = response.get ("average response time") + " sec"; data["Maximum Response Time"] = response.get ("maximum response time") + " sec"; taskd_renderMap (data, "Tracked Statistic", "Data"); } else { std::cout << Color ("red").colorize ("ERROR: Task server not responding.") << "\n"; status = 1; } return status; } //////////////////////////////////////////////////////////////////////////////// int command_status (Config& config, const std::vector <std::string>& args) { // taskd_requireConfiguration (config); // taskd_resume (config); bool verbose = true; bool debug = false; std::string root; std::vector <std::string>::const_iterator i; for (i = ++(args.begin ()); i != args.end (); ++i) { if (closeEnough ("--debug", *i, 3)) debug = true; else if (closeEnough ("--data", *i, 3)) root = *(++i); else if (closeEnough ("--quiet", *i, 3)) verbose = false; else if (taskd_applyOverride (config, *i)) ; else throw std::string ("ERROR: Unrecognized argument '") + *i + "'"; } if (root == "") { char* root_env = getenv ("TASKDDATA"); if (root_env) root = root_env; } // Preserve the verbose setting for this run. config.set ("verbose", verbose); return status_statistics (config); } //////////////////////////////////////////////////////////////////////////////// <commit_msg>Code Cleanup<commit_after>//////////////////////////////////////////////////////////////////////////////// // taskd - Task Server // // Copyright 2010 - 2013, Göteborg Bit Factory. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <iostream> #include <cstring> #include <stdlib.h> #include <Date.h> #include <Color.h> #include <Timer.h> #include <text.h> #include <util.h> #include <taskd.h> //////////////////////////////////////////////////////////////////////////////// int status_statistics (Config& config) { int status = 0; // Request statistics, but do not spool request, in the event of failure. Msg request; request.set ("type", "statistics"); request.set ("time", Date ().toISO ()); Msg response; if (taskd_sendMessage (config, "server", request, response)) { std::vector <std::string> names; response.all (names); std::map <std::string, std::string> data; data["Uptime"] = formatTime (strtol (response.get ("uptime").c_str (), NULL, 10)); data["Transactions"] = commify (response.get ("transactions")); data["TPS"] = format (strtod (response.get ("tps").c_str (), NULL), 4, 5); data["Errors"] = commify (response.get ("errors")); data["Idle"] = format (100.0 * strtod (response.get ("idle").c_str (), NULL), 3, 5) + "%"; data["Total In"] = formatBytes (strtol (response.get ("total bytes in").c_str (), NULL, 10)); data["Total Out"] = formatBytes (strtol (response.get ("total bytes out").c_str (), NULL, 10)); data["Average Request"] = formatBytes (strtol (response.get ("average request bytes").c_str (), NULL, 10)); data["Average Response"] = formatBytes (strtol (response.get ("average response bytes").c_str (), NULL, 10)); data["Average Response Time"] = response.get ("average response time") + " sec"; data["Maximum Response Time"] = response.get ("maximum response time") + " sec"; taskd_renderMap (data, "Tracked Statistic", "Data"); } else { std::cout << Color ("red").colorize ("ERROR: Task server not responding.") << "\n"; status = 1; } return status; } //////////////////////////////////////////////////////////////////////////////// int command_status (Config& config, const std::vector <std::string>& args) { // taskd_requireConfiguration (config); // taskd_resume (config); bool verbose = true; std::string root; std::vector <std::string>::const_iterator i; for (i = ++(args.begin ()); i != args.end (); ++i) { if (closeEnough ("--debug", *i, 3)) ; // TODO Is this necessary? else if (closeEnough ("--data", *i, 3)) root = *(++i); else if (closeEnough ("--quiet", *i, 3)) verbose = false; else if (taskd_applyOverride (config, *i)) ; else throw std::string ("ERROR: Unrecognized argument '") + *i + "'"; } if (root == "") { char* root_env = getenv ("TASKDDATA"); if (root_env) root = root_env; } // Preserve the verbose setting for this run. config.set ("verbose", verbose); return status_statistics (config); } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/ui/npapi_test_helper.h" #include "chrome/test/ui_test_utils.h" #if defined(OS_WIN) static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.dll"; #elif defined(OS_MACOSX) static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.plugin"; #elif defined(OS_LINUX) static const char kPepperTestPluginName[] = "libnpapi_pepper_test_plugin.so"; #endif using npapi_test::kTestCompleteCookie; using npapi_test::kTestCompleteSuccess; // Helper class pepper NPAPI tests. class PepperTester : public NPAPITesterBase { protected: PepperTester() : NPAPITesterBase(kPepperTestPluginName) {} virtual void SetUp() { // TODO(alokp): Remove no-sandbox flag once gpu plugin can run in sandbox. launch_arguments_.AppendSwitch(switches::kNoSandbox); launch_arguments_.AppendSwitch(switches::kInternalPepper); launch_arguments_.AppendSwitch(switches::kEnableGPUPlugin); NPAPITesterBase::SetUp(); } }; // Test that a pepper 3d plugin loads and renders. // TODO(alokp): Enable the test after making sure it works on all platforms // and buildbots have OpenGL support. #if defined(OS_WIN) TEST_F(PepperTester, Pepper3D) { const FilePath dir(FILE_PATH_LITERAL("pepper")); const FilePath file(FILE_PATH_LITERAL("pepper_3d.html")); GURL url = ui_test_utils::GetTestUrl(dir, file); ASSERT_NO_FATAL_FAILURE(NavigateToURL(url)); WaitForFinish("pepper_3d", "1", url, kTestCompleteCookie, kTestCompleteSuccess, action_max_timeout_ms()); } #endif <commit_msg>Disable failing test PepperTester.Pepper3D .<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/ui/npapi_test_helper.h" #include "chrome/test/ui_test_utils.h" #if defined(OS_WIN) static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.dll"; #elif defined(OS_MACOSX) static const char kPepperTestPluginName[] = "npapi_pepper_test_plugin.plugin"; #elif defined(OS_LINUX) static const char kPepperTestPluginName[] = "libnpapi_pepper_test_plugin.so"; #endif using npapi_test::kTestCompleteCookie; using npapi_test::kTestCompleteSuccess; // Helper class pepper NPAPI tests. class PepperTester : public NPAPITesterBase { protected: PepperTester() : NPAPITesterBase(kPepperTestPluginName) {} virtual void SetUp() { // TODO(alokp): Remove no-sandbox flag once gpu plugin can run in sandbox. launch_arguments_.AppendSwitch(switches::kNoSandbox); launch_arguments_.AppendSwitch(switches::kInternalPepper); launch_arguments_.AppendSwitch(switches::kEnableGPUPlugin); NPAPITesterBase::SetUp(); } }; // Test that a pepper 3d plugin loads and renders. // TODO(alokp): Enable the test after making sure it works on all platforms // and buildbots have OpenGL support. #if defined(OS_WIN) // Disabled after failing on buildbots: crbug/46662 TEST_F(PepperTester, DISABLED_Pepper3D) { const FilePath dir(FILE_PATH_LITERAL("pepper")); const FilePath file(FILE_PATH_LITERAL("pepper_3d.html")); GURL url = ui_test_utils::GetTestUrl(dir, file); ASSERT_NO_FATAL_FAILURE(NavigateToURL(url)); WaitForFinish("pepper_3d", "1", url, kTestCompleteCookie, kTestCompleteSuccess, action_max_timeout_ms()); } #endif <|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "absl/strings/str_split.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/InitLLVM.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/ToolOutputFile.h" #include "mlir/IR/Diagnostics.h" // TF:llvm-project #include "mlir/IR/Function.h" // TF:llvm-project #include "mlir/IR/MLIRContext.h" // TF:llvm-project #include "mlir/IR/Module.h" // TF:llvm-project #include "mlir/Pass/Pass.h" // TF:llvm-project #include "mlir/Support/FileUtilities.h" // TF:llvm-project #include "tensorflow/compiler/mlir/init_mlir.h" #include "tensorflow/compiler/mlir/lite/common/tfl_pass_config.h" #include "tensorflow/compiler/mlir/lite/flatbuffer_translate.h" #include "tensorflow/compiler/mlir/lite/flatbuffer_translate_flags.h" #include "tensorflow/compiler/mlir/lite/tf_tfl_passes.h" #include "tensorflow/compiler/mlir/lite/tf_tfl_translate_cl.h" #include "tensorflow/compiler/mlir/lite/tf_to_tfl_flatbuffer.h" #include "tensorflow/compiler/mlir/lite/transforms/passes.h" #include "tensorflow/compiler/mlir/tensorflow/translate/tf_mlir_translate_cl.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/lite/model.h" #include "tensorflow/lite/schema/schema_generated.h" #include "tensorflow/stream_executor/lib/statusor.h" using mlir::FuncOp; using mlir::MLIRContext; using mlir::ModuleOp; using stream_executor::port::StatusOr; // Debugging flag to print function mapping in the flatbuffer. // NOLINTNEXTLINE static llvm::cl::opt<bool> print_function_result_mapping( "print-function-result-mapping", llvm::cl::desc( "Print the mapping of function result to flatbuffer output buffer"), llvm::cl::init(false)); // NOLINTNEXTLINE static llvm::cl::opt<std::string> weight_quantization( "weight_quantization", llvm::cl::desc("The type of the quantized weight buffer. Must be NONE, " "INT8, FLOAT16."), llvm::cl::init("NONE")); enum TranslationStatus { kTrSuccess, kTrFailure }; static int PrintFunctionResultMapping(const std::string &result, ModuleOp module) { // Build model from the resultant string to extract the return values from // their source of truth. auto model = tflite::FlatBufferModel::BuildFromBuffer(result.data(), result.size()); if (!model) return kTrFailure; // Get an unknown location for where we don't have a terminator to get the // location of the return value from. auto unknown_loc = mlir::UnknownLoc::get(module.getContext()); auto print_buffer = [&](const tflite::SubGraph &subgraph, int id, int buffer, std::function<mlir::Location(int)> loc) { const auto &output_tensor = (*subgraph.tensors())[buffer]; std::cout << "\tname: '" << (output_tensor->name() ? output_tensor->name()->str() : "<<unnamed>>") << "' buffer: " << buffer; if (loc) std::cout << llvm::formatv(" {0}", loc(id)).str(); std::cout << '\n'; }; // For every subgraph print out the name (if available), each result's output // buffer number and location of the return value (if available). for (auto *subgraph : *(*model)->subgraphs()) { std::string subgraph_name = subgraph->name() ? subgraph->name()->str() : "<<unnamed subgraph>>"; std::cout << '\'' << subgraph_name << "' inputs:\n"; int i = 0; for (auto input : *subgraph->inputs()) print_buffer(*subgraph, i++, input, nullptr); std::cout << '\'' << subgraph_name << "' outputs:\n"; mlir::Operation *terminator = nullptr; if (subgraph->name()) { if (auto fn = module.lookupSymbol<FuncOp>(subgraph->name()->str())) terminator = fn.back().getTerminator(); } i = 0; for (auto output : *subgraph->outputs()) { print_buffer(*subgraph, i, output, [&](int i) { return terminator ? terminator->getOperand(i).getLoc() : unknown_loc; }); } } return kTrSuccess; } int main(int argc, char **argv) { // TODO(jpienaar): Revise the command line option parsing here. tensorflow::InitMlir y(&argc, &argv); // TODO(antiagainst): We are pulling in multiple transformations as follows. // Each transformation has its own set of command-line options; options of one // transformation can essentially be aliases to another. For example, the // -tfl-annotate-inputs has -tfl-input-arrays, -tfl-input-data-types, and // -tfl-input-shapes, which are the same as -graphdef-to-mlir transformation's // -tf_input_arrays, -tf_input_data_types, and -tf_input_shapes, respectively. // We need to disable duplicated ones to provide a cleaner command-line option // interface. That also means we need to relay the value set in one option to // all its aliases. llvm::cl::ParseCommandLineOptions( argc, argv, "TF GraphDef to TFLite FlatBuffer converter\n"); MLIRContext context; llvm::SourceMgr source_mgr; mlir::SourceMgrDiagnosticHandler sourceMgrHandler(source_mgr, &context); StatusOr<mlir::OwningModuleRef> module; // TODO(b/147435528): We need to test the e2e behavior once the graph freezing // inside mlir is done. if (import_saved_model || import_saved_model_v1) { if (input_mlir) module = tensorflow::errors::InvalidArgument( "Importing saved model should not have input_mlir set"); module = tensorflow::ImportSavedModel( import_saved_model, import_saved_model_v1, input_file_name, saved_model_tags, saved_model_exported_names, &context); } else { module = tensorflow::LoadFromGraphdefOrMlirSource( input_file_name, input_mlir, use_splatted_constant, custom_opdefs, debug_info_file, input_arrays, input_dtypes, input_shapes, output_arrays, /*prune_unused_nodes=*/true, &source_mgr, &context); } // If errors occur, the library call in the above already logged the error // message. So we can just return here. if (!module.ok()) return kTrFailure; mlir::PassManager pm(&context); // Set the quantization specifications from the command line flags. mlir::TFL::QuantizationSpecs quant_specs; if (mlir::TFL::ParseInputNodeQuantSpecs(input_arrays, min_values, max_values, inference_type, &quant_specs)) { llvm::errs() << "Failed to get input quant spec."; return kTrFailure; } if (weight_quantization != "NONE") { quant_specs.weight_quantization = true; if (weight_quantization == "INT8") { quant_specs.inference_type = tensorflow::DT_QINT8; } else if (weight_quantization == "FLOAT16") { quant_specs.inference_type = tensorflow::DT_HALF; } else { llvm::errs() << "Unknown weight quantization " << weight_quantization; return kTrFailure; } } if (!emit_quant_adaptor_ops) { quant_specs.inference_input_type = quant_specs.inference_type; } if (!quant_stats_file_name.empty()) { std::string error_message; auto file = mlir::openInputFile(quant_stats_file_name, &error_message); if (!file) { llvm::errs() << "fail to open quant stats file: " << quant_stats_file_name; return kTrFailure; } quant_specs.serialized_quant_stats = file->getBuffer().str(); } mlir::TFL::PassConfig pass_config(quant_specs); pass_config.emit_builtin_tflite_ops = emit_builtin_tflite_ops; pass_config.lower_tensor_list_ops = lower_tensor_list_ops; // Currently we only do shape inference for saved model import. if (import_saved_model || import_saved_model_v1) { pass_config.shape_inference = true; } tensorflow::AddTFToTFLConversionPasses(pass_config, &pm); pm.addPass(mlir::TFL::CreateRuntimeTypeVerifyPass()); std::string result; auto status = tensorflow::ConvertTFExecutorToTFLOrFlatbuffer( module.ValueOrDie().get(), output_mlir, emit_builtin_tflite_ops, emit_select_tf_ops, emit_custom_ops, quant_specs, &result, &pm); if (!status.ok()) return kTrFailure; std::string error_msg; auto output = mlir::openOutputFile(output_file_name, &error_msg); if (output == nullptr) { llvm::errs() << error_msg << '\n'; return kTrFailure; } output->os() << result; output->keep(); // Print out debugging info related to function mapping. if (print_function_result_mapping) return PrintFunctionResultMapping(result, module.ValueOrDie().get()); return kTrSuccess; } <commit_msg>Add while loop outline pass in tf_tfl_translate.cc.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "absl/strings/str_split.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/InitLLVM.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/ToolOutputFile.h" #include "mlir/IR/Diagnostics.h" // TF:llvm-project #include "mlir/IR/Function.h" // TF:llvm-project #include "mlir/IR/MLIRContext.h" // TF:llvm-project #include "mlir/IR/Module.h" // TF:llvm-project #include "mlir/Pass/Pass.h" // TF:llvm-project #include "mlir/Support/FileUtilities.h" // TF:llvm-project #include "tensorflow/compiler/mlir/init_mlir.h" #include "tensorflow/compiler/mlir/lite/common/tfl_pass_config.h" #include "tensorflow/compiler/mlir/lite/flatbuffer_translate.h" #include "tensorflow/compiler/mlir/lite/flatbuffer_translate_flags.h" #include "tensorflow/compiler/mlir/lite/tf_tfl_passes.h" #include "tensorflow/compiler/mlir/lite/tf_tfl_translate_cl.h" #include "tensorflow/compiler/mlir/lite/tf_to_tfl_flatbuffer.h" #include "tensorflow/compiler/mlir/lite/transforms/passes.h" #include "tensorflow/compiler/mlir/tensorflow/translate/tf_mlir_translate_cl.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/lite/model.h" #include "tensorflow/lite/schema/schema_generated.h" #include "tensorflow/stream_executor/lib/statusor.h" using mlir::FuncOp; using mlir::MLIRContext; using mlir::ModuleOp; using stream_executor::port::StatusOr; // Debugging flag to print function mapping in the flatbuffer. // NOLINTNEXTLINE static llvm::cl::opt<bool> print_function_result_mapping( "print-function-result-mapping", llvm::cl::desc( "Print the mapping of function result to flatbuffer output buffer"), llvm::cl::init(false)); // NOLINTNEXTLINE static llvm::cl::opt<std::string> weight_quantization( "weight_quantization", llvm::cl::desc("The type of the quantized weight buffer. Must be NONE, " "INT8, FLOAT16."), llvm::cl::init("NONE")); enum TranslationStatus { kTrSuccess, kTrFailure }; static int PrintFunctionResultMapping(const std::string &result, ModuleOp module) { // Build model from the resultant string to extract the return values from // their source of truth. auto model = tflite::FlatBufferModel::BuildFromBuffer(result.data(), result.size()); if (!model) return kTrFailure; // Get an unknown location for where we don't have a terminator to get the // location of the return value from. auto unknown_loc = mlir::UnknownLoc::get(module.getContext()); auto print_buffer = [&](const tflite::SubGraph &subgraph, int id, int buffer, std::function<mlir::Location(int)> loc) { const auto &output_tensor = (*subgraph.tensors())[buffer]; std::cout << "\tname: '" << (output_tensor->name() ? output_tensor->name()->str() : "<<unnamed>>") << "' buffer: " << buffer; if (loc) std::cout << llvm::formatv(" {0}", loc(id)).str(); std::cout << '\n'; }; // For every subgraph print out the name (if available), each result's output // buffer number and location of the return value (if available). for (auto *subgraph : *(*model)->subgraphs()) { std::string subgraph_name = subgraph->name() ? subgraph->name()->str() : "<<unnamed subgraph>>"; std::cout << '\'' << subgraph_name << "' inputs:\n"; int i = 0; for (auto input : *subgraph->inputs()) print_buffer(*subgraph, i++, input, nullptr); std::cout << '\'' << subgraph_name << "' outputs:\n"; mlir::Operation *terminator = nullptr; if (subgraph->name()) { if (auto fn = module.lookupSymbol<FuncOp>(subgraph->name()->str())) terminator = fn.back().getTerminator(); } i = 0; for (auto output : *subgraph->outputs()) { print_buffer(*subgraph, i, output, [&](int i) { return terminator ? terminator->getOperand(i).getLoc() : unknown_loc; }); } } return kTrSuccess; } int main(int argc, char **argv) { // TODO(jpienaar): Revise the command line option parsing here. tensorflow::InitMlir y(&argc, &argv); // TODO(antiagainst): We are pulling in multiple transformations as follows. // Each transformation has its own set of command-line options; options of one // transformation can essentially be aliases to another. For example, the // -tfl-annotate-inputs has -tfl-input-arrays, -tfl-input-data-types, and // -tfl-input-shapes, which are the same as -graphdef-to-mlir transformation's // -tf_input_arrays, -tf_input_data_types, and -tf_input_shapes, respectively. // We need to disable duplicated ones to provide a cleaner command-line option // interface. That also means we need to relay the value set in one option to // all its aliases. llvm::cl::ParseCommandLineOptions( argc, argv, "TF GraphDef to TFLite FlatBuffer converter\n"); MLIRContext context; llvm::SourceMgr source_mgr; mlir::SourceMgrDiagnosticHandler sourceMgrHandler(source_mgr, &context); StatusOr<mlir::OwningModuleRef> module; // TODO(b/147435528): We need to test the e2e behavior once the graph freezing // inside mlir is done. if (import_saved_model || import_saved_model_v1) { if (input_mlir) module = tensorflow::errors::InvalidArgument( "Importing saved model should not have input_mlir set"); module = tensorflow::ImportSavedModel( import_saved_model, import_saved_model_v1, input_file_name, saved_model_tags, saved_model_exported_names, &context); } else { module = tensorflow::LoadFromGraphdefOrMlirSource( input_file_name, input_mlir, use_splatted_constant, custom_opdefs, debug_info_file, input_arrays, input_dtypes, input_shapes, output_arrays, /*prune_unused_nodes=*/true, &source_mgr, &context); } // If errors occur, the library call in the above already logged the error // message. So we can just return here. if (!module.ok()) return kTrFailure; mlir::PassManager pm(&context); // Set the quantization specifications from the command line flags. mlir::TFL::QuantizationSpecs quant_specs; if (mlir::TFL::ParseInputNodeQuantSpecs(input_arrays, min_values, max_values, inference_type, &quant_specs)) { llvm::errs() << "Failed to get input quant spec."; return kTrFailure; } if (weight_quantization != "NONE") { quant_specs.weight_quantization = true; if (weight_quantization == "INT8") { quant_specs.inference_type = tensorflow::DT_QINT8; } else if (weight_quantization == "FLOAT16") { quant_specs.inference_type = tensorflow::DT_HALF; } else { llvm::errs() << "Unknown weight quantization " << weight_quantization; return kTrFailure; } } if (!emit_quant_adaptor_ops) { quant_specs.inference_input_type = quant_specs.inference_type; } if (!quant_stats_file_name.empty()) { std::string error_message; auto file = mlir::openInputFile(quant_stats_file_name, &error_message); if (!file) { llvm::errs() << "fail to open quant stats file: " << quant_stats_file_name; return kTrFailure; } quant_specs.serialized_quant_stats = file->getBuffer().str(); } mlir::TFL::PassConfig pass_config(quant_specs); pass_config.emit_builtin_tflite_ops = emit_builtin_tflite_ops; pass_config.lower_tensor_list_ops = lower_tensor_list_ops; // Currently we only do shape inference for saved model import. if (import_saved_model || import_saved_model_v1) { pass_config.shape_inference = true; } tensorflow::AddTFToTFLConversionPasses(pass_config, &pm); // TODO(b/150901738): Move those into tf_tfl_translate.cc. // Convert back to outlined while format for export back to flatbuffer. if (pass_config.legalize_tf_while) { pm.addPass(mlir::TFL::CreateWhileOutlinePass()); } pm.addPass(mlir::TFL::CreateRuntimeTypeVerifyPass()); std::string result; auto status = tensorflow::ConvertTFExecutorToTFLOrFlatbuffer( module.ValueOrDie().get(), output_mlir, emit_builtin_tflite_ops, emit_select_tf_ops, emit_custom_ops, quant_specs, &result, &pm); if (!status.ok()) return kTrFailure; std::string error_msg; auto output = mlir::openOutputFile(output_file_name, &error_msg); if (output == nullptr) { llvm::errs() << error_msg << '\n'; return kTrFailure; } output->os() << result; output->keep(); // Print out debugging info related to function mapping. if (print_function_result_mapping) return PrintFunctionResultMapping(result, module.ValueOrDie().get()); return kTrSuccess; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fileview.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: dv $ $Date: 2001-07-18 13:44:55 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVT_FILEVIEW_HXX #define _SVT_FILEVIEW_HXX #ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_ #include <com/sun/star/uno/Sequence.h> #endif #include <vcl/ctrl.hxx> #include <vcl/image.hxx> #include <vcl/fixed.hxx> #include <vcl/button.hxx> #include <vcl/dialog.hxx> // class SvtFileView ----------------------------------------------------- #define FILEVIEW_ONLYFOLDER 0x0001 #define FILEVIEW_MULTISELECTION 0x0002 #define FILEVIEW_SHOW_TITLE 0x0010 #define FILEVIEW_SHOW_SIZE 0x0020 #define FILEVIEW_SHOW_DATE 0x0040 #define FILEVIEW_SHOW_ALL 0x0070 class ViewTabListBox_Impl; class SvtFileView_Impl; class SvLBoxEntry; class HeaderBar; class SvtFileView : public Control { private: SvtFileView_Impl* mpImp; void OpenFolder( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aContents ); DECL_LINK( HeaderSelect_Impl, HeaderBar * ); public: SvtFileView( Window* pParent, const ResId& rResId, sal_Bool bOnlyFolder, sal_Bool bMultiSelection ); SvtFileView( Window* pParent, const ResId& rResId, sal_Int8 nFlags ); ~SvtFileView(); const String& GetViewURL() const; String GetURL( SvLBoxEntry* pEntry ) const; String GetCurrentURL() const; void CreateNewFolder( const String& rNewFolder ); sal_Bool HasPreviousLevel( String& rParentURL ) const; sal_Bool PreviousLevel( String& rNewURL ); void SetHelpId( sal_uInt32 nHelpId ); void SetSizePixel( const Size& rNewSize ); void SetPosSizePixel( const Point& rNewPos, const Size& rNewSize ); void Initialize( const String& rURL, const String& rFilter ); void Initialize( const String& rURL, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aContents ); void ExecuteFilter( const String& rFilter ); void SetNoSelection(); void SetFocusInView(); void ResetCursor(); void SetSelectHdl( const Link& rHdl ); void SetDoubleClickHdl( const Link& rHdl ); void SetOpenDoneHdl( const Link& rHdl ); ULONG GetSelectionCount() const; SvLBoxEntry* FirstSelected() const; SvLBoxEntry* NextSelected( SvLBoxEntry* pEntry ) const; void EnableAutoResize(); void SetFocus(); void EnableContextMenu( sal_Bool bEnable ); }; // struct SvtContentEntry ------------------------------------------------ struct SvtContentEntry { sal_Bool mbIsFolder; UniString maURL; SvtContentEntry( const UniString& rURL, sal_Bool bIsFolder ) : mbIsFolder( bIsFolder ), maURL( rURL ) {} }; namespace svtools { // QueryDeleteDlg_Impl class QueryDeleteDlg_Impl : public ModalDialog { FixedText _aEntryLabel; FixedText _aEntry; FixedText _aQueryMsg; PushButton _aYesButton; PushButton _aNoButton; CancelButton _aCancelButton; private: DECL_STATIC_LINK( QueryDeleteDlg_Impl, ClickLink, PushButton* ); public: QueryDeleteDlg_Impl( Window* pParent, const String& rName ); }; } #endif // _SVT_FILEVIEW_HXX <commit_msg>#88656# Added delete all button to QueryDelete dialog, added EnableDelete()<commit_after>/************************************************************************* * * $RCSfile: fileview.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: dv $ $Date: 2001-07-19 10:05:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVT_FILEVIEW_HXX #define _SVT_FILEVIEW_HXX #ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_ #include <com/sun/star/uno/Sequence.h> #endif #include <vcl/ctrl.hxx> #include <vcl/image.hxx> #include <vcl/fixed.hxx> #include <vcl/button.hxx> #include <vcl/dialog.hxx> // class SvtFileView ----------------------------------------------------- #define FILEVIEW_ONLYFOLDER 0x0001 #define FILEVIEW_MULTISELECTION 0x0002 #define FILEVIEW_SHOW_TITLE 0x0010 #define FILEVIEW_SHOW_SIZE 0x0020 #define FILEVIEW_SHOW_DATE 0x0040 #define FILEVIEW_SHOW_ALL 0x0070 class ViewTabListBox_Impl; class SvtFileView_Impl; class SvLBoxEntry; class HeaderBar; class SvtFileView : public Control { private: SvtFileView_Impl* mpImp; void OpenFolder( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aContents ); DECL_LINK( HeaderSelect_Impl, HeaderBar * ); public: SvtFileView( Window* pParent, const ResId& rResId, sal_Bool bOnlyFolder, sal_Bool bMultiSelection ); SvtFileView( Window* pParent, const ResId& rResId, sal_Int8 nFlags ); ~SvtFileView(); const String& GetViewURL() const; String GetURL( SvLBoxEntry* pEntry ) const; String GetCurrentURL() const; void CreateNewFolder( const String& rNewFolder ); sal_Bool HasPreviousLevel( String& rParentURL ) const; sal_Bool PreviousLevel( String& rNewURL ); void SetHelpId( sal_uInt32 nHelpId ); void SetSizePixel( const Size& rNewSize ); void SetPosSizePixel( const Point& rNewPos, const Size& rNewSize ); void Initialize( const String& rURL, const String& rFilter ); void Initialize( const String& rURL, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aContents ); void ExecuteFilter( const String& rFilter ); void SetNoSelection(); void SetFocusInView(); void ResetCursor(); void SetSelectHdl( const Link& rHdl ); void SetDoubleClickHdl( const Link& rHdl ); void SetOpenDoneHdl( const Link& rHdl ); ULONG GetSelectionCount() const; SvLBoxEntry* FirstSelected() const; SvLBoxEntry* NextSelected( SvLBoxEntry* pEntry ) const; void EnableAutoResize(); void SetFocus(); void EnableContextMenu( sal_Bool bEnable ); void EnableDelete( sal_Bool bEnable ); }; // struct SvtContentEntry ------------------------------------------------ struct SvtContentEntry { sal_Bool mbIsFolder; UniString maURL; SvtContentEntry( const UniString& rURL, sal_Bool bIsFolder ) : mbIsFolder( bIsFolder ), maURL( rURL ) {} }; namespace svtools { // ----------------------------------------------------------------------- // QueryDeleteDlg_Impl // ----------------------------------------------------------------------- enum QueryDeleteResult_Impl { QUERYDELETE_YES = 0, QUERYDELETE_NO, QUERYDELETE_ALL, QUERYDELETE_CANCEL }; class QueryDeleteDlg_Impl : public ModalDialog { FixedText _aEntryLabel; FixedText _aEntry; FixedText _aQueryMsg; PushButton _aYesButton; PushButton _aAllButton; PushButton _aNoButton; CancelButton _aCancelButton; QueryDeleteResult_Impl _eResult; private: DECL_STATIC_LINK( QueryDeleteDlg_Impl, ClickLink, PushButton* ); public: QueryDeleteDlg_Impl( Window* pParent, const String& rName ); void EnableAllButton() { _aAllButton.Enable( sal_True ); } QueryDeleteResult_Impl GetResult() const { return _eResult; } }; } #endif // _SVT_FILEVIEW_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: testtool.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2003-04-15 17:51:23 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SVTOOLS_TESTTOOL_HXX #define SVTOOLS_TESTTOOL_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef _LINK_HXX //autogen #include <tools/link.hxx> #endif class Application; class SvStream; class StatementFlow; class CommunicationManager; class CommunicationLink; #if OSL_DEBUG_LEVEL > 1 class EditWindow; #endif class ImplRC; class RemoteControl { friend class StatementFlow; BOOL m_bIdleInserted; #if OSL_DEBUG_LEVEL > 1 EditWindow *m_pDbgWin; #endif ImplRC* pImplRC; public: RemoteControl(); ~RemoteControl(); BOOL QueCommands( ULONG nServiceId, SvStream *pIn ); SvStream* GetReturnStream(); DECL_LINK( IdleHdl, Application* ); DECL_LINK( CommandHdl, Application* ); DECL_LINK( QueCommandsEvent, CommunicationLink* ); ULONG nStoredServiceId; SvStream *pStoredStream; void ExecuteURL( String &aURL ); protected: CommunicationManager *pServiceMgr; SvStream *pRetStream; }; #endif // SVTOOLS_TESTTOOL_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.2.906); FILE MERGED 2005/09/05 14:51:13 rt 1.2.906.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: testtool.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 14:07:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SVTOOLS_TESTTOOL_HXX #define SVTOOLS_TESTTOOL_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef _LINK_HXX //autogen #include <tools/link.hxx> #endif class Application; class SvStream; class StatementFlow; class CommunicationManager; class CommunicationLink; #if OSL_DEBUG_LEVEL > 1 class EditWindow; #endif class ImplRC; class RemoteControl { friend class StatementFlow; BOOL m_bIdleInserted; #if OSL_DEBUG_LEVEL > 1 EditWindow *m_pDbgWin; #endif ImplRC* pImplRC; public: RemoteControl(); ~RemoteControl(); BOOL QueCommands( ULONG nServiceId, SvStream *pIn ); SvStream* GetReturnStream(); DECL_LINK( IdleHdl, Application* ); DECL_LINK( CommandHdl, Application* ); DECL_LINK( QueCommandsEvent, CommunicationLink* ); ULONG nStoredServiceId; SvStream *pStoredStream; void ExecuteURL( String &aURL ); protected: CommunicationManager *pServiceMgr; SvStream *pRetStream; }; #endif // SVTOOLS_TESTTOOL_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fmobj.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: oj $ $Date: 2002-10-31 12:54:22 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVX_FMOBJ_HXX #define _SVX_FMOBJ_HXX #ifndef _SVDOUNO_HXX #include "svdouno.hxx" #endif #ifndef _COM_SUN_STAR_SCRIPT_SCRIPTEVENTDESCRIPTOR_HPP_ #include <com/sun/star/script/ScriptEventDescriptor.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_ #include <com/sun/star/container/XIndexContainer.hpp> #endif class FmFormView; //================================================================== // FmFormObj //================================================================== class FmXForms; class FmFormObj: public SdrUnoObj { friend class FmForm; friend class FmFormPage; friend class FmFormPageImpl; friend class FmFormObjFactory; friend class FmXUndoEnvironment; friend class SvxFmDrawPage; friend class SvxFmMSFactory; ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor > aEvts; // events des Objects ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor> m_aEventsHistory; // valid if and only if m_pEnvironmentHistory != NULL, this are the events which we're set when // m_pEnvironmentHistory was created FmFormView* pTempView; sal_uInt32 nEvent; // Informationen fuer die Controlumgebung // werden nur vorgehalten, wenn ein Object sich nicht in einer Objectliste befindet ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer> xParent; ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer > m_xEnvironmentHistory; sal_Int32 nPos; sal_Int32 m_nType; public: TYPEINFO(); protected: FmFormObj(const ::rtl::OUString& rModelName,sal_Int32 _nType); FmFormObj(sal_Int32 _nType); const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer>& GetParent() const {return xParent;} void SetObjEnv(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer>& xForm, sal_Int32 nIdx = -1, const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& rEvts= ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >()); const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& GetEvents() const {return aEvts;} sal_Int32 GetPos() const {return nPos;} public: virtual ~FmFormObj(); virtual void SetPage(SdrPage* pNewPage); virtual sal_uInt32 GetObjInventor() const; virtual sal_uInt16 GetObjIdentifier() const; virtual SdrObject* Clone() const; virtual SdrObject* Clone(SdrPage* pPage, SdrModel* pModel) const; virtual void operator= (const SdrObject& rObj); virtual void clonedFrom(const FmFormObj* _pSource); static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface> ensureModelEnv(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>& _rSourceContainer, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer> _rTopLevelDestContainer); /** returns the type of this form object. See fmglob.hxx */ sal_Int32 getType() const; protected: virtual void WriteData(SvStream& rOut) const; virtual void ReadData(const SdrObjIOHeader& rHead, SvStream& rIn); virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd); DECL_LINK(OnCreate, void* ); }; #endif // _FM_FMOBJ_HXX <commit_msg>INTEGRATION: CWS frmcontrols03 (1.2.554); FILE MERGED 2004/02/23 11:39:07 fs 1.2.554.1: care for a changing ref device at the drawing layer<commit_after>/************************************************************************* * * $RCSfile: fmobj.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-05-07 15:49:25 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVX_FMOBJ_HXX #define _SVX_FMOBJ_HXX #ifndef _SVDOUNO_HXX #include "svdouno.hxx" #endif #ifndef _COM_SUN_STAR_SCRIPT_SCRIPTEVENTDESCRIPTOR_HPP_ #include <com/sun/star/script/ScriptEventDescriptor.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_ #include <com/sun/star/container/XIndexContainer.hpp> #endif class FmFormView; //================================================================== // FmFormObj //================================================================== class FmXForms; class FmFormObj: public SdrUnoObj { friend class FmForm; friend class FmFormPage; friend class FmFormPageImpl; friend class FmFormObjFactory; friend class FmXUndoEnvironment; friend class SvxFmDrawPage; friend class SvxFmMSFactory; ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor > aEvts; // events des Objects ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor> m_aEventsHistory; // valid if and only if m_pEnvironmentHistory != NULL, this are the events which we're set when // m_pEnvironmentHistory was created FmFormView* m_pControlCreationView; sal_uInt32 m_nControlCreationEvent; // Informationen fuer die Controlumgebung // werden nur vorgehalten, wenn ein Object sich nicht in einer Objectliste befindet ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer> m_xParent; ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer > m_xEnvironmentHistory; sal_Int32 m_nPos; sal_Int32 m_nType; OutputDevice* m_pLastKnownRefDevice; // the last ref device we know, as set at the model // only to be used for comparison with the current ref device! public: TYPEINFO(); protected: FmFormObj(const ::rtl::OUString& rModelName,sal_Int32 _nType); FmFormObj(sal_Int32 _nType); const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer>& GetParent() const {return m_xParent;} void SetObjEnv(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer>& xForm, sal_Int32 nIdx = -1, const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& rEvts= ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >()); const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& GetEvents() const {return aEvts;} sal_Int32 GetPos() const { return m_nPos; } public: virtual ~FmFormObj(); virtual void SetPage(SdrPage* pNewPage); virtual sal_uInt32 GetObjInventor() const; virtual sal_uInt16 GetObjIdentifier() const; virtual void ReformatText(); virtual SdrObject* Clone() const; virtual SdrObject* Clone(SdrPage* pPage, SdrModel* pModel) const; virtual void operator= (const SdrObject& rObj); virtual void clonedFrom(const FmFormObj* _pSource); static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface> ensureModelEnv(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>& _rSourceContainer, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer> _rTopLevelDestContainer); /** returns the type of this form object. See fmglob.hxx */ sal_Int32 getType() const; protected: virtual void WriteData(SvStream& rOut) const; virtual void ReadData(const SdrObjIOHeader& rHead, SvStream& rIn); virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd); DECL_LINK(OnCreate, void* ); }; #endif // _FM_FMOBJ_HXX <|endoftext|>
<commit_before>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015 Baldur Karlsson * * 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 "vk_core.h" uint32_t WrappedVulkan::GetReadbackMemoryIndex(uint32_t resourceRequiredBitmask) { if(resourceRequiredBitmask & (1 << m_PhysicalDeviceData.readbackMemIndex)) return m_PhysicalDeviceData.readbackMemIndex; return m_PhysicalDeviceData.GetMemoryIndex( resourceRequiredBitmask, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, VK_MEMORY_PROPERTY_HOST_WRITE_COMBINED_BIT); } uint32_t WrappedVulkan::GetUploadMemoryIndex(uint32_t resourceRequiredBitmask) { if(resourceRequiredBitmask & (1 << m_PhysicalDeviceData.uploadMemIndex)) return m_PhysicalDeviceData.uploadMemIndex; return m_PhysicalDeviceData.GetMemoryIndex( resourceRequiredBitmask, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 0); } uint32_t WrappedVulkan::GetGPULocalMemoryIndex(uint32_t resourceRequiredBitmask) { if(resourceRequiredBitmask & (1 << m_PhysicalDeviceData.GPULocalMemIndex)) return m_PhysicalDeviceData.GPULocalMemIndex; return m_PhysicalDeviceData.GetMemoryIndex( resourceRequiredBitmask, VK_MEMORY_PROPERTY_DEVICE_ONLY, 0); } uint32_t WrappedVulkan::PhysicalDeviceData::GetMemoryIndex(uint32_t resourceRequiredBitmask, uint32_t allocRequiredProps, uint32_t allocUndesiredProps) { uint32_t best = memProps.memoryTypeCount; for(uint32_t memIndex = 0; memIndex < memProps.memoryTypeCount; memIndex++) { if(resourceRequiredBitmask & (1 << memIndex)) { uint32_t memTypeFlags = memProps.memoryTypes[memIndex].propertyFlags; if((memTypeFlags & allocRequiredProps) == allocRequiredProps) { if(memTypeFlags & allocUndesiredProps) best = memIndex; else return memIndex; } } } if(best == memProps.memoryTypeCount) { RDCERR("Couldn't find any matching heap! requirements %x / %x too strict", resourceRequiredBitmask, allocRequiredProps); return 0; } return best; } void WrappedVulkan::RemapMemoryIndices(VkPhysicalDeviceMemoryProperties *memProps, uint32_t **memIdxMap) { uint32_t *memmap = new uint32_t[32]; *memIdxMap = memmap; m_MemIdxMaps.push_back(memmap); RDCEraseMem(memmap, sizeof(uint32_t)*32); // basic idea here: // We want to discourage coherent memory maps as much as possible while capturing, // as they're painful to track. Unfortunately the spec guarantees that at least // one such memory type will be available, and we must follow that. // // So, rather than removing the coherent memory type we make it as unappealing as // possible and try and ensure that only someone looking specifically for a coherent // memory type will find it. That way hopefully memory selection algorithms will // pick non-coherent memory and do proper flushing as necessary. // we want to add a new heap, hopefully there is room RDCASSERT(memProps->memoryHeapCount < VK_MAX_MEMORY_HEAPS-1); uint32_t coherentHeap = memProps->memoryHeapCount; memProps->memoryHeapCount++; // make a new heap that's tiny. If any applications look at heap sizes to determine // viability, they'll dislike the look of this one (the real heaps should be much // bigger). memProps->memoryHeaps[coherentHeap].flags = VK_MEMORY_HEAP_HOST_LOCAL_BIT; memProps->memoryHeaps[coherentHeap].size = 32*1024*1024; // for every coherent memory type, add a non-coherent type first, then // mark the coherent type with our crappy heap uint32_t origCount = memProps->memoryTypeCount; VkMemoryType origTypes[VK_MAX_MEMORY_TYPES]; memcpy(origTypes, memProps->memoryTypes, sizeof(origTypes)); uint32_t newtypeidx = 0; for(uint32_t i=0; i < origCount; i++) { if((origTypes[i].propertyFlags & (VK_MEMORY_PROPERTY_HOST_NON_COHERENT_BIT|VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) == VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) { // coherent type found. // can we still add a new type without exceeding the max? if(memProps->memoryTypeCount+1 <= VK_MAX_MEMORY_TYPES) { // copy both types from the original type memProps->memoryTypes[newtypeidx] = origTypes[i]; memProps->memoryTypes[newtypeidx+1] = origTypes[i]; // mark first as non-coherent memProps->memoryTypes[newtypeidx].propertyFlags &= ~VK_MEMORY_PROPERTY_HOST_UNCACHED_BIT; memProps->memoryTypes[newtypeidx].propertyFlags |= VK_MEMORY_PROPERTY_HOST_NON_COHERENT_BIT; // point second at bad heap memProps->memoryTypes[newtypeidx+1].heapIndex = coherentHeap; // point both new types at this original type memmap[newtypeidx++] = i; memmap[newtypeidx++] = i; // we added a type memProps->memoryTypeCount++; } else { // can't add a new type, but we can at least repoint this coherent // type at the bad heap to discourage use memProps->memoryTypes[newtypeidx] = origTypes[i]; memProps->memoryTypes[newtypeidx].heapIndex = coherentHeap; memmap[newtypeidx++] = i; } } else { // non-coherent already or non-hostvisible, just copy through memProps->memoryTypes[newtypeidx] = origTypes[i]; memmap[newtypeidx++] = i; } } } <commit_msg>Update memory type handling<commit_after>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015 Baldur Karlsson * * 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 "vk_core.h" uint32_t WrappedVulkan::GetReadbackMemoryIndex(uint32_t resourceRequiredBitmask) { if(resourceRequiredBitmask & (1 << m_PhysicalDeviceData.readbackMemIndex)) return m_PhysicalDeviceData.readbackMemIndex; return m_PhysicalDeviceData.GetMemoryIndex( resourceRequiredBitmask, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 0); } uint32_t WrappedVulkan::GetUploadMemoryIndex(uint32_t resourceRequiredBitmask) { if(resourceRequiredBitmask & (1 << m_PhysicalDeviceData.uploadMemIndex)) return m_PhysicalDeviceData.uploadMemIndex; return m_PhysicalDeviceData.GetMemoryIndex( resourceRequiredBitmask, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 0); } uint32_t WrappedVulkan::GetGPULocalMemoryIndex(uint32_t resourceRequiredBitmask) { if(resourceRequiredBitmask & (1 << m_PhysicalDeviceData.GPULocalMemIndex)) return m_PhysicalDeviceData.GPULocalMemIndex; return m_PhysicalDeviceData.GetMemoryIndex( resourceRequiredBitmask, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); } uint32_t WrappedVulkan::PhysicalDeviceData::GetMemoryIndex(uint32_t resourceRequiredBitmask, uint32_t allocRequiredProps, uint32_t allocUndesiredProps) { uint32_t best = memProps.memoryTypeCount; for(uint32_t memIndex = 0; memIndex < memProps.memoryTypeCount; memIndex++) { if(resourceRequiredBitmask & (1 << memIndex)) { uint32_t memTypeFlags = memProps.memoryTypes[memIndex].propertyFlags; if((memTypeFlags & allocRequiredProps) == allocRequiredProps) { if(memTypeFlags & allocUndesiredProps) best = memIndex; else return memIndex; } } } if(best == memProps.memoryTypeCount) { RDCERR("Couldn't find any matching heap! requirements %x / %x too strict", resourceRequiredBitmask, allocRequiredProps); return 0; } return best; } void WrappedVulkan::RemapMemoryIndices(VkPhysicalDeviceMemoryProperties *memProps, uint32_t **memIdxMap) { uint32_t *memmap = new uint32_t[32]; *memIdxMap = memmap; m_MemIdxMaps.push_back(memmap); RDCEraseMem(memmap, sizeof(uint32_t)*32); // basic idea here: // We want to discourage coherent memory maps as much as possible while capturing, // as they're painful to track. Unfortunately the spec guarantees that at least // one such memory type will be available, and we must follow that. // // So, rather than removing the coherent memory type we make it as unappealing as // possible and try and ensure that only someone looking specifically for a coherent // memory type will find it. That way hopefully memory selection algorithms will // pick non-coherent memory and do proper flushing as necessary. // we want to add a new heap, hopefully there is room RDCASSERT(memProps->memoryHeapCount < VK_MAX_MEMORY_HEAPS-1); uint32_t coherentHeap = memProps->memoryHeapCount; memProps->memoryHeapCount++; // make a new heap that's tiny. If any applications look at heap sizes to determine // viability, they'll dislike the look of this one (the real heaps should be much // bigger). memProps->memoryHeaps[coherentHeap].flags = 0; // not device local memProps->memoryHeaps[coherentHeap].size = 32*1024*1024; // for every coherent memory type, add a non-coherent type first, then // mark the coherent type with our crappy heap uint32_t origCount = memProps->memoryTypeCount; VkMemoryType origTypes[VK_MAX_MEMORY_TYPES]; memcpy(origTypes, memProps->memoryTypes, sizeof(origTypes)); uint32_t newtypeidx = 0; for(uint32_t i=0; i < origCount; i++) { if((origTypes[i].propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0) { // coherent type found. // can we still add a new type without exceeding the max? if(memProps->memoryTypeCount+1 <= VK_MAX_MEMORY_TYPES) { // copy both types from the original type memProps->memoryTypes[newtypeidx] = origTypes[i]; memProps->memoryTypes[newtypeidx+1] = origTypes[i]; // mark first as non-coherent, cached memProps->memoryTypes[newtypeidx].propertyFlags &= ~VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; memProps->memoryTypes[newtypeidx].propertyFlags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT; // point second at bad heap memProps->memoryTypes[newtypeidx+1].heapIndex = coherentHeap; // point both new types at this original type memmap[newtypeidx++] = i; memmap[newtypeidx++] = i; // we added a type memProps->memoryTypeCount++; } else { // can't add a new type, but we can at least repoint this coherent // type at the bad heap to discourage use memProps->memoryTypes[newtypeidx] = origTypes[i]; memProps->memoryTypes[newtypeidx].heapIndex = coherentHeap; memmap[newtypeidx++] = i; } } else { // non-coherent already or non-hostvisible, just copy through memProps->memoryTypes[newtypeidx] = origTypes[i]; memmap[newtypeidx++] = i; } } } <|endoftext|>