text
stringlengths
54
60.6k
<commit_before>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <fstream> #include <string> #include <vector> #include <exception> // StdAir #include <stdair/stdair_demand_types.hpp> #include <stdair/bom/EventStruct.hpp> #include <stdair/bom/EventQueue.hpp> #include <stdair/bom/BookingRequestStruct.hpp> #include <stdair/bom/TravelSolutionStruct.hpp> #include <stdair/service/Logger.hpp> // Distribution #include <simcrs/SIMCRS_Service.hpp> // TRADEMGEN #include <trademgen/TRADEMGEN_Service.hpp> // Airsched #include <airsched/AIRSCHED_Service.hpp> // Dsim #include <dsim/DSIM_Types.hpp> #include <dsim/command/Simulator.hpp> namespace DSIM { // //////////////////////////////////////////////////////////////////// void Simulator::simulate (SIMCRS::SIMCRS_Service& ioSIMCRS_Service, TRADEMGEN::TRADEMGEN_Service& ioTRADEMGEN_Service) { try { // DEBUG STDAIR_LOG_DEBUG ("The simulation is starting"); // ///////////////////////////////////////////////////// // Event queue stdair::EventQueue lEventQueue; /** Initialisation step. <br>Generate the first event for each demand stream. */ ioTRADEMGEN_Service.generateFirstRequests (lEventQueue); /** (Boost) progress display (current number of events, total number of events) for every demand stream. */ stdair::ProgressDisplayMap_T lProgressDisplays; lEventQueue.initProgressDisplays (lProgressDisplays); /** Main loop. <ul> <li>Pop a request and get its associated type/demand stream.</li> <li>Generate the next request for the same type/demand stream.</li> </ul> */ stdair::Count_T eventIdx = 1; while (lEventQueue.isQueueDone() == false) { // Get the next event from the event queue stdair::EventStruct& lEventStruct = lEventQueue.popEvent (); // Extract the corresponding demand/booking request const stdair::BookingRequestStruct& lPoppedRequest = lEventStruct.getBookingRequest (); // DEBUG STDAIR_LOG_DEBUG ("[" << eventIdx << "] Poped booking request: '" << lPoppedRequest.describe() << "'."); // Play booking request playBookingRequest (ioSIMCRS_Service, lPoppedRequest); // Retrieve the corresponding demand stream const stdair::DemandStreamKeyStr_T& lDemandStreamKey = lEventStruct.getDemandStreamKey (); // Assess whether more events should be generated for that // demand stream bool stillHavingRequestsToBeGenerated = ioTRADEMGEN_Service. stillHavingRequestsToBeGenerated (lDemandStreamKey); // Retrieve, from the demand stream, the total number of events // to be generated const stdair::NbOfRequests_T& lNbOfRequests = ioTRADEMGEN_Service. getTotalNumberOfRequestsToBeGenerated (lDemandStreamKey); // DEBUG STDAIR_LOG_DEBUG ("=> [" << lDemandStreamKey << "] is now processed. " << "Still generate events for that demand stream? " << stillHavingRequestsToBeGenerated); // If there are still events to be generated for that demand // stream, generate and add them to the event queue if (stillHavingRequestsToBeGenerated) { stdair::BookingRequestPtr_T lNextRequest_ptr = ioTRADEMGEN_Service.generateNextRequest (lDemandStreamKey); assert (lNextRequest_ptr != NULL); // Sanity check const stdair::Duration_T lDuration = lNextRequest_ptr->getRequestDateTime() - lPoppedRequest.getRequestDateTime(); if (lDuration.total_milliseconds() < 0) { STDAIR_LOG_ERROR ("[" << lDemandStreamKey << "] The date-time of the generated event (" << lNextRequest_ptr->getRequestDateTime() << ") is lower than the date-time " << "of the current event (" << lPoppedRequest.getRequestDateTime() << ")"); assert (false); } // stdair::EventStruct lNextEventStruct (stdair::EventType::BKG_REQ, lDemandStreamKey, lNextRequest_ptr); /** Note that when adding an event in the event queue, the former can be altered. It happends when an event already exists in the event queue with exactly the same date-time stamp. In that case, the date-time stamp is altered for the newly added event, so that the unicity on the date-time stamp can be guaranteed. */ lEventQueue.addEvent (lNextEventStruct); // DEBUG STDAIR_LOG_DEBUG ("[" << lDemandStreamKey << "] Added request: '" << lNextRequest_ptr->describe() << "'. Is queue done? " << lEventQueue.isQueueDone()); } /** Remove the last used event, so that, at any given moment, the queue keeps only the active events. */ lEventQueue.eraseLastUsedEvent (); // Iterate ++eventIdx; } // DEBUG STDAIR_LOG_DEBUG ("The simulation has ended"); } catch (const std::exception& lStdError) { STDAIR_LOG_ERROR ("Error: " << lStdError.what()); throw SimulationException(); } } // //////////////////////////////////////////////////////////////////// void Simulator:: playBookingRequest (SIMCRS::SIMCRS_Service& ioSIMCRS_Service, const stdair::BookingRequestStruct& iBookingRequest) { // Retrieve a list of travel solutions corresponding the given // booking request. const stdair::SegmentPathList_T& lSegmentPathList = ioSIMCRS_Service.calculateSegmentPathList (iBookingRequest); if (lSegmentPathList.empty() == false) { // Get the fare quote for each travel solution. stdair::TravelSolutionList_T lTravelSolutionList = ioSIMCRS_Service.fareQuote (iBookingRequest, lSegmentPathList); // Get the availability for each travel solution. ioSIMCRS_Service.calculateAvailability (lTravelSolutionList); // Hardcode a travel solution choice. stdair::TravelSolutionList_T::const_iterator itTS = lTravelSolutionList.begin(); const stdair::TravelSolutionStruct& lChosenTS = *itTS; // DEBUG STDAIR_LOG_DEBUG ("Chosen TS: " << lChosenTS << "\n"); // Make a sale. const stdair::NbOfSeats_T& lPartySize = iBookingRequest.getPartySize(); ioSIMCRS_Service.sell (lChosenTS, lPartySize); } else { // DEBUG STDAIR_LOG_DEBUG ("No travel solution has been found/chosen."); } } } <commit_msg>[DSim] Updated the code for the new Discrete Event related StdAir code.<commit_after>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <fstream> #include <string> #include <vector> #include <exception> // StdAir #include <stdair/stdair_demand_types.hpp> #include <stdair/bom/EventStruct.hpp> #include <stdair/bom/EventQueue.hpp> #include <stdair/bom/BookingRequestStruct.hpp> #include <stdair/bom/TravelSolutionStruct.hpp> #include <stdair/service/Logger.hpp> // Distribution #include <simcrs/SIMCRS_Service.hpp> // TRADEMGEN #include <trademgen/TRADEMGEN_Service.hpp> // Airsched #include <airsched/AIRSCHED_Service.hpp> // Dsim #include <dsim/DSIM_Types.hpp> #include <dsim/command/Simulator.hpp> namespace DSIM { // //////////////////////////////////////////////////////////////////// void Simulator::simulate (SIMCRS::SIMCRS_Service& ioSIMCRS_Service, TRADEMGEN::TRADEMGEN_Service& ioTRADEMGEN_Service) { try { // DEBUG STDAIR_LOG_DEBUG ("The simulation is starting"); /** Initialisation step. <br>Generate the first event for each demand stream. */ ioTRADEMGEN_Service.generateFirstRequests(); /** (Boost) progress display (current number of events, total number of events) for every demand stream. */ stdair::ProgressDisplayMap_T lProgressDisplays; ioTRADEMGEN_Service.initProgressDisplays (lProgressDisplays); /** Main loop. <ul> <li>Pop a request and get its associated type/demand stream.</li> <li>Generate the next request for the same type/demand stream.</li> </ul> */ stdair::Count_T eventIdx = 1; while (ioTRADEMGEN_Service.isQueueDone() == false) { // Get the next event from the event queue const stdair::EventStruct& lEventStruct= ioTRADEMGEN_Service.popEvent(); // Extract the corresponding demand/booking request const stdair::BookingRequestStruct& lPoppedRequest = lEventStruct.getBookingRequest (); // DEBUG STDAIR_LOG_DEBUG ("[" << eventIdx << "] Poped booking request: '" << lPoppedRequest.describe() << "'."); // Play booking request playBookingRequest (ioSIMCRS_Service, lPoppedRequest); // Retrieve the corresponding demand stream const stdair::DemandStreamKeyStr_T& lDemandStreamKey = lEventStruct.getDemandStreamKey (); // Assess whether more events should be generated for that // demand stream bool stillHavingRequestsToBeGenerated = ioTRADEMGEN_Service. stillHavingRequestsToBeGenerated (lDemandStreamKey); // Retrieve, from the demand stream, the total number of events // to be generated const stdair::NbOfRequests_T& lNbOfRequests = ioTRADEMGEN_Service. getTotalNumberOfRequestsToBeGenerated (lDemandStreamKey); // DEBUG STDAIR_LOG_DEBUG ("=> [" << lDemandStreamKey << "] is now processed. " << "Still generate events for that demand stream? " << stillHavingRequestsToBeGenerated); // If there are still events to be generated for that demand // stream, generate and add them to the event queue if (stillHavingRequestsToBeGenerated) { stdair::BookingRequestPtr_T lNextRequest_ptr = ioTRADEMGEN_Service.generateNextRequest (lDemandStreamKey); assert (lNextRequest_ptr != NULL); // Sanity check const stdair::Duration_T lDuration = lNextRequest_ptr->getRequestDateTime() - lPoppedRequest.getRequestDateTime(); if (lDuration.total_milliseconds() < 0) { STDAIR_LOG_ERROR ("[" << lDemandStreamKey << "] The date-time of the generated event (" << lNextRequest_ptr->getRequestDateTime() << ") is lower than the date-time " << "of the current event (" << lPoppedRequest.getRequestDateTime() << ")"); assert (false); } // stdair::EventStruct lNextEventStruct (stdair::EventType::BKG_REQ, lDemandStreamKey, lNextRequest_ptr); /** Note that when adding an event in the event queue, the former can be altered. It happends when an event already exists in the event queue with exactly the same date-time stamp. In that case, the date-time stamp is altered for the newly added event, so that the unicity on the date-time stamp can be guaranteed. */ ioTRADEMGEN_Service.addEvent (lNextEventStruct); // DEBUG STDAIR_LOG_DEBUG ("[" << lDemandStreamKey << "] Added request: '" << lNextRequest_ptr->describe() << "'. Is queue done? " << ioTRADEMGEN_Service.isQueueDone()); } // Iterate ++eventIdx; } // DEBUG STDAIR_LOG_DEBUG ("The simulation has ended"); } catch (const std::exception& lStdError) { STDAIR_LOG_ERROR ("Error: " << lStdError.what()); throw SimulationException(); } } // //////////////////////////////////////////////////////////////////// void Simulator:: playBookingRequest (SIMCRS::SIMCRS_Service& ioSIMCRS_Service, const stdair::BookingRequestStruct& iBookingRequest) { // Retrieve a list of travel solutions corresponding the given // booking request. const stdair::SegmentPathList_T& lSegmentPathList = ioSIMCRS_Service.calculateSegmentPathList (iBookingRequest); if (lSegmentPathList.empty() == false) { // Get the fare quote for each travel solution. stdair::TravelSolutionList_T lTravelSolutionList = ioSIMCRS_Service.fareQuote (iBookingRequest, lSegmentPathList); // Get the availability for each travel solution. ioSIMCRS_Service.calculateAvailability (lTravelSolutionList); // Hardcode a travel solution choice. stdair::TravelSolutionList_T::const_iterator itTS = lTravelSolutionList.begin(); const stdair::TravelSolutionStruct& lChosenTS = *itTS; // DEBUG STDAIR_LOG_DEBUG ("Chosen TS: " << lChosenTS << "\n"); // Make a sale. const stdair::NbOfSeats_T& lPartySize = iBookingRequest.getPartySize(); ioSIMCRS_Service.sell (lChosenTS, lPartySize); } else { // DEBUG STDAIR_LOG_DEBUG ("No travel solution has been found/chosen."); } } } <|endoftext|>
<commit_before>#ifndef INTEGER_RANGE_HPP #define INTEGER_RANGE_HPP #include <boost/assert.hpp> #include <type_traits> #include <cstdint> namespace osrm { namespace util { template <typename Integer> class range { private: const Integer last; Integer iter; public: range(Integer start, Integer end) noexcept : last(end), iter(start) { BOOST_ASSERT_MSG(start <= end, "backwards counting ranges not suppoted"); static_assert(std::is_integral<Integer>::value, "range type must be integral"); } // Iterable functions const range &begin() const noexcept { return *this; } const range &end() const noexcept { return *this; } Integer front() const noexcept { return iter; } Integer back() const noexcept { return last - 1; } std::size_t size() const noexcept { return static_cast<std::size_t>(last - iter); } // Iterator functions bool operator!=(const range &) const noexcept { return iter < last; } void operator++() noexcept { ++iter; } Integer operator*() const noexcept { return iter; } }; // convenience function to construct an integer range with type deduction template <typename Integer> range<Integer> irange(const Integer first, const Integer last, typename std::enable_if<std::is_integral<Integer>::value>::type * = 0) noexcept { return range<Integer>(first, last); } } } #endif // INTEGER_RANGE_HPP <commit_msg>Documents why not to use boost::irange in favor of our hand-written irange<commit_after>#ifndef INTEGER_RANGE_HPP #define INTEGER_RANGE_HPP #include <boost/assert.hpp> #include <type_traits> #include <cstdint> namespace osrm { namespace util { // Warning: do not try to replace this with Boost's irange, as it is broken on Boost 1.55: // auto r = boost::irange<unsigned int>(0, 15); // std::cout << r.size() << std::endl; // results in -4294967281. Latest Boost versions fix this, but we still support older ones. template <typename Integer> class range { private: const Integer last; Integer iter; public: range(Integer start, Integer end) noexcept : last(end), iter(start) { BOOST_ASSERT_MSG(start <= end, "backwards counting ranges not suppoted"); static_assert(std::is_integral<Integer>::value, "range type must be integral"); } // Iterable functions const range &begin() const noexcept { return *this; } const range &end() const noexcept { return *this; } Integer front() const noexcept { return iter; } Integer back() const noexcept { return last - 1; } std::size_t size() const noexcept { return static_cast<std::size_t>(last - iter); } // Iterator functions bool operator!=(const range &) const noexcept { return iter < last; } void operator++() noexcept { ++iter; } Integer operator*() const noexcept { return iter; } }; // convenience function to construct an integer range with type deduction template <typename Integer> range<Integer> irange(const Integer first, const Integer last, typename std::enable_if<std::is_integral<Integer>::value>::type * = 0) noexcept { return range<Integer>(first, last); } } } #endif // INTEGER_RANGE_HPP <|endoftext|>
<commit_before>#include "indexer/feature_visibility.hpp" #include "indexer/classificator.hpp" #include "indexer/drawing_rules.hpp" #include "indexer/scales.hpp" #include "base/assert.hpp" #include "std/array.hpp" template <class ToDo> typename ToDo::ResultType Classificator::ProcessObjects(uint32_t type, ToDo & toDo) const { typedef typename ToDo::ResultType ResultType; ResultType res = ResultType(); // default initialization ClassifObject const * p = GetObject(type); if (p != &m_root) { ASSERT(p, ()); toDo(p, res); } return res; } ClassifObject const * Classificator::GetObject(uint32_t type) const { ClassifObject const * p = &m_root; uint8_t i = 0; // get the final ClassifObject uint8_t v; while (ftype::GetValue(type, i, v)) { ++i; p = p->GetObject(v); } return p; } string Classificator::GetFullObjectName(uint32_t type) const { ClassifObject const * p = &m_root; uint8_t i = 0; string s; // get the final ClassifObject uint8_t v; while (ftype::GetValue(type, i, v)) { ++i; p = p->GetObject(v); s = s + p->GetName() + '|'; } return s; } namespace feature { namespace { class DrawRuleGetter { int m_scale; EGeomType m_ft; drule::KeysT & m_keys; public: DrawRuleGetter(int scale, EGeomType ft, drule::KeysT & keys) : m_scale(scale), m_ft(ft), m_keys(keys) { } typedef bool ResultType; void operator() (ClassifObject const *) { } bool operator() (ClassifObject const * p, bool & res) { res = true; p->GetSuitable(min(m_scale, scales::GetUpperStyleScale()), m_ft, m_keys); return false; } }; } pair<int, bool> GetDrawRule(TypesHolder const & types, int level, drule::KeysT & keys) { ASSERT ( keys.empty(), () ); Classificator const & c = classif(); DrawRuleGetter doRules(level, types.GetGeoType(), keys); for (uint32_t t : types) (void)c.ProcessObjects(t, doRules); return make_pair(types.GetGeoType(), types.Has(c.GetCoastType())); } void GetDrawRule(vector<uint32_t> const & types, int level, int geoType, drule::KeysT & keys) { ASSERT ( keys.empty(), () ); Classificator const & c = classif(); DrawRuleGetter doRules(level, EGeomType(geoType), keys); for (uint32_t t : types) (void)c.ProcessObjects(t, doRules); } void FilterRulesByRuntimeSelector(FeatureType const & f, int zoomLevel, drule::KeysT & keys) { keys.erase_if([&f, zoomLevel](drule::Key const & key)->bool { drule::BaseRule const * const rule = drule::rules().Find(key); if (rule == nullptr) return true; return !rule->TestFeature(f, zoomLevel); }); } namespace { class IsDrawableChecker { int m_scale; public: IsDrawableChecker(int scale) : m_scale(scale) {} typedef bool ResultType; void operator() (ClassifObject const *) {} bool operator() (ClassifObject const * p, bool & res) { if (p->IsDrawable(m_scale)) { res = true; return true; } return false; } }; class IsDrawableLikeChecker { EGeomType m_geomType; bool m_emptyName; public: IsDrawableLikeChecker(EGeomType geomType, bool emptyName = false) : m_geomType(geomType), m_emptyName(emptyName) { } typedef bool ResultType; void operator() (ClassifObject const *) {} bool operator() (ClassifObject const * p, bool & res) { if (p->IsDrawableLike(m_geomType, m_emptyName)) { res = true; return true; } return false; } }; class IsDrawableRulesChecker { int m_scale; EGeomType m_ft; bool m_arr[3]; public: IsDrawableRulesChecker(int scale, EGeomType ft, int rules) : m_scale(scale), m_ft(ft) { m_arr[0] = rules & RULE_CAPTION; m_arr[1] = rules & RULE_PATH_TEXT; m_arr[2] = rules & RULE_SYMBOL; } typedef bool ResultType; void operator() (ClassifObject const *) {} bool operator() (ClassifObject const * p, bool & res) { drule::KeysT keys; p->GetSuitable(m_scale, m_ft, keys); for (auto const & k : keys) { if ((m_arr[0] && k.m_type == drule::caption) || (m_arr[1] && k.m_type == drule::pathtext) || (m_arr[2] && k.m_type == drule::symbol)) { res = true; return true; } } return false; } }; bool HasRoutingExceptionType(uint32_t t) { static const uint32_t s = classif().GetTypeByPath({ "route", "shuttle_train" }); return s == t; } /// Add here all exception classificator types: needed for algorithms, /// but don't have drawing rules. /// See also ftypes_matcher.cpp, IsInvisibleIndexedChecker. bool TypeAlwaysExists(uint32_t type, EGeomType g = GEOM_UNDEFINED) { if (!classif().IsTypeValid(type)) return false; static const uint32_t roundabout = classif().GetTypeByPath({ "junction", "roundabout" }); static const uint32_t hwtag = classif().GetTypeByPath({ "hwtag" }); static const uint32_t psurface = classif().GetTypeByPath({ "psurface" }); static const uint32_t wheelchair = classif().GetTypeByPath({ "wheelchair" }); static const uint32_t sponsored = classif().GetTypeByPath({ "sponsored" }); static const uint32_t event = classif().GetTypeByPath({ "event" }); static const uint32_t internet = classif().GetTypeByPath({ "internet_access" }); // Caching type length to exclude generic [wheelchair]. uint8_t const typeLength = ftype::GetLevel(type); if (g == GEOM_LINE || g == GEOM_UNDEFINED) { if (roundabout == type) return true; if (HasRoutingExceptionType(type)) return true; ftype::TruncValue(type, 1); if (hwtag == type || psurface == type) return true; } // We're okay with the type being already truncated above. ftype::TruncValue(type, 1); if (wheelchair == type && typeLength == 2) return true; if (sponsored == type || internet == type || event == type) return true; return false; } } bool RequireGeometryInIndex(FeatureBase const & f) { TypesHolder const types(f); for (uint32_t t : types) { if (HasRoutingExceptionType(t)) return true; } return false; } bool IsDrawableAny(uint32_t type) { return (TypeAlwaysExists(type) || classif().GetObject(type)->IsDrawableAny()); } bool IsDrawableLike(vector<uint32_t> const & types, EGeomType geomType) { Classificator const & c = classif(); IsDrawableLikeChecker doCheck(geomType); for (uint32_t t : types) if (c.ProcessObjects(t, doCheck)) return true; return false; } bool IsDrawableForIndex(FeatureBase const & f, int level) { return IsDrawableForIndexGeometryOnly(f, level) && IsDrawableForIndexClassifOnly(f, level); } bool IsDrawableForIndexGeometryOnly(FeatureBase const & f, int level) { Classificator const & c = classif(); static uint32_t const buildingPartType = c.GetTypeByPath({"building:part"}); TypesHolder const types(f); if (types.GetGeoType() == GEOM_AREA && !types.Has(c.GetCoastType()) && !types.Has(buildingPartType) && !scales::IsGoodForLevel(level, f.GetLimitRect())) return false; return true; } bool IsDrawableForIndexClassifOnly(FeatureBase const & f, int level) { Classificator const & c = classif(); TypesHolder const types(f); IsDrawableChecker doCheck(level); for (uint32_t t : types) if (c.ProcessObjects(t, doCheck)) return true; return false; } bool RemoveNoDrawableTypes(vector<uint32_t> & types, EGeomType geomType, bool emptyName) { Classificator const & c = classif(); types.erase(remove_if(types.begin(), types.end(), [&] (uint32_t t) { if (TypeAlwaysExists(t, geomType)) return false; IsDrawableLikeChecker doCheck(geomType, emptyName); if (c.ProcessObjects(t, doCheck)) return false; // IsDrawableLikeChecker checks only unique area styles, // so we need to take into account point styles too. if (geomType == GEOM_AREA) { IsDrawableLikeChecker doCheck(GEOM_POINT, emptyName); if (c.ProcessObjects(t, doCheck)) return false; } return true; }), types.end()); return !types.empty(); } int GetMinDrawableScale(FeatureBase const & f) { int const upBound = scales::GetUpperStyleScale(); for (int level = 0; level <= upBound; ++level) if (IsDrawableForIndex(f, level)) return level; return -1; } int GetMinDrawableScaleClassifOnly(FeatureBase const & f) { int const upBound = scales::GetUpperStyleScale(); for (int level = 0; level <= upBound; ++level) if (IsDrawableForIndexClassifOnly(f, level)) return level; return -1; } namespace { void AddRange(pair<int, int> & dest, pair<int, int> const & src) { if (src.first != -1) { ASSERT_GREATER(src.first, -1, ()); ASSERT_GREATER(src.second, -1, ()); dest.first = min(dest.first, src.first); dest.second = max(dest.second, src.second); ASSERT_GREATER(dest.first, -1, ()); ASSERT_GREATER(dest.second, -1, ()); } } class DoGetScalesRange { pair<int, int> m_scales; public: DoGetScalesRange() : m_scales(1000, -1000) {} typedef bool ResultType; void operator() (ClassifObject const *) {} bool operator() (ClassifObject const * p, bool & res) { res = true; AddRange(m_scales, p->GetDrawScaleRange()); return false; } pair<int, int> GetScale() const { return (m_scales.first > m_scales.second ? make_pair(-1, -1) : m_scales); } }; } pair<int, int> GetDrawableScaleRange(uint32_t type) { DoGetScalesRange doGet; (void)classif().ProcessObjects(type, doGet); return doGet.GetScale(); } pair<int, int> GetDrawableScaleRange(TypesHolder const & types) { pair<int, int> res(1000, -1000); for (uint32_t t : types) AddRange(res, GetDrawableScaleRange(t)); return (res.first > res.second ? make_pair(-1, -1) : res); } namespace { bool IsDrawableForRules(TypesHolder const & types, int level, int rules) { Classificator const & c = classif(); IsDrawableRulesChecker doCheck(level, types.GetGeoType(), rules); for (uint32_t t : types) if (c.ProcessObjects(t, doCheck)) return true; return false; } } pair<int, int> GetDrawableScaleRangeForRules(TypesHolder const & types, int rules) { int const upBound = scales::GetUpperStyleScale(); int lowL = -1; for (int level = 0; level <= upBound; ++level) { if (IsDrawableForRules(types, level, rules)) { lowL = level; break; } } if (lowL == -1) return make_pair(-1, -1); int highL = lowL; for (int level = upBound; level > lowL; --level) { if (IsDrawableForRules(types, level, rules)) { highL = level; break; } } return make_pair(lowL, highL); } pair<int, int> GetDrawableScaleRangeForRules(FeatureBase const & f, int rules) { return GetDrawableScaleRangeForRules(TypesHolder(f), rules); } TypeSetChecker::TypeSetChecker(initializer_list<char const *> const & lst) { m_type = classif().GetTypeByPath(lst); m_level = lst.size(); } bool TypeSetChecker::IsEqual(uint32_t type) const { ftype::TruncValue(type, m_level); return (m_type == type); } } // namespace feature <commit_msg>[generator] Disable fake types for lines<commit_after>#include "indexer/feature_visibility.hpp" #include "indexer/classificator.hpp" #include "indexer/drawing_rules.hpp" #include "indexer/scales.hpp" #include "base/assert.hpp" #include "std/array.hpp" template <class ToDo> typename ToDo::ResultType Classificator::ProcessObjects(uint32_t type, ToDo & toDo) const { typedef typename ToDo::ResultType ResultType; ResultType res = ResultType(); // default initialization ClassifObject const * p = GetObject(type); if (p != &m_root) { ASSERT(p, ()); toDo(p, res); } return res; } ClassifObject const * Classificator::GetObject(uint32_t type) const { ClassifObject const * p = &m_root; uint8_t i = 0; // get the final ClassifObject uint8_t v; while (ftype::GetValue(type, i, v)) { ++i; p = p->GetObject(v); } return p; } string Classificator::GetFullObjectName(uint32_t type) const { ClassifObject const * p = &m_root; uint8_t i = 0; string s; // get the final ClassifObject uint8_t v; while (ftype::GetValue(type, i, v)) { ++i; p = p->GetObject(v); s = s + p->GetName() + '|'; } return s; } namespace feature { namespace { class DrawRuleGetter { int m_scale; EGeomType m_ft; drule::KeysT & m_keys; public: DrawRuleGetter(int scale, EGeomType ft, drule::KeysT & keys) : m_scale(scale), m_ft(ft), m_keys(keys) { } typedef bool ResultType; void operator() (ClassifObject const *) { } bool operator() (ClassifObject const * p, bool & res) { res = true; p->GetSuitable(min(m_scale, scales::GetUpperStyleScale()), m_ft, m_keys); return false; } }; } pair<int, bool> GetDrawRule(TypesHolder const & types, int level, drule::KeysT & keys) { ASSERT ( keys.empty(), () ); Classificator const & c = classif(); DrawRuleGetter doRules(level, types.GetGeoType(), keys); for (uint32_t t : types) (void)c.ProcessObjects(t, doRules); return make_pair(types.GetGeoType(), types.Has(c.GetCoastType())); } void GetDrawRule(vector<uint32_t> const & types, int level, int geoType, drule::KeysT & keys) { ASSERT ( keys.empty(), () ); Classificator const & c = classif(); DrawRuleGetter doRules(level, EGeomType(geoType), keys); for (uint32_t t : types) (void)c.ProcessObjects(t, doRules); } void FilterRulesByRuntimeSelector(FeatureType const & f, int zoomLevel, drule::KeysT & keys) { keys.erase_if([&f, zoomLevel](drule::Key const & key)->bool { drule::BaseRule const * const rule = drule::rules().Find(key); if (rule == nullptr) return true; return !rule->TestFeature(f, zoomLevel); }); } namespace { class IsDrawableChecker { int m_scale; public: IsDrawableChecker(int scale) : m_scale(scale) {} typedef bool ResultType; void operator() (ClassifObject const *) {} bool operator() (ClassifObject const * p, bool & res) { if (p->IsDrawable(m_scale)) { res = true; return true; } return false; } }; class IsDrawableLikeChecker { EGeomType m_geomType; bool m_emptyName; public: IsDrawableLikeChecker(EGeomType geomType, bool emptyName = false) : m_geomType(geomType), m_emptyName(emptyName) { } typedef bool ResultType; void operator() (ClassifObject const *) {} bool operator() (ClassifObject const * p, bool & res) { if (p->IsDrawableLike(m_geomType, m_emptyName)) { res = true; return true; } return false; } }; class IsDrawableRulesChecker { int m_scale; EGeomType m_ft; bool m_arr[3]; public: IsDrawableRulesChecker(int scale, EGeomType ft, int rules) : m_scale(scale), m_ft(ft) { m_arr[0] = rules & RULE_CAPTION; m_arr[1] = rules & RULE_PATH_TEXT; m_arr[2] = rules & RULE_SYMBOL; } typedef bool ResultType; void operator() (ClassifObject const *) {} bool operator() (ClassifObject const * p, bool & res) { drule::KeysT keys; p->GetSuitable(m_scale, m_ft, keys); for (auto const & k : keys) { if ((m_arr[0] && k.m_type == drule::caption) || (m_arr[1] && k.m_type == drule::pathtext) || (m_arr[2] && k.m_type == drule::symbol)) { res = true; return true; } } return false; } }; bool HasRoutingExceptionType(uint32_t t) { static const uint32_t s = classif().GetTypeByPath({ "route", "shuttle_train" }); return s == t; } /// Add here all exception classificator types: needed for algorithms, /// but don't have drawing rules. /// See also ftypes_matcher.cpp, IsInvisibleIndexedChecker. bool TypeAlwaysExists(uint32_t type, EGeomType g = GEOM_UNDEFINED) { if (!classif().IsTypeValid(type)) return false; static const uint32_t roundabout = classif().GetTypeByPath({ "junction", "roundabout" }); static const uint32_t hwtag = classif().GetTypeByPath({ "hwtag" }); static const uint32_t psurface = classif().GetTypeByPath({ "psurface" }); static const uint32_t wheelchair = classif().GetTypeByPath({ "wheelchair" }); static const uint32_t sponsored = classif().GetTypeByPath({ "sponsored" }); static const uint32_t event = classif().GetTypeByPath({ "event" }); static const uint32_t internet = classif().GetTypeByPath({ "internet_access" }); // Caching type length to exclude generic [wheelchair]. uint8_t const typeLength = ftype::GetLevel(type); if (g == GEOM_LINE || g == GEOM_UNDEFINED) { if (roundabout == type) return true; if (HasRoutingExceptionType(type)) return true; ftype::TruncValue(type, 1); if (hwtag == type || psurface == type) return true; } // We're okay with the type being already truncated above. ftype::TruncValue(type, 1); if (wheelchair == type && typeLength == 2) return true; if (g != GEOM_LINE) { if (sponsored == type || internet == type || event == type) return true; } return false; } } bool RequireGeometryInIndex(FeatureBase const & f) { TypesHolder const types(f); for (uint32_t t : types) { if (HasRoutingExceptionType(t)) return true; } return false; } bool IsDrawableAny(uint32_t type) { return (TypeAlwaysExists(type) || classif().GetObject(type)->IsDrawableAny()); } bool IsDrawableLike(vector<uint32_t> const & types, EGeomType geomType) { Classificator const & c = classif(); IsDrawableLikeChecker doCheck(geomType); for (uint32_t t : types) if (c.ProcessObjects(t, doCheck)) return true; return false; } bool IsDrawableForIndex(FeatureBase const & f, int level) { return IsDrawableForIndexGeometryOnly(f, level) && IsDrawableForIndexClassifOnly(f, level); } bool IsDrawableForIndexGeometryOnly(FeatureBase const & f, int level) { Classificator const & c = classif(); static uint32_t const buildingPartType = c.GetTypeByPath({"building:part"}); TypesHolder const types(f); if (types.GetGeoType() == GEOM_AREA && !types.Has(c.GetCoastType()) && !types.Has(buildingPartType) && !scales::IsGoodForLevel(level, f.GetLimitRect())) return false; return true; } bool IsDrawableForIndexClassifOnly(FeatureBase const & f, int level) { Classificator const & c = classif(); TypesHolder const types(f); IsDrawableChecker doCheck(level); for (uint32_t t : types) if (c.ProcessObjects(t, doCheck)) return true; return false; } bool RemoveNoDrawableTypes(vector<uint32_t> & types, EGeomType geomType, bool emptyName) { Classificator const & c = classif(); types.erase(remove_if(types.begin(), types.end(), [&] (uint32_t t) { if (TypeAlwaysExists(t, geomType)) return false; IsDrawableLikeChecker doCheck(geomType, emptyName); if (c.ProcessObjects(t, doCheck)) return false; // IsDrawableLikeChecker checks only unique area styles, // so we need to take into account point styles too. if (geomType == GEOM_AREA) { IsDrawableLikeChecker doCheck(GEOM_POINT, emptyName); if (c.ProcessObjects(t, doCheck)) return false; } return true; }), types.end()); return !types.empty(); } int GetMinDrawableScale(FeatureBase const & f) { int const upBound = scales::GetUpperStyleScale(); for (int level = 0; level <= upBound; ++level) if (IsDrawableForIndex(f, level)) return level; return -1; } int GetMinDrawableScaleClassifOnly(FeatureBase const & f) { int const upBound = scales::GetUpperStyleScale(); for (int level = 0; level <= upBound; ++level) if (IsDrawableForIndexClassifOnly(f, level)) return level; return -1; } namespace { void AddRange(pair<int, int> & dest, pair<int, int> const & src) { if (src.first != -1) { ASSERT_GREATER(src.first, -1, ()); ASSERT_GREATER(src.second, -1, ()); dest.first = min(dest.first, src.first); dest.second = max(dest.second, src.second); ASSERT_GREATER(dest.first, -1, ()); ASSERT_GREATER(dest.second, -1, ()); } } class DoGetScalesRange { pair<int, int> m_scales; public: DoGetScalesRange() : m_scales(1000, -1000) {} typedef bool ResultType; void operator() (ClassifObject const *) {} bool operator() (ClassifObject const * p, bool & res) { res = true; AddRange(m_scales, p->GetDrawScaleRange()); return false; } pair<int, int> GetScale() const { return (m_scales.first > m_scales.second ? make_pair(-1, -1) : m_scales); } }; } pair<int, int> GetDrawableScaleRange(uint32_t type) { DoGetScalesRange doGet; (void)classif().ProcessObjects(type, doGet); return doGet.GetScale(); } pair<int, int> GetDrawableScaleRange(TypesHolder const & types) { pair<int, int> res(1000, -1000); for (uint32_t t : types) AddRange(res, GetDrawableScaleRange(t)); return (res.first > res.second ? make_pair(-1, -1) : res); } namespace { bool IsDrawableForRules(TypesHolder const & types, int level, int rules) { Classificator const & c = classif(); IsDrawableRulesChecker doCheck(level, types.GetGeoType(), rules); for (uint32_t t : types) if (c.ProcessObjects(t, doCheck)) return true; return false; } } pair<int, int> GetDrawableScaleRangeForRules(TypesHolder const & types, int rules) { int const upBound = scales::GetUpperStyleScale(); int lowL = -1; for (int level = 0; level <= upBound; ++level) { if (IsDrawableForRules(types, level, rules)) { lowL = level; break; } } if (lowL == -1) return make_pair(-1, -1); int highL = lowL; for (int level = upBound; level > lowL; --level) { if (IsDrawableForRules(types, level, rules)) { highL = level; break; } } return make_pair(lowL, highL); } pair<int, int> GetDrawableScaleRangeForRules(FeatureBase const & f, int rules) { return GetDrawableScaleRangeForRules(TypesHolder(f), rules); } TypeSetChecker::TypeSetChecker(initializer_list<char const *> const & lst) { m_type = classif().GetTypeByPath(lst); m_level = lst.size(); } bool TypeSetChecker::IsEqual(uint32_t type) const { ftype::TruncValue(type, m_level); return (m_type == type); } } // namespace feature <|endoftext|>
<commit_before>#include "SQLiteQuery.h" /** * The function to call when running the 'index' command. */ SQLiteQuery::SQLiteQuery(char * indexdir, EMatrix * ematrix) : IndexQuery(indexdir, ematrix) { } /** * Destructor */ SQLiteQuery::~SQLiteQuery() { } /** * Performs the indexing. */ void SQLiteQuery::run(int x_coord, int y_coord, float score) { int i; char q[2048]; sqlite3_stmt *cluster_select_stmt; int rc; int j, k, cluster_num, num_clusters, num_missing, num_samples; char * samples; float cv; // Iterate through the directories. for (i = 100; i >= 0; i--) { // If a threshold is set then don't examine indexes below the requested value. if (i / 100.0 <= score) { continue; } char dirname[1024]; char dbname[1024]; if (i > 0) { sprintf(dirname, "./%s/%03d", indexdir, i); sprintf(dbname, "%s/%03d.db", dirname, i); } else { sprintf(dirname, "./%s/nan", indexdir); sprintf(dbname, "%s/nan.db", dirname); } // Open the output directory. DIR * dir; dir = opendir(dirname); if (!dir) { fprintf(stderr, "WARNING: The output directory, %s, is missing. skipping.\n", dirname); continue; } // Each directory has it's own SQLite database. sqlite3 * db; if (sqlite3_open(dbname, &db)){ fprintf(stderr, "ERROR: Can't open SQLite database: %s\n", sqlite3_errmsg(db)); exit(-1); } // Build the SQL query for filtering. sprintf(q, "%s", "\ SELECT gene1, gene2, num_clusters, cluster_num, num_missing, \ num_samples, score, samples \ FROM clusters C WHERE (1=1) "); if (x_coord) { sprintf(q, "%s AND (gene1 = %d OR gene2 = %d) ", q, x_coord, x_coord); } if (y_coord) { sprintf(q, "%s AND (gene1 = %d OR gene2 = %d) ", q, y_coord, y_coord); } if (score) { sprintf(q, "%s AND (score >= %f OR score <= -%f) ", q, score, score); } // sprintf(q, "%s ORDER BY score DESC;", q); sprintf(q, "%s;", q); // printf("%s\n", q); // Prepare the query for execution. rc = sqlite3_prepare_v2(db, q, 2048, &cluster_select_stmt, NULL); if (rc != SQLITE_OK) { fprintf(stderr, "Failed to prepare cluster select statement: %s\n", sqlite3_errmsg(db)); exit(-1); } // Iterate through the results of the query rc = sqlite3_step(cluster_select_stmt); while (rc == SQLITE_ROW) { // Get the values for this row in the result set. j = sqlite3_column_int(cluster_select_stmt, 0); k = sqlite3_column_int(cluster_select_stmt, 1); num_clusters = sqlite3_column_int(cluster_select_stmt, 2); cluster_num = sqlite3_column_int(cluster_select_stmt, 3); num_missing = sqlite3_column_int(cluster_select_stmt, 4); num_samples = sqlite3_column_int(cluster_select_stmt, 5); cv = sqlite3_column_double(cluster_select_stmt, 6); samples = (char *) sqlite3_column_text(cluster_select_stmt, 7); // Write the line to output. printf("%s\t%s\t%0.8f\tco\t%d\t%d\t%d\t%d\t%s\n", ematrix->getGene(j), ematrix->getGene(k), cv, cluster_num, num_clusters, num_samples, num_missing, samples); // Get the next row. rc = sqlite3_step(cluster_select_stmt); } // Finalize the statement. sqlite3_finalize(cluster_select_stmt); // Close the database. sqlite3_close(db); } } <commit_msg>Change to error messaging<commit_after>#include "SQLiteQuery.h" /** * The function to call when running the 'index' command. */ SQLiteQuery::SQLiteQuery(char * indexdir, EMatrix * ematrix) : IndexQuery(indexdir, ematrix) { } /** * Destructor */ SQLiteQuery::~SQLiteQuery() { } /** * Performs the indexing. */ void SQLiteQuery::run(int x_coord, int y_coord, float score) { int i; char q[2048]; sqlite3_stmt *cluster_select_stmt; int rc; int j, k, cluster_num, num_clusters, num_missing, num_samples; char * samples; float cv; // Iterate through the directories. for (i = 100; i >= 0; i--) { // If a threshold is set then don't examine indexes below the requested value. if (i / 100.0 <= score) { continue; } char dirname[1024]; char dbname[1024]; if (i > 0) { sprintf(dirname, "./%s/%03d", indexdir, i); sprintf(dbname, "%s/%03d.db", dirname, i); } else { sprintf(dirname, "./%s/nan", indexdir); sprintf(dbname, "%s/nan.db", dirname); } // Open the output directory. DIR * dir; dir = opendir(dirname); if (!dir) { fprintf(stderr, "WARNING: The output directory, %s, is missing. skipping.\n", dirname); continue; } // Each directory has it's own SQLite database. sqlite3 * db; if (sqlite3_open(dbname, &db)){ fprintf(stderr, "ERROR: Can't open SQLite database: %s\n", sqlite3_errmsg(db)); exit(-1); } // Build the SQL query for filtering. sprintf(q, "%s", "\ SELECT gene1, gene2, num_clusters, cluster_num, num_missing, \ num_samples, score, samples \ FROM clusters C WHERE (1=1) "); if (x_coord) { sprintf(q, "%s AND (gene1 = %d OR gene2 = %d) ", q, x_coord, x_coord); } if (y_coord) { sprintf(q, "%s AND (gene1 = %d OR gene2 = %d) ", q, y_coord, y_coord); } if (score) { sprintf(q, "%s AND (score >= %f OR score <= -%f) ", q, score, score); } // sprintf(q, "%s ORDER BY score DESC;", q); sprintf(q, "%s;", q); // printf("%s\n", q); // Prepare the query for execution. rc = sqlite3_prepare_v2(db, q, 2048, &cluster_select_stmt, NULL); if (rc != SQLITE_OK) { fprintf(stderr, "Failed to prepare cluster select statement for index %s: %s\n", dirname, sqlite3_errmsg(db)); exit(-1); } // Iterate through the results of the query rc = sqlite3_step(cluster_select_stmt); while (rc == SQLITE_ROW) { // Get the values for this row in the result set. j = sqlite3_column_int(cluster_select_stmt, 0); k = sqlite3_column_int(cluster_select_stmt, 1); num_clusters = sqlite3_column_int(cluster_select_stmt, 2); cluster_num = sqlite3_column_int(cluster_select_stmt, 3); num_missing = sqlite3_column_int(cluster_select_stmt, 4); num_samples = sqlite3_column_int(cluster_select_stmt, 5); cv = sqlite3_column_double(cluster_select_stmt, 6); samples = (char *) sqlite3_column_text(cluster_select_stmt, 7); // Write the line to output. printf("%s\t%s\t%0.8f\tco\t%d\t%d\t%d\t%d\t%s\n", ematrix->getGene(j), ematrix->getGene(k), cv, cluster_num, num_clusters, num_samples, num_missing, samples); // Get the next row. rc = sqlite3_step(cluster_select_stmt); } // Finalize the statement. sqlite3_finalize(cluster_select_stmt); // Close the database. sqlite3_close(db); } } <|endoftext|>
<commit_before>/** * @file llfloatermap.cpp * @brief The "mini-map" or radar in the upper right part of the screen. * * $LicenseInfo:firstyear=2001&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" // self include #include "llfloatermap.h" // Library includes #include "llfloaterreg.h" #include "llfontgl.h" #include "llglheaders.h" // Viewer includes #include "llagentcamera.h" #include "llviewercontrol.h" #include "llnetmap.h" #include "lltracker.h" #include "llviewercamera.h" #include "lldraghandle.h" #include "lltextbox.h" #include "llviewermenu.h" // // Constants // // The minor cardinal direction labels are hidden if their height is more // than this proportion of the map. const F32 MAP_MINOR_DIR_THRESHOLD = 0.07f; const S32 MAP_PADDING_LEFT = 0; const S32 MAP_PADDING_TOP = 2; const S32 MAP_PADDING_RIGHT = 2; const S32 MAP_PADDING_BOTTOM = 0; // // Member functions // LLFloaterMap::LLFloaterMap(const LLSD& key) : LLFloater(key), mPopupMenu(NULL), mTextBoxEast(NULL), mTextBoxNorth(NULL), mTextBoxWest(NULL), mTextBoxSouth(NULL), mTextBoxSouthEast(NULL), mTextBoxNorthEast(NULL), mTextBoxNorthWest(NULL), mTextBoxSouthWest(NULL), mMap(NULL) { //Called from floater reg: LLUICtrlFactory::getInstance()->buildFloater(this, "floater_map.xml", FALSE); } LLFloaterMap::~LLFloaterMap() { } BOOL LLFloaterMap::postBuild() { mMap = getChild<LLNetMap>("Net Map"); mMap->setScale(gSavedSettings.getF32("MiniMapScale")); mMap->setToolTipMsg(getString("ToolTipMsg")); sendChildToBack(mMap); mTextBoxNorth = getChild<LLTextBox> ("floater_map_north"); mTextBoxEast = getChild<LLTextBox> ("floater_map_east"); mTextBoxWest = getChild<LLTextBox> ("floater_map_west"); mTextBoxSouth = getChild<LLTextBox> ("floater_map_south"); mTextBoxSouthEast = getChild<LLTextBox> ("floater_map_southeast"); mTextBoxNorthEast = getChild<LLTextBox> ("floater_map_northeast"); mTextBoxSouthWest = getChild<LLTextBox> ("floater_map_southwest"); mTextBoxNorthWest = getChild<LLTextBox> ("floater_map_northwest"); LLUICtrl::CommitCallbackRegistry::ScopedRegistrar registrar; registrar.add("Minimap.Zoom", boost::bind(&LLFloaterMap::handleZoom, this, _2)); registrar.add("Minimap.Tracker", boost::bind(&LLFloaterMap::handleStopTracking, this, _2)); mPopupMenu = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_mini_map.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance()); if (mPopupMenu && !LLTracker::isTracking(0)) { mPopupMenu->setItemEnabled ("Stop Tracking", false); } stretchMiniMap(getRect().getWidth() - MAP_PADDING_LEFT - MAP_PADDING_RIGHT ,getRect().getHeight() - MAP_PADDING_TOP - MAP_PADDING_BOTTOM); updateMinorDirections(); // Get the drag handle all the way in back sendChildToBack(getDragHandle()); setIsChrome(TRUE); getDragHandle()->setTitleVisible(TRUE); // keep onscreen gFloaterView->adjustToFitScreen(this, FALSE); return TRUE; } BOOL LLFloaterMap::handleDoubleClick( S32 x, S32 y, MASK mask ) { LLFloaterReg::showInstance("world_map"); return TRUE; } BOOL LLFloaterMap::handleRightMouseDown(S32 x, S32 y, MASK mask) { if (mPopupMenu) { mPopupMenu->buildDrawLabels(); mPopupMenu->updateParent(LLMenuGL::sMenuContainer); LLMenuGL::showPopup(this, mPopupMenu, x, y); } return TRUE; } void LLFloaterMap::setDirectionPos( LLTextBox* text_box, F32 rotation ) { // Rotation is in radians. // Rotation of 0 means x = 1, y = 0 on the unit circle. F32 map_half_height = (F32)(getRect().getHeight() / 2) - getHeaderHeight()/2; F32 map_half_width = (F32)(getRect().getWidth() / 2) ; F32 text_half_height = (F32)(text_box->getRect().getHeight() / 2); F32 text_half_width = (F32)(text_box->getRect().getWidth() / 2); F32 radius = llmin( map_half_height - text_half_height, map_half_width - text_half_width ); // Inset by a little to account for position display. radius -= 8.f; text_box->setOrigin( llround(map_half_width - text_half_width + radius * cos( rotation )), llround(map_half_height - text_half_height + radius * sin( rotation )) ); } void LLFloaterMap::updateMinorDirections() { if (mTextBoxNorthEast == NULL) { return; } // Hide minor directions if they cover too much of the map bool show_minors = mTextBoxNorthEast->getRect().getHeight() < MAP_MINOR_DIR_THRESHOLD * llmin(getRect().getWidth(), getRect().getHeight()); mTextBoxNorthEast->setVisible(show_minors); mTextBoxNorthWest->setVisible(show_minors); mTextBoxSouthWest->setVisible(show_minors); mTextBoxSouthEast->setVisible(show_minors); } // virtual void LLFloaterMap::draw() { F32 rotation = 0; static LLUICachedControl<bool> rotate_map("MiniMapRotate", true); if( rotate_map ) { // rotate subsequent draws to agent rotation rotation = atan2( LLViewerCamera::getInstance()->getAtAxis().mV[VX], LLViewerCamera::getInstance()->getAtAxis().mV[VY] ); } setDirectionPos( mTextBoxEast, rotation ); setDirectionPos( mTextBoxNorth, rotation + F_PI_BY_TWO ); setDirectionPos( mTextBoxWest, rotation + F_PI ); setDirectionPos( mTextBoxSouth, rotation + F_PI + F_PI_BY_TWO ); setDirectionPos( mTextBoxNorthEast, rotation + F_PI_BY_TWO / 2); setDirectionPos( mTextBoxNorthWest, rotation + F_PI_BY_TWO + F_PI_BY_TWO / 2); setDirectionPos( mTextBoxSouthWest, rotation + F_PI + F_PI_BY_TWO / 2); setDirectionPos( mTextBoxSouthEast, rotation + F_PI + F_PI_BY_TWO + F_PI_BY_TWO / 2); // Note: we can't just gAgent.check cameraMouselook() because the transition states are wrong. if(gAgentCamera.cameraMouselook()) { setMouseOpaque(FALSE); getDragHandle()->setMouseOpaque(FALSE); } else { setMouseOpaque(TRUE); getDragHandle()->setMouseOpaque(TRUE); } if (LLTracker::isTracking(0)) { mPopupMenu->setItemEnabled ("Stop Tracking", true); } LLFloater::draw(); } // virtual void LLFloaterMap::onFocusReceived() { setBackgroundOpaque(true); LLPanel::onFocusReceived(); } // virtual void LLFloaterMap::onFocusLost() { setBackgroundOpaque(false); LLPanel::onFocusLost(); } void LLFloaterMap::stretchMiniMap(S32 width,S32 height) { //fix for ext-7112 //by default ctrl can't overlap caption area if(mMap) { LLRect map_rect; map_rect.setLeftTopAndSize( MAP_PADDING_LEFT, getRect().getHeight() - MAP_PADDING_TOP, width, height); mMap->reshape( width, height, 1); mMap->setRect(map_rect); } } void LLFloaterMap::reshape(S32 width, S32 height, BOOL called_from_parent) { LLFloater::reshape(width, height, called_from_parent); stretchMiniMap(width - MAP_PADDING_LEFT - MAP_PADDING_RIGHT ,height - MAP_PADDING_TOP - MAP_PADDING_BOTTOM); updateMinorDirections(); } void LLFloaterMap::handleZoom(const LLSD& userdata) { std::string level = userdata.asString(); F32 scale = 0.0f; if (level == std::string("close")) scale = LLNetMap::MAP_SCALE_MAX; else if (level == std::string("medium")) scale = LLNetMap::MAP_SCALE_MID; else if (level == std::string("far")) scale = LLNetMap::MAP_SCALE_MIN; if (scale != 0.0f) { gSavedSettings.setF32("MiniMapScale", scale ); mMap->setScale(scale); } } void LLFloaterMap::handleStopTracking (const LLSD& userdata) { if (mPopupMenu) { mPopupMenu->setItemEnabled ("Stop Tracking", false); LLTracker::stopTracking ((void*)LLTracker::isTracking(NULL)); } } void LLFloaterMap::setMinimized(BOOL b) { LLFloater::setMinimized(b); if(b) { setTitle(getString("mini_map_caption")); } else { setTitle(""); } } <commit_msg>STORM-299 FIXED World map floater opening instead Mini-map if double-click on minimized Mini-map.<commit_after>/** * @file llfloatermap.cpp * @brief The "mini-map" or radar in the upper right part of the screen. * * $LicenseInfo:firstyear=2001&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" // self include #include "llfloatermap.h" // Library includes #include "llfloaterreg.h" #include "llfontgl.h" #include "llglheaders.h" // Viewer includes #include "llagentcamera.h" #include "llviewercontrol.h" #include "llnetmap.h" #include "lltracker.h" #include "llviewercamera.h" #include "lldraghandle.h" #include "lltextbox.h" #include "llviewermenu.h" // // Constants // // The minor cardinal direction labels are hidden if their height is more // than this proportion of the map. const F32 MAP_MINOR_DIR_THRESHOLD = 0.07f; const S32 MAP_PADDING_LEFT = 0; const S32 MAP_PADDING_TOP = 2; const S32 MAP_PADDING_RIGHT = 2; const S32 MAP_PADDING_BOTTOM = 0; // // Member functions // LLFloaterMap::LLFloaterMap(const LLSD& key) : LLFloater(key), mPopupMenu(NULL), mTextBoxEast(NULL), mTextBoxNorth(NULL), mTextBoxWest(NULL), mTextBoxSouth(NULL), mTextBoxSouthEast(NULL), mTextBoxNorthEast(NULL), mTextBoxNorthWest(NULL), mTextBoxSouthWest(NULL), mMap(NULL) { //Called from floater reg: LLUICtrlFactory::getInstance()->buildFloater(this, "floater_map.xml", FALSE); } LLFloaterMap::~LLFloaterMap() { } BOOL LLFloaterMap::postBuild() { mMap = getChild<LLNetMap>("Net Map"); mMap->setScale(gSavedSettings.getF32("MiniMapScale")); mMap->setToolTipMsg(getString("ToolTipMsg")); sendChildToBack(mMap); mTextBoxNorth = getChild<LLTextBox> ("floater_map_north"); mTextBoxEast = getChild<LLTextBox> ("floater_map_east"); mTextBoxWest = getChild<LLTextBox> ("floater_map_west"); mTextBoxSouth = getChild<LLTextBox> ("floater_map_south"); mTextBoxSouthEast = getChild<LLTextBox> ("floater_map_southeast"); mTextBoxNorthEast = getChild<LLTextBox> ("floater_map_northeast"); mTextBoxSouthWest = getChild<LLTextBox> ("floater_map_southwest"); mTextBoxNorthWest = getChild<LLTextBox> ("floater_map_northwest"); LLUICtrl::CommitCallbackRegistry::ScopedRegistrar registrar; registrar.add("Minimap.Zoom", boost::bind(&LLFloaterMap::handleZoom, this, _2)); registrar.add("Minimap.Tracker", boost::bind(&LLFloaterMap::handleStopTracking, this, _2)); mPopupMenu = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_mini_map.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance()); if (mPopupMenu && !LLTracker::isTracking(0)) { mPopupMenu->setItemEnabled ("Stop Tracking", false); } stretchMiniMap(getRect().getWidth() - MAP_PADDING_LEFT - MAP_PADDING_RIGHT ,getRect().getHeight() - MAP_PADDING_TOP - MAP_PADDING_BOTTOM); updateMinorDirections(); // Get the drag handle all the way in back sendChildToBack(getDragHandle()); setIsChrome(TRUE); getDragHandle()->setTitleVisible(TRUE); // keep onscreen gFloaterView->adjustToFitScreen(this, FALSE); return TRUE; } BOOL LLFloaterMap::handleDoubleClick( S32 x, S32 y, MASK mask ) { // If floater is minimized, minimap should be shown on doubleclick (STORM-299) std::string floater_to_show = this->isMinimized() ? "mini_map" : "world_map"; LLFloaterReg::showInstance(floater_to_show); return TRUE; } BOOL LLFloaterMap::handleRightMouseDown(S32 x, S32 y, MASK mask) { if (mPopupMenu) { mPopupMenu->buildDrawLabels(); mPopupMenu->updateParent(LLMenuGL::sMenuContainer); LLMenuGL::showPopup(this, mPopupMenu, x, y); } return TRUE; } void LLFloaterMap::setDirectionPos( LLTextBox* text_box, F32 rotation ) { // Rotation is in radians. // Rotation of 0 means x = 1, y = 0 on the unit circle. F32 map_half_height = (F32)(getRect().getHeight() / 2) - getHeaderHeight()/2; F32 map_half_width = (F32)(getRect().getWidth() / 2) ; F32 text_half_height = (F32)(text_box->getRect().getHeight() / 2); F32 text_half_width = (F32)(text_box->getRect().getWidth() / 2); F32 radius = llmin( map_half_height - text_half_height, map_half_width - text_half_width ); // Inset by a little to account for position display. radius -= 8.f; text_box->setOrigin( llround(map_half_width - text_half_width + radius * cos( rotation )), llround(map_half_height - text_half_height + radius * sin( rotation )) ); } void LLFloaterMap::updateMinorDirections() { if (mTextBoxNorthEast == NULL) { return; } // Hide minor directions if they cover too much of the map bool show_minors = mTextBoxNorthEast->getRect().getHeight() < MAP_MINOR_DIR_THRESHOLD * llmin(getRect().getWidth(), getRect().getHeight()); mTextBoxNorthEast->setVisible(show_minors); mTextBoxNorthWest->setVisible(show_minors); mTextBoxSouthWest->setVisible(show_minors); mTextBoxSouthEast->setVisible(show_minors); } // virtual void LLFloaterMap::draw() { F32 rotation = 0; static LLUICachedControl<bool> rotate_map("MiniMapRotate", true); if( rotate_map ) { // rotate subsequent draws to agent rotation rotation = atan2( LLViewerCamera::getInstance()->getAtAxis().mV[VX], LLViewerCamera::getInstance()->getAtAxis().mV[VY] ); } setDirectionPos( mTextBoxEast, rotation ); setDirectionPos( mTextBoxNorth, rotation + F_PI_BY_TWO ); setDirectionPos( mTextBoxWest, rotation + F_PI ); setDirectionPos( mTextBoxSouth, rotation + F_PI + F_PI_BY_TWO ); setDirectionPos( mTextBoxNorthEast, rotation + F_PI_BY_TWO / 2); setDirectionPos( mTextBoxNorthWest, rotation + F_PI_BY_TWO + F_PI_BY_TWO / 2); setDirectionPos( mTextBoxSouthWest, rotation + F_PI + F_PI_BY_TWO / 2); setDirectionPos( mTextBoxSouthEast, rotation + F_PI + F_PI_BY_TWO + F_PI_BY_TWO / 2); // Note: we can't just gAgent.check cameraMouselook() because the transition states are wrong. if(gAgentCamera.cameraMouselook()) { setMouseOpaque(FALSE); getDragHandle()->setMouseOpaque(FALSE); } else { setMouseOpaque(TRUE); getDragHandle()->setMouseOpaque(TRUE); } if (LLTracker::isTracking(0)) { mPopupMenu->setItemEnabled ("Stop Tracking", true); } LLFloater::draw(); } // virtual void LLFloaterMap::onFocusReceived() { setBackgroundOpaque(true); LLPanel::onFocusReceived(); } // virtual void LLFloaterMap::onFocusLost() { setBackgroundOpaque(false); LLPanel::onFocusLost(); } void LLFloaterMap::stretchMiniMap(S32 width,S32 height) { //fix for ext-7112 //by default ctrl can't overlap caption area if(mMap) { LLRect map_rect; map_rect.setLeftTopAndSize( MAP_PADDING_LEFT, getRect().getHeight() - MAP_PADDING_TOP, width, height); mMap->reshape( width, height, 1); mMap->setRect(map_rect); } } void LLFloaterMap::reshape(S32 width, S32 height, BOOL called_from_parent) { LLFloater::reshape(width, height, called_from_parent); stretchMiniMap(width - MAP_PADDING_LEFT - MAP_PADDING_RIGHT ,height - MAP_PADDING_TOP - MAP_PADDING_BOTTOM); updateMinorDirections(); } void LLFloaterMap::handleZoom(const LLSD& userdata) { std::string level = userdata.asString(); F32 scale = 0.0f; if (level == std::string("close")) scale = LLNetMap::MAP_SCALE_MAX; else if (level == std::string("medium")) scale = LLNetMap::MAP_SCALE_MID; else if (level == std::string("far")) scale = LLNetMap::MAP_SCALE_MIN; if (scale != 0.0f) { gSavedSettings.setF32("MiniMapScale", scale ); mMap->setScale(scale); } } void LLFloaterMap::handleStopTracking (const LLSD& userdata) { if (mPopupMenu) { mPopupMenu->setItemEnabled ("Stop Tracking", false); LLTracker::stopTracking ((void*)LLTracker::isTracking(NULL)); } } void LLFloaterMap::setMinimized(BOOL b) { LLFloater::setMinimized(b); if(b) { setTitle(getString("mini_map_caption")); } else { setTitle(""); } } <|endoftext|>
<commit_before>/* $Id$ */ # ifndef CPPAD_EXP_2_INCLUDED # define CPPAD_EXP_2_INCLUDED /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-07 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Common Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin exp_2$$ $spell cppad-%yyyymmdd% hpp Apx cpp const exp bool $$ $section Second Order Exponential Approximation$$ $index exp_2$$ $index example, algorithm$$ $index algorithm, example$$ $index exp, example$$ $head Syntax$$ $codei%# include "exp_2.hpp"%$$ $pre $$ $icode%y% = exp_2(%x%)%$$ $head Purpose$$ This is a simple example algorithm that is used to demonstrate Algorithmic Differentiation (see $cref exp_eps$$ for a more complex example). $head Mathematical Form$$ The exponential function can be defined by $latex \[ \exp (x) = 1 + x^1 / 1 ! + x^2 / 2 ! + \cdots \] $$ The second order approximation for the exponential function is $latex \[ {\rm exp\_2} (x) = 1 + x + x^2 / 2 \] $$ $head include$$ The include command in the syntax is relative to $codei% cppad-%yyyymmdd%/introduction/exp_apx %$$ where $codei%cppad-%yyyymmdd%$$ is the distribution directory created during the beginning steps of the $cref%installation%Install%$$ of CppAD. $head x$$ The argument $icode x$$ has prototype $codei% const %Type% &%x% %$$ (see $icode Type$$ below). It specifies the point at which to evaluate the approximation for the second order exponential approximation. $head y$$ The result $icode y$$ has prototype $codei% %Type% %y% %$$ It is the value of the exponential function approximation defined above. $head Type$$ If $icode u$$ and $italic v$$ are $italic Type$$ objects and $italic i$$ is an $code int$$: $table $bold Operation$$ $cnext $bold Result Type$$ $cnext $bold Description$$ $rnext $icode%Type%(%i%)%$$ $cnext $icode Type$$ $cnext object with value equal to $icode i$$ $rnext $icode%u% = %v%$$ $cnext $icode Type$$ $cnext new $icode u$$ (and result) is value of $italic v$$ $rnext $icode%u% * %v%$$ $cnext $icode Type$$ $cnext result is value of $latex u * v$$ $rnext $icode%u% / %v%$$ $cnext $icode Type$$ $cnext result is value of $latex u / v$$ $rnext $icode%u% + %v%$$ $cnext $icode Type$$ $cnext result is value of $latex u + v$$ $tend $childtable% introduction/exp_apx/exp_2.omh% introduction/exp_apx/exp_2_cppad.cpp %$$ $head Implementation$$ The file $cref/exp_2.hpp/$$ contains a C++ implementation of this function. $head Test$$ The file $cref/exp_2.cpp/$$ contains a test of this implementation. It returns true for success and false for failure. $head Exercises$$ $list number$$ Suppose that we make the call $codep double x = .1; double y = exp_2(x); $$ What is the value assigned to $code v1$$, $code v2$$, ... ,$code v5$$ in $cref/exp_2.hpp/$$ ? $lnext Extend the routine $code exp_2.hpp$$ to a routine $code exp_3.hpp$$ that computes $latex \[ 1 + x^2 / 2 ! + x^3 / 3 ! \] $$ Do this in a way that only assigns one value to each variable (as $code exp_2$$ does). $lnext Suppose that we make the call $codep double x = .5; double y = exp_3(x); $$ using $code exp_3$$ created in the previous problem. What is the value assigned to the new variables in $code exp_3$$ (variables that are in $code exp_3$$ and not in $code exp_2$$) ? $lend $end ------------------------------------------------------------------------------ */ // BEGIN PROGRAM template <class Type> Type exp_2(const Type &x) { Type v1 = x; // v1 = x Type v2 = Type(1) + v1; // v2 = 1 + x Type v3 = v1 * v1; // v3 = x^2 Type v4 = v3 / Type(2); // v4 = x^2 / 2 Type v5 = v2 + v4; // v5 = 1 + x + x^2 / 2 return v5; // exp_2(x) = 1 + x + x^2 / 2 } // END PROGRAM # endif <commit_msg>fix specifications for templated Type<commit_after>/* $Id$ */ # ifndef CPPAD_EXP_2_INCLUDED # define CPPAD_EXP_2_INCLUDED /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-07 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Common Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin exp_2$$ $spell cppad-%yyyymmdd% hpp Apx cpp const exp bool $$ $section Second Order Exponential Approximation$$ $index exp_2$$ $index example, algorithm$$ $index algorithm, example$$ $index exp, example$$ $head Syntax$$ $codei%# include "exp_2.hpp"%$$ $pre $$ $icode%y% = exp_2(%x%)%$$ $head Purpose$$ This is a simple example algorithm that is used to demonstrate Algorithmic Differentiation (see $cref exp_eps$$ for a more complex example). $head Mathematical Form$$ The exponential function can be defined by $latex \[ \exp (x) = 1 + x^1 / 1 ! + x^2 / 2 ! + \cdots \] $$ The second order approximation for the exponential function is $latex \[ {\rm exp\_2} (x) = 1 + x + x^2 / 2 \] $$ $head include$$ The include command in the syntax is relative to $codei% cppad-%yyyymmdd%/introduction/exp_apx %$$ where $codei%cppad-%yyyymmdd%$$ is the distribution directory created during the beginning steps of the $cref%installation%Install%$$ of CppAD. $head x$$ The argument $icode x$$ has prototype $codei% const %Type% &%x% %$$ (see $icode Type$$ below). It specifies the point at which to evaluate the approximation for the second order exponential approximation. $head y$$ The result $icode y$$ has prototype $codei% %Type% %y% %$$ It is the value of the exponential function approximation defined above. $head Type$$ If $icode u$$ and $italic v$$ are $italic Type$$ objects and $italic i$$ is an $code int$$: $table $bold Operation$$ $cnext $bold Result Type$$ $cnext $bold Description$$ $rnext $icode%Type%(%i%)%$$ $cnext $icode Type$$ $cnext construct object with value equal to $icode i$$ $rnext $icode%Type u %=% v%$$ $cnext $icode Type$$ $cnext construct $icode u$$ with value equal to $icode v$$ $rnext $icode%u% * %v%$$ $cnext $icode Type$$ $cnext result is value of $latex u * v$$ $rnext $icode%u% / %v%$$ $cnext $icode Type$$ $cnext result is value of $latex u / v$$ $rnext $icode%u% + %v%$$ $cnext $icode Type$$ $cnext result is value of $latex u + v$$ $tend $childtable% introduction/exp_apx/exp_2.omh% introduction/exp_apx/exp_2_cppad.cpp %$$ $head Implementation$$ The file $cref/exp_2.hpp/$$ contains a C++ implementation of this function. $head Test$$ The file $cref/exp_2.cpp/$$ contains a test of this implementation. It returns true for success and false for failure. $head Exercises$$ $list number$$ Suppose that we make the call $codep double x = .1; double y = exp_2(x); $$ What is the value assigned to $code v1$$, $code v2$$, ... ,$code v5$$ in $cref/exp_2.hpp/$$ ? $lnext Extend the routine $code exp_2.hpp$$ to a routine $code exp_3.hpp$$ that computes $latex \[ 1 + x^2 / 2 ! + x^3 / 3 ! \] $$ Do this in a way that only assigns one value to each variable (as $code exp_2$$ does). $lnext Suppose that we make the call $codep double x = .5; double y = exp_3(x); $$ using $code exp_3$$ created in the previous problem. What is the value assigned to the new variables in $code exp_3$$ (variables that are in $code exp_3$$ and not in $code exp_2$$) ? $lend $end ------------------------------------------------------------------------------ */ // BEGIN PROGRAM template <class Type> Type exp_2(const Type &x) { Type v1 = x; // v1 = x Type v2 = Type(1) + v1; // v2 = 1 + x Type v3 = v1 * v1; // v3 = x^2 Type v4 = v3 / Type(2); // v4 = x^2 / 2 Type v5 = v2 + v4; // v5 = 1 + x + x^2 / 2 return v5; // exp_2(x) = 1 + x + x^2 / 2 } // END PROGRAM # endif <|endoftext|>
<commit_before>// @(#)root/io:$Id$ // Author: Jakob Blomer /************************************************************************* * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_RRawFileWin #define ROOT_RRawFileWin #include <ROOT/RRawFile.hxx> #include <ROOT/RStringView.hxx> #include <cstddef> #include <cstdint> #include <cstdio> namespace ROOT { namespace Detail { /** * \class RRawFileWin RRawFileWin.hxx * \ingroup IO * * The RRawFileWin class uses portable C I/O calls to read from a drive. The standard C I/O buffering is turned off * for the buffering of RRawFile base class. */ class RRawFileWin : public RRawFile { private: FILE *fFilePtr; void Seek(long offset, int whence); protected: void DoOpen() final; size_t DoReadAt(void *buffer, size_t nbytes, std::uint64_t offset) final; std::uint64_t DoGetSize() final; public: RRawFileWin(std::string_view url, RRawFile::ROptions options); ~RRawFileWin(); }; } // namespace Detail } // namespace ROOT #endif <commit_msg>[io] fix RRawFile header on Windows<commit_after>// @(#)root/io:$Id$ // Author: Jakob Blomer /************************************************************************* * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_RRawFileWin #define ROOT_RRawFileWin #include <ROOT/RRawFile.hxx> #include <ROOT/RStringView.hxx> #include <cstddef> #include <cstdint> #include <cstdio> namespace ROOT { namespace Experimental { namespace Detail { /** * \class RRawFileWin RRawFileWin.hxx * \ingroup IO * * The RRawFileWin class uses portable C I/O calls to read from a drive. The standard C I/O buffering is turned off * for the buffering of RRawFile base class. */ class RRawFileWin : public RRawFile { private: FILE *fFilePtr; void Seek(long offset, int whence); protected: void DoOpen() final; size_t DoReadAt(void *buffer, size_t nbytes, std::uint64_t offset) final; std::uint64_t DoGetSize() final; public: RRawFileWin(std::string_view url, RRawFile::ROptions options); ~RRawFileWin(); }; } // namespace Detail } // namespace Experimental } // namespace ROOT #endif <|endoftext|>
<commit_before>#pragma once #include <limits> #include <algorithm> #include <vector> #include <map> #include <functional> using std::max; using std::make_pair; using std::min; using std::abs; using std::hypot; using std::vector; using std::map; using std::function; namespace search { // // Lifelong planning // namespace lp { constexpr auto infinity() { return std::numeric_limits<int>::max(); } constexpr auto cost() { return 1; } struct Coordinate { int x, y; friend auto operator== (Coordinate l, Coordinate r) { return l.x == r.x && l.y == r.y; } friend auto operator!= (Coordinate l, Coordinate r) { return !(l == r); } auto neighbours() const { struct Directions : public map< char, function< Coordinate(Coordinate) >> { Directions() { (*this)['1'] = [](Coordinate c) { return Coordinate{ c.x - 1, c.y - 1 }; }; (*this)['2'] = [](Coordinate c) { return Coordinate{ c.x - 0, c.y - 1 }; }; (*this)['3'] = [](Coordinate c) { return Coordinate{ c.x + 1, c.y - 1 }; }; (*this)['4'] = [](Coordinate c) { return Coordinate{ c.x - 1, c.y - 0 }; }; (*this)['5'] = [](Coordinate c) { return Coordinate{ c.x + 1, c.y + 0 }; }; (*this)['6'] = [](Coordinate c) { return Coordinate{ c.x - 1, c.y + 1 }; }; (*this)['7'] = [](Coordinate c) { return Coordinate{ c.x - 0, c.y + 1 }; }; (*this)['8'] = [](Coordinate c) { return Coordinate{ c.x + 1, c.y + 1 }; }; } } static const directions; vector<Coordinate> result; for (auto n = '1'; n != '9'; ++n) result.push_back(directions.at(n)(*this)); return result; } }; struct LpState { struct Key { const int first, second; friend auto operator== (Key l, Key r) { return l.first == r.first && l.second == r.second; } friend auto operator < (Key l, Key r) { return (l.first < r.first) || (l.first == r.first && l.second < r.second); } }; friend auto operator==(LpState const& l, LpState const& r) { return l.coordinate == r.coordinate && l.g == r.g && l.r == r.r; } Coordinate coordinate; int g, r; template<typename Hfunc> auto key(Hfunc h) const { return Key{ min(g, r + h(coordinate)), min(g, r) }; } }; struct LpManhattanDistance { const Coordinate goal; auto operator()(Coordinate c) const { return max(abs(goal.x - c.x), abs(goal.y - c.y)); } }; struct LpEuclideanDistance { const Coordinate goal; auto operator()(Coordinate c) const { auto result = hypot(abs(goal.x - c.x), abs(goal.y - c.y)); return static_cast<int>(round(result)); } }; class Matrix { public: Matrix(unsigned height, unsigned width) : _data{ height, vector<LpState>(width)} { } auto at(Coordinate c) -> LpState& { return{ _data[c.y][c.x] }; } auto at(Coordinate c) const -> LpState const& { return{ _data[c.y][c.x] }; } private: vector<vector<LpState>> _data; }; } }<commit_msg>add LpLess for ording in priority queue.<commit_after>#pragma once #include <limits> #include <algorithm> #include <vector> #include <map> #include <functional> using std::max; using std::make_pair; using std::min; using std::abs; using std::hypot; using std::vector; using std::map; using std::function; namespace search { // // Lifelong planning // namespace lp { constexpr auto infinity() { return std::numeric_limits<int>::max(); } constexpr auto cost() { return 1; } struct Coordinate { int x, y; friend auto operator== (Coordinate l, Coordinate r) { return l.x == r.x && l.y == r.y; } friend auto operator!= (Coordinate l, Coordinate r) { return !(l == r); } auto neighbours() const { struct Directions : public map< char, function< Coordinate(Coordinate) >> { Directions() { (*this)['1'] = [](Coordinate c) { return Coordinate{ c.x - 1, c.y - 1 }; }; (*this)['2'] = [](Coordinate c) { return Coordinate{ c.x - 0, c.y - 1 }; }; (*this)['3'] = [](Coordinate c) { return Coordinate{ c.x + 1, c.y - 1 }; }; (*this)['4'] = [](Coordinate c) { return Coordinate{ c.x - 1, c.y - 0 }; }; (*this)['5'] = [](Coordinate c) { return Coordinate{ c.x + 1, c.y + 0 }; }; (*this)['6'] = [](Coordinate c) { return Coordinate{ c.x - 1, c.y + 1 }; }; (*this)['7'] = [](Coordinate c) { return Coordinate{ c.x - 0, c.y + 1 }; }; (*this)['8'] = [](Coordinate c) { return Coordinate{ c.x + 1, c.y + 1 }; }; } } static const directions; vector<Coordinate> result; for (auto n = '1'; n != '9'; ++n) result.push_back(directions.at(n)(*this)); return result; } }; struct LpState { struct Key { const int first, second; friend auto operator== (Key l, Key r) { return l.first == r.first && l.second == r.second; } friend auto operator < (Key l, Key r) { return (l.first < r.first) || (l.first == r.first && l.second < r.second); } }; friend auto operator==(LpState const& l, LpState const& r) { return l.coordinate == r.coordinate && l.g == r.g && l.r == r.r; } Coordinate coordinate; int g, r; template<typename Hfunc> auto key(Hfunc h) const { return Key{ min(g, r + h(coordinate)), min(g, r) }; } }; template<typename Hfunc> struct LpLess { LpLess() = delete; LpLess(Coordinate goal): _goal(goal){ } auto operator()(LpState const& l, LpState const& r) const { return l.key(Hfunc{ _goal }) < r.key(Hfunc{ _goal }); } private: Coordinate _goal; }; struct LpManhattanDistance { const Coordinate goal; auto operator()(Coordinate c) const { return max(abs(goal.x - c.x), abs(goal.y - c.y)); } }; struct LpEuclideanDistance { const Coordinate goal; auto operator()(Coordinate c) const { auto result = hypot(abs(goal.x - c.x), abs(goal.y - c.y)); return static_cast<int>(round(result)); } }; class Matrix { public: Matrix(unsigned height, unsigned width) : _data{ height, vector<LpState>(width)} { } auto at(Coordinate c) -> LpState& { return{ _data[c.y][c.x] }; } auto at(Coordinate c) const -> LpState const& { return{ _data[c.y][c.x] }; } private: vector<vector<LpState>> _data; }; } }<|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2015 Mark Charlebois. 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. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file simulator.cpp * A device simulator */ #include <px4_log.h> #include <px4_tasks.h> #include <px4_time.h> #include <pthread.h> #include <poll.h> #include <systemlib/err.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <drivers/drv_led.h> #include "simulator.h" using namespace simulator; static px4_task_t g_sim_task = -1; Simulator *Simulator::_instance = NULL; Simulator *Simulator::getInstance() { return _instance; } bool Simulator::getMPUReport(uint8_t *buf, int len) { return _mpu.copyData(buf, len); } bool Simulator::getRawAccelReport(uint8_t *buf, int len) { return _accel.copyData(buf, len); } bool Simulator::getMagReport(uint8_t *buf, int len) { return _mag.copyData(buf, len); } bool Simulator::getBaroSample(uint8_t *buf, int len) { return _baro.copyData(buf, len); } bool Simulator::getGPSSample(uint8_t *buf, int len) { return _gps.copyData(buf, len); } bool Simulator::getAirspeedSample(uint8_t *buf, int len) { return _airspeed.copyData(buf, len); } void Simulator::write_MPU_data(void *buf) { _mpu.writeData(buf); } void Simulator::write_accel_data(void *buf) { _accel.writeData(buf); } void Simulator::write_mag_data(void *buf) { _mag.writeData(buf); } void Simulator::write_baro_data(void *buf) { _baro.writeData(buf); } void Simulator::write_gps_data(void *buf) { _gps.writeData(buf); } void Simulator::write_airspeed_data(void *buf) { _airspeed.writeData(buf); } int Simulator::start(int argc, char *argv[]) { int ret = 0; int udp_port = 0; _instance = new Simulator(); if (_instance) { drv_led_start(); if (argc == 5 && strcmp(argv[3], "-u") == 0) udp_port = atoi(argv[4]); if (argv[2][1] == 's') { _instance->initializeSensorData(); #ifndef __PX4_QURT // Update sensor data _instance->pollForMAVLinkMessages(false,udp_port); #endif } else if (argv[2][1] == 'p') { // Update sensor data _instance->pollForMAVLinkMessages(true,udp_port); } else { _instance->initializeSensorData(); _instance->_initialized = true; } } else { PX4_WARN("Simulator creation failed"); ret = 1; } return ret; } static void usage() { PX4_WARN("Usage: simulator {start -[spt] [-u udp_port] |stop}"); PX4_WARN("Simulate raw sensors: simulator start -s"); PX4_WARN("Publish sensors combined: simulator start -p"); PX4_WARN("Dummy unit test data: simulator start -t"); } __BEGIN_DECLS extern int simulator_main(int argc, char *argv[]); __END_DECLS extern "C" { int simulator_main(int argc, char *argv[]) { int ret = 0; if (argc > 2 && strcmp(argv[1], "start") == 0) { if (strcmp(argv[2], "-s") == 0 || strcmp(argv[2], "-p") == 0 || strcmp(argv[2], "-t") == 0) { if (g_sim_task >= 0) { warnx("Simulator already started"); return 0; } // enable lockstep support px4_enable_sim_lockstep(); g_sim_task = px4_task_spawn_cmd("simulator", SCHED_DEFAULT, SCHED_PRIORITY_MAX, 1500, Simulator::start, argv); // now wait for the command to complete while (true) { if (Simulator::getInstance() && Simulator::getInstance()->isInitialized()) { break; } else { usleep(100000); } } } else { usage(); ret = -EINVAL; } } else if (argc == 2 && strcmp(argv[1], "stop") == 0) { if (g_sim_task < 0) { PX4_WARN("Simulator not running"); } else { px4_task_delete(g_sim_task); g_sim_task = -1; } } else { usage(); ret = -EINVAL; } return ret; } } <commit_msg>fix code style for Travis<commit_after>/**************************************************************************** * * Copyright (c) 2015 Mark Charlebois. 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. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file simulator.cpp * A device simulator */ #include <px4_log.h> #include <px4_tasks.h> #include <px4_time.h> #include <pthread.h> #include <poll.h> #include <systemlib/err.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <drivers/drv_led.h> #include "simulator.h" using namespace simulator; static px4_task_t g_sim_task = -1; Simulator *Simulator::_instance = NULL; Simulator *Simulator::getInstance() { return _instance; } bool Simulator::getMPUReport(uint8_t *buf, int len) { return _mpu.copyData(buf, len); } bool Simulator::getRawAccelReport(uint8_t *buf, int len) { return _accel.copyData(buf, len); } bool Simulator::getMagReport(uint8_t *buf, int len) { return _mag.copyData(buf, len); } bool Simulator::getBaroSample(uint8_t *buf, int len) { return _baro.copyData(buf, len); } bool Simulator::getGPSSample(uint8_t *buf, int len) { return _gps.copyData(buf, len); } bool Simulator::getAirspeedSample(uint8_t *buf, int len) { return _airspeed.copyData(buf, len); } void Simulator::write_MPU_data(void *buf) { _mpu.writeData(buf); } void Simulator::write_accel_data(void *buf) { _accel.writeData(buf); } void Simulator::write_mag_data(void *buf) { _mag.writeData(buf); } void Simulator::write_baro_data(void *buf) { _baro.writeData(buf); } void Simulator::write_gps_data(void *buf) { _gps.writeData(buf); } void Simulator::write_airspeed_data(void *buf) { _airspeed.writeData(buf); } int Simulator::start(int argc, char *argv[]) { int ret = 0; int udp_port = 0; _instance = new Simulator(); if (_instance) { drv_led_start(); if (argc == 5 && strcmp(argv[3], "-u") == 0) { udp_port = atoi(argv[4]); } if (argv[2][1] == 's') { _instance->initializeSensorData(); #ifndef __PX4_QURT // Update sensor data _instance->pollForMAVLinkMessages(false, udp_port); #endif } else if (argv[2][1] == 'p') { // Update sensor data _instance->pollForMAVLinkMessages(true, udp_port); } else { _instance->initializeSensorData(); _instance->_initialized = true; } } else { PX4_WARN("Simulator creation failed"); ret = 1; } return ret; } static void usage() { PX4_WARN("Usage: simulator {start -[spt] [-u udp_port] |stop}"); PX4_WARN("Simulate raw sensors: simulator start -s"); PX4_WARN("Publish sensors combined: simulator start -p"); PX4_WARN("Dummy unit test data: simulator start -t"); } __BEGIN_DECLS extern int simulator_main(int argc, char *argv[]); __END_DECLS extern "C" { int simulator_main(int argc, char *argv[]) { int ret = 0; if (argc > 2 && strcmp(argv[1], "start") == 0) { if (strcmp(argv[2], "-s") == 0 || strcmp(argv[2], "-p") == 0 || strcmp(argv[2], "-t") == 0) { if (g_sim_task >= 0) { warnx("Simulator already started"); return 0; } // enable lockstep support px4_enable_sim_lockstep(); g_sim_task = px4_task_spawn_cmd("simulator", SCHED_DEFAULT, SCHED_PRIORITY_MAX, 1500, Simulator::start, argv); // now wait for the command to complete while (true) { if (Simulator::getInstance() && Simulator::getInstance()->isInitialized()) { break; } else { usleep(100000); } } } else { usage(); ret = -EINVAL; } } else if (argc == 2 && strcmp(argv[1], "stop") == 0) { if (g_sim_task < 0) { PX4_WARN("Simulator not running"); } else { px4_task_delete(g_sim_task); g_sim_task = -1; } } else { usage(); ret = -EINVAL; } return ret; } } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/value_type.h> #include <vespa/searchlib/fef/feature_type.h> #include <vespa/searchlib/fef/featurenameparser.h> #include <vespa/searchlib/features/rankingexpressionfeature.h> #include <vespa/searchlib/fef/test/dummy_dependency_handler.h> #include <vespa/searchlib/fef/test/indexenvironment.h> using namespace search::features; using namespace search::features::rankingexpression; using namespace search::fef::test; using namespace search::fef; using namespace vespalib::eval; using TypeMap = std::map<vespalib::string,vespalib::string>; struct DummyExpression : IntrinsicExpression { FeatureType type; DummyExpression(const FeatureType &type_in) : type(type_in) {} FeatureType result_type() const override { return type; } FeatureExecutor &create_executor(const QueryEnv &, vespalib::Stash &) const override { abort(); } }; struct DummyReplacer : ExpressionReplacer { vespalib::string trigger; FeatureType type; DummyReplacer(const vespalib::string trigger_in, const FeatureType &type_in) : trigger(trigger_in), type(type_in) {} IntrinsicExpression::UP maybe_replace(const vespalib::eval::Function &function, const search::fef::IIndexEnvironment &) const override { for (size_t i = 0; i < function.num_params(); ++i) { if (function.param_name(i) == trigger) { return std::make_unique<DummyExpression>(type); } } return IntrinsicExpression::UP(nullptr); } }; ExpressionReplacer::SP make_replacer() { auto replacer = std::make_shared<ListExpressionReplacer>(); replacer->add(std::make_unique<NullExpressionReplacer>()); replacer->add(std::make_unique<DummyReplacer>("foo", FeatureType::number())); replacer->add(std::make_unique<DummyReplacer>("bar", FeatureType::object(ValueType::from_spec("tensor(x[])")))); return replacer; } struct SetupResult { IndexEnvironment index_env; RankingExpressionBlueprint rank; DummyDependencyHandler deps; bool setup_ok; SetupResult(const TypeMap &object_inputs, const vespalib::string &expression); ~SetupResult(); }; SetupResult::SetupResult(const TypeMap &object_inputs, const vespalib::string &expression) : index_env(), rank(make_replacer()), deps(rank), setup_ok(false) { rank.setName("self"); index_env.getProperties().add("self.rankingScript", expression); for (const auto &input: object_inputs) { deps.define_object_input(input.first, ValueType::from_spec(input.second)); } setup_ok = rank.setup(index_env, {}); EXPECT_TRUE(!deps.accept_type_mismatch); } SetupResult::~SetupResult() {} void verify_output_type(const TypeMap &object_inputs, const vespalib::string &expression, const FeatureType &expect) { SetupResult result(object_inputs, expression); EXPECT_TRUE(result.setup_ok); EXPECT_EQUAL(1u, result.deps.output.size()); ASSERT_EQUAL(1u, result.deps.output_type.size()); if (expect.is_object()) { EXPECT_EQUAL(expect.type(), result.deps.output_type[0].type()); } else { EXPECT_TRUE(!result.deps.output_type[0].is_object()); } } void verify_setup_fail(const TypeMap &object_inputs, const vespalib::string &expression) { SetupResult result(object_inputs, expression); EXPECT_TRUE(!result.setup_ok); EXPECT_EQUAL(0u, result.deps.output.size()); } void verify_input_count(const vespalib::string &expression, size_t expect) { SetupResult result({}, expression); EXPECT_TRUE(result.setup_ok); EXPECT_EQUAL(result.deps.input.size(), expect); } TEST("require that expression with only number inputs produce number output (compiled)") { TEST_DO(verify_output_type({}, "a*b", FeatureType::number())); } TEST("require that expression with object input produces object output (interpreted)") { TEST_DO(verify_output_type({{"b", "double"}}, "a*b", FeatureType::object(ValueType::double_type()))); } TEST("require that ranking expression can resolve to concrete complex type") { TEST_DO(verify_output_type({{"a", "tensor(x{},y{})"}, {"b", "tensor(y{},z{})"}}, "a*b", FeatureType::object(ValueType::from_spec("tensor(x{},y{},z{})")))); } TEST("require that ranking expression can resolve to abstract complex type") { TEST_DO(verify_output_type({{"a", "tensor"}}, "a*b", FeatureType::object(ValueType::from_spec("tensor")))); } TEST("require that ranking expression can resolve to 'any' type") { TEST_DO(verify_output_type({{"a", "tensor(x{},y{})"}, {"b", "tensor"}}, "a*b", FeatureType::object(ValueType::from_spec("any")))); } TEST("require that setup fails for incompatible types") { TEST_DO(verify_setup_fail({{"a", "tensor(x{},y{})"}, {"b", "tensor(y[10],z{})"}}, "a*b")); } TEST("require that replaced expressions have no inputs") { TEST_DO(verify_input_count("a*b*c", 3u)); TEST_DO(verify_input_count("foo*b*c", 0u)); TEST_DO(verify_input_count("a*b*bar", 0u)); TEST_DO(verify_input_count("foo*b*bar", 0u)); } TEST("require that replaced expressions override result type") { TEST_DO(verify_output_type({{"b", "tensor(z{})"}}, "a*b*c", FeatureType::object(ValueType::from_spec("tensor(z{})")))); TEST_DO(verify_output_type({{"b", "tensor(z{})"}}, "foo*b*c", FeatureType::number())); TEST_DO(verify_output_type({{"b", "tensor(z{})"}}, "a*b*bar", FeatureType::object(ValueType::from_spec("tensor(x[])")))); TEST_DO(verify_output_type({{"b", "tensor(z{})"}}, "foo*b*bar", FeatureType::number())); } TEST_MAIN() { TEST_RUN_ALL(); } <commit_msg>test that appropriate executor is created<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/value_type.h> #include <vespa/searchlib/fef/feature_type.h> #include <vespa/searchlib/fef/featurenameparser.h> #include <vespa/searchlib/features/rankingexpressionfeature.h> #include <vespa/searchlib/fef/test/dummy_dependency_handler.h> #include <vespa/searchlib/fef/test/indexenvironment.h> #include <vespa/searchlib/fef/test/queryenvironment.h> using namespace search::features; using namespace search::features::rankingexpression; using namespace search::fef::test; using namespace search::fef; using namespace vespalib::eval; using TypeMap = std::map<vespalib::string,vespalib::string>; struct DummyExecutor : FeatureExecutor { void execute(uint32_t) override {} }; struct DummyExpression : IntrinsicExpression { FeatureType type; DummyExpression(const FeatureType &type_in) : type(type_in) {} FeatureType result_type() const override { return type; } FeatureExecutor &create_executor(const QueryEnv &, vespalib::Stash &stash) const override { return stash.create<DummyExecutor>(); } }; struct DummyReplacer : ExpressionReplacer { vespalib::string trigger; FeatureType type; DummyReplacer(const vespalib::string trigger_in, const FeatureType &type_in) : trigger(trigger_in), type(type_in) {} IntrinsicExpression::UP maybe_replace(const vespalib::eval::Function &function, const search::fef::IIndexEnvironment &) const override { for (size_t i = 0; i < function.num_params(); ++i) { if (function.param_name(i) == trigger) { return std::make_unique<DummyExpression>(type); } } return IntrinsicExpression::UP(nullptr); } }; ExpressionReplacer::SP make_replacer() { auto replacer = std::make_shared<ListExpressionReplacer>(); replacer->add(std::make_unique<NullExpressionReplacer>()); replacer->add(std::make_unique<DummyReplacer>("foo", FeatureType::number())); replacer->add(std::make_unique<DummyReplacer>("bar", FeatureType::object(ValueType::from_spec("tensor(x[])")))); return replacer; } struct SetupResult { vespalib::Stash stash; IndexEnvironment index_env; QueryEnvironment query_env; RankingExpressionBlueprint rank; DummyDependencyHandler deps; bool setup_ok; SetupResult(const TypeMap &object_inputs, const vespalib::string &expression); ~SetupResult(); }; SetupResult::SetupResult(const TypeMap &object_inputs, const vespalib::string &expression) : stash(), index_env(), query_env(&index_env), rank(make_replacer()), deps(rank), setup_ok(false) { rank.setName("self"); index_env.getProperties().add("self.rankingScript", expression); for (const auto &input: object_inputs) { deps.define_object_input(input.first, ValueType::from_spec(input.second)); } setup_ok = rank.setup(index_env, {}); EXPECT_TRUE(!deps.accept_type_mismatch); } SetupResult::~SetupResult() {} void verify_output_type(const TypeMap &object_inputs, const vespalib::string &expression, const FeatureType &expect) { SetupResult result(object_inputs, expression); EXPECT_TRUE(result.setup_ok); EXPECT_EQUAL(1u, result.deps.output.size()); ASSERT_EQUAL(1u, result.deps.output_type.size()); if (expect.is_object()) { EXPECT_EQUAL(expect.type(), result.deps.output_type[0].type()); } else { EXPECT_TRUE(!result.deps.output_type[0].is_object()); } } void verify_setup_fail(const TypeMap &object_inputs, const vespalib::string &expression) { SetupResult result(object_inputs, expression); EXPECT_TRUE(!result.setup_ok); EXPECT_EQUAL(0u, result.deps.output.size()); } void verify_input_count(const vespalib::string &expression, size_t expect) { SetupResult result({}, expression); EXPECT_TRUE(result.setup_ok); EXPECT_EQUAL(result.deps.input.size(), expect); } TEST("require that expression with only number inputs produce number output (compiled)") { TEST_DO(verify_output_type({}, "a*b", FeatureType::number())); } TEST("require that expression with object input produces object output (interpreted)") { TEST_DO(verify_output_type({{"b", "double"}}, "a*b", FeatureType::object(ValueType::double_type()))); } TEST("require that ranking expression can resolve to concrete complex type") { TEST_DO(verify_output_type({{"a", "tensor(x{},y{})"}, {"b", "tensor(y{},z{})"}}, "a*b", FeatureType::object(ValueType::from_spec("tensor(x{},y{},z{})")))); } TEST("require that ranking expression can resolve to abstract complex type") { TEST_DO(verify_output_type({{"a", "tensor"}}, "a*b", FeatureType::object(ValueType::from_spec("tensor")))); } TEST("require that ranking expression can resolve to 'any' type") { TEST_DO(verify_output_type({{"a", "tensor(x{},y{})"}, {"b", "tensor"}}, "a*b", FeatureType::object(ValueType::from_spec("any")))); } TEST("require that setup fails for incompatible types") { TEST_DO(verify_setup_fail({{"a", "tensor(x{},y{})"}, {"b", "tensor(y[10],z{})"}}, "a*b")); } TEST("require that replaced expressions have no inputs") { TEST_DO(verify_input_count("a*b*c", 3u)); TEST_DO(verify_input_count("foo*b*c", 0u)); TEST_DO(verify_input_count("a*b*bar", 0u)); TEST_DO(verify_input_count("foo*b*bar", 0u)); } TEST("require that replaced expressions override result type") { TEST_DO(verify_output_type({{"b", "tensor(z{})"}}, "a*b*c", FeatureType::object(ValueType::from_spec("tensor(z{})")))); TEST_DO(verify_output_type({{"b", "tensor(z{})"}}, "foo*b*c", FeatureType::number())); TEST_DO(verify_output_type({{"b", "tensor(z{})"}}, "a*b*bar", FeatureType::object(ValueType::from_spec("tensor(x[])")))); TEST_DO(verify_output_type({{"b", "tensor(z{})"}}, "foo*b*bar", FeatureType::number())); } TEST_F("require that replaced expressions create the appropriate executor", SetupResult({}, "foo")) { EXPECT_TRUE(f1.setup_ok); FeatureExecutor &executor = f1.rank.createExecutor(f1.query_env, f1.stash); EXPECT_TRUE(dynamic_cast<DummyExecutor*>(&executor) != nullptr); } TEST_MAIN() { TEST_RUN_ALL(); } <|endoftext|>
<commit_before>// Copyright (c) 2008 The Chromium Authors. All rights reserved. Use of this // source code is governed by a BSD-style license that can be found in the // LICENSE file. #include "net/proxy/proxy_script_fetcher.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/ref_counted.h" #include "base/string_util.h" #include "net/base/io_buffer.h" #include "net/base/load_flags.h" #include "net/url_request/url_request.h" // TODO(eroman): // - Support auth-prompts. namespace net { namespace { // The maximum size (in bytes) allowed for a PAC script. Responses exceeding // this will fail with ERR_FILE_TOO_BIG. int max_response_bytes = 1048576; // 1 megabyte // The maximum duration (in milliseconds) allowed for fetching the PAC script. // Responses exceeding this will fail with ERR_TIMED_OUT. int max_duration_ms = 300000; // 5 minutes // Returns true if |mime_type| is one of the known PAC mime type. bool IsPacMimeType(const std::string& mime_type) { static const char * const kSupportedPacMimeTypes[] = { "application/x-ns-proxy-autoconfig", "application/x-javascript-config", }; for (size_t i = 0; i < arraysize(kSupportedPacMimeTypes); ++i) { if (LowerCaseEqualsASCII(mime_type, kSupportedPacMimeTypes[i])) return true; } return false; } } // namespace class ProxyScriptFetcherImpl : public ProxyScriptFetcher, public URLRequest::Delegate { public: // Creates a ProxyScriptFetcher that issues requests through // |url_request_context|. |url_request_context| must remain valid for the // lifetime of ProxyScriptFetcherImpl. explicit ProxyScriptFetcherImpl(URLRequestContext* url_request_context); virtual ~ProxyScriptFetcherImpl(); // ProxyScriptFetcher methods: virtual void Fetch(const GURL& url, std::string* bytes, CompletionCallback* callback); virtual void Cancel(); // URLRequest::Delegate methods: virtual void OnAuthRequired(URLRequest* request, AuthChallengeInfo* auth_info); virtual void OnSSLCertificateError(URLRequest* request, int cert_error, X509Certificate* cert); virtual void OnReceivedRedirect(URLRequest* request, const GURL& to_url); virtual void OnResponseStarted(URLRequest* request); virtual void OnReadCompleted(URLRequest* request, int num_bytes); virtual void OnResponseCompleted(URLRequest* request); private: // Read more bytes from the response. void ReadBody(URLRequest* request); // Called once the request has completed to notify the caller of // |response_code_| and |response_bytes_|. void FetchCompleted(); // Clear out the state for the current request. void ResetCurRequestState(); // Callback for time-out task of request with id |id|. void OnTimeout(int id); // Factory for creating the time-out task. This takes care of revoking // outstanding tasks when |this| is deleted. ScopedRunnableMethodFactory<ProxyScriptFetcherImpl> task_factory_; // The context used for making network requests. URLRequestContext* url_request_context_; // Buffer that URLRequest writes into. enum { kBufSize = 4096 }; scoped_refptr<net::IOBuffer> buf_; // The next ID to use for |cur_request_| (monotonically increasing). int next_id_; // The current (in progress) request, or NULL. scoped_ptr<URLRequest> cur_request_; // State for current request (only valid when |cur_request_| is not NULL): // Unique ID for the current request. int cur_request_id_; // Callback to invoke on completion of the fetch. CompletionCallback* callback_; // Holds the error condition that was hit on the current request, or OK. int result_code_; // Holds the bytes read so far. Will not exceed |max_response_bytes|. This // buffer is owned by the owner of |callback|. std::string* result_bytes_; }; ProxyScriptFetcherImpl::ProxyScriptFetcherImpl( URLRequestContext* url_request_context) : ALLOW_THIS_IN_INITIALIZER_LIST(task_factory_(this)), url_request_context_(url_request_context), buf_(new net::IOBuffer(kBufSize)), next_id_(0), cur_request_(NULL), cur_request_id_(0), callback_(NULL), result_code_(OK), result_bytes_(NULL) { DCHECK(url_request_context); } ProxyScriptFetcherImpl::~ProxyScriptFetcherImpl() { // The URLRequest's destructor will cancel the outstanding request, and // ensure that the delegate (this) is not called again. } void ProxyScriptFetcherImpl::Fetch(const GURL& url, std::string* bytes, CompletionCallback* callback) { // It is invalid to call Fetch() while a request is already in progress. DCHECK(!cur_request_.get()); DCHECK(callback); DCHECK(bytes); cur_request_.reset(new URLRequest(url, this)); cur_request_->set_context(url_request_context_); cur_request_->set_method("GET"); // Make sure that the PAC script is downloaded using a direct connection, // to avoid circular dependencies (fetching is a part of proxy resolution). cur_request_->set_load_flags(LOAD_BYPASS_PROXY); // Save the caller's info for notification on completion. callback_ = callback; result_bytes_ = bytes; result_bytes_->clear(); // Post a task to timeout this request if it takes too long. cur_request_id_ = ++next_id_; MessageLoop::current()->PostDelayedTask(FROM_HERE, task_factory_.NewRunnableMethod(&ProxyScriptFetcherImpl::OnTimeout, cur_request_id_), static_cast<int>(max_duration_ms)); // Start the request. cur_request_->Start(); } void ProxyScriptFetcherImpl::Cancel() { // ResetCurRequestState will free the URLRequest, which will cause // cancellation. ResetCurRequestState(); } void ProxyScriptFetcherImpl::OnAuthRequired(URLRequest* request, AuthChallengeInfo* auth_info) { DCHECK(request == cur_request_.get()); // TODO(eroman): LOG(WARNING) << "Auth required to fetch PAC script, aborting."; result_code_ = ERR_NOT_IMPLEMENTED; request->CancelAuth(); } void ProxyScriptFetcherImpl::OnSSLCertificateError(URLRequest* request, int cert_error, X509Certificate* cert) { DCHECK(request == cur_request_.get()); LOG(WARNING) << "SSL certificate error when fetching PAC script, aborting."; // Certificate errors are in same space as net errors. result_code_ = cert_error; request->Cancel(); } void ProxyScriptFetcherImpl::OnReceivedRedirect(URLRequest* request, const GURL& to_url) { DCHECK(request == cur_request_.get()); // OK, thanks for telling. } void ProxyScriptFetcherImpl::OnResponseStarted(URLRequest* request) { DCHECK(request == cur_request_.get()); if (!request->status().is_success()) { OnResponseCompleted(request); return; } // Require HTTP responses to have a success status code. if (request->url().SchemeIs("http") || request->url().SchemeIs("https")) { // NOTE about status codes: We are like Firefox 3 in this respect. // {IE 7, Safari 3, Opera 9.5} do not care about the status code. if (request->GetResponseCode() != 200) { result_code_ = ERR_PAC_STATUS_NOT_OK; request->Cancel(); return; } // NOTE about mime types: We do not enforce mime types on PAC files. // This is for compatibility with {IE 7, Firefox 3, Opera 9.5}. We will // however log mismatches to help with debugging. if (logging::GetMinLogLevel() <= logging::LOG_INFO) { std::string mime_type; cur_request_->GetMimeType(&mime_type); if (!!IsPacMimeType(mime_type)) { LOG(INFO) << "Fetched PAC script does not have a proper mime type: " << mime_type; } } } ReadBody(request); } void ProxyScriptFetcherImpl::OnReadCompleted(URLRequest* request, int num_bytes) { DCHECK(request == cur_request_.get()); if (num_bytes > 0) { // Enforce maximum size bound. if (num_bytes + result_bytes_->size() > static_cast<size_t>(max_response_bytes)) { result_code_ = ERR_FILE_TOO_BIG; request->Cancel(); return; } result_bytes_->append(buf_->data(), num_bytes); ReadBody(request); } else { // Error while reading, or EOF OnResponseCompleted(request); } } void ProxyScriptFetcherImpl::OnResponseCompleted(URLRequest* request) { DCHECK(request == cur_request_.get()); // Use |result_code_| as the request's error if we have already set it to // something specific. if (result_code_ == OK && !request->status().is_success()) result_code_ = request->status().os_error(); FetchCompleted(); } void ProxyScriptFetcherImpl::ReadBody(URLRequest* request) { int num_bytes; if (request->Read(buf_, kBufSize, &num_bytes)) { OnReadCompleted(request, num_bytes); } else if (!request->status().is_io_pending()) { // Read failed synchronously. OnResponseCompleted(request); } } void ProxyScriptFetcherImpl::FetchCompleted() { // On error, the caller expects empty string for bytes. if (result_code_ != OK) result_bytes_->clear(); int result_code = result_code_; CompletionCallback* callback = callback_; ResetCurRequestState(); callback->Run(result_code); } void ProxyScriptFetcherImpl::ResetCurRequestState() { cur_request_.reset(); cur_request_id_ = 0; callback_ = NULL; result_code_ = OK; result_bytes_ = NULL; } void ProxyScriptFetcherImpl::OnTimeout(int id) { // Timeout tasks may outlive the URLRequest they reference. Make sure it // is still applicable. if (cur_request_id_ != id) return; DCHECK(cur_request_.get()); result_code_ = ERR_TIMED_OUT; cur_request_->Cancel(); } // static ProxyScriptFetcher* ProxyScriptFetcher::Create( URLRequestContext* url_request_context) { return new ProxyScriptFetcherImpl(url_request_context); } // static int ProxyScriptFetcher::SetTimeoutConstraintForUnittest( int timeout_ms) { int prev = max_duration_ms; max_duration_ms = timeout_ms; return prev; } // static size_t ProxyScriptFetcher::SetSizeConstraintForUnittest(size_t size_bytes) { size_t prev = max_response_bytes; max_response_bytes = size_bytes; return prev; } } // namespace net <commit_msg>Fix a typo (one extra '!') in the previous checkin (r13601).<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved. Use of this // source code is governed by a BSD-style license that can be found in the // LICENSE file. #include "net/proxy/proxy_script_fetcher.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/ref_counted.h" #include "base/string_util.h" #include "net/base/io_buffer.h" #include "net/base/load_flags.h" #include "net/url_request/url_request.h" // TODO(eroman): // - Support auth-prompts. namespace net { namespace { // The maximum size (in bytes) allowed for a PAC script. Responses exceeding // this will fail with ERR_FILE_TOO_BIG. int max_response_bytes = 1048576; // 1 megabyte // The maximum duration (in milliseconds) allowed for fetching the PAC script. // Responses exceeding this will fail with ERR_TIMED_OUT. int max_duration_ms = 300000; // 5 minutes // Returns true if |mime_type| is one of the known PAC mime type. bool IsPacMimeType(const std::string& mime_type) { static const char * const kSupportedPacMimeTypes[] = { "application/x-ns-proxy-autoconfig", "application/x-javascript-config", }; for (size_t i = 0; i < arraysize(kSupportedPacMimeTypes); ++i) { if (LowerCaseEqualsASCII(mime_type, kSupportedPacMimeTypes[i])) return true; } return false; } } // namespace class ProxyScriptFetcherImpl : public ProxyScriptFetcher, public URLRequest::Delegate { public: // Creates a ProxyScriptFetcher that issues requests through // |url_request_context|. |url_request_context| must remain valid for the // lifetime of ProxyScriptFetcherImpl. explicit ProxyScriptFetcherImpl(URLRequestContext* url_request_context); virtual ~ProxyScriptFetcherImpl(); // ProxyScriptFetcher methods: virtual void Fetch(const GURL& url, std::string* bytes, CompletionCallback* callback); virtual void Cancel(); // URLRequest::Delegate methods: virtual void OnAuthRequired(URLRequest* request, AuthChallengeInfo* auth_info); virtual void OnSSLCertificateError(URLRequest* request, int cert_error, X509Certificate* cert); virtual void OnReceivedRedirect(URLRequest* request, const GURL& to_url); virtual void OnResponseStarted(URLRequest* request); virtual void OnReadCompleted(URLRequest* request, int num_bytes); virtual void OnResponseCompleted(URLRequest* request); private: // Read more bytes from the response. void ReadBody(URLRequest* request); // Called once the request has completed to notify the caller of // |response_code_| and |response_bytes_|. void FetchCompleted(); // Clear out the state for the current request. void ResetCurRequestState(); // Callback for time-out task of request with id |id|. void OnTimeout(int id); // Factory for creating the time-out task. This takes care of revoking // outstanding tasks when |this| is deleted. ScopedRunnableMethodFactory<ProxyScriptFetcherImpl> task_factory_; // The context used for making network requests. URLRequestContext* url_request_context_; // Buffer that URLRequest writes into. enum { kBufSize = 4096 }; scoped_refptr<net::IOBuffer> buf_; // The next ID to use for |cur_request_| (monotonically increasing). int next_id_; // The current (in progress) request, or NULL. scoped_ptr<URLRequest> cur_request_; // State for current request (only valid when |cur_request_| is not NULL): // Unique ID for the current request. int cur_request_id_; // Callback to invoke on completion of the fetch. CompletionCallback* callback_; // Holds the error condition that was hit on the current request, or OK. int result_code_; // Holds the bytes read so far. Will not exceed |max_response_bytes|. This // buffer is owned by the owner of |callback|. std::string* result_bytes_; }; ProxyScriptFetcherImpl::ProxyScriptFetcherImpl( URLRequestContext* url_request_context) : ALLOW_THIS_IN_INITIALIZER_LIST(task_factory_(this)), url_request_context_(url_request_context), buf_(new net::IOBuffer(kBufSize)), next_id_(0), cur_request_(NULL), cur_request_id_(0), callback_(NULL), result_code_(OK), result_bytes_(NULL) { DCHECK(url_request_context); } ProxyScriptFetcherImpl::~ProxyScriptFetcherImpl() { // The URLRequest's destructor will cancel the outstanding request, and // ensure that the delegate (this) is not called again. } void ProxyScriptFetcherImpl::Fetch(const GURL& url, std::string* bytes, CompletionCallback* callback) { // It is invalid to call Fetch() while a request is already in progress. DCHECK(!cur_request_.get()); DCHECK(callback); DCHECK(bytes); cur_request_.reset(new URLRequest(url, this)); cur_request_->set_context(url_request_context_); cur_request_->set_method("GET"); // Make sure that the PAC script is downloaded using a direct connection, // to avoid circular dependencies (fetching is a part of proxy resolution). cur_request_->set_load_flags(LOAD_BYPASS_PROXY); // Save the caller's info for notification on completion. callback_ = callback; result_bytes_ = bytes; result_bytes_->clear(); // Post a task to timeout this request if it takes too long. cur_request_id_ = ++next_id_; MessageLoop::current()->PostDelayedTask(FROM_HERE, task_factory_.NewRunnableMethod(&ProxyScriptFetcherImpl::OnTimeout, cur_request_id_), static_cast<int>(max_duration_ms)); // Start the request. cur_request_->Start(); } void ProxyScriptFetcherImpl::Cancel() { // ResetCurRequestState will free the URLRequest, which will cause // cancellation. ResetCurRequestState(); } void ProxyScriptFetcherImpl::OnAuthRequired(URLRequest* request, AuthChallengeInfo* auth_info) { DCHECK(request == cur_request_.get()); // TODO(eroman): LOG(WARNING) << "Auth required to fetch PAC script, aborting."; result_code_ = ERR_NOT_IMPLEMENTED; request->CancelAuth(); } void ProxyScriptFetcherImpl::OnSSLCertificateError(URLRequest* request, int cert_error, X509Certificate* cert) { DCHECK(request == cur_request_.get()); LOG(WARNING) << "SSL certificate error when fetching PAC script, aborting."; // Certificate errors are in same space as net errors. result_code_ = cert_error; request->Cancel(); } void ProxyScriptFetcherImpl::OnReceivedRedirect(URLRequest* request, const GURL& to_url) { DCHECK(request == cur_request_.get()); // OK, thanks for telling. } void ProxyScriptFetcherImpl::OnResponseStarted(URLRequest* request) { DCHECK(request == cur_request_.get()); if (!request->status().is_success()) { OnResponseCompleted(request); return; } // Require HTTP responses to have a success status code. if (request->url().SchemeIs("http") || request->url().SchemeIs("https")) { // NOTE about status codes: We are like Firefox 3 in this respect. // {IE 7, Safari 3, Opera 9.5} do not care about the status code. if (request->GetResponseCode() != 200) { result_code_ = ERR_PAC_STATUS_NOT_OK; request->Cancel(); return; } // NOTE about mime types: We do not enforce mime types on PAC files. // This is for compatibility with {IE 7, Firefox 3, Opera 9.5}. We will // however log mismatches to help with debugging. if (logging::GetMinLogLevel() <= logging::LOG_INFO) { std::string mime_type; cur_request_->GetMimeType(&mime_type); if (!IsPacMimeType(mime_type)) { LOG(INFO) << "Fetched PAC script does not have a proper mime type: " << mime_type; } } } ReadBody(request); } void ProxyScriptFetcherImpl::OnReadCompleted(URLRequest* request, int num_bytes) { DCHECK(request == cur_request_.get()); if (num_bytes > 0) { // Enforce maximum size bound. if (num_bytes + result_bytes_->size() > static_cast<size_t>(max_response_bytes)) { result_code_ = ERR_FILE_TOO_BIG; request->Cancel(); return; } result_bytes_->append(buf_->data(), num_bytes); ReadBody(request); } else { // Error while reading, or EOF OnResponseCompleted(request); } } void ProxyScriptFetcherImpl::OnResponseCompleted(URLRequest* request) { DCHECK(request == cur_request_.get()); // Use |result_code_| as the request's error if we have already set it to // something specific. if (result_code_ == OK && !request->status().is_success()) result_code_ = request->status().os_error(); FetchCompleted(); } void ProxyScriptFetcherImpl::ReadBody(URLRequest* request) { int num_bytes; if (request->Read(buf_, kBufSize, &num_bytes)) { OnReadCompleted(request, num_bytes); } else if (!request->status().is_io_pending()) { // Read failed synchronously. OnResponseCompleted(request); } } void ProxyScriptFetcherImpl::FetchCompleted() { // On error, the caller expects empty string for bytes. if (result_code_ != OK) result_bytes_->clear(); int result_code = result_code_; CompletionCallback* callback = callback_; ResetCurRequestState(); callback->Run(result_code); } void ProxyScriptFetcherImpl::ResetCurRequestState() { cur_request_.reset(); cur_request_id_ = 0; callback_ = NULL; result_code_ = OK; result_bytes_ = NULL; } void ProxyScriptFetcherImpl::OnTimeout(int id) { // Timeout tasks may outlive the URLRequest they reference. Make sure it // is still applicable. if (cur_request_id_ != id) return; DCHECK(cur_request_.get()); result_code_ = ERR_TIMED_OUT; cur_request_->Cancel(); } // static ProxyScriptFetcher* ProxyScriptFetcher::Create( URLRequestContext* url_request_context) { return new ProxyScriptFetcherImpl(url_request_context); } // static int ProxyScriptFetcher::SetTimeoutConstraintForUnittest( int timeout_ms) { int prev = max_duration_ms; max_duration_ms = timeout_ms; return prev; } // static size_t ProxyScriptFetcher::SetSizeConstraintForUnittest(size_t size_bytes) { size_t prev = max_response_bytes; max_response_bytes = size_bytes; return prev; } } // namespace net <|endoftext|>
<commit_before>#ifndef _ordering_annealing_cpp_included_ #define _ordering_annealing_cpp_included_ // c++ header files #include <algorithm> #include <cmath> #include <cstdio> #include <cstdlib> #include <ctime> #include <fstream> #include <iostream> #include <iterator> #include <string> #include <utility> #include <vector> // my header files #include "ordering-annealing.hpp" #include "ordering-io.hpp" #include "ordering-tools.hpp" // namespaces using namespace std; /***************************** This program reorders the elements of a matrix making first a blocking into kernels (so it is better that they are hierarchically clustered first. The program will not perform hierarhchical clustering itself. Then, the algorith repositions bloks selected at random, the width of the block is selected so that at low temperature is of size one. *****************************/ int ChangeSegmentOrder(vector<int>& order, int line1, int line2, int width){ if( line1 < line2 ) rotate(order.begin()+line1,order.begin()+line1+width,order.begin()+line2+width); else rotate(order.begin()+line2,order.begin()+line1,order.begin()+line1+width); return 1; } /****************************************************************/ int MakeChangeVectors(const vector <int>& order, vector<int>& change, vector<int>& nochange, int line1, int line2, int width, int n, const vector<int>& klines){ int i,in,in2,j,jmax, nk = klines.size(); vector<bool> changed(n,false); change.clear(); change.reserve(n); for(i=line1; i<line1+width; i++){ in = order[i]; if(in != nk-1) jmax = klines[in+1] - klines[in]; else jmax = n - klines[in]; for(j=0;j<jmax;j++){ change.push_back( klines[in] + j ); changed[klines[in]+j] = true; } } if(line1<line2){ for(i=line1+width; i<line2+width; i++){ in = order[i]; if(in != nk-1) jmax = klines[in+1] - klines[in]; else jmax = n-klines[in]; for(j=0; j<jmax; j++){ change.push_back( klines[in] + j ); changed[klines[in]+j] = true; } } } if( line1 > line2 ){ for(i=line2; i<line1; i++){ in = order[i]; if(in != nk-1) jmax = klines[in+1] - klines[in]; else jmax = n - klines[in]; for(j=0; j<jmax; j++){ change.push_back( klines[in] + j ); changed[klines[in]+j] = true; } } } nochange.clear(); nochange.reserve(n-change.size()); for(i=0;i<n;i++){ if(!changed[i]){ nochange.push_back(i); } } return 1; } /*************************************************************/ double ComputeEnergy(const vector<double>& mat, int netSize, const vector<int>& kernelOrder, const vector<int>& klines){ //kernelOrder: vector with the order of kernels //klines: line in original matrix where kernel starts int i,j; double energy = 0.; vector<int> nodeOrder = GetNodeOrder(kernelOrder, klines, netSize, 1); for(i=0;i<netSize-1;i++){ for(j=i+1;j<netSize;j++){ energy += double(abs(i-j)) * mat[ nodeOrder[i] + netSize* nodeOrder[j] ]; // cout<<i<< " "<<j<<" "<< nodeOrder[i] << " "<< netSize<<endl; // cout<<i<< " "<<j<<" "<<mat[ nodeOrder[i] + netSize* nodeOrder[j] ]<<endl; } } energy = 2*energy/double(netSize); return energy; } /*****************************************************************/ /*****************************************************************/ double EnergyChangeReOrd(const vector<double>& mat,int l1,int l2,int w,int n, const vector<int>& kernelOrder, const vector<int>& klines, vector<int>& newKernelOrder){ double deltaen = 0; unsigned int i,j; int line1,line2; int do1, do2, oo1, no1; // determine what the new order will be ChangeSegmentOrder(newKernelOrder,l1,l2,w); // only calculate a change in energy when some lines actually changed if(newKernelOrder != kernelOrder){ // determine what the node by node order is based on their kernels vector<int> oldorder,neworder; oldorder=GetNodeOrder(kernelOrder,klines,n,0); neworder=GetNodeOrder(newKernelOrder,klines,n,0); //make two vectors, one with the rows that //change position and one with the rows //that keep the same position vector<int> lchange,lfix; MakeChangeVectors(kernelOrder, lchange, lfix, l1, l2, w, n, klines); // calculate the change in energy only for pairs that are altered by change for(i=0;i<lchange.size();i++){ line1 = lchange[i]; oo1 = oldorder[line1]; no1 = neworder[line1]; for(j=0;j<lfix.size();j++){ line2=lfix[j]; do1 = abs(oo1-oldorder[line2]); do2 = abs(no1-neworder[line2]); deltaen+=mat[line1+line2*n]*(do2-do1); } for(j=i+1;j<lchange.size();j++){ line2=lchange[j]; do1 = abs(oo1-oldorder[line2]); do2 = abs(no1-neworder[line2]); deltaen+=mat[line1+line2*n]*(do2-do1); } } deltaen = 2*deltaen/double(n); } return deltaen; } /**************************************************************/ double AnnealStep(double temperature, const vector<double>& matrix, int netSize, vector <int>& order, int nblocks, const vector<int>& klines, bool freeStep) //Only reordering matrix rordering matrix { int line1,line2,width, nkernels=klines.size(); double deltaE; // double energy,energyold; // energyold=energy=ComputeEnergy(*mat, n, *order, klines); //1 pick two random numbers (starting line that we are swapping) line1 = line2 = width = 0; //"Computing line and width\n"; width = (int)( fabs(gauss(sqrt(temperature)*.05*nkernels) ) ) + nblocks; // width = nblocks; width -= (width%nblocks); line1 = width/2 + (int)( (nkernels-width)*ran1f() ); line1 -= width/2; line1 -= (line1%nblocks); if ( line1 < 0 ) line1 = 0; while( width > nkernels-line1 ){ width = (int)( fabs( gauss( sqrt(temperature)*.05*nkernels ) ) ) + nblocks; width -= (width%nblocks); } line2=(int)(gauss(sqrt(temperature)*.1)); if( line2 < 0 ){ line2 -= line1; if( line2 < 0 ) line2=0; } else{ line2 += line1 + width; if ( line2 > nkernels-width ) line2 = nkernels-width; } line2 -= (line2%nblocks); vector<int> neworder(order); deltaE = EnergyChangeReOrd(matrix, line1, line2, width, netSize, order, klines, neworder); if(freeStep || ranf() < exp( -deltaE/temperature )){ order = neworder; return deltaE; } return 0; } /**************************************************************/ void AnnealIter(double temperature, const vector<double>& matrix, const vector<int>& translationTable, const vector<vector<int> >& kernels, int nsteps,int n, vector<int>& order,double& energy,double& minenergy,int nblocks, const vector<int>& kline){ int step,i1,ii1; double deltaen; for( step=0; step<nsteps; step++ ){ deltaen = AnnealStep(temperature, matrix, n, order, nblocks, kline, false); energy += deltaen; if(energy < minenergy ){ minenergy = energy; //PrintMatrix( "coclas-minimum.dat", matrix, order, kline, n, 0); PrintTranstable( "transtable-minimum.dat", translationTable, order, kernels); PrintValue( "energy-minimum.dat", minenergy); } } } /**************************************************************/ void InitialTemp(double& temperature, const vector<double>& matrix, const vector<int>& translationTable, const vector<vector<int> >& kernels, int nsteps,int n, vector<int>& order, int nblocks, const vector<int>& kline){ int step; double deltaen; double initialProbability = 0.95; int i; vector<int> itorder(order); temperature = ComputeEnergy(matrix, n, itorder, kline); for(i=0;i<20;i++){ deltaen = 0; for( step=0; step<nsteps; step++ ){ deltaen += fabs(AnnealStep(temperature, matrix, n, itorder, nblocks, kline, true)); } deltaen /= double(nsteps); temperature = deltaen/(-log(initialProbability)); } order = itorder; } /*****************************************************************/ /*****************************************************************/ double ExhaustiveStep(const vector<double>& matrix,int n, vector<int>& order, const vector<int>& klines, int row, int nblocks) { int line1, line2, width, nk=klines.size(); double deltaE,maxdeltaE=0; int line=-1,wl=0; vector<int> maxorder, neworder(order); line1=row; //cout<<"Iterating \n"<<endl; for (width = nblocks; width>0 ; width--){ if( line1+width < nk ){ for (line2=0;line2<= nk-width;line2++){ if(line2<line1 || line2 >= line1+width){ deltaE = EnergyChangeReOrd(matrix, line1, line2, width, n, order, klines, neworder); if(deltaE<maxdeltaE){ maxdeltaE = deltaE; line = line2; wl = width; maxorder = neworder; } } } } } if(line !=-1){ order = maxorder; return maxdeltaE; } else{ return 0; } } void ExhaustiveIter(const vector<double>& matrix, int n, vector<int>& order, double& energy, const vector<int>& kline, int nblocks){ int step,nsteps=kline.size(); double deltaen; int line; for(step=0;step<nsteps;step++){ ///we try to change the kernel originally at position 0, line is ist current position line = find(order.begin(),order.end(),step) - order.begin(); deltaen = ExhaustiveStep(matrix, n, order, kline, line, nblocks); energy+=deltaen; } } #endif <commit_msg>removing a few more warnings about unused variables and making ChangeSegmentOrder fully consistent<commit_after>#ifndef _ordering_annealing_cpp_included_ #define _ordering_annealing_cpp_included_ // c++ header files #include <algorithm> #include <cmath> #include <cstdio> #include <cstdlib> #include <ctime> #include <fstream> #include <iostream> #include <iterator> #include <string> #include <utility> #include <vector> // my header files #include "ordering-annealing.hpp" #include "ordering-io.hpp" #include "ordering-tools.hpp" // namespaces using namespace std; /***************************** This program reorders the elements of a matrix making first a blocking into kernels (so it is better that they are hierarchically clustered first. The program will not perform hierarhchical clustering itself. Then, the algorith repositions bloks selected at random, the width of the block is selected so that at low temperature is of size one. *****************************/ int ChangeSegmentOrder(vector<int>& order, int line1, int line2, int width){ if( line1 < line2 ) rotate(order.begin()+line1,order.begin()+line2,order.begin()+line2+width); else rotate(order.begin()+line2,order.begin()+line1,order.begin()+line1+width); return 1; } /****************************************************************/ int MakeChangeVectors(const vector <int>& order, vector<int>& change, vector<int>& nochange, int line1, int line2, int width, int n, const vector<int>& klines){ int i,in,j,jmax, nk = klines.size(); vector<bool> changed(n,false); change.clear(); change.reserve(n); for(i=line1; i<line1+width; i++){ in = order[i]; if(in != nk-1) jmax = klines[in+1] - klines[in]; else jmax = n - klines[in]; for(j=0;j<jmax;j++){ change.push_back( klines[in] + j ); changed[klines[in]+j] = true; } } if(line1<line2){ for(i=line1+width; i<line2+width; i++){ in = order[i]; if(in != nk-1) jmax = klines[in+1] - klines[in]; else jmax = n-klines[in]; for(j=0; j<jmax; j++){ change.push_back( klines[in] + j ); changed[klines[in]+j] = true; } } } if( line1 > line2 ){ for(i=line2; i<line1; i++){ in = order[i]; if(in != nk-1) jmax = klines[in+1] - klines[in]; else jmax = n - klines[in]; for(j=0; j<jmax; j++){ change.push_back( klines[in] + j ); changed[klines[in]+j] = true; } } } nochange.clear(); nochange.reserve(n-change.size()); for(i=0;i<n;i++){ if(!changed[i]){ nochange.push_back(i); } } return 1; } /*************************************************************/ double ComputeEnergy(const vector<double>& mat, int netSize, const vector<int>& kernelOrder, const vector<int>& klines){ //kernelOrder: vector with the order of kernels //klines: line in original matrix where kernel starts int i,j; double energy = 0.; vector<int> nodeOrder = GetNodeOrder(kernelOrder, klines, netSize, 1); for(i=0;i<netSize-1;i++){ for(j=i+1;j<netSize;j++){ energy += double(abs(i-j)) * mat[ nodeOrder[i] + netSize* nodeOrder[j] ]; // cout<<i<< " "<<j<<" "<< nodeOrder[i] << " "<< netSize<<endl; // cout<<i<< " "<<j<<" "<<mat[ nodeOrder[i] + netSize* nodeOrder[j] ]<<endl; } } energy = 2*energy/double(netSize); return energy; } /*****************************************************************/ /*****************************************************************/ double EnergyChangeReOrd(const vector<double>& mat,int l1,int l2,int w,int n, const vector<int>& kernelOrder, const vector<int>& klines, vector<int>& newKernelOrder){ double deltaen = 0; unsigned int i,j; int line1,line2; int do1, do2, oo1, no1; // determine what the new order will be ChangeSegmentOrder(newKernelOrder,l1,l2,w); // only calculate a change in energy when some lines actually changed if(newKernelOrder != kernelOrder){ // determine what the node by node order is based on their kernels vector<int> oldorder,neworder; oldorder=GetNodeOrder(kernelOrder,klines,n,0); neworder=GetNodeOrder(newKernelOrder,klines,n,0); //make two vectors, one with the rows that //change position and one with the rows //that keep the same position vector<int> lchange,lfix; MakeChangeVectors(kernelOrder, lchange, lfix, l1, l2, w, n, klines); // calculate the change in energy only for pairs that are altered by change for(i=0;i<lchange.size();i++){ line1 = lchange[i]; oo1 = oldorder[line1]; no1 = neworder[line1]; for(j=0;j<lfix.size();j++){ line2=lfix[j]; do1 = abs(oo1-oldorder[line2]); do2 = abs(no1-neworder[line2]); deltaen+=mat[line1+line2*n]*(do2-do1); } for(j=i+1;j<lchange.size();j++){ line2=lchange[j]; do1 = abs(oo1-oldorder[line2]); do2 = abs(no1-neworder[line2]); deltaen+=mat[line1+line2*n]*(do2-do1); } } deltaen = 2*deltaen/double(n); } return deltaen; } /**************************************************************/ double AnnealStep(double temperature, const vector<double>& matrix, int netSize, vector <int>& order, int nblocks, const vector<int>& klines, bool freeStep) //Only reordering matrix rordering matrix { int line1,line2,width, nkernels=klines.size(); double deltaE; // double energy,energyold; // energyold=energy=ComputeEnergy(*mat, n, *order, klines); //1 pick two random numbers (starting line that we are swapping) line1 = line2 = width = 0; //"Computing line and width\n"; width = (int)( fabs(gauss(sqrt(temperature)*.05*nkernels) ) ) + nblocks; // width = nblocks; width -= (width%nblocks); line1 = width/2 + (int)( (nkernels-width)*ran1f() ); line1 -= width/2; line1 -= (line1%nblocks); if ( line1 < 0 ) line1 = 0; while( width > nkernels-line1 ){ width = (int)( fabs( gauss( sqrt(temperature)*.05*nkernels ) ) ) + nblocks; width -= (width%nblocks); } line2=(int)(gauss(sqrt(temperature)*.1)); if( line2 < 0 ){ line2 -= line1; if( line2 < 0 ) line2=0; } else{ line2 += line1 + width; if ( line2 > nkernels-width ) line2 = nkernels-width; } line2 -= (line2%nblocks); vector<int> neworder(order); deltaE = EnergyChangeReOrd(matrix, line1, line2, width, netSize, order, klines, neworder); if(freeStep || ranf() < exp( -deltaE/temperature )){ order = neworder; return deltaE; } return 0; } /**************************************************************/ void AnnealIter(double temperature, const vector<double>& matrix, const vector<int>& translationTable, const vector<vector<int> >& kernels, int nsteps,int n, vector<int>& order,double& energy,double& minenergy,int nblocks, const vector<int>& kline){ int step; //,i1,ii1; double deltaen; for( step=0; step<nsteps; step++ ){ deltaen = AnnealStep(temperature, matrix, n, order, nblocks, kline, false); energy += deltaen; if(energy < minenergy ){ minenergy = energy; //PrintMatrix( "coclas-minimum.dat", matrix, order, kline, n, 0); PrintTranstable( "transtable-minimum.dat", translationTable, order, kernels); PrintValue( "energy-minimum.dat", minenergy); } } } /**************************************************************/ void InitialTemp(double& temperature, const vector<double>& matrix, const vector<int>& translationTable, const vector<vector<int> >& kernels, int nsteps,int n, vector<int>& order, int nblocks, const vector<int>& kline){ int step; double deltaen; double initialProbability = 0.95; int i; vector<int> itorder(order); temperature = ComputeEnergy(matrix, n, itorder, kline); for(i=0;i<20;i++){ deltaen = 0; for( step=0; step<nsteps; step++ ){ deltaen += fabs(AnnealStep(temperature, matrix, n, itorder, nblocks, kline, true)); } deltaen /= double(nsteps); temperature = deltaen/(-log(initialProbability)); } order = itorder; } /*****************************************************************/ /*****************************************************************/ double ExhaustiveStep(const vector<double>& matrix,int n, vector<int>& order, const vector<int>& klines, int row, int nblocks) { int line1, line2, width, nk=klines.size(); double deltaE,maxdeltaE=0; int line=-1,wl=0; vector<int> maxorder, neworder(order); line1=row; //cout<<"Iterating \n"<<endl; for (width = nblocks; width>0 ; width--){ if( line1+width < nk ){ for (line2=0;line2<= nk-width;line2++){ if(line2<line1 || line2 >= line1+width){ deltaE = EnergyChangeReOrd(matrix, line1, line2, width, n, order, klines, neworder); if(deltaE<maxdeltaE){ maxdeltaE = deltaE; line = line2; wl = width; maxorder = neworder; } } } } } if(line !=-1){ order = maxorder; return maxdeltaE; } else{ return 0; } } void ExhaustiveIter(const vector<double>& matrix, int n, vector<int>& order, double& energy, const vector<int>& kline, int nblocks){ int step,nsteps=kline.size(); double deltaen; int line; for(step=0;step<nsteps;step++){ ///we try to change the kernel originally at position 0, line is ist current position line = find(order.begin(),order.end(),step) - order.begin(); deltaen = ExhaustiveStep(matrix, n, order, kline, line, nblocks); energy+=deltaen; } } #endif <|endoftext|>
<commit_before><commit_msg>set up the basic arena endpoint<commit_after><|endoftext|>
<commit_before><commit_msg>binding: fix build on *nix<commit_after><|endoftext|>
<commit_before>#include "Codegen.h" #include <stdexcept> #define __ m_Assembler. namespace snow { namespace x86_64 { static const Register* arg_regs[] = { &rdi, &rsi, &rdx, &rcx, &r8, &r9 }; static const Register* tmp_regs[] = { &rax, &r10, &r11, &rbx, &r12, &r13, &r14, &r15 }; static const bool preserve_regs[] = { false, false, false, true, true, true, true, true }; static inline Address addr_for_local(const Scope::Local& local) { return Address(rbp, (local.index + 1 + sizeof(StackFrame)) * -8, true); } static inline const Register& reg_for_arg(int index) { return *arg_regs[index]; } static inline const Register& reg_for_tmp(int index) { return *tmp_regs[index]; } void Codegen::preserve_tmp_reg(int index) { if (preserve_regs[index]) { m_CurrentScope.enter_asm->push(*tmp_regs[index]); m_PreservedTempRegisters.push_back(tmp_regs[index]); } } RefPtr<CompiledCode> Codegen::compile() { return __ compile(); } Scope Codegen::function_entry(int num_locals) { int stack_size = sizeof(StackFrame) + sizeof(VALUE)*num_locals; // maintain 16-byte stack alignment stack_size += stack_size % 16; // enter uses a 16-bit immediate for stack size if (stack_size < 1 << 16) __ enter(stack_size); else { // ... which may be too little __ push(rbp); __ mov(rsp, rbp); __ sub(stack_size, rsp); } // Establish scope x86_64::Assembler* enter_asm = new x86_64::Assembler; x86_64::Assembler* leave_asm = new x86_64::Assembler; if (m_CurrentScope.enter_asm) m_ScopeData.push_back(m_CurrentScope); m_CurrentScope = ScopeData(enter_asm, leave_asm); int stack_frame_offset = -(int)sizeof(StackFrame); // Create stack frame __ mov(rdi, rbx); // preserve first argument __ mov(num_locals, rcx); // frame->num_locals = num_locals __ mov(rcx, Address(rbp, stack_frame_offset+offsetof(StackFrame, num_locals))); __ mov(rbp, rax); __ add(stack_frame_offset, rax); __ mov(rax, rdi); // StackFrame* is first argument below __ sub(sizeof(VALUE)*num_locals, rax); // frame->locals = %rbp - stack_frame - locals __ mov(rax, Address(rbp, stack_frame_offset+offsetof(StackFrame, locals))); __ call("snow_create_stack_frame"); // initialize with runtime info __ mov(rbx, rdi); // restore first argument // Preserve registers __ subasm(enter_asm); return Scope(); } void Codegen::function_return() { // Restore non-volatile registers for (auto iter = riterate(m_PreservedTempRegisters); iter; ++iter) { m_CurrentScope.leave_asm->pop(**iter); } m_PreservedTempRegisters.clear(); __ subasm(m_CurrentScope.leave_asm); __ leave(); __ ret(); // Restore parent scope, if any if (m_ScopeData.size() > 0) { m_CurrentScope = ScopeData(m_ScopeData.back()); m_ScopeData.pop_back(); } else { m_CurrentScope = ScopeData(); } } void Codegen::set_argument(int index, const Scope::Local& src) { __ mov(addr_for_local(src), reg_for_arg(index)); } void Codegen::set_argument(int index, const Scope::Temporary& src) { __ mov(reg_for_tmp(src.index), reg_for_arg(index)); } void Codegen::set_argument(int index, const void* ptr) { __ mov((const char*)ptr, reg_for_arg(index)); } void Codegen::set_argument(int index, int immediate) { __ mov(immediate, reg_for_arg(index)); } void Codegen::get_argument(int index, const Scope::Local& dst) { __ mov(reg_for_arg(index), addr_for_local(dst)); } void Codegen::get_argument(int index, const Scope::Temporary& dst) { preserve_tmp_reg(dst.index); __ mov(reg_for_arg(index), reg_for_tmp(dst.index)); } void Codegen::set_return(const Scope::Local& src) { __ mov(addr_for_local(src), rax); } void Codegen::set_return(const Scope::Temporary& src) { if (reg_for_tmp(src.index) != rax) __ mov(reg_for_tmp(src.index), rax); } void Codegen::call(const char* symbol) { __ clear(rax); __ call(symbol); } void Codegen::call(const char* symbol, const Scope::Local& retval) { call(symbol); __ mov(rax, addr_for_local(retval)); } void Codegen::call(const char* symbol, const Scope::Temporary& retval) { call(symbol); if (reg_for_tmp(retval.index) != rax) __ mov(rax, reg_for_tmp(retval.index)); } } }<commit_msg>comment: stack layout<commit_after>#include "Codegen.h" #include <stdexcept> #define __ m_Assembler. namespace snow { namespace x86_64 { static const Register* arg_regs[] = { &rdi, &rsi, &rdx, &rcx, &r8, &r9 }; static const Register* tmp_regs[] = { &rax, &r10, &r11, &rbx, &r12, &r13, &r14, &r15 }; static const bool preserve_regs[] = { false, false, false, true, true, true, true, true }; static inline Address addr_for_local(const Scope::Local& local) { return Address(rbp, (local.index + 1 + sizeof(StackFrame)) * -8, true); } static inline const Register& reg_for_arg(int index) { return *arg_regs[index]; } static inline const Register& reg_for_tmp(int index) { return *tmp_regs[index]; } void Codegen::preserve_tmp_reg(int index) { if (preserve_regs[index]) { m_CurrentScope.enter_asm->push(*tmp_regs[index]); m_PreservedTempRegisters.push_back(tmp_regs[index]); } } RefPtr<CompiledCode> Codegen::compile() { return __ compile(); } Scope Codegen::function_entry(int num_locals) { /* STACK LAYOUT: struct StackFrame StackFrame* previous uint64_t num_locals VALUE* locals VALUE* local1 = self VALUE* local2 = arg1 VALUE* local3 = arg2 VALUE* local4 ... VALUE* local(num_locals-1) */ int stack_size = sizeof(StackFrame) + sizeof(VALUE)*num_locals; // maintain 16-byte stack alignment stack_size += stack_size % 16; // enter uses a 16-bit immediate for stack size if (stack_size < 1 << 16) __ enter(stack_size); else { // ... which may be too little __ push(rbp); __ mov(rsp, rbp); __ sub(stack_size, rsp); } // Establish scope x86_64::Assembler* enter_asm = new x86_64::Assembler; x86_64::Assembler* leave_asm = new x86_64::Assembler; if (m_CurrentScope.enter_asm) m_ScopeData.push_back(m_CurrentScope); m_CurrentScope = ScopeData(enter_asm, leave_asm); int stack_frame_offset = -(int)sizeof(StackFrame); // Create stack frame __ mov(rdi, rbx); // preserve first argument __ mov(num_locals, rcx); // frame->num_locals = num_locals __ mov(rcx, Address(rbp, stack_frame_offset+offsetof(StackFrame, num_locals))); __ mov(rbp, rax); __ add(stack_frame_offset, rax); __ mov(rax, rdi); // StackFrame* is first argument below __ sub(sizeof(VALUE)*num_locals, rax); // frame->locals = %rbp - stack_frame - locals __ mov(rax, Address(rbp, stack_frame_offset+offsetof(StackFrame, locals))); __ call("snow_create_stack_frame"); // initialize with runtime info __ mov(rbx, rdi); // restore first argument // Preserve registers __ subasm(enter_asm); return Scope(); } void Codegen::function_return() { // Restore non-volatile registers for (auto iter = riterate(m_PreservedTempRegisters); iter; ++iter) { m_CurrentScope.leave_asm->pop(**iter); } m_PreservedTempRegisters.clear(); __ subasm(m_CurrentScope.leave_asm); __ leave(); __ ret(); // Restore parent scope, if any if (m_ScopeData.size() > 0) { m_CurrentScope = ScopeData(m_ScopeData.back()); m_ScopeData.pop_back(); } else { m_CurrentScope = ScopeData(); } } void Codegen::set_argument(int index, const Scope::Local& src) { __ mov(addr_for_local(src), reg_for_arg(index)); } void Codegen::set_argument(int index, const Scope::Temporary& src) { __ mov(reg_for_tmp(src.index), reg_for_arg(index)); } void Codegen::set_argument(int index, const void* ptr) { __ mov((const char*)ptr, reg_for_arg(index)); } void Codegen::set_argument(int index, int immediate) { __ mov(immediate, reg_for_arg(index)); } void Codegen::get_argument(int index, const Scope::Local& dst) { __ mov(reg_for_arg(index), addr_for_local(dst)); } void Codegen::get_argument(int index, const Scope::Temporary& dst) { preserve_tmp_reg(dst.index); __ mov(reg_for_arg(index), reg_for_tmp(dst.index)); } void Codegen::set_return(const Scope::Local& src) { __ mov(addr_for_local(src), rax); } void Codegen::set_return(const Scope::Temporary& src) { if (reg_for_tmp(src.index) != rax) __ mov(reg_for_tmp(src.index), rax); } void Codegen::call(const char* symbol) { __ clear(rax); __ call(symbol); } void Codegen::call(const char* symbol, const Scope::Local& retval) { call(symbol); __ mov(rax, addr_for_local(retval)); } void Codegen::call(const char* symbol, const Scope::Temporary& retval) { call(symbol); if (reg_for_tmp(retval.index) != rax) __ mov(rax, reg_for_tmp(retval.index)); } } }<|endoftext|>
<commit_before><commit_msg>Flush the queue after every run iteration<commit_after><|endoftext|>
<commit_before>/* Q Light Controller Plus audio.cpp Copyright (c) Massimo Callegari Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <QCoreApplication> #include <QDomDocument> #include <QDomElement> #include <QDebug> #include <QFile> #include "audiodecoder.h" #ifdef HAS_LIBSNDFILE #include "audiodecoder_sndfile.h" #endif #ifdef HAS_LIBMAD #include "audiodecoder_mad.h" #endif #include "audiorenderer.h" #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #if defined(__APPLE__) || defined(Q_OS_MAC) #include "audiorenderer_portaudio.h" #elif defined(WIN32) || defined(Q_OS_WIN) #include "audiorenderer_waveout.h" #else #include "audiorenderer_alsa.h" #endif #else #include "audiorenderer_qt.h" #endif #include "audio.h" #include "doc.h" #define KXMLQLCAudioSource "Source" #define KXMLQLCAudioDevice "Device" #define KXMLQLCAudioStartTime "StartTime" #define KXMLQLCAudioColor "Color" #define KXMLQLCAudioLocked "Locked" /***************************************************************************** * Initialization *****************************************************************************/ Audio::Audio(Doc* doc) : Function(doc, Function::Audio) , m_doc(doc) , m_decoder(NULL) , m_audio_out(NULL) , m_audioDevice(QString()) , m_startTime(UINT_MAX) , m_color(96, 128, 83) , m_locked(false) , m_sourceFileName("") , m_audioDuration(0) { setName(tr("New Audio")); // Listen to member Function removals connect(doc, SIGNAL(functionRemoved(quint32)), this, SLOT(slotFunctionRemoved(quint32))); } Audio::~Audio() { if (m_audio_out != NULL) { m_audio_out->stop(); delete m_audio_out; } if (m_decoder != NULL) delete m_decoder; } /***************************************************************************** * Copying *****************************************************************************/ Function* Audio::createCopy(Doc* doc, bool addToDoc) { Q_ASSERT(doc != NULL); Function* copy = new Audio(doc); if (copy->copyFrom(this) == false) { delete copy; copy = NULL; } if (addToDoc == true && doc->addFunction(copy) == false) { delete copy; copy = NULL; } return copy; } bool Audio::copyFrom(const Function* function) { const Audio* aud = qobject_cast<const Audio*> (function); if (aud == NULL) return false; setSourceFileName(aud->m_sourceFileName); m_audioDuration = aud->m_audioDuration; m_color = aud->m_color; return Function::copyFrom(function); } QStringList Audio::getCapabilities() { QStringList cap; #ifdef HAS_LIBSNDFILE cap << AudioDecoderSndFile::getSupportedFormats(); #endif #ifdef HAS_LIBMAD cap << AudioDecoderMAD::getSupportedFormats(); #endif return cap; } /********************************************************************* * Properties *********************************************************************/ void Audio::setStartTime(quint32 time) { m_startTime = time; } quint32 Audio::getStartTime() const { return m_startTime; } qint64 Audio::totalDuration() { return m_audioDuration; } void Audio::setColor(QColor color) { m_color = color; } QColor Audio::getColor() { return m_color; } void Audio::setLocked(bool locked) { m_locked = locked; } bool Audio::isLocked() { return m_locked; } bool Audio::setSourceFileName(QString filename) { if (m_sourceFileName.isEmpty() == false) { // unload previous source if (m_decoder != NULL) { delete m_decoder; m_decoder = NULL; } } m_sourceFileName = filename; //QMessageBox::warning(0,"Warning", QString("File complete path: %1").arg(m_sourceFileName)); if (QFile(m_sourceFileName).exists()) setName(QFileInfo(m_sourceFileName).fileName()); else { setName(tr("File not found")); m_audioDuration = 0; emit changed(id()); return true; } #ifdef HAS_LIBSNDFILE m_decoder = new AudioDecoderSndFile(m_sourceFileName); if (m_decoder->initialize() == false) { delete m_decoder; m_decoder = NULL; } else { m_audioDuration = m_decoder->totalTime(); emit changed(id()); return true; } #endif #ifdef HAS_LIBMAD m_decoder = new AudioDecoderMAD(m_sourceFileName); if (m_decoder->initialize() == false) { delete m_decoder; m_decoder = NULL; } else { m_audioDuration = m_decoder->totalTime(); emit changed(id()); return true; } #endif return false; } QString Audio::getSourceFileName() { return m_sourceFileName; } AudioDecoder* Audio::getAudioDecoder() { return m_decoder; } void Audio::setAudioDevice(QString dev) { m_audioDevice = dev; } QString Audio::audioDevice() { return m_audioDevice; } void Audio::adjustAttribute(qreal fraction, int attributeIndex) { if (m_audio_out != NULL && attributeIndex == Intensity) m_audio_out->adjustIntensity(fraction); Function::adjustAttribute(fraction, attributeIndex); } void Audio::slotEndOfStream() { if (m_audio_out != NULL) { m_audio_out->stop(); m_audio_out->deleteLater(); m_audio_out = NULL; m_decoder->seek(0); } Function::postRun(NULL, QList<Universe *>()); } void Audio::slotFunctionRemoved(quint32 fid) { Q_UNUSED(fid) } /********************************************************************* * Save & Load *********************************************************************/ bool Audio::saveXML(QDomDocument* doc, QDomElement* wksp_root) { QDomElement root; QDomText text; Q_ASSERT(doc != NULL); Q_ASSERT(wksp_root != NULL); /* Function tag */ root = doc->createElement(KXMLQLCFunction); wksp_root->appendChild(root); /* Common attributes */ saveXMLCommon(&root); /* Speed */ saveXMLSpeed(doc, &root); QDomElement source = doc->createElement(KXMLQLCAudioSource); if (m_audioDevice.isEmpty() == false) source.setAttribute(KXMLQLCAudioDevice, m_audioDevice); text = doc->createTextNode(m_doc->normalizeComponentPath(m_sourceFileName)); source.appendChild(text); root.appendChild(source); return true; } bool Audio::loadXML(const QDomElement& root) { if (root.tagName() != KXMLQLCFunction) { qWarning() << Q_FUNC_INFO << "Function node not found"; return false; } if (root.attribute(KXMLQLCFunctionType) != typeToString(Function::Audio)) { qWarning() << Q_FUNC_INFO << root.attribute(KXMLQLCFunctionType) << "is not Audio"; return false; } QString fname = name(); QDomNode node = root.firstChild(); while (node.isNull() == false) { QDomElement tag = node.toElement(); if (tag.tagName() == KXMLQLCAudioSource) { if (tag.hasAttribute(KXMLQLCAudioDevice)) setAudioDevice(tag.attribute(KXMLQLCAudioDevice)); if (tag.hasAttribute(KXMLQLCAudioStartTime)) setStartTime(tag.attribute(KXMLQLCAudioStartTime).toUInt()); if (tag.hasAttribute(KXMLQLCAudioColor)) setColor(QColor(tag.attribute(KXMLQLCAudioColor))); if (tag.hasAttribute(KXMLQLCAudioLocked)) setLocked(true); setSourceFileName(m_doc->denormalizeComponentPath(tag.text())); } else if (tag.tagName() == KXMLQLCFunctionSpeed) { loadXMLSpeed(tag); } node = node.nextSibling(); } setName(fname); return true; } void Audio::postLoad() { } /********************************************************************* * Running *********************************************************************/ void Audio::preRun(MasterTimer* timer) { if (m_decoder != NULL) { m_decoder->seek(elapsed()); AudioParameters ap = m_decoder->audioParameters(); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #if defined(__APPLE__) || defined(Q_OS_MAC) //m_audio_out = new AudioRendererCoreAudio(); m_audio_out = new AudioRendererPortAudio(m_audioDevice); #elif defined(WIN32) || defined(Q_OS_WIN) m_audio_out = new AudioRendererWaveOut(m_audioDevice); #else m_audio_out = new AudioRendererAlsa(m_audioDevice); #endif m_audio_out->moveToThread(QCoreApplication::instance()->thread()); #else m_audio_out = new AudioRendererQt(m_audioDevice); #endif m_audio_out->setDecoder(m_decoder); m_audio_out->initialize(ap.sampleRate(), ap.channels(), ap.format()); m_audio_out->setFadeIn(fadeInSpeed()); m_audio_out->start(); m_audio_out->adjustIntensity(getAttributeValue(Intensity)); connect(m_audio_out, SIGNAL(endOfStreamReached()), this, SLOT(slotEndOfStream())); } else return; // avoid this function to even start Function::preRun(timer); } void Audio::write(MasterTimer* timer, QList<Universe *> universes) { Q_UNUSED(timer) Q_UNUSED(universes) incrementElapsed(); if (fadeOutSpeed() != 0) { if (m_audio_out != NULL && totalDuration() - elapsed() <= fadeOutSpeed()) m_audio_out->setFadeOut(fadeOutSpeed()); } } void Audio::postRun(MasterTimer* timer, QList<Universe*> universes) { Q_UNUSED(timer) Q_UNUSED(universes) slotEndOfStream(); } <commit_msg>engine: fixed audio end of stream not stopping the running function<commit_after>/* Q Light Controller Plus audio.cpp Copyright (c) Massimo Callegari Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <QCoreApplication> #include <QDomDocument> #include <QDomElement> #include <QDebug> #include <QFile> #include "audiodecoder.h" #ifdef HAS_LIBSNDFILE #include "audiodecoder_sndfile.h" #endif #ifdef HAS_LIBMAD #include "audiodecoder_mad.h" #endif #include "audiorenderer.h" #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #if defined(__APPLE__) || defined(Q_OS_MAC) #include "audiorenderer_portaudio.h" #elif defined(WIN32) || defined(Q_OS_WIN) #include "audiorenderer_waveout.h" #else #include "audiorenderer_alsa.h" #endif #else #include "audiorenderer_qt.h" #endif #include "audio.h" #include "doc.h" #define KXMLQLCAudioSource "Source" #define KXMLQLCAudioDevice "Device" #define KXMLQLCAudioStartTime "StartTime" #define KXMLQLCAudioColor "Color" #define KXMLQLCAudioLocked "Locked" /***************************************************************************** * Initialization *****************************************************************************/ Audio::Audio(Doc* doc) : Function(doc, Function::Audio) , m_doc(doc) , m_decoder(NULL) , m_audio_out(NULL) , m_audioDevice(QString()) , m_startTime(UINT_MAX) , m_color(96, 128, 83) , m_locked(false) , m_sourceFileName("") , m_audioDuration(0) { setName(tr("New Audio")); // Listen to member Function removals connect(doc, SIGNAL(functionRemoved(quint32)), this, SLOT(slotFunctionRemoved(quint32))); } Audio::~Audio() { if (m_audio_out != NULL) { m_audio_out->stop(); delete m_audio_out; } if (m_decoder != NULL) delete m_decoder; } /***************************************************************************** * Copying *****************************************************************************/ Function* Audio::createCopy(Doc* doc, bool addToDoc) { Q_ASSERT(doc != NULL); Function* copy = new Audio(doc); if (copy->copyFrom(this) == false) { delete copy; copy = NULL; } if (addToDoc == true && doc->addFunction(copy) == false) { delete copy; copy = NULL; } return copy; } bool Audio::copyFrom(const Function* function) { const Audio* aud = qobject_cast<const Audio*> (function); if (aud == NULL) return false; setSourceFileName(aud->m_sourceFileName); m_audioDuration = aud->m_audioDuration; m_color = aud->m_color; return Function::copyFrom(function); } QStringList Audio::getCapabilities() { QStringList cap; #ifdef HAS_LIBSNDFILE cap << AudioDecoderSndFile::getSupportedFormats(); #endif #ifdef HAS_LIBMAD cap << AudioDecoderMAD::getSupportedFormats(); #endif return cap; } /********************************************************************* * Properties *********************************************************************/ void Audio::setStartTime(quint32 time) { m_startTime = time; } quint32 Audio::getStartTime() const { return m_startTime; } qint64 Audio::totalDuration() { return m_audioDuration; } void Audio::setColor(QColor color) { m_color = color; } QColor Audio::getColor() { return m_color; } void Audio::setLocked(bool locked) { m_locked = locked; } bool Audio::isLocked() { return m_locked; } bool Audio::setSourceFileName(QString filename) { if (m_sourceFileName.isEmpty() == false) { // unload previous source if (m_decoder != NULL) { delete m_decoder; m_decoder = NULL; } } m_sourceFileName = filename; //QMessageBox::warning(0,"Warning", QString("File complete path: %1").arg(m_sourceFileName)); if (QFile(m_sourceFileName).exists()) setName(QFileInfo(m_sourceFileName).fileName()); else { setName(tr("File not found")); m_audioDuration = 0; emit changed(id()); return true; } #ifdef HAS_LIBSNDFILE m_decoder = new AudioDecoderSndFile(m_sourceFileName); if (m_decoder->initialize() == false) { delete m_decoder; m_decoder = NULL; } else { m_audioDuration = m_decoder->totalTime(); emit changed(id()); return true; } #endif #ifdef HAS_LIBMAD m_decoder = new AudioDecoderMAD(m_sourceFileName); if (m_decoder->initialize() == false) { delete m_decoder; m_decoder = NULL; } else { m_audioDuration = m_decoder->totalTime(); emit changed(id()); return true; } #endif return false; } QString Audio::getSourceFileName() { return m_sourceFileName; } AudioDecoder* Audio::getAudioDecoder() { return m_decoder; } void Audio::setAudioDevice(QString dev) { m_audioDevice = dev; } QString Audio::audioDevice() { return m_audioDevice; } void Audio::adjustAttribute(qreal fraction, int attributeIndex) { if (m_audio_out != NULL && attributeIndex == Intensity) m_audio_out->adjustIntensity(fraction); Function::adjustAttribute(fraction, attributeIndex); } void Audio::slotEndOfStream() { if (m_audio_out != NULL) { m_audio_out->stop(); m_audio_out->deleteLater(); m_audio_out = NULL; m_decoder->seek(0); } Function::postRun(NULL, QList<Universe *>()); if (!stopped()) stop(); } void Audio::slotFunctionRemoved(quint32 fid) { Q_UNUSED(fid) } /********************************************************************* * Save & Load *********************************************************************/ bool Audio::saveXML(QDomDocument* doc, QDomElement* wksp_root) { QDomElement root; QDomText text; Q_ASSERT(doc != NULL); Q_ASSERT(wksp_root != NULL); /* Function tag */ root = doc->createElement(KXMLQLCFunction); wksp_root->appendChild(root); /* Common attributes */ saveXMLCommon(&root); /* Speed */ saveXMLSpeed(doc, &root); QDomElement source = doc->createElement(KXMLQLCAudioSource); if (m_audioDevice.isEmpty() == false) source.setAttribute(KXMLQLCAudioDevice, m_audioDevice); text = doc->createTextNode(m_doc->normalizeComponentPath(m_sourceFileName)); source.appendChild(text); root.appendChild(source); return true; } bool Audio::loadXML(const QDomElement& root) { if (root.tagName() != KXMLQLCFunction) { qWarning() << Q_FUNC_INFO << "Function node not found"; return false; } if (root.attribute(KXMLQLCFunctionType) != typeToString(Function::Audio)) { qWarning() << Q_FUNC_INFO << root.attribute(KXMLQLCFunctionType) << "is not Audio"; return false; } QString fname = name(); QDomNode node = root.firstChild(); while (node.isNull() == false) { QDomElement tag = node.toElement(); if (tag.tagName() == KXMLQLCAudioSource) { if (tag.hasAttribute(KXMLQLCAudioDevice)) setAudioDevice(tag.attribute(KXMLQLCAudioDevice)); if (tag.hasAttribute(KXMLQLCAudioStartTime)) setStartTime(tag.attribute(KXMLQLCAudioStartTime).toUInt()); if (tag.hasAttribute(KXMLQLCAudioColor)) setColor(QColor(tag.attribute(KXMLQLCAudioColor))); if (tag.hasAttribute(KXMLQLCAudioLocked)) setLocked(true); setSourceFileName(m_doc->denormalizeComponentPath(tag.text())); } else if (tag.tagName() == KXMLQLCFunctionSpeed) { loadXMLSpeed(tag); } node = node.nextSibling(); } setName(fname); return true; } void Audio::postLoad() { } /********************************************************************* * Running *********************************************************************/ void Audio::preRun(MasterTimer* timer) { if (m_decoder != NULL) { m_decoder->seek(elapsed()); AudioParameters ap = m_decoder->audioParameters(); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #if defined(__APPLE__) || defined(Q_OS_MAC) //m_audio_out = new AudioRendererCoreAudio(); m_audio_out = new AudioRendererPortAudio(m_audioDevice); #elif defined(WIN32) || defined(Q_OS_WIN) m_audio_out = new AudioRendererWaveOut(m_audioDevice); #else m_audio_out = new AudioRendererAlsa(m_audioDevice); #endif m_audio_out->moveToThread(QCoreApplication::instance()->thread()); #else m_audio_out = new AudioRendererQt(m_audioDevice); #endif m_audio_out->setDecoder(m_decoder); m_audio_out->initialize(ap.sampleRate(), ap.channels(), ap.format()); m_audio_out->setFadeIn(fadeInSpeed()); m_audio_out->start(); m_audio_out->adjustIntensity(getAttributeValue(Intensity)); connect(m_audio_out, SIGNAL(endOfStreamReached()), this, SLOT(slotEndOfStream())); } Function::preRun(timer); } void Audio::write(MasterTimer* timer, QList<Universe *> universes) { Q_UNUSED(timer) Q_UNUSED(universes) incrementElapsed(); if (fadeOutSpeed() != 0) { if (m_audio_out != NULL && totalDuration() - elapsed() <= fadeOutSpeed()) m_audio_out->setFadeOut(fadeOutSpeed()); } } void Audio::postRun(MasterTimer* timer, QList<Universe*> universes) { Q_UNUSED(timer) Q_UNUSED(universes) slotEndOfStream(); } <|endoftext|>
<commit_before><commit_msg>config: wrap statefs_variant string in dquotes<commit_after><|endoftext|>
<commit_before><commit_msg>fcache: convert functions to methods<commit_after><|endoftext|>
<commit_before><commit_msg>Removed useless preprocessing<commit_after><|endoftext|>
<commit_before><commit_msg>Delete floppy.cpp<commit_after><|endoftext|>
<commit_before>#include <iomanip> #include "server.hpp" #include "tools.hpp" #include "test_tool.hpp" // 🍣🍣🍣 パーサ 🍣🍣🍣 void pcserver::parse(question_data const& problem, answer_type const& answer) { // outputに本番サーバと同じ情報、outerrにそれ以外を吐く std::cerr << "TARGET CAPTURED...\n"; test_tool::emulator emu(problem); std::cerr << "BODY SENSOR\n"; auto const result = emu.start(answer); std::cerr << "EMULATED EMULATED EMULATED\n"; output << "ACCEPTED " << std::setw(2) << std::setfill('0') << result.wrong << std::endl; sane = true; } <commit_msg>emulatorの例外を受け取るようにした<commit_after>#include <iomanip> #include "server.hpp" #include "tools.hpp" #include "test_tool.hpp" // 🍣🍣🍣 パーサ 🍣🍣🍣 void pcserver::parse(question_data const& problem, answer_type const& answer) { // outputに本番サーバと同じ情報、outerrにそれ以外を吐く try { std::cerr << "TARGET CAPTURED...\n"; test_tool::emulator emu(problem); std::cerr << "BODY SENSOR\n"; auto const result = emu.start(answer); std::cerr << "EMULATED EMULATED EMULATED\n"; output << "ACCEPTED " << std::setw(2) << std::setfill('0') << result.wrong << std::endl; sane = true; } catch(std::exception &e) { outerr << e.what() << std::endl; } } <|endoftext|>
<commit_before>// Copyright 2016 Strength in Numbers Foundation #include "giftcardpage.h" #include "ui_giftcardpage.h" #include "giftcardtablemodel.h" #include "optionsmodel.h" #include "bitcoingui.h" #include "creategiftdialog.h" #include "csvmodelwriter.h" #include "guiutil.h" #include "paperwallet.h" #include <QSortFilterProxyModel> #include <QClipboard> #include <QMessageBox> #include <QMenu> #include <QDir> #include <QFile> #include <QTextStream> #include <QDesktopServices> // dvd add for launching URL #include <QUrl> // dvd add for launching URL #ifdef USE_QRCODE #include "qrcodedialog.h" #endif extern int VanityGen(int addrtype, char *prefix, char *pubKey, char *privKey); GiftCardPage::GiftCardPage(Mode mode, Tabs tab, QWidget *parent) : QDialog(parent), ui(new Ui::GiftCardPage), model(0), optionsModel(0), mode(mode), tab(tab) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->newAddressButton->setIcon(QIcon()); ui->templateButton->setIcon(QIcon()); ui->copyToClipboard->setIcon(QIcon()); ui->deleteButton->setIcon(QIcon()); #endif #ifndef USE_QRCODE ui->showQRCode->setVisible(false); #endif switch(mode) { case ForSending: connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); break; case ForEditing: ui->buttonBox->setVisible(false); break; } ui->labelExplanation->setVisible(true); ui->deleteButton->setVisible(true); ui->signMessage->setVisible(false); //dvd considering adding a "Give" option from the right click // Context menu actions QAction *copyLabelAction = new QAction(tr("Copy &Label"), this); QAction *copyAddressAction = new QAction(ui->copyToClipboard->text(), this); QAction *editAction = new QAction(tr("&Edit"), this); QAction *showQRCodeAction = new QAction(ui->showQRCode->text(), this); // QAction *signMessageAction = new QAction(ui->signMessage->text(), this); QAction *verifyMessageAction = new QAction(ui->verifyMessage->text(), this); deleteAction = new QAction(ui->deleteButton->text(), this); // Build context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); contextMenu->addAction(deleteAction); contextMenu->addSeparator(); contextMenu->addAction(showQRCodeAction); contextMenu->addAction(verifyMessageAction); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyToClipboard_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteButton_clicked())); connect(showQRCodeAction, SIGNAL(triggered()), this, SLOT(on_showQRCode_clicked())); // connect(signMessageAction, SIGNAL(triggered()), this, SLOT(on_signMessage_clicked())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(on_verifyMessage_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); // Pass through accept action from button box connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); // Set default filepath to save to filePath = QDir::homePath(); printf("homePath = %s\n", filePath.toStdString().c_str()); } GiftCardPage::~GiftCardPage() { delete ui; } void GiftCardPage::setModel(GiftCardTableModel *model) { this->model = model; if(!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterRole(GiftCardTableModel::TypeRole); proxyModel->setFilterFixedString(GiftCardTableModel::Gift); ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->resizeSection( GiftCardTableModel::Address, 333); ui->tableView->horizontalHeader()->setResizeMode( GiftCardTableModel::Label, QHeaderView::Stretch); #else ui->tableView->horizontalHeader()->setSectionResizeMode(GiftCardTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(GiftCardTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int))); selectionChanged(); } void GiftCardPage::setOptionsModel(OptionsModel *optionsModel) { this->optionsModel = optionsModel; } void GiftCardPage::on_copyToClipboard_clicked() { GUIUtil::copyEntryData(ui->tableView, GiftCardTableModel::Address); } void GiftCardPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, GiftCardTableModel::Label); } void GiftCardPage::onEditAction() { if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; CreateGiftDialog dlg(CreateGiftDialog::EditGiftAddress); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void GiftCardPage::on_signMessage_clicked() { QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(GiftCardTableModel::Address); QString addr; foreach (QModelIndex index, indexes) { QVariant address = index.data(); addr = address.toString(); } emit signMessage(addr); } void GiftCardPage::on_verifyMessage_clicked() { QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(GiftCardTableModel::Address); QString addr; foreach (QModelIndex index, indexes) { QVariant address = index.data(); addr = address.toString(); } emit verifyMessage(addr); } void GiftCardPage::on_newAddressButton_clicked() { char strPubKey[256], strPrivKey[256]; if(!model) return; printf("GiftCardPage::on_newAddressButton(): CreateGiftDialog\n"); CreateGiftDialog dlg(CreateGiftDialog::NewGiftAddress); dlg.setModel(model); if(dlg.exec()) { printf("GiftCardPage::on_newAddressButton(): dlg.exec()\n"); newAddressToSelect = dlg.getAddress(); QStringList giftKeys = newAddressToSelect.split(":"); strcpy(strPubKey, giftKeys.at(0).toStdString().c_str()); strcpy(strPrivKey, giftKeys.at(1).toStdString().c_str()); printf("strPubKey = %s\tstrPrivKey = %s\n", strPubKey, strPrivKey); // QString appDirPath = QCoreApplication::applicationDirPath(); // printf("appDirPath = %s\n", appDirPath.toStdString().c_str()); QString defaultFileName = filePath + QDir::separator() + giftKeys.at(0) + ".html"; QString fileName = GUIUtil::getSaveFileName( this, tr("Save Gift* Card"), defaultFileName, tr(".html")); if (!fileName.isNull()) { PaperWallet pWallet = PaperWallet::PaperWallet(fileName, giftKeys.at(0), giftKeys.at(1), ""); if (pWallet.genWallet()) { QFile file(fileName); if (file.exists()) { // save the user selected folder for easy next use QFileInfo fileInfo(file.fileName()); filePath = fileInfo.absolutePath(); // launch browser to display/print QString url = "file://" + fileName; QDesktopServices::openUrl(QUrl(url)); } } } } } void GiftCardPage::on_templateButton_clicked() { QMessageBox msgBox; msgBox.setWindowTitle("Update Templates"); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); PaperWallet pWallet = PaperWallet("", "", "", ""); if (pWallet.updateTemplates()) msgBox.setText("Template Update Successful"); else { msgBox.setText("Template Update Failed"); msgBox.setInformativeText("Check your network connectivity and retry"); } msgBox.exec(); } void GiftCardPage::on_deleteButton_clicked() { QTableView *table = ui->tableView; if(!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if(!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void GiftCardPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { // In gift tab, allow deletion of selection ui->deleteButton->setEnabled(true); ui->deleteButton->setVisible(true); deleteAction->setEnabled(true); ui->signMessage->setEnabled(false); ui->signMessage->setVisible(false); ui->verifyMessage->setEnabled(true); ui->verifyMessage->setVisible(true); ui->copyToClipboard->setEnabled(true); ui->showQRCode->setEnabled(true); } else { ui->deleteButton->setEnabled(false); ui->showQRCode->setEnabled(false); ui->copyToClipboard->setEnabled(false); ui->signMessage->setEnabled(false); ui->verifyMessage->setEnabled(false); } } void GiftCardPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // When this is a tab/widget and not a model dialog, ignore "done" if(mode == ForEditing) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(GiftCardTableModel::Address); foreach (QModelIndex index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if(returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void GiftCardPage::exportClicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName( this, tr("Export Address Book Data"), QString(), tr("Comma separated file (*.csv)")); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", GiftCardTableModel::Label, Qt::EditRole); writer.addColumn("Address", GiftCardTableModel::Address, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename), QMessageBox::Abort, QMessageBox::Abort); } } void GiftCardPage::on_showQRCode_clicked() { #ifdef USE_QRCODE QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(GiftCardTableModel::Address); foreach (QModelIndex index, indexes) { QString address = index.data().toString(), label = index.sibling(index.row(), 0).data(Qt::EditRole).toString(); QRCodeDialog *dialog = new QRCodeDialog(address, label, tab == ReceivingTab, this); if(optionsModel) dialog->setModel(optionsModel); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); } #endif } void GiftCardPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void GiftCardPage::selectNewAddress(const QModelIndex &parent, int begin, int end) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, GiftCardTableModel::Address, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } } <commit_msg>See previous commit :p<commit_after>// Copyright 2016 Strength in Numbers Foundation #include "giftcardpage.h" #include "ui_giftcardpage.h" #include "giftcardtablemodel.h" #include "optionsmodel.h" #include "bitcoingui.h" #include "creategiftdialog.h" #include "csvmodelwriter.h" #include "guiutil.h" #include "paperwallet.h" #include <QSortFilterProxyModel> #include <QClipboard> #include <QMessageBox> #include <QMenu> #include <QDir> #include <QFile> #include <QTextStream> #include <QDesktopServices> // dvd add for launching URL #include <QUrl> // dvd add for launching URL #ifdef USE_QRCODE #include "qrcodedialog.h" #endif extern int VanityGen(int addrtype, char *prefix, char *pubKey, char *privKey); GiftCardPage::GiftCardPage(Mode mode, Tabs tab, QWidget *parent) : QDialog(parent), ui(new Ui::GiftCardPage), model(0), optionsModel(0), mode(mode), tab(tab) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->newAddressButton->setIcon(QIcon()); ui->templateButton->setIcon(QIcon()); ui->copyToClipboard->setIcon(QIcon()); ui->deleteButton->setIcon(QIcon()); #endif #ifndef USE_QRCODE ui->showQRCode->setVisible(false); #endif switch(mode) { case ForSending: connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); break; case ForEditing: ui->buttonBox->setVisible(false); break; } ui->labelExplanation->setVisible(true); ui->deleteButton->setVisible(true); ui->signMessage->setVisible(false); //dvd considering adding a "Give" option from the right click // Context menu actions QAction *copyLabelAction = new QAction(tr("Copy &Label"), this); QAction *copyAddressAction = new QAction(ui->copyToClipboard->text(), this); QAction *editAction = new QAction(tr("&Edit"), this); QAction *showQRCodeAction = new QAction(ui->showQRCode->text(), this); // QAction *signMessageAction = new QAction(ui->signMessage->text(), this); QAction *verifyMessageAction = new QAction(ui->verifyMessage->text(), this); deleteAction = new QAction(ui->deleteButton->text(), this); // Build context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); contextMenu->addAction(deleteAction); contextMenu->addSeparator(); contextMenu->addAction(showQRCodeAction); contextMenu->addAction(verifyMessageAction); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyToClipboard_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteButton_clicked())); connect(showQRCodeAction, SIGNAL(triggered()), this, SLOT(on_showQRCode_clicked())); // connect(signMessageAction, SIGNAL(triggered()), this, SLOT(on_signMessage_clicked())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(on_verifyMessage_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); // Pass through accept action from button box connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); // Set default filepath to save to filePath = QDir::homePath(); printf("homePath = %s\n", filePath.toStdString().c_str()); } GiftCardPage::~GiftCardPage() { delete ui; } void GiftCardPage::setModel(GiftCardTableModel *model) { this->model = model; if(!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterRole(GiftCardTableModel::TypeRole); proxyModel->setFilterFixedString(GiftCardTableModel::Gift); ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->resizeSection( GiftCardTableModel::Address, 333); ui->tableView->horizontalHeader()->setResizeMode( GiftCardTableModel::Label, QHeaderView::Stretch); #else ui->tableView->horizontalHeader()->setSectionResizeMode(GiftCardTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(GiftCardTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int))); selectionChanged(); } void GiftCardPage::setOptionsModel(OptionsModel *optionsModel) { this->optionsModel = optionsModel; } void GiftCardPage::on_copyToClipboard_clicked() { GUIUtil::copyEntryData(ui->tableView, GiftCardTableModel::Address); } void GiftCardPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, GiftCardTableModel::Label); } void GiftCardPage::onEditAction() { if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; CreateGiftDialog dlg(CreateGiftDialog::EditGiftAddress); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void GiftCardPage::on_signMessage_clicked() { QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(GiftCardTableModel::Address); QString addr; foreach (QModelIndex index, indexes) { QVariant address = index.data(); addr = address.toString(); } emit signMessage(addr); } void GiftCardPage::on_verifyMessage_clicked() { QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(GiftCardTableModel::Address); QString addr; foreach (QModelIndex index, indexes) { QVariant address = index.data(); addr = address.toString(); } emit verifyMessage(addr); } void GiftCardPage::on_newAddressButton_clicked() { char strPubKey[256], strPrivKey[256]; if(!model) return; printf("GiftCardPage::on_newAddressButton(): CreateGiftDialog\n"); CreateGiftDialog dlg(CreateGiftDialog::NewGiftAddress); dlg.setModel(model); if(dlg.exec()) { printf("GiftCardPage::on_newAddressButton(): dlg.exec()\n"); newAddressToSelect = dlg.getAddress(); QStringList giftKeys = newAddressToSelect.split(":"); strcpy(strPubKey, giftKeys.at(0).toStdString().c_str()); strcpy(strPrivKey, giftKeys.at(1).toStdString().c_str()); printf("strPubKey = %s\tstrPrivKey = %s\n", strPubKey, strPrivKey); // QString appDirPath = QCoreApplication::applicationDirPath(); // printf("appDirPath = %s\n", appDirPath.toStdString().c_str()); QString defaultFileName = filePath + QDir::separator() + giftKeys.at(0) + ".html"; QString fileName = GUIUtil::getSaveFileName( this, tr("Save Gift* Card"), defaultFileName, tr(".html")); if (!fileName.isNull()) { PaperWallet pWallet = PaperWallet(fileName, giftKeys.at(0), giftKeys.at(1), ""); if (pWallet.genWallet()) { QFile file(fileName); if (file.exists()) { // save the user selected folder for easy next use QFileInfo fileInfo(file.fileName()); filePath = fileInfo.absolutePath(); // launch browser to display/print QString url = "file://" + fileName; QDesktopServices::openUrl(QUrl(url)); } } } } } void GiftCardPage::on_templateButton_clicked() { QMessageBox msgBox; msgBox.setWindowTitle("Update Templates"); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); PaperWallet pWallet = PaperWallet("", "", "", ""); if (pWallet.updateTemplates()) msgBox.setText("Template Update Successful"); else { msgBox.setText("Template Update Failed"); msgBox.setInformativeText("Check your network connectivity and retry"); } msgBox.exec(); } void GiftCardPage::on_deleteButton_clicked() { QTableView *table = ui->tableView; if(!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if(!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void GiftCardPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { // In gift tab, allow deletion of selection ui->deleteButton->setEnabled(true); ui->deleteButton->setVisible(true); deleteAction->setEnabled(true); ui->signMessage->setEnabled(false); ui->signMessage->setVisible(false); ui->verifyMessage->setEnabled(true); ui->verifyMessage->setVisible(true); ui->copyToClipboard->setEnabled(true); ui->showQRCode->setEnabled(true); } else { ui->deleteButton->setEnabled(false); ui->showQRCode->setEnabled(false); ui->copyToClipboard->setEnabled(false); ui->signMessage->setEnabled(false); ui->verifyMessage->setEnabled(false); } } void GiftCardPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // When this is a tab/widget and not a model dialog, ignore "done" if(mode == ForEditing) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(GiftCardTableModel::Address); foreach (QModelIndex index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if(returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void GiftCardPage::exportClicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName( this, tr("Export Address Book Data"), QString(), tr("Comma separated file (*.csv)")); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", GiftCardTableModel::Label, Qt::EditRole); writer.addColumn("Address", GiftCardTableModel::Address, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename), QMessageBox::Abort, QMessageBox::Abort); } } void GiftCardPage::on_showQRCode_clicked() { #ifdef USE_QRCODE QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(GiftCardTableModel::Address); foreach (QModelIndex index, indexes) { QString address = index.data().toString(), label = index.sibling(index.row(), 0).data(Qt::EditRole).toString(); QRCodeDialog *dialog = new QRCodeDialog(address, label, tab == ReceivingTab, this); if(optionsModel) dialog->setModel(optionsModel); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); } #endif } void GiftCardPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void GiftCardPage::selectNewAddress(const QModelIndex &parent, int begin, int end) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, GiftCardTableModel::Address, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } } <|endoftext|>
<commit_before>// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "modaloverlay.h" #include "ui_modaloverlay.h" #include "guiutil.h" #include "chainparams.h" #include <QResizeEvent> #include <QPropertyAnimation> ModalOverlay::ModalOverlay(QWidget *parent) : QWidget(parent), ui(new Ui::ModalOverlay), bestHeaderHeight(0), bestHeaderDate(QDateTime()), layerIsVisible(false), userClosed(false) { ui->setupUi(this); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(closeClicked())); if (parent) { parent->installEventFilter(this); raise(); } blockProcessTime.clear(); setVisible(false); } ModalOverlay::~ModalOverlay() { delete ui; } bool ModalOverlay::eventFilter(QObject * obj, QEvent * ev) { if (obj == parent()) { if (ev->type() == QEvent::Resize) { QResizeEvent * rev = static_cast<QResizeEvent*>(ev); resize(rev->size()); if (!layerIsVisible) setGeometry(0, height(), width(), height()); } else if (ev->type() == QEvent::ChildAdded) { raise(); } } return QWidget::eventFilter(obj, ev); } //! Tracks parent widget changes bool ModalOverlay::event(QEvent* ev) { if (ev->type() == QEvent::ParentAboutToChange) { if (parent()) parent()->removeEventFilter(this); } else if (ev->type() == QEvent::ParentChange) { if (parent()) { parent()->installEventFilter(this); raise(); } } return QWidget::event(ev); } void ModalOverlay::setKnownBestHeight(int count, const QDateTime& blockDate) { if (count > bestHeaderHeight) { bestHeaderHeight = count; bestHeaderDate = blockDate; } } void ModalOverlay::tipUpdate(int count, const QDateTime& blockDate, double nVerificationProgress) { QDateTime currentDate = QDateTime::currentDateTime(); // keep a vector of samples of verification progress at height blockProcessTime.push_front(qMakePair(currentDate.toMSecsSinceEpoch(), nVerificationProgress)); // show progress speed if we have more then one sample if (blockProcessTime.size() >= 2) { double progressStart = blockProcessTime[0].second; double progressDelta = 0; double progressPerHour = 0; qint64 timeDelta = 0; qint64 remainingMSecs = 0; double remainingProgress = 1.0 - nVerificationProgress; for (int i = 1; i < blockProcessTime.size(); i++) { QPair<qint64, double> sample = blockProcessTime[i]; // take first sample after 500 seconds or last available one if (sample.first < (currentDate.toMSecsSinceEpoch() - 500 * 1000) || i == blockProcessTime.size() - 1) { progressDelta = progressStart-sample.second; timeDelta = blockProcessTime[0].first - sample.first; progressPerHour = progressDelta/(double)timeDelta*1000*3600; remainingMSecs = remainingProgress / progressDelta * timeDelta; break; } } // show progress increase per hour ui->progressIncreasePerH->setText(QString::number(progressPerHour*100, 'f', 2)+"%"); // show expected remaining time ui->expectedTimeLeft->setText(GUIUtil::formatNiceTimeOffset(remainingMSecs/1000.0)); static const int MAX_SAMPLES = 5000; if (blockProcessTime.count() > MAX_SAMPLES) blockProcessTime.remove(MAX_SAMPLES, blockProcessTime.count()-MAX_SAMPLES); } // show the last block date ui->newestBlockDate->setText(blockDate.toString()); // show the percentage done according to nVerificationProgress ui->percentageProgress->setText(QString::number(nVerificationProgress*100, 'f', 2)+"%"); ui->progressBar->setValue(nVerificationProgress*100); if (!bestHeaderDate.isValid()) // not syncing return; // estimate the number of headers left based on nPowTargetSpacing // and check if the gui is not aware of the the best header (happens rarely) int estimateNumHeadersLeft = bestHeaderDate.secsTo(currentDate) / Params().GetConsensus().nPowTargetSpacing; bool hasBestHeader = bestHeaderHeight >= count; // show remaining number of blocks if (estimateNumHeadersLeft < HEADER_HEIGHT_DELTA_SYNC && hasBestHeader) { ui->numberOfBlocksLeft->setText(QString::number(bestHeaderHeight - count)); } else { ui->numberOfBlocksLeft->setText(tr("Unknown. Syncing Headers (%1)...").arg(bestHeaderHeight)); ui->expectedTimeLeft->setText(tr("Unknown...")); } } void ModalOverlay::toggleVisibility() { showHide(layerIsVisible, true); if (!layerIsVisible) userClosed = true; } void ModalOverlay::showHide(bool hide, bool userRequested) { if ( (layerIsVisible && !hide) || (!layerIsVisible && hide) || (!hide && userClosed && !userRequested)) return; if (!isVisible() && !hide) setVisible(true); setGeometry(0, hide ? 0 : height(), width(), height()); QPropertyAnimation* animation = new QPropertyAnimation(this, "pos"); animation->setDuration(300); animation->setStartValue(QPoint(0, hide ? 0 : this->height())); animation->setEndValue(QPoint(0, hide ? this->height() : 0)); animation->setEasingCurve(QEasingCurve::OutQuad); animation->start(QAbstractAnimation::DeleteWhenStopped); layerIsVisible = !hide; } void ModalOverlay::closeClicked() { showHide(true); userClosed = true; } <commit_msg>sync speed estimate<commit_after>// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "modaloverlay.h" #include "ui_modaloverlay.h" #include "guiutil.h" #include "chainparams.h" #include <QResizeEvent> #include <QPropertyAnimation> ModalOverlay::ModalOverlay(QWidget *parent) : QWidget(parent), ui(new Ui::ModalOverlay), bestHeaderHeight(0), bestHeaderDate(QDateTime()), layerIsVisible(false), userClosed(false) { ui->setupUi(this); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(closeClicked())); if (parent) { parent->installEventFilter(this); raise(); } blockProcessTime.clear(); setVisible(false); } ModalOverlay::~ModalOverlay() { delete ui; } bool ModalOverlay::eventFilter(QObject * obj, QEvent * ev) { if (obj == parent()) { if (ev->type() == QEvent::Resize) { QResizeEvent * rev = static_cast<QResizeEvent*>(ev); resize(rev->size()); if (!layerIsVisible) setGeometry(0, height(), width(), height()); } else if (ev->type() == QEvent::ChildAdded) { raise(); } } return QWidget::eventFilter(obj, ev); } //! Tracks parent widget changes bool ModalOverlay::event(QEvent* ev) { if (ev->type() == QEvent::ParentAboutToChange) { if (parent()) parent()->removeEventFilter(this); } else if (ev->type() == QEvent::ParentChange) { if (parent()) { parent()->installEventFilter(this); raise(); } } return QWidget::event(ev); } void ModalOverlay::setKnownBestHeight(int count, const QDateTime& blockDate) { if (count > bestHeaderHeight) { bestHeaderHeight = count; bestHeaderDate = blockDate; } } void ModalOverlay::tipUpdate(int count, const QDateTime& blockDate, double nVerificationProgress) { QDateTime currentDate = QDateTime::currentDateTime(); // keep a vector of samples of verification progress at height blockProcessTime.push_front(qMakePair(currentDate.toMSecsSinceEpoch(), nVerificationProgress)); // show progress speed if we have more then one sample if (blockProcessTime.size() >= 2) { double progressStart = blockProcessTime[0].second; double progressDelta = 0; double progressPerHour = 0; qint64 timeDelta = 0; qint64 remainingMSecs = 0; double remainingProgress = 1.0 - nVerificationProgress; for (int i = 1; i < blockProcessTime.size(); i++) { QPair<qint64, double> sample = blockProcessTime[i]; // take first sample after 500 seconds or last available one if (sample.first < (currentDate.toMSecsSinceEpoch() - 500 * 1000) || i == blockProcessTime.size() - 1) { progressDelta = progressStart-sample.second; timeDelta = blockProcessTime[0].first - sample.first; progressPerHour = progressDelta/(double)timeDelta*1000*3600; remainingMSecs = remainingProgress / progressDelta * timeDelta; break; } } // show progress increase per hour ui->progressIncreasePerH->setText(QString::number(progressPerHour*100, 'f', 2)+"%"); // show expected remaining time ui->expectedTimeLeft->setText(GUIUtil::formatNiceTimeOffset(remainingMSecs/1000.0)); static const int MAX_SAMPLES = 5000; if (blockProcessTime.count() > MAX_SAMPLES) blockProcessTime.remove(MAX_SAMPLES, blockProcessTime.count()-MAX_SAMPLES); } // show the last block date ui->newestBlockDate->setText(blockDate.toString()); // show the percentage done according to nVerificationProgress ui->percentageProgress->setText(QString::number(nVerificationProgress*100, 'f', 2)+"%"); ui->progressBar->setValue(nVerificationProgress*100); if (!bestHeaderDate.isValid()) // not syncing return; // estimate the number of headers left based on nPowTargetSpacing // and check if the gui is not aware of the the best header (happens rarely) int64_t targetSpacing; if(count < Params().GetConsensus().nDiffChangeTarget ){ Params().GetConsensus().nTargetSpacingRe; } else if (count < Params().GetConsensus().multiAlgoDiffChangeTarget){ Params().GetConsensus().multiAlgoTargetSpacing; } else { Params().GetConsensus().multiAlgoTargetSpacingV4; } int estimateNumHeadersLeft = bestHeaderDate.secsTo(currentDate) / targetSpacing; bool hasBestHeader = bestHeaderHeight >= count; // show remaining number of blocks if (estimateNumHeadersLeft < HEADER_HEIGHT_DELTA_SYNC && hasBestHeader) { ui->numberOfBlocksLeft->setText(QString::number(bestHeaderHeight - count)); } else { ui->numberOfBlocksLeft->setText(tr("Unknown. Syncing Headers (%1)...").arg(bestHeaderHeight)); ui->expectedTimeLeft->setText(tr("Unknown...")); } } void ModalOverlay::toggleVisibility() { showHide(layerIsVisible, true); if (!layerIsVisible) userClosed = true; } void ModalOverlay::showHide(bool hide, bool userRequested) { if ( (layerIsVisible && !hide) || (!layerIsVisible && hide) || (!hide && userClosed && !userRequested)) return; if (!isVisible() && !hide) setVisible(true); setGeometry(0, hide ? 0 : height(), width(), height()); QPropertyAnimation* animation = new QPropertyAnimation(this, "pos"); animation->setDuration(300); animation->setStartValue(QPoint(0, hide ? 0 : this->height())); animation->setEndValue(QPoint(0, hide ? this->height() : 0)); animation->setEasingCurve(QEasingCurve::OutQuad); animation->start(QAbstractAnimation::DeleteWhenStopped); layerIsVisible = !hide; } void ModalOverlay::closeClicked() { showHide(true); userClosed = true; } <|endoftext|>
<commit_before><commit_msg>new diagnostics for LRGs<commit_after><|endoftext|>
<commit_before>#include "optionsmodel.h" #include "bitcoinunits.h" #include "headers.h" #include "init.h" OptionsModel::OptionsModel(CWallet *wallet, QObject *parent) : QAbstractListModel(parent), wallet(wallet), nDisplayUnit(BitcoinUnits::BTC), bDisplayAddresses(false) { // Read our specific settings from the wallet db CWalletDB walletdb(wallet->strWalletFile); walletdb.ReadSetting("nDisplayUnit", nDisplayUnit); walletdb.ReadSetting("bDisplayAddresses", bDisplayAddresses); } int OptionsModel::rowCount(const QModelIndex & parent) const { return OptionIDRowCount; } QVariant OptionsModel::data(const QModelIndex & index, int role) const { if(role == Qt::EditRole) { switch(index.row()) { case StartAtStartup: return QVariant(GetStartOnSystemStartup()); case MinimizeToTray: return QVariant(fMinimizeToTray); case MapPortUPnP: return QVariant(fUseUPnP); case MinimizeOnClose: return QVariant(fMinimizeOnClose); case ConnectSOCKS4: return QVariant(fUseProxy); case ProxyIP: return QVariant(QString::fromStdString(addrProxy.ToStringIP())); case ProxyPort: return QVariant(QString::fromStdString(addrProxy.ToStringPort())); case Fee: return QVariant(nTransactionFee); case DisplayUnit: return QVariant(nDisplayUnit); case DisplayAddresses: return QVariant(bDisplayAddresses); default: return QVariant(); } } return QVariant(); } bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role) { bool successful = true; /* set to false on parse error */ if(role == Qt::EditRole) { CWalletDB walletdb(wallet->strWalletFile); switch(index.row()) { case StartAtStartup: successful = SetStartOnSystemStartup(value.toBool()); break; case MinimizeToTray: fMinimizeToTray = value.toBool(); walletdb.WriteSetting("fMinimizeToTray", fMinimizeToTray); break; case MapPortUPnP: fUseUPnP = value.toBool(); walletdb.WriteSetting("fUseUPnP", fUseUPnP); #ifdef USE_UPNP MapPort(fUseUPnP); #endif break; case MinimizeOnClose: fMinimizeOnClose = value.toBool(); walletdb.WriteSetting("fMinimizeOnClose", fMinimizeOnClose); break; case ConnectSOCKS4: fUseProxy = value.toBool(); walletdb.WriteSetting("fUseProxy", fUseProxy); break; case ProxyIP: { // Use CAddress to parse and check IP CNetAddr addr(value.toString().toStdString()); if (addr.IsValid()) { addrProxy.SetIP(addr); walletdb.WriteSetting("addrProxy", addrProxy); } else { successful = false; } } break; case ProxyPort: { int nPort = atoi(value.toString().toAscii().data()); if (nPort > 0 && nPort < std::numeric_limits<unsigned short>::max()) { addrProxy.SetPort(nPort); walletdb.WriteSetting("addrProxy", addrProxy); } else { successful = false; } } break; case Fee: { nTransactionFee = value.toLongLong(); walletdb.WriteSetting("nTransactionFee", nTransactionFee); } break; case DisplayUnit: { int unit = value.toInt(); nDisplayUnit = unit; walletdb.WriteSetting("nDisplayUnit", nDisplayUnit); emit displayUnitChanged(unit); } case DisplayAddresses: { bDisplayAddresses = value.toBool(); walletdb.WriteSetting("bDisplayAddresses", bDisplayAddresses); } default: break; } } emit dataChanged(index, index); return successful; } qint64 OptionsModel::getTransactionFee() { return nTransactionFee; } bool OptionsModel::getMinimizeToTray() { return fMinimizeToTray; } bool OptionsModel::getMinimizeOnClose() { return fMinimizeOnClose; } int OptionsModel::getDisplayUnit() { return nDisplayUnit; } bool OptionsModel::getDisplayAddresses() { return bDisplayAddresses; } <commit_msg>Remove erroneous ":" in front of port in options dialog (introduced with network refactor)<commit_after>#include "optionsmodel.h" #include "bitcoinunits.h" #include "headers.h" #include "init.h" OptionsModel::OptionsModel(CWallet *wallet, QObject *parent) : QAbstractListModel(parent), wallet(wallet), nDisplayUnit(BitcoinUnits::BTC), bDisplayAddresses(false) { // Read our specific settings from the wallet db CWalletDB walletdb(wallet->strWalletFile); walletdb.ReadSetting("nDisplayUnit", nDisplayUnit); walletdb.ReadSetting("bDisplayAddresses", bDisplayAddresses); } int OptionsModel::rowCount(const QModelIndex & parent) const { return OptionIDRowCount; } QVariant OptionsModel::data(const QModelIndex & index, int role) const { if(role == Qt::EditRole) { switch(index.row()) { case StartAtStartup: return QVariant(GetStartOnSystemStartup()); case MinimizeToTray: return QVariant(fMinimizeToTray); case MapPortUPnP: return QVariant(fUseUPnP); case MinimizeOnClose: return QVariant(fMinimizeOnClose); case ConnectSOCKS4: return QVariant(fUseProxy); case ProxyIP: return QVariant(QString::fromStdString(addrProxy.ToStringIP())); case ProxyPort: return QVariant(addrProxy.GetPort()); case Fee: return QVariant(nTransactionFee); case DisplayUnit: return QVariant(nDisplayUnit); case DisplayAddresses: return QVariant(bDisplayAddresses); default: return QVariant(); } } return QVariant(); } bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role) { bool successful = true; /* set to false on parse error */ if(role == Qt::EditRole) { CWalletDB walletdb(wallet->strWalletFile); switch(index.row()) { case StartAtStartup: successful = SetStartOnSystemStartup(value.toBool()); break; case MinimizeToTray: fMinimizeToTray = value.toBool(); walletdb.WriteSetting("fMinimizeToTray", fMinimizeToTray); break; case MapPortUPnP: fUseUPnP = value.toBool(); walletdb.WriteSetting("fUseUPnP", fUseUPnP); #ifdef USE_UPNP MapPort(fUseUPnP); #endif break; case MinimizeOnClose: fMinimizeOnClose = value.toBool(); walletdb.WriteSetting("fMinimizeOnClose", fMinimizeOnClose); break; case ConnectSOCKS4: fUseProxy = value.toBool(); walletdb.WriteSetting("fUseProxy", fUseProxy); break; case ProxyIP: { // Use CAddress to parse and check IP CNetAddr addr(value.toString().toStdString()); if (addr.IsValid()) { addrProxy.SetIP(addr); walletdb.WriteSetting("addrProxy", addrProxy); } else { successful = false; } } break; case ProxyPort: { int nPort = atoi(value.toString().toAscii().data()); if (nPort > 0 && nPort < std::numeric_limits<unsigned short>::max()) { addrProxy.SetPort(nPort); walletdb.WriteSetting("addrProxy", addrProxy); } else { successful = false; } } break; case Fee: { nTransactionFee = value.toLongLong(); walletdb.WriteSetting("nTransactionFee", nTransactionFee); } break; case DisplayUnit: { int unit = value.toInt(); nDisplayUnit = unit; walletdb.WriteSetting("nDisplayUnit", nDisplayUnit); emit displayUnitChanged(unit); } case DisplayAddresses: { bDisplayAddresses = value.toBool(); walletdb.WriteSetting("bDisplayAddresses", bDisplayAddresses); } default: break; } } emit dataChanged(index, index); return successful; } qint64 OptionsModel::getTransactionFee() { return nTransactionFee; } bool OptionsModel::getMinimizeToTray() { return fMinimizeToTray; } bool OptionsModel::getMinimizeOnClose() { return fMinimizeOnClose; } int OptionsModel::getDisplayUnit() { return nDisplayUnit; } bool OptionsModel::getDisplayAddresses() { return bDisplayAddresses; } <|endoftext|>
<commit_before><commit_msg>remove diagnostics<commit_after><|endoftext|>
<commit_before>/* ************************ Copyright Terrain Experts Inc. Terrain Experts Inc (TERREX) reserves all rights to this source code unless otherwise specified in writing by the President of TERREX. This copyright may be updated in the future, in which case that version supercedes this one. ------------------- Terrex Experts Inc. 4400 East Broadway #314 Tucson, AZ 85711 info@terrex.com Tel: (520) 323-7990 ************************ */ #include <stdlib.h> #include <stdio.h> #include <string.h> #define OLDMODELSTYLE /* trpage_model.cpp This source file contains the methods trpgModel and trpgModelTable. You should only modify this code if you want to add data to these classes. */ #include <trpage_geom.h> #include <trpage_read.h> /* Write Model class Represents a model reference. */ trpgModel::trpgModel() { name = NULL; type = External; useCount = 0; diskRef = -1; handle = -1; writeHandle = false; } trpgModel::trpgModel(const trpgModel &in): trpgReadWriteable(in) { if (in.name) { name = new char[strlen(in.name)+1]; strcpy(name,in.name); } else name = NULL; type=in.type; useCount=in.useCount; diskRef=in.diskRef; handle = in.handle; writeHandle = in.writeHandle; } // Reset function void trpgModel::Reset() { if (name) delete [] name; name = NULL; useCount = 0; diskRef = -1; handle = -1; writeHandle = false; } trpgModel::~trpgModel() { Reset(); } // Set functions void trpgModel::SetType(int t) { type = t; } void trpgModel::SetName(const char *nm) { if (name) delete [] name; if (nm) { name = new char[strlen(nm)+1]; strcpy(name,nm); } } void trpgModel::SetReference(trpgDiskRef pos) { diskRef = pos; } void trpgModel::SetNumTiles(int num) { useCount = num; } void trpgModel::AddTile() { useCount++; } // Validity check bool trpgModel::isValid() const { if (type == External && !name) { errMess.assign("Model is external with no name"); return false; } return true; } // Copy from one to another trpgModel& trpgModel::operator = (const trpgModel &in) { if (name) { delete [] name; name = NULL; } type = in.type; if (in.name) SetName(in.name); diskRef = in.diskRef; useCount = in.useCount; writeHandle = in.writeHandle; handle = in.handle; return *this; } // Compare two models int trpgModel::operator == (const trpgModel &in) const { if (type != in.type) return 0; switch (type) { case Local: if (diskRef == in.diskRef) return 1; else return 0; break; case External: if (!name && !in.name) return 1; if (!name || !in.name) return 0; if (strcmp(name,in.name)) return 0; break; } return 1; } // Write a model reference out bool trpgModel::Write(trpgWriteBuffer &buf) { if (!isValid()) return false; // We will use two different tokens to track the // format used in terrapage 2.2, and older versions int tok = TRPGMODELREF; if(writeHandle) tok = TRPGMODELREF2; // Nick messed up the model entries when checking into txv4; now we're // a bit stuck because U3 dbs don't have models in the U2 viewer. // This will force the old behavior. #ifdef OLDMODELSTYLE buf.Begin(tok); buf.Add(type); //writeHandle is only set for terrapage 2.2, and we use the different token. if(writeHandle) { buf.Add((int)handle); } if (name) buf.Add(name); else buf.Add(diskRef); buf.Add(useCount); #else buf.Begin(tok); if(writeHandle) { buf.Add((int)handle); } buf.Add(type); buf.Add(name); buf.Add(diskRef); buf.Add(useCount); #endif buf.End(); return true; } /* ******************* Model Read Methods ******************* */ // Get methods bool trpgModel::GetType(int &t) { if (!isValid()) return false; t = type; return true; } bool trpgModel::GetName(char *str,int strLen) const { if (!isValid()) return false; int len = (name ? strlen(name) : 0); strncpy(str,name,MIN(len,strLen)+1); return true; } bool trpgModel::GetNumTiles(int &ret) const { if (!isValid()) return false; ret = useCount; return true; } bool trpgModel::GetReference(trpgDiskRef &ref) const { if (!isValid() || type != Local) return false; ref = diskRef; return true; } bool trpgModel::Read(trpgReadBuffer &buf, bool hasHandle) { // MD: added complexity here - written multiple ways by // mistake, unraveling the various cases. char tmpName[1024]; try { buf.Get(type); // TerraPage 2.2 will store the unique handle after the type // we use a different token, so this is backwards compatible. if(hasHandle) { int32 tempHandle; if(buf.Get(tempHandle)) { handle = tempHandle; } else { handle = -1; } } else handle = -1; if (type == Local) { // two possibilities: // name, diskRef, useCount // diskRef, useCount // diskRef + useCount = 12 bytes... if (buf.TestLimit(13)) { buf.Get(tmpName,1023); SetName(tmpName); } buf.Get(diskRef); buf.Get(useCount); } else { // two possibilities: // name, diskRef, useCount // name, useCount buf.Get(tmpName,1023); SetName(tmpName); // useCount = 4 bytes... if (buf.TestLimit(5)) buf.Get(diskRef); buf.Get(useCount); } } catch(...) { return false; } // going to make this fail if the buffer isn't empty. if (buf.TestLimit(1)) return false; return isValid(); } /* Write Model Reference table Groups of models for the entire file. */ // Constructor trpgModelTable::trpgModelTable() { } trpgModelTable::~trpgModelTable() { } // Reset function void trpgModelTable::Reset() { modelsMap.clear(); } // Set functions void trpgModelTable::SetNumModels(int /*no*/) { // This method isn't needed with a map //models.resize(no); } void trpgModelTable::SetModel(int id,const trpgModel &mod) { if (id < 0) return; modelsMap[id] = mod; //models[id] = mod; } int trpgModelTable::AddModel(trpgModel &mod) { int hdl = modelsMap.size(); if(mod.GetHandle()==-1) { modelsMap[hdl] = mod; return hdl; } modelsMap[mod.GetHandle()] = mod; return mod.GetHandle(); } int trpgModelTable::FindAddModel(trpgModel &mod) { ModelMapType::iterator itr = modelsMap.begin(); for ( ; itr != modelsMap.end( ); itr++) { if(itr->second == mod) { return itr->first; } } return AddModel(mod); } bool trpgModelTable::FindByName(const char *name, unsigned int &mId) { ModelMapType::const_iterator itr = modelsMap.begin(); for ( ; itr != modelsMap.end( ); itr++) { char theName[1023]; itr->second.GetName(theName,1023); if(strcmp(name,theName)==0) { mId = itr->first; return true; } } return false; } // Validity check bool trpgModelTable::isValid() const { ModelMapType::const_iterator itr = modelsMap.begin(); for ( ; itr != modelsMap.end( ); itr++) { if(!itr->second.isValid()) { if(itr->second.getErrMess()) errMess.assign(itr->second.getErrMess()); return false; } } return true; } // Write out the model table bool trpgModelTable::Write(trpgWriteBuffer &buf) { if (!isValid()) return false; buf.Begin(TRPGMODELTABLE); buf.Add((int32)modelsMap.size()); ModelMapType::iterator itr = modelsMap.begin(); for ( ; itr != modelsMap.end( ); itr++) { itr->second.Write(buf); } buf.End(); return true; } /* *************** Model Table Read methods *************** */ // Get methods bool trpgModelTable::GetNumModels(int &nm) const { if (!isValid()) return false; nm = modelsMap.size(); return true; } bool trpgModelTable::GetModel(int id,trpgModel &model) const { if (!isValid() || id < 0 ) //|| id >= models.size()) return false; //model = models[id]; ModelMapType::const_iterator itr = modelsMap.find(id); if(itr == modelsMap.end()) { return false; } model = itr->second; return true; } trpgModel *trpgModelTable::GetModelRef(int id) { if (id < 0 ) //|| id >= models.size()) return NULL; //return &models[id]; ModelMapType::iterator itr = modelsMap.find(id); if(itr == modelsMap.end()) { return 0; } return &(itr->second); } bool trpgModelTable::Read(trpgReadBuffer &buf) { int32 numModel; trpgToken tok; int32 len; bool status; try { buf.Get(numModel); for (int i=0;i<numModel;i++) { trpgModel model; buf.GetToken(tok,len); bool readHandle; if (tok == TRPGMODELREF) readHandle = false; else if (tok == TRPGMODELREF2) readHandle = true; else throw 1; buf.PushLimit(len); status = model.Read(buf,readHandle); buf.PopLimit(); if (!status) throw 1; AddModel(model); } } catch (...) { return false; } return isValid(); } <commit_msg>Added null pointer handling<commit_after>/* ************************ Copyright Terrain Experts Inc. Terrain Experts Inc (TERREX) reserves all rights to this source code unless otherwise specified in writing by the President of TERREX. This copyright may be updated in the future, in which case that version supercedes this one. ------------------- Terrex Experts Inc. 4400 East Broadway #314 Tucson, AZ 85711 info@terrex.com Tel: (520) 323-7990 ************************ */ #include <stdlib.h> #include <stdio.h> #include <string.h> #define OLDMODELSTYLE /* trpage_model.cpp This source file contains the methods trpgModel and trpgModelTable. You should only modify this code if you want to add data to these classes. */ #include <trpage_geom.h> #include <trpage_read.h> /* Write Model class Represents a model reference. */ trpgModel::trpgModel() { name = NULL; type = External; useCount = 0; diskRef = -1; handle = -1; writeHandle = false; } trpgModel::trpgModel(const trpgModel &in): trpgReadWriteable(in) { if (in.name) { name = new char[strlen(in.name)+1]; strcpy(name,in.name); } else name = NULL; type=in.type; useCount=in.useCount; diskRef=in.diskRef; handle = in.handle; writeHandle = in.writeHandle; } // Reset function void trpgModel::Reset() { if (name) delete [] name; name = NULL; useCount = 0; diskRef = -1; handle = -1; writeHandle = false; } trpgModel::~trpgModel() { Reset(); } // Set functions void trpgModel::SetType(int t) { type = t; } void trpgModel::SetName(const char *nm) { if (name) delete [] name; if (nm) { name = new char[strlen(nm)+1]; strcpy(name,nm); } } void trpgModel::SetReference(trpgDiskRef pos) { diskRef = pos; } void trpgModel::SetNumTiles(int num) { useCount = num; } void trpgModel::AddTile() { useCount++; } // Validity check bool trpgModel::isValid() const { if (type == External && !name) { errMess.assign("Model is external with no name"); return false; } return true; } // Copy from one to another trpgModel& trpgModel::operator = (const trpgModel &in) { if (name) { delete [] name; name = NULL; } type = in.type; if (in.name) SetName(in.name); diskRef = in.diskRef; useCount = in.useCount; writeHandle = in.writeHandle; handle = in.handle; return *this; } // Compare two models int trpgModel::operator == (const trpgModel &in) const { if (type != in.type) return 0; switch (type) { case Local: if (diskRef == in.diskRef) return 1; else return 0; break; case External: if (!name && !in.name) return 1; if (!name || !in.name) return 0; if (strcmp(name,in.name)) return 0; break; } return 1; } // Write a model reference out bool trpgModel::Write(trpgWriteBuffer &buf) { if (!isValid()) return false; // We will use two different tokens to track the // format used in terrapage 2.2, and older versions int tok = TRPGMODELREF; if(writeHandle) tok = TRPGMODELREF2; // Nick messed up the model entries when checking into txv4; now we're // a bit stuck because U3 dbs don't have models in the U2 viewer. // This will force the old behavior. #ifdef OLDMODELSTYLE buf.Begin(tok); buf.Add(type); //writeHandle is only set for terrapage 2.2, and we use the different token. if(writeHandle) { buf.Add((int)handle); } if (name) buf.Add(name); else buf.Add(diskRef); buf.Add(useCount); #else buf.Begin(tok); if(writeHandle) { buf.Add((int)handle); } buf.Add(type); buf.Add(name); buf.Add(diskRef); buf.Add(useCount); #endif buf.End(); return true; } /* ******************* Model Read Methods ******************* */ // Get methods bool trpgModel::GetType(int &t) { if (!isValid()) return false; t = type; return true; } bool trpgModel::GetName(char *str,int strLen) const { if (!isValid() || !name) { return false; } int len = strlen(name); strncpy(str,name,MIN(len,strLen)+1); return true; } bool trpgModel::GetNumTiles(int &ret) const { if (!isValid()) return false; ret = useCount; return true; } bool trpgModel::GetReference(trpgDiskRef &ref) const { if (!isValid() || type != Local) return false; ref = diskRef; return true; } bool trpgModel::Read(trpgReadBuffer &buf, bool hasHandle) { // MD: added complexity here - written multiple ways by // mistake, unraveling the various cases. char tmpName[1024]; try { buf.Get(type); // TerraPage 2.2 will store the unique handle after the type // we use a different token, so this is backwards compatible. if(hasHandle) { int32 tempHandle; if(buf.Get(tempHandle)) { handle = tempHandle; } else { handle = -1; } } else handle = -1; if (type == Local) { // two possibilities: // name, diskRef, useCount // diskRef, useCount // diskRef + useCount = 12 bytes... if (buf.TestLimit(13)) { buf.Get(tmpName,1023); SetName(tmpName); } buf.Get(diskRef); buf.Get(useCount); } else { // two possibilities: // name, diskRef, useCount // name, useCount buf.Get(tmpName,1023); SetName(tmpName); // useCount = 4 bytes... if (buf.TestLimit(5)) buf.Get(diskRef); buf.Get(useCount); } } catch(...) { return false; } // going to make this fail if the buffer isn't empty. if (buf.TestLimit(1)) return false; return isValid(); } /* Write Model Reference table Groups of models for the entire file. */ // Constructor trpgModelTable::trpgModelTable() { } trpgModelTable::~trpgModelTable() { } // Reset function void trpgModelTable::Reset() { modelsMap.clear(); } // Set functions void trpgModelTable::SetNumModels(int /*no*/) { // This method isn't needed with a map //models.resize(no); } void trpgModelTable::SetModel(int id,const trpgModel &mod) { if (id < 0) return; modelsMap[id] = mod; //models[id] = mod; } int trpgModelTable::AddModel(trpgModel &mod) { int hdl = modelsMap.size(); if(mod.GetHandle()==-1) { modelsMap[hdl] = mod; return hdl; } modelsMap[mod.GetHandle()] = mod; return mod.GetHandle(); } int trpgModelTable::FindAddModel(trpgModel &mod) { ModelMapType::iterator itr = modelsMap.begin(); for ( ; itr != modelsMap.end( ); itr++) { if(itr->second == mod) { return itr->first; } } return AddModel(mod); } bool trpgModelTable::FindByName(const char *name, unsigned int &mId) { ModelMapType::const_iterator itr = modelsMap.begin(); for ( ; itr != modelsMap.end( ); itr++) { char theName[1023]; itr->second.GetName(theName,1023); if(strcmp(name,theName)==0) { mId = itr->first; return true; } } return false; } // Validity check bool trpgModelTable::isValid() const { ModelMapType::const_iterator itr = modelsMap.begin(); for ( ; itr != modelsMap.end( ); itr++) { if(!itr->second.isValid()) { if(itr->second.getErrMess()) errMess.assign(itr->second.getErrMess()); return false; } } return true; } // Write out the model table bool trpgModelTable::Write(trpgWriteBuffer &buf) { if (!isValid()) return false; buf.Begin(TRPGMODELTABLE); buf.Add((int32)modelsMap.size()); ModelMapType::iterator itr = modelsMap.begin(); for ( ; itr != modelsMap.end( ); itr++) { itr->second.Write(buf); } buf.End(); return true; } /* *************** Model Table Read methods *************** */ // Get methods bool trpgModelTable::GetNumModels(int &nm) const { if (!isValid()) return false; nm = modelsMap.size(); return true; } bool trpgModelTable::GetModel(int id,trpgModel &model) const { if (!isValid() || id < 0 ) //|| id >= models.size()) return false; //model = models[id]; ModelMapType::const_iterator itr = modelsMap.find(id); if(itr == modelsMap.end()) { return false; } model = itr->second; return true; } trpgModel *trpgModelTable::GetModelRef(int id) { if (id < 0 ) //|| id >= models.size()) return NULL; //return &models[id]; ModelMapType::iterator itr = modelsMap.find(id); if(itr == modelsMap.end()) { return 0; } return &(itr->second); } bool trpgModelTable::Read(trpgReadBuffer &buf) { int32 numModel; trpgToken tok; int32 len; bool status; try { buf.Get(numModel); for (int i=0;i<numModel;i++) { trpgModel model; buf.GetToken(tok,len); bool readHandle; if (tok == TRPGMODELREF) readHandle = false; else if (tok == TRPGMODELREF2) readHandle = true; else throw 1; buf.PushLimit(len); status = model.Read(buf,readHandle); buf.PopLimit(); if (!status) throw 1; AddModel(model); } } catch (...) { return false; } return isValid(); } <|endoftext|>
<commit_before>#include "overviewpage.h" #include "ui_overviewpage.h" #include "walletmodel.h" #include "tekcoinunits.h" #include "optionsmodel.h" #include "transactiontablemodel.h" #include "transactionfilterproxy.h" #include "guiutil.h" #include "guiconstants.h" #include <QAbstractItemDelegate> #include <QPainter> #define DECORATION_SIZE 64 #define NUM_ITEMS 3 class TxViewDelegate : public QAbstractItemDelegate { Q_OBJECT public: TxViewDelegate(): QAbstractItemDelegate(), unit(tekcoinUnits::BTC) { } inline void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { painter->save(); QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole)); QRect mainRect = option.rect; QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE)); int xspace = DECORATION_SIZE + 8; int ypad = 6; int halfheight = (mainRect.height() - 2*ypad)/2; QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight); QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight); icon.paint(painter, decorationRect); QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime(); QString address = index.data(Qt::DisplayRole).toString(); qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong(); bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool(); QVariant value = index.data(Qt::ForegroundRole); QColor foreground = option.palette.color(QPalette::Text); #if QT_VERSION < 0x050000 //presstab qt5 if(qVariantCanConvert<QColor>(value)) #else if(value.canConvert<QColor>()) #endif { foreground = qvariant_cast<QColor>(value); } painter->setPen(foreground); painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address); if(amount < 0) { foreground = COLOR_NEGATIVE; } else if(!confirmed) { foreground = COLOR_UNCONFIRMED; } else { foreground = option.palette.color(QPalette::Text); } painter->setPen(foreground); QString amountText = tekcoinUnits::formatWithUnit(unit, amount, true); if(!confirmed) { amountText = QString("[") + amountText + QString("]"); } painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText); painter->setPen(option.palette.color(QPalette::Text)); painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date)); painter->restore(); } inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QSize(DECORATION_SIZE, DECORATION_SIZE); } int unit; }; #include "overviewpage.moc" OverviewPage::OverviewPage(QWidget *parent) : QWidget(parent), ui(new Ui::OverviewPage), currentBalance(-1), currentStake(0), currentUnconfirmedBalance(-1), currentImmatureBalance(-1), txdelegate(new TxViewDelegate()), filter(0) { ui->setupUi(this); // Recent transactions ui->listTransactions->setItemDelegate(txdelegate); ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); // init "out of sync" warning labels ui->labelWalletStatus->setText("(" + tr("out of sync") + ")"); ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")"); QPalette p; p.setColor(QPalette::WindowText,Qt::red); ui->label_tekcoin_Intro->setPalette(p); // start with displaying the "out of sync" warnings showOutOfSyncWarning(true); } void OverviewPage::handleTransactionClicked(const QModelIndex &index) { if(filter) emit transactionClicked(filter->mapToSource(index)); } OverviewPage::~OverviewPage() { delete ui; } void OverviewPage::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance) { int unit = model->getOptionsModel()->getDisplayUnit(); currentBalance = balance; currentStake = stake; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; ui->labelBalance->setText(tekcoinUnits::formatWithUnit(unit, balance)); ui->labelStake->setText(tekcoinUnits::formatWithUnit(unit, stake)); ui->labelUnconfirmed->setText(tekcoinUnits::formatWithUnit(unit, unconfirmedBalance)); ui->labelImmature->setText(tekcoinUnits::formatWithUnit(unit, immatureBalance)); // only show immature (newly mined) balance if it's non-zero, so as not to complicate things // for the non-mining users bool showImmature = immatureBalance != 0; ui->labelImmature->setVisible(showImmature); ui->labelImmatureText->setVisible(showImmature); } void OverviewPage::setNumTransactions(int count) { ui->labelNumTransactions->setText(QLocale::system().toString(count)); } void OverviewPage::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) { // Set up transaction list filter = new TransactionFilterProxy(); filter->setSourceModel(model->getTransactionTableModel()); filter->setLimit(NUM_ITEMS); filter->setDynamicSortFilter(true); filter->setSortRole(Qt::EditRole); filter->sort(TransactionTableModel::Status, Qt::DescendingOrder); ui->listTransactions->setModel(filter); ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); // Keep up to date with wallet setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64))); setNumTransactions(model->getNumTransactions()); connect(model, SIGNAL(numTransactionsChanged(int)), this, SLOT(setNumTransactions(int))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void OverviewPage::updateDisplayUnit() { if(model && model->getOptionsModel()) { if(currentBalance != -1) setBalance(currentBalance, model->getStake(), currentUnconfirmedBalance, currentImmatureBalance); // Update txdelegate->unit with the current unit txdelegate->unit = model->getOptionsModel()->getDisplayUnit(); ui->listTransactions->update(); } } void OverviewPage::showOutOfSyncWarning(bool fShow) { ui->labelWalletStatus->setVisible(fShow); ui->labelTransactionsStatus->setVisible(fShow); } <commit_msg>6 recent transactions on overview page<commit_after>#include "overviewpage.h" #include "ui_overviewpage.h" #include "walletmodel.h" #include "tekcoinunits.h" #include "optionsmodel.h" #include "transactiontablemodel.h" #include "transactionfilterproxy.h" #include "guiutil.h" #include "guiconstants.h" #include <QAbstractItemDelegate> #include <QPainter> #define DECORATION_SIZE 64 #define NUM_ITEMS 6 class TxViewDelegate : public QAbstractItemDelegate { Q_OBJECT public: TxViewDelegate(): QAbstractItemDelegate(), unit(tekcoinUnits::BTC) { } inline void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { painter->save(); QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole)); QRect mainRect = option.rect; QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE)); int xspace = DECORATION_SIZE + 8; int ypad = 6; int halfheight = (mainRect.height() - 2*ypad)/2; QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight); QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight); icon.paint(painter, decorationRect); QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime(); QString address = index.data(Qt::DisplayRole).toString(); qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong(); bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool(); QVariant value = index.data(Qt::ForegroundRole); QColor foreground = option.palette.color(QPalette::Text); #if QT_VERSION < 0x050000 //presstab qt5 if(qVariantCanConvert<QColor>(value)) #else if(value.canConvert<QColor>()) #endif { foreground = qvariant_cast<QColor>(value); } painter->setPen(foreground); painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address); if(amount < 0) { foreground = COLOR_NEGATIVE; } else if(!confirmed) { foreground = COLOR_UNCONFIRMED; } else { foreground = option.palette.color(QPalette::Text); } painter->setPen(foreground); QString amountText = tekcoinUnits::formatWithUnit(unit, amount, true); if(!confirmed) { amountText = QString("[") + amountText + QString("]"); } painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText); painter->setPen(option.palette.color(QPalette::Text)); painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date)); painter->restore(); } inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QSize(DECORATION_SIZE, DECORATION_SIZE); } int unit; }; #include "overviewpage.moc" OverviewPage::OverviewPage(QWidget *parent) : QWidget(parent), ui(new Ui::OverviewPage), currentBalance(-1), currentStake(0), currentUnconfirmedBalance(-1), currentImmatureBalance(-1), txdelegate(new TxViewDelegate()), filter(0) { ui->setupUi(this); // Recent transactions ui->listTransactions->setItemDelegate(txdelegate); ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); // init "out of sync" warning labels ui->labelWalletStatus->setText("(" + tr("out of sync") + ")"); ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")"); QPalette p; p.setColor(QPalette::WindowText,Qt::red); ui->label_tekcoin_Intro->setPalette(p); // start with displaying the "out of sync" warnings showOutOfSyncWarning(true); } void OverviewPage::handleTransactionClicked(const QModelIndex &index) { if(filter) emit transactionClicked(filter->mapToSource(index)); } OverviewPage::~OverviewPage() { delete ui; } void OverviewPage::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance) { int unit = model->getOptionsModel()->getDisplayUnit(); currentBalance = balance; currentStake = stake; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; ui->labelBalance->setText(tekcoinUnits::formatWithUnit(unit, balance)); ui->labelStake->setText(tekcoinUnits::formatWithUnit(unit, stake)); ui->labelUnconfirmed->setText(tekcoinUnits::formatWithUnit(unit, unconfirmedBalance)); ui->labelImmature->setText(tekcoinUnits::formatWithUnit(unit, immatureBalance)); // only show immature (newly mined) balance if it's non-zero, so as not to complicate things // for the non-mining users bool showImmature = immatureBalance != 0; ui->labelImmature->setVisible(showImmature); ui->labelImmatureText->setVisible(showImmature); } void OverviewPage::setNumTransactions(int count) { ui->labelNumTransactions->setText(QLocale::system().toString(count)); } void OverviewPage::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) { // Set up transaction list filter = new TransactionFilterProxy(); filter->setSourceModel(model->getTransactionTableModel()); filter->setLimit(NUM_ITEMS); filter->setDynamicSortFilter(true); filter->setSortRole(Qt::EditRole); filter->sort(TransactionTableModel::Status, Qt::DescendingOrder); ui->listTransactions->setModel(filter); ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); // Keep up to date with wallet setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64))); setNumTransactions(model->getNumTransactions()); connect(model, SIGNAL(numTransactionsChanged(int)), this, SLOT(setNumTransactions(int))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void OverviewPage::updateDisplayUnit() { if(model && model->getOptionsModel()) { if(currentBalance != -1) setBalance(currentBalance, model->getStake(), currentUnconfirmedBalance, currentImmatureBalance); // Update txdelegate->unit with the current unit txdelegate->unit = model->getOptionsModel()->getDisplayUnit(); ui->listTransactions->update(); } } void OverviewPage::showOutOfSyncWarning(bool fShow) { ui->labelWalletStatus->setVisible(fShow); ui->labelTransactionsStatus->setVisible(fShow); } <|endoftext|>
<commit_before>#include "qrcodedialog.h" #include "ui_qrcodedialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include <QPixmap> #include <QUrl> #include <qrencode.h> QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : QDialog(parent), ui(new Ui::QRCodeDialog), model(0), address(addr) { ui->setupUi(this); setWindowTitle(QString("%1").arg(address)); ui->chkReqPayment->setVisible(enableReq); ui->lblAmount->setVisible(enableReq); ui->lnReqAmount->setVisible(enableReq); ui->lnLabel->setText(label); ui->btnSaveAs->setEnabled(false); genCode(); } QRCodeDialog::~QRCodeDialog() { delete ui; } void QRCodeDialog::setModel(OptionsModel *model) { this->model = model; if (model) connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void QRCodeDialog::genCode() { QString uri = getURI(); if (uri != "") { ui->lblQRCode->setText(""); QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char *p = code->data; for (int y = 0; y < code->width; y++) { for (int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); ui->outUri->setPlainText(uri); } } QString QRCodeDialog::getURI() { QString ret = QString("FuelCoin:%1").arg(address); int paramCount = 0; ui->outUri->clear(); if (ui->chkReqPayment->isChecked()) { if (ui->lnReqAmount->validate()) { // even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21) ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value())); paramCount++; } else { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("The entered amount is invalid, please check.")); return QString(""); } } if (!ui->lnLabel->text().isEmpty()) { QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if (!ui->lnMessage->text().isEmpty()) { QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } // limit URI length to prevent a DoS against the QR-Code dialog if (ret.length() > MAX_URI_LENGTH) { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); return QString(""); } ui->btnSaveAs->setEnabled(true); return ret; } void QRCodeDialog::on_lnReqAmount_textChanged() { genCode(); } void QRCodeDialog::on_lnLabel_textChanged() { genCode(); } void QRCodeDialog::on_lnMessage_textChanged() { genCode(); } void QRCodeDialog::on_btnSaveAs_clicked() { QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)")); if (!fn.isEmpty()) myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); } void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked) { if (!fChecked) // if chkReqPayment is not active, don't display lnReqAmount as invalid ui->lnReqAmount->setValid(true); genCode(); } void QRCodeDialog::updateDisplayUnit() { if (model) { // Update lnReqAmount with the current unit ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit()); } } <commit_msg>Update qrcodedialog.cpp<commit_after>#include "qrcodedialog.h" #include "ui_qrcodedialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include <QPixmap> #include <QUrl> #include <qrencode.h> QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : QDialog(parent), ui(new Ui::QRCodeDialog), model(0), address(addr) { ui->setupUi(this); setWindowTitle(QString("%1").arg(address)); ui->chkReqPayment->setVisible(enableReq); ui->lblAmount->setVisible(enableReq); ui->lnReqAmount->setVisible(enableReq); ui->lnLabel->setText(label); ui->btnSaveAs->setEnabled(false); genCode(); } QRCodeDialog::~QRCodeDialog() { delete ui; } void QRCodeDialog::setModel(OptionsModel *model) { this->model = model; if (model) connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void QRCodeDialog::genCode() { QString uri = getURI(); if (uri != "") { ui->lblQRCode->setText(""); QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char *p = code->data; for (int y = 0; y < code->width; y++) { for (int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); ui->outUri->setPlainText(uri); } } QString QRCodeDialog::getURI() { QString ret = QString("Fuelcoin:%1").arg(address); int paramCount = 0; ui->outUri->clear(); if (ui->chkReqPayment->isChecked()) { if (ui->lnReqAmount->validate()) { // even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21) ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value())); paramCount++; } else { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("The entered amount is invalid, please check.")); return QString(""); } } if (!ui->lnLabel->text().isEmpty()) { QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if (!ui->lnMessage->text().isEmpty()) { QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } // limit URI length to prevent a DoS against the QR-Code dialog if (ret.length() > MAX_URI_LENGTH) { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); return QString(""); } ui->btnSaveAs->setEnabled(true); return ret; } void QRCodeDialog::on_lnReqAmount_textChanged() { genCode(); } void QRCodeDialog::on_lnLabel_textChanged() { genCode(); } void QRCodeDialog::on_lnMessage_textChanged() { genCode(); } void QRCodeDialog::on_btnSaveAs_clicked() { QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)")); if (!fn.isEmpty()) myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); } void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked) { if (!fChecked) // if chkReqPayment is not active, don't display lnReqAmount as invalid ui->lnReqAmount->setValid(true); genCode(); } void QRCodeDialog::updateDisplayUnit() { if (model) { // Update lnReqAmount with the current unit ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit()); } } <|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <qlayout.h> #include <qtextbrowser.h> #include <qtextcodec.h> #include <qfileinfo.h> #include <qlabel.h> #include <kglobal.h> #include <klocale.h> #include <kdebug.h> #include <kiconloader.h> #include <kmessagebox.h> #include <libkcal/calendar.h> #ifndef KORG_NOPRINTER #include "calprinter.h" #endif #include "koglobals.h" #include "koprefs.h" #include "koeventviewerdialog.h" #include "kowhatsnextview.h" using namespace KOrg; #include "kowhatsnextview.moc" void WhatsNextTextBrowser::setSource(const QString& n) { kdDebug() << "WhatsNextTextBrowser::setSource(): " << n << endl; if (n.startsWith("event:")) { emit showIncidence(n); return; } else if (n.startsWith("todo:")) { emit showIncidence(n); return; } else { QTextBrowser::setSource(n); } } KOWhatsNextView::KOWhatsNextView(Calendar *calendar, QWidget *parent, const char *name) : KOrg::BaseView(calendar, parent, name) { QLabel *dateLabel = new QLabel(KGlobal::locale()->formatDate(QDate::currentDate()),this); dateLabel->setMargin(2); dateLabel->setAlignment(AlignCenter); mView = new WhatsNextTextBrowser(this); connect(mView,SIGNAL(showIncidence(const QString &)),SLOT(showIncidence(const QString &))); mEventViewer = 0; QBoxLayout *topLayout = new QVBoxLayout(this); topLayout->addWidget(dateLabel); topLayout->addWidget(mView); } KOWhatsNextView::~KOWhatsNextView() { } int KOWhatsNextView::maxDatesHint() { return 0; } int KOWhatsNextView::currentDateCount() { return 0; } QPtrList<Incidence> KOWhatsNextView::selectedIncidences() { QPtrList<Incidence> eventList; return eventList; } void KOWhatsNextView::printPreview(CalPrinter *calPrinter, const QDate &fd, const QDate &td) { #ifndef KORG_NOPRINTER calPrinter->preview(CalPrinter::Day, fd, td); #endif } void KOWhatsNextView::updateView() { KIconLoader kil("korganizer"); QString *ipath = new QString(); kil.loadIcon("korganizer",KIcon::NoGroup,32,KIcon::DefaultState,ipath); mText = "<table width=\"100%\">\n"; mText += "<tr bgcolor=\"#3679AD\"><td><h1>"; mText += "<img src=\""; mText += *ipath; mText += "\">"; mText += "<font color=\"white\"> What's next?</h1></font>"; mText += "</td></tr>\n<tr><td>"; QPtrList<Event> events = calendar()->events( QDate::currentDate(), true ); if (events.count() > 0) { mText += "<p></p>"; kil.loadIcon("appointment",KIcon::NoGroup,22,KIcon::DefaultState,ipath); mText += "<h2><img src=\""; mText += *ipath; mText += "\">"; mText += i18n("Events:") + "</h2>\n"; mText += "<table>\n"; Event *ev = events.first(); while(ev) { if (!ev->recurrence()->doesRecur() || ev->recursOn( QDate::currentDate())) { appendEvent(ev); } ev = events.next(); } mText += "</table>\n"; } QPtrList<Todo> todos = calendar()->todos(); if (todos.count() > 0) { kil.loadIcon("todo",KIcon::NoGroup,22,KIcon::DefaultState,ipath); mText += "<h2><img src=\""; mText += *ipath; mText += "\">"; mText += i18n("To-Do:") + "</h2>\n"; mText += "<ul>\n"; Todo *todo = todos.first(); while(todo) { if ( todo->hasDueDate() && todo->dtDue().date() == QDate::currentDate() ) appendTodo(todo); todo = todos.next(); } bool gotone = false; int priority = 1; while (!gotone && priority<6) { todo = todos.first(); while(todo) { if (!todo->isCompleted() && (todo->priority() == priority) ) { appendTodo(todo); gotone = true; } todo = todos.next(); } priority++; kdDebug() << "adding the todos..." << endl; } mText += "</ul>\n"; } int replys = 0; events = calendar()->events(QDate::currentDate(), QDate(2975,12,6)); if (events.count() > 0) { Event *ev = events.first(); while(ev) { Attendee *me = ev->attendeeByMails(KOPrefs::instance()->mAdditionalMails,KOPrefs::instance()->email()); if (me!=0) { if (me->status()==Attendee::NeedsAction && me->RSVP()) { if (replys == 0) { mText += "<p></p>"; kil.loadIcon("reply",KIcon::NoGroup,22,KIcon::DefaultState,ipath); mText += "<h2><img src=\""; mText += *ipath; mText += "\">"; mText += i18n("Events and To-Dos that need a reply:") + "</h2>\n"; mText += "<table>\n"; } replys++; appendEvent(ev,true); } } ev = events.next(); } } todos = calendar()->todos(); if (todos.count() > 0) { Todo *to = todos.first(); while(to) { Attendee *me = to->attendeeByMails(KOPrefs::instance()->mAdditionalMails,KOPrefs::instance()->email()); if (me!=0) { if (me->status()==Attendee::NeedsAction && me->RSVP()) { if (replys == 0) { mText += "<p></p>"; kil.loadIcon("reply",KIcon::NoGroup,22,KIcon::DefaultState,ipath); mText += "<h2><img src=\""; mText += *ipath; mText += "\">"; mText += i18n("Events and To-Dos that need a reply:") + "</h2>\n"; mText += "<table>\n"; } replys++; appendEvent(to); } } kdDebug () << "check for todo-replys..." << endl; to = todos.next(); } } if (replys > 0 ) mText += "</table>\n"; mText += "</td></tr>\n</table>\n"; kdDebug() << "KOWhatsNextView::updateView: text: " << mText << endl; mView->setText(mText); } void KOWhatsNextView::showDates(const QDate &, const QDate &) { updateView(); } void KOWhatsNextView::showEvents(QPtrList<Event>) { } void KOWhatsNextView::changeEventDisplay(Event *, int action) { switch(action) { case KOGlobals::EVENTADDED: break; case KOGlobals::EVENTEDITED: break; case KOGlobals::EVENTDELETED: break; default: kdDebug() << "KOWhatsNextView::changeEventDisplay(): Illegal action " << action << endl; } } void KOWhatsNextView::appendEvent(Incidence *ev, bool reply) { kdDebug() << "KOWhatsNextView::appendEvent(): " << ev->uid() << endl; mText += "<tr><td><b>"; if (!ev->doesFloat()) { if (ev->type()=="Event") { Event *event = static_cast<Event *>(ev); if (reply) mText += "on " + event->dtStartDateStr() + ": "; mText += event->dtStartTimeStr() + " - " + event->dtEndTimeStr(); } } mText += "</b></td><td><a "; if (ev->type()=="Event") mText += "href=\"event:"; if (ev->type()=="Todo") mText += "href=\"todo:"; mText += ev->uid() + "\">"; mText += ev->summary(); mText += "</a></td></tr>\n"; } void KOWhatsNextView::appendTodo(Incidence *ev) { mText += "<li><a href=\"todo:" + ev->uid() + "\">"; mText += ev->summary(); mText += "</a></li>\n"; } void KOWhatsNextView::createEventViewer() { if (!mEventViewer) { mEventViewer = new KOEventViewerDialog(this); } } // TODO: Create this function in CalendarView and remove it from here void KOWhatsNextView::showIncidence(const QString &uid) { kdDebug() << "KOWhatsNextView::showIncidence(): " << uid << endl; if (uid.startsWith("event://")) { Event *event = calendar()->event(uid.mid(8)); if (!event) return; createEventViewer(); mEventViewer->setEvent(event); } else if (uid.startsWith("todo://")) { Todo *todo = calendar()->todo(uid.mid(7)); if (!todo) return; createEventViewer(); mEventViewer->setTodo(todo); } mEventViewer->show(); mEventViewer->raise(); } <commit_msg>- mText += "<font color=\"white\"> What's next?</h1></font>"; + mText += i18n("<font color=\"white\"> What's next?</h1></font>");<commit_after>/* This file is part of KOrganizer. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <qlayout.h> #include <qtextbrowser.h> #include <qtextcodec.h> #include <qfileinfo.h> #include <qlabel.h> #include <kglobal.h> #include <klocale.h> #include <kdebug.h> #include <kiconloader.h> #include <kmessagebox.h> #include <libkcal/calendar.h> #ifndef KORG_NOPRINTER #include "calprinter.h" #endif #include "koglobals.h" #include "koprefs.h" #include "koeventviewerdialog.h" #include "kowhatsnextview.h" using namespace KOrg; #include "kowhatsnextview.moc" void WhatsNextTextBrowser::setSource(const QString& n) { kdDebug() << "WhatsNextTextBrowser::setSource(): " << n << endl; if (n.startsWith("event:")) { emit showIncidence(n); return; } else if (n.startsWith("todo:")) { emit showIncidence(n); return; } else { QTextBrowser::setSource(n); } } KOWhatsNextView::KOWhatsNextView(Calendar *calendar, QWidget *parent, const char *name) : KOrg::BaseView(calendar, parent, name) { QLabel *dateLabel = new QLabel(KGlobal::locale()->formatDate(QDate::currentDate()),this); dateLabel->setMargin(2); dateLabel->setAlignment(AlignCenter); mView = new WhatsNextTextBrowser(this); connect(mView,SIGNAL(showIncidence(const QString &)),SLOT(showIncidence(const QString &))); mEventViewer = 0; QBoxLayout *topLayout = new QVBoxLayout(this); topLayout->addWidget(dateLabel); topLayout->addWidget(mView); } KOWhatsNextView::~KOWhatsNextView() { } int KOWhatsNextView::maxDatesHint() { return 0; } int KOWhatsNextView::currentDateCount() { return 0; } QPtrList<Incidence> KOWhatsNextView::selectedIncidences() { QPtrList<Incidence> eventList; return eventList; } void KOWhatsNextView::printPreview(CalPrinter *calPrinter, const QDate &fd, const QDate &td) { #ifndef KORG_NOPRINTER calPrinter->preview(CalPrinter::Day, fd, td); #endif } void KOWhatsNextView::updateView() { KIconLoader kil("korganizer"); QString *ipath = new QString(); kil.loadIcon("korganizer",KIcon::NoGroup,32,KIcon::DefaultState,ipath); mText = "<table width=\"100%\">\n"; mText += "<tr bgcolor=\"#3679AD\"><td><h1>"; mText += "<img src=\""; mText += *ipath; mText += "\">"; mText += i18n("<font color=\"white\"> What's next?</h1></font>"); mText += "</td></tr>\n<tr><td>"; QPtrList<Event> events = calendar()->events( QDate::currentDate(), true ); if (events.count() > 0) { mText += "<p></p>"; kil.loadIcon("appointment",KIcon::NoGroup,22,KIcon::DefaultState,ipath); mText += "<h2><img src=\""; mText += *ipath; mText += "\">"; mText += i18n("Events:") + "</h2>\n"; mText += "<table>\n"; Event *ev = events.first(); while(ev) { if (!ev->recurrence()->doesRecur() || ev->recursOn( QDate::currentDate())) { appendEvent(ev); } ev = events.next(); } mText += "</table>\n"; } QPtrList<Todo> todos = calendar()->todos(); if (todos.count() > 0) { kil.loadIcon("todo",KIcon::NoGroup,22,KIcon::DefaultState,ipath); mText += "<h2><img src=\""; mText += *ipath; mText += "\">"; mText += i18n("To-Do:") + "</h2>\n"; mText += "<ul>\n"; Todo *todo = todos.first(); while(todo) { if ( todo->hasDueDate() && todo->dtDue().date() == QDate::currentDate() ) appendTodo(todo); todo = todos.next(); } bool gotone = false; int priority = 1; while (!gotone && priority<6) { todo = todos.first(); while(todo) { if (!todo->isCompleted() && (todo->priority() == priority) ) { appendTodo(todo); gotone = true; } todo = todos.next(); } priority++; kdDebug() << "adding the todos..." << endl; } mText += "</ul>\n"; } int replys = 0; events = calendar()->events(QDate::currentDate(), QDate(2975,12,6)); if (events.count() > 0) { Event *ev = events.first(); while(ev) { Attendee *me = ev->attendeeByMails(KOPrefs::instance()->mAdditionalMails,KOPrefs::instance()->email()); if (me!=0) { if (me->status()==Attendee::NeedsAction && me->RSVP()) { if (replys == 0) { mText += "<p></p>"; kil.loadIcon("reply",KIcon::NoGroup,22,KIcon::DefaultState,ipath); mText += "<h2><img src=\""; mText += *ipath; mText += "\">"; mText += i18n("Events and To-Dos that need a reply:") + "</h2>\n"; mText += "<table>\n"; } replys++; appendEvent(ev,true); } } ev = events.next(); } } todos = calendar()->todos(); if (todos.count() > 0) { Todo *to = todos.first(); while(to) { Attendee *me = to->attendeeByMails(KOPrefs::instance()->mAdditionalMails,KOPrefs::instance()->email()); if (me!=0) { if (me->status()==Attendee::NeedsAction && me->RSVP()) { if (replys == 0) { mText += "<p></p>"; kil.loadIcon("reply",KIcon::NoGroup,22,KIcon::DefaultState,ipath); mText += "<h2><img src=\""; mText += *ipath; mText += "\">"; mText += i18n("Events and To-Dos that need a reply:") + "</h2>\n"; mText += "<table>\n"; } replys++; appendEvent(to); } } kdDebug () << "check for todo-replys..." << endl; to = todos.next(); } } if (replys > 0 ) mText += "</table>\n"; mText += "</td></tr>\n</table>\n"; kdDebug() << "KOWhatsNextView::updateView: text: " << mText << endl; mView->setText(mText); } void KOWhatsNextView::showDates(const QDate &, const QDate &) { updateView(); } void KOWhatsNextView::showEvents(QPtrList<Event>) { } void KOWhatsNextView::changeEventDisplay(Event *, int action) { switch(action) { case KOGlobals::EVENTADDED: break; case KOGlobals::EVENTEDITED: break; case KOGlobals::EVENTDELETED: break; default: kdDebug() << "KOWhatsNextView::changeEventDisplay(): Illegal action " << action << endl; } } void KOWhatsNextView::appendEvent(Incidence *ev, bool reply) { kdDebug() << "KOWhatsNextView::appendEvent(): " << ev->uid() << endl; mText += "<tr><td><b>"; if (!ev->doesFloat()) { if (ev->type()=="Event") { Event *event = static_cast<Event *>(ev); if (reply) mText += "on " + event->dtStartDateStr() + ": "; mText += event->dtStartTimeStr() + " - " + event->dtEndTimeStr(); } } mText += "</b></td><td><a "; if (ev->type()=="Event") mText += "href=\"event:"; if (ev->type()=="Todo") mText += "href=\"todo:"; mText += ev->uid() + "\">"; mText += ev->summary(); mText += "</a></td></tr>\n"; } void KOWhatsNextView::appendTodo(Incidence *ev) { mText += "<li><a href=\"todo:" + ev->uid() + "\">"; mText += ev->summary(); mText += "</a></li>\n"; } void KOWhatsNextView::createEventViewer() { if (!mEventViewer) { mEventViewer = new KOEventViewerDialog(this); } } // TODO: Create this function in CalendarView and remove it from here void KOWhatsNextView::showIncidence(const QString &uid) { kdDebug() << "KOWhatsNextView::showIncidence(): " << uid << endl; if (uid.startsWith("event://")) { Event *event = calendar()->event(uid.mid(8)); if (!event) return; createEventViewer(); mEventViewer->setEvent(event); } else if (uid.startsWith("todo://")) { Todo *todo = calendar()->todo(uid.mid(7)); if (!todo) return; createEventViewer(); mEventViewer->setTodo(todo); } mEventViewer->show(); mEventViewer->raise(); } <|endoftext|>
<commit_before>// // Created by dar on 11/25/15. // #include "Renderer.h" Renderer::Renderer(Core *core) : core(core) { } bool Renderer::init() { if (!this->initWindow()) { printf("Failed to initialize window!\n"); } else if (!this->initGL()) { printf("Unable to initialize OpenGL!\n"); } else if (!this->initTextures()) { printf("Unable to initialize textures!\n"); } else { initRenderers(); initTexData(); fbo.init(3, windowWidth, windowHeight, new float[4]{0.9, 0.9, 0.9, 1.0}, "fboshader"); return true; } return false; } bool Renderer::initWindow() { bool success = true; if (SDL_Init(SDL_INIT_VIDEO) < 0) { //Initialize SDL printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError()); success = false; } else { //Use OpenGL 3.3 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); //Create window gWindow = SDL_CreateWindow("C003", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, windowWidth, windowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); if (gWindow == NULL) { printf("Window could not be created! SDL Error: %s\n", SDL_GetError()); success = false; } else { gContext = SDL_GL_CreateContext(gWindow); //Create context if (gContext == NULL) { printf("OpenGL context could not be created! SDL Error: %s\n", SDL_GetError()); success = false; } else { //Use Vsync if (SDL_GL_SetSwapInterval(1) < 0) { printf("Warning: Unable to set VSync! SDL Error: %s\n", SDL_GetError()); } } } } return success; } bool Renderer::initGL() { viewMatrix = glm::lookAt(glm::vec3(0, 0, 0.0f), glm::vec3(0, 0, 1.0f), glm::vec3(0.0f, 1.0f, 0.0f)); projectionMatrix = glm::ortho(0.0f, float(windowWidth), 0.0f, float(windowHeight)); glEnable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); return true; } bool Renderer::initTextures() { bool ret = true; if (!textureAtlas.loadTexture2D("terrain.png", true)) ret = false; textureAtlas.setFiltering(TEXTURE_FILTER_MAG_BILINEAR, TEXTURE_FILTER_MIN_BILINEAR_MIPMAP); return ret; } void Renderer::tick() { fbo.bind(); glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); textureAtlas.bindTexture(0); for (Block *block : core->getMap()->getBlocks()) { if (block->getX() * this->core->getGeneralScale() * this->core->getBlockSize() > -(signed) windowWidth / 2.0f - this->core->getCamX() && (block->getX() - 1) * this->core->getGeneralScale() * this->core->getBlockSize() < -(signed) windowWidth / 2.0f - this->core->getCamX() + (signed) windowWidth && block->getY() * this->core->getGeneralScale() * this->core->getBlockSize() > -(signed) windowHeight / 2.0f - this->core->getCamY() && (block->getY() - 1) * this->core->getGeneralScale() * this->core->getBlockSize() < -(signed) windowHeight / 2.0f - this->core->getCamY() + (signed) windowHeight) getBlockRender(block)->render(block, textureAtlas.getBoundId(), projectionMatrix, glm::translate(viewMatrix, glm::vec3( (int) (-(signed) windowWidth / 2.0f - this->core->getCamX()), (int) ((signed) windowHeight / 2.0f - this->core->getCamY()), 0.0f )), this->core->getBlockSize() * this->core->getGeneralScale()); } int entitiesNum = 0; for (int i = core->getMap()->getEntities().size() - 1; i >= 0; i--) { Entity *entity = core->getMap()->getEntities().at(i); if (entity->getX() * this->core->getGeneralScale() * this->core->getBlockSize() > -(signed) windowWidth / 2.0f - this->core->getCamX() && (entity->getX() - 1) * this->core->getGeneralScale() * this->core->getBlockSize() < -(signed) windowWidth / 2.0f - this->core->getCamX() + (signed) windowWidth && entity->getY() * this->core->getGeneralScale() * this->core->getBlockSize() > -(signed) windowHeight / 2.0f - this->core->getCamY() && (entity->getY() - 1) * this->core->getGeneralScale() * this->core->getBlockSize() < -(signed) windowHeight / 2.0f - this->core->getCamY() + (signed) windowHeight) { getEntityRender(entity)->render(entity, projectionMatrix, glm::translate(viewMatrix, glm::vec3( (int) (-(signed) windowWidth / 2.0f - this->core->getCamX()), (int) ((signed) windowHeight / 2.0f - this->core->getCamY()), 0.0f)), this->core->getBlockSize() * this->core->getGeneralScale()); fbo.getShaderProgram()->useProgram(); if (entity != this->core->getPlayer() && entitiesNum < fbo.MAX_LIGHT_SRCS) { fbo.getShaderProgram()->setUniform("lightPoints[" + to_string(entitiesNum) + "]", glm::vec2(this->core->getCamX() + (entity->getX() - 0.5 + entity->getWidth() / 2) * this->core->getBlockSize() * this->core->getGeneralScale() + (double) this->windowWidth / 2, -this->core->getCamY() - (entity->getY() - 0.5 + entity->getHeight() / 2) * this->core->getBlockSize() * this->core->getGeneralScale() + (double) this->windowHeight / 2)); entitiesNum++; } } } fbo.unbind(); fbo.getShaderProgram()->useProgram(); fbo.getShaderProgram()->setUniform("lightPointsNum", entitiesNum); fbo.getShaderProgram()->setUniform("scale", (float)(this->core->getBlockSize() * this->core->getGeneralScale())); fbo.render(0); } void Renderer::run() { this->tick(); SDL_GL_SwapWindow(gWindow); } void Renderer::resize(unsigned int width, unsigned int height) { if (width != this->windowWidth || height != this->windowHeight) { this->windowWidth = width; this->windowHeight = height; glViewport(0, 0, windowWidth, windowHeight); viewMatrix = glm::lookAt(glm::vec3(0, 0, 0.0f), glm::vec3(0, 0, 1.0f), glm::vec3(0.0f, 1.0f, 0.0f)); this->projectionMatrix = glm::ortho(0.0f, float(windowWidth), 0.0f, float(windowHeight)); this->fbo.resize(this->windowWidth, this->windowHeight); } } Renderer::~Renderer() { SDL_DestroyWindow(this->gWindow); SDL_Quit(); } <commit_msg>Adjusted light position<commit_after>// // Created by dar on 11/25/15. // #include "Renderer.h" Renderer::Renderer(Core *core) : core(core) { } bool Renderer::init() { if (!this->initWindow()) { printf("Failed to initialize window!\n"); } else if (!this->initGL()) { printf("Unable to initialize OpenGL!\n"); } else if (!this->initTextures()) { printf("Unable to initialize textures!\n"); } else { initRenderers(); initTexData(); fbo.init(3, windowWidth, windowHeight, new float[4]{0.9, 0.9, 0.9, 1.0}, "fboshader"); return true; } return false; } bool Renderer::initWindow() { bool success = true; if (SDL_Init(SDL_INIT_VIDEO) < 0) { //Initialize SDL printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError()); success = false; } else { //Use OpenGL 3.3 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); //Create window gWindow = SDL_CreateWindow("C003", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, windowWidth, windowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); if (gWindow == NULL) { printf("Window could not be created! SDL Error: %s\n", SDL_GetError()); success = false; } else { gContext = SDL_GL_CreateContext(gWindow); //Create context if (gContext == NULL) { printf("OpenGL context could not be created! SDL Error: %s\n", SDL_GetError()); success = false; } else { //Use Vsync if (SDL_GL_SetSwapInterval(1) < 0) { printf("Warning: Unable to set VSync! SDL Error: %s\n", SDL_GetError()); } } } } return success; } bool Renderer::initGL() { viewMatrix = glm::lookAt(glm::vec3(0, 0, 0.0f), glm::vec3(0, 0, 1.0f), glm::vec3(0.0f, 1.0f, 0.0f)); projectionMatrix = glm::ortho(0.0f, float(windowWidth), 0.0f, float(windowHeight)); glEnable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); return true; } bool Renderer::initTextures() { bool ret = true; if (!textureAtlas.loadTexture2D("terrain.png", true)) ret = false; textureAtlas.setFiltering(TEXTURE_FILTER_MAG_BILINEAR, TEXTURE_FILTER_MIN_BILINEAR_MIPMAP); return ret; } void Renderer::tick() { fbo.bind(); glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); textureAtlas.bindTexture(0); for (Block *block : core->getMap()->getBlocks()) { if (block->getX() * this->core->getGeneralScale() * this->core->getBlockSize() > -(signed) windowWidth / 2.0f - this->core->getCamX() && (block->getX() - 1) * this->core->getGeneralScale() * this->core->getBlockSize() < -(signed) windowWidth / 2.0f - this->core->getCamX() + (signed) windowWidth && block->getY() * this->core->getGeneralScale() * this->core->getBlockSize() > -(signed) windowHeight / 2.0f - this->core->getCamY() && (block->getY() - 1) * this->core->getGeneralScale() * this->core->getBlockSize() < -(signed) windowHeight / 2.0f - this->core->getCamY() + (signed) windowHeight) getBlockRender(block)->render(block, textureAtlas.getBoundId(), projectionMatrix, glm::translate(viewMatrix, glm::vec3( (int) (-(signed) windowWidth / 2.0f - this->core->getCamX()), (int) ((signed) windowHeight / 2.0f - this->core->getCamY()), 0.0f )), this->core->getBlockSize() * this->core->getGeneralScale()); } int entitiesNum = 0; for (int i = core->getMap()->getEntities().size() - 1; i >= 0; i--) { Entity *entity = core->getMap()->getEntities().at(i); if (entity->getX() * this->core->getGeneralScale() * this->core->getBlockSize() > -(signed) windowWidth / 2.0f - this->core->getCamX() && (entity->getX() - 1) * this->core->getGeneralScale() * this->core->getBlockSize() < -(signed) windowWidth / 2.0f - this->core->getCamX() + (signed) windowWidth && entity->getY() * this->core->getGeneralScale() * this->core->getBlockSize() > -(signed) windowHeight / 2.0f - this->core->getCamY() && (entity->getY() - 1) * this->core->getGeneralScale() * this->core->getBlockSize() < -(signed) windowHeight / 2.0f - this->core->getCamY() + (signed) windowHeight) { getEntityRender(entity)->render(entity, projectionMatrix, glm::translate(viewMatrix, glm::vec3( (int) (-(signed) windowWidth / 2.0f - this->core->getCamX()), (int) ((signed) windowHeight / 2.0f - this->core->getCamY()), 0.0f)), this->core->getBlockSize() * this->core->getGeneralScale()); fbo.getShaderProgram()->useProgram(); if (entity != this->core->getPlayer() && entitiesNum < fbo.MAX_LIGHT_SRCS) { fbo.getShaderProgram()->setUniform("lightPoints[" + to_string(entitiesNum) + "]", glm::vec2(this->core->getCamX() + (entity->getX() - 1 + entity->getWidth() / 2) * this->core->getBlockSize() * this->core->getGeneralScale() + (double) this->windowWidth / 2, -this->core->getCamY() - (entity->getY() - 1 + entity->getHeight() / 2) * this->core->getBlockSize() * this->core->getGeneralScale() + (double) this->windowHeight / 2)); entitiesNum++; } } } fbo.unbind(); fbo.getShaderProgram()->useProgram(); fbo.getShaderProgram()->setUniform("lightPointsNum", entitiesNum); fbo.getShaderProgram()->setUniform("scale", (float) (this->core->getBlockSize() * this->core->getGeneralScale())); fbo.render(0); } void Renderer::run() { this->tick(); SDL_GL_SwapWindow(gWindow); } void Renderer::resize(unsigned int width, unsigned int height) { if (width != this->windowWidth || height != this->windowHeight) { this->windowWidth = width; this->windowHeight = height; glViewport(0, 0, windowWidth, windowHeight); viewMatrix = glm::lookAt(glm::vec3(0, 0, 0.0f), glm::vec3(0, 0, 1.0f), glm::vec3(0.0f, 1.0f, 0.0f)); this->projectionMatrix = glm::ortho(0.0f, float(windowWidth), 0.0f, float(windowHeight)); this->fbo.resize(this->windowWidth, this->windowHeight); } } Renderer::~Renderer() { SDL_DestroyWindow(this->gWindow); SDL_Quit(); } <|endoftext|>
<commit_before>/* RTcmix - Copyright (C) 2005 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ #include <stdlib.h> #include <string.h> #include <math.h> #include <rtcmix_types.h> #include <tableutils.h> #include <PField.h> #include <utils.h> #include <ugens.h> // for warn, die // Functions for modifying table PFields. -JGG, 4/8/05 #define NORMALIZE_USAGE "table = modtable(table, \"normalize\" [, peak])" #define REVERSE_USAGE "table = modtable(table, \"reverse\")" #define SHIFT_USAGE "table = modtable(table, \"shift\", shift)" // ============================================================================= // local utilities static PField *_modtable_usage(const char *msg) { die(NULL, "Usage: %s", msg); return NULL; } // ============================================================================= // Set up the various table modifications. // Rescale the values in table so that the maximum absolute value is <peak>. // If no <peak>, peak is 1. Result depends on the sign of values in the table. // // sign of values resulting range of values // -------------------------------------------------------------- // all positive between 0 and peak // all negative between 0 and -peak // positive and negative between -peak and peak static PField * _normalize_table(PField *intable, const Arg args[], const int nargs) { double peak = 1.0; if (nargs > 0) peak = (double) args[0]; if (peak == 0.0) peak = 0.00001; const int len = intable->values(); const double *array = (double *) *intable; double max = 0.0; for (int i = 0; i < len; i++) { double absval = fabs(array[i]); if (absval > max) max = absval; } max /= peak; if (max == 0.0) return intable; PField *factorpf = new ConstPField(1.0 / max); return new MultPField(intable, factorpf); } static PField * _reverse_table(PField *intable, const Arg args[], const int nargs) { return new ReversePField(intable); } static PField * _shift_table(PField *intable, const Arg args[], const int nargs) { if (nargs < 1) return _modtable_usage(SHIFT_USAGE); const int shift = (int) args[0]; return new ShiftPField(intable, shift); } // ============================================================================= // The remaining functions are public, callable from scripts. extern "C" { Handle modtable(const Arg args[], const int nargs); } // ---------------------------------------------------------------- modtable --- static Handle _modtable_usage() { die("modtable", "\n usage: " NORMALIZE_USAGE "\nOR" "\n usage: " REVERSE_USAGE "\nOR" "\n usage: " SHIFT_USAGE "\n"); return NULL; } Handle modtable(const Arg args[], const int nargs) { if (nargs < 2) return _modtable_usage(); PField *intable = (PField *) args[0]; if (intable == NULL || !is_table(intable)) return _modtable_usage(); PField *outtable = NULL; if (args[1].isType(StringType)) { if (args[1] == "normalize") outtable = _normalize_table(intable, &args[2], nargs - 2); else if (args[1] == "reverse") outtable = _reverse_table(intable, &args[2], nargs - 2); else if (args[1] == "shift") outtable = _shift_table(intable, &args[2], nargs - 2); else { die("modtable", "Unsupported modification \"%s\".", (const char *) args[1]); return NULL; } } else return _modtable_usage(); return (outtable == NULL) ? NULL : createPFieldHandle(outtable); } <commit_msg>shift comment.<commit_after>/* RTcmix - Copyright (C) 2005 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ #include <stdlib.h> #include <string.h> #include <math.h> #include <rtcmix_types.h> #include <tableutils.h> #include <PField.h> #include <utils.h> #include <ugens.h> // for warn, die // Functions for modifying table PFields. -JGG, 4/8/05 #define NORMALIZE_USAGE "table = modtable(table, \"normalize\" [, peak])" #define REVERSE_USAGE "table = modtable(table, \"reverse\")" #define SHIFT_USAGE "table = modtable(table, \"shift\", shift)" // ============================================================================= // local utilities static PField *_modtable_usage(const char *msg) { die(NULL, "Usage: %s", msg); return NULL; } // ============================================================================= // Set up the various table modifications. // Rescale the values in table so that the maximum absolute value is <peak>. // If no <peak>, peak is 1. Result depends on the sign of values in the table. // // sign of values resulting range of values // -------------------------------------------------------------- // all positive between 0 and peak // all negative between 0 and -peak // positive and negative between -peak and peak static PField * _normalize_table(PField *intable, const Arg args[], const int nargs) { double peak = 1.0; if (nargs > 0) peak = (double) args[0]; if (peak == 0.0) peak = 0.00001; const int len = intable->values(); const double *array = (double *) *intable; double max = 0.0; for (int i = 0; i < len; i++) { double absval = fabs(array[i]); if (absval > max) max = absval; } max /= peak; if (max == 0.0) return intable; PField *factorpf = new ConstPField(1.0 / max); return new MultPField(intable, factorpf); } static PField * _reverse_table(PField *intable, const Arg args[], const int nargs) { return new ReversePField(intable); } // Shift values of the table by <shift> array locations. Positive values of // <shift> shift to the right; negative values to the left. If a value is // shifted off the end of the array in either direction, it reenters the other // end of the array. Two examples: // // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] original table, size = 10 // [7, 8, 9, 0, 1, 2, 3, 4, 5, 6] shift = 3 // [3, 4, 5, 6, 7, 8, 9, 0, 1, 2] shift = -3 // // Note that the shifting is actually done on-the-fly by ShiftPField. static PField * _shift_table(PField *intable, const Arg args[], const int nargs) { if (nargs < 1) return _modtable_usage(SHIFT_USAGE); const int shift = (int) args[0]; return new ShiftPField(intable, shift); } // ============================================================================= // The remaining functions are public, callable from scripts. extern "C" { Handle modtable(const Arg args[], const int nargs); } // ---------------------------------------------------------------- modtable --- static Handle _modtable_usage() { die("modtable", "\n usage: " NORMALIZE_USAGE "\nOR" "\n usage: " REVERSE_USAGE "\nOR" "\n usage: " SHIFT_USAGE "\n"); return NULL; } Handle modtable(const Arg args[], const int nargs) { if (nargs < 2) return _modtable_usage(); PField *intable = (PField *) args[0]; if (intable == NULL || !is_table(intable)) return _modtable_usage(); PField *outtable = NULL; if (args[1].isType(StringType)) { if (args[1] == "normalize") outtable = _normalize_table(intable, &args[2], nargs - 2); else if (args[1] == "reverse") outtable = _reverse_table(intable, &args[2], nargs - 2); else if (args[1] == "shift") outtable = _shift_table(intable, &args[2], nargs - 2); else { die("modtable", "Unsupported modification \"%s\".", (const char *) args[1]); return NULL; } } else return _modtable_usage(); return (outtable == NULL) ? NULL : createPFieldHandle(outtable); } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2017-2020 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "script/standard.h" #include "pubkey.h" #include "script/script.h" #include "util.h" #include "utilstrencodings.h" typedef std::vector<unsigned char> valtype; unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY; CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {} const char* GetTxnOutputType(txnouttype t) { switch (t) { case TX_NONSTANDARD: return "nonstandard"; case TX_PUBKEY: return "pubkey"; case TX_PUBKEYHASH: return "pubkeyhash"; case TX_SCRIPTHASH: return "scripthash"; case TX_MULTISIG: return "multisig"; case TX_COLDSTAKE: return "coldstake"; case TX_NULL_DATA: return "nulldata"; case TX_ZEROCOINMINT: return "zerocoinmint"; } return NULL; } static bool MatchPayToPubkey(const CScript& script, valtype& pubkey) { if (script.size() == CPubKey::PUBLIC_KEY_SIZE + 2 && script[0] == CPubKey::PUBLIC_KEY_SIZE && script.back() == OP_CHECKSIG) { pubkey = valtype(script.begin() + 1, script.begin() + CPubKey::PUBLIC_KEY_SIZE + 1); return CPubKey::ValidSize(pubkey); } if (script.size() == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 2 && script[0] == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE && script.back() == OP_CHECKSIG) { pubkey = valtype(script.begin() + 1, script.begin() + CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 1); return CPubKey::ValidSize(pubkey); } return false; } static bool MatchPayToPubkeyHash(const CScript& script, valtype& pubkeyhash) { if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160 && script[2] == 20 && script[23] == OP_EQUALVERIFY && script[24] == OP_CHECKSIG) { pubkeyhash = valtype(script.begin () + 3, script.begin() + 23); return true; } return false; } static bool MatchPayToColdStaking(const CScript& script, valtype& stakerPubKeyHash, valtype& ownerPubKeyHash) { if (script.IsPayToColdStaking()) { stakerPubKeyHash = valtype(script.begin () + 6, script.begin() + 26); ownerPubKeyHash = valtype(script.begin () + 28, script.begin() + 48); return true; } return false; } /** Test for "small positive integer" script opcodes - OP_1 through OP_16. */ static constexpr bool IsSmallInteger(opcodetype opcode) { return opcode >= OP_1 && opcode <= OP_16; } static bool MatchMultisig(const CScript& script, unsigned int& required, std::vector<valtype>& pubkeys) { opcodetype opcode; valtype data; CScript::const_iterator it = script.begin(); if (script.size() < 1 || script.back() != OP_CHECKMULTISIG) return false; if (!script.GetOp(it, opcode, data) || !IsSmallInteger(opcode)) return false; required = CScript::DecodeOP_N(opcode); while (script.GetOp(it, opcode, data) && CPubKey::ValidSize(data)) { pubkeys.emplace_back(std::move(data)); } if (!IsSmallInteger(opcode)) return false; unsigned int keys = CScript::DecodeOP_N(opcode); if (pubkeys.size() != keys || keys < required) return false; return (it + 1 == script.end()); } /** * Return public keys or hashes from scriptPubKey, for 'standard' transaction types. */ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet) { vSolutionsRet.clear(); // Shortcut for pay-to-script-hash, which are more constrained than the other types: // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL if (scriptPubKey.IsPayToScriptHash()) { typeRet = TX_SCRIPTHASH; std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22); vSolutionsRet.push_back(hashBytes); return true; } // Zerocoin if (scriptPubKey.IsZerocoinMint()) { typeRet = TX_ZEROCOINMINT; if(scriptPubKey.size() > 150) return false; std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.end()); vSolutionsRet.push_back(hashBytes); return true; } // Provably prunable, data-carrying output // // So long as script passes the IsUnspendable() test and all but the first // byte passes the IsPushOnly() test we don't care what exactly is in the // script. if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) { typeRet = TX_NULL_DATA; return true; } std::vector<unsigned char> data; if (MatchPayToPubkey(scriptPubKey, data)) { typeRet = TX_PUBKEY; vSolutionsRet.push_back(std::move(data)); return true; } if (MatchPayToPubkeyHash(scriptPubKey, data)) { typeRet = TX_PUBKEYHASH; vSolutionsRet.push_back(std::move(data)); return true; } std::vector<unsigned char> data1; if (MatchPayToColdStaking(scriptPubKey, data, data1)) { typeRet = TX_COLDSTAKE; vSolutionsRet.push_back(std::move(data)); vSolutionsRet.push_back(std::move(data1)); return true; } unsigned int required; std::vector<std::vector<unsigned char>> keys; if (MatchMultisig(scriptPubKey, required, keys)) { typeRet = TX_MULTISIG; vSolutionsRet.push_back({static_cast<unsigned char>(required)}); // safe as required is in range 1..16 vSolutionsRet.insert(vSolutionsRet.end(), keys.begin(), keys.end()); vSolutionsRet.push_back({static_cast<unsigned char>(keys.size())}); // safe as size is in range 1..16 return true; } vSolutionsRet.clear(); typeRet = TX_NONSTANDARD; return false; } int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions) { switch (t) { case TX_NONSTANDARD: case TX_NULL_DATA: case TX_ZEROCOINMINT: return -1; case TX_PUBKEY: return 1; case TX_PUBKEYHASH: return 2; case TX_COLDSTAKE: return 3; case TX_MULTISIG: if (vSolutions.size() < 1 || vSolutions[0].size() < 1) return -1; return vSolutions[0][0] + 1; case TX_SCRIPTHASH: return 1; // doesn't include args needed by the script } return -1; } bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet, bool fColdStake) { std::vector<valtype> vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { CPubKey pubKey(vSolutions[0]); if (!pubKey.IsValid()) return false; addressRet = pubKey.GetID(); return true; } else if (whichType == TX_PUBKEYHASH) { addressRet = CKeyID(uint160(vSolutions[0])); return true; } else if (whichType == TX_SCRIPTHASH) { addressRet = CScriptID(uint160(vSolutions[0])); return true; } else if (whichType == TX_COLDSTAKE) { addressRet = CKeyID(uint160(vSolutions[!fColdStake])); return true; } // Multisig txns have more than one address... return false; } bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet) { addressRet.clear(); typeRet = TX_NONSTANDARD; std::vector<valtype> vSolutions; if (!Solver(scriptPubKey, typeRet, vSolutions)) return false; if (typeRet == TX_NULL_DATA){ // This is data, not addresses return false; } if (typeRet == TX_MULTISIG) { nRequiredRet = vSolutions.front()[0]; for (unsigned int i = 1; i < vSolutions.size()-1; i++) { CPubKey pubKey(vSolutions[i]); if (!pubKey.IsValid()) continue; CTxDestination address = pubKey.GetID(); addressRet.push_back(address); } if (addressRet.empty()) return false; } else if (typeRet == TX_COLDSTAKE) { if (vSolutions.size() < 2) return false; nRequiredRet = 2; addressRet.push_back(CKeyID(uint160(vSolutions[0]))); addressRet.push_back(CKeyID(uint160(vSolutions[1]))); return true; } else { nRequiredRet = 1; CTxDestination address; if (!ExtractDestination(scriptPubKey, address)) return false; addressRet.push_back(address); } return true; } namespace { class CScriptVisitor : public boost::static_visitor<bool> { private: CScript *script; public: CScriptVisitor(CScript *scriptin) { script = scriptin; } bool operator()(const CNoDestination &dest) const { script->clear(); return false; } bool operator()(const CKeyID &keyID) const { script->clear(); *script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; return true; } bool operator()(const CScriptID &scriptID) const { script->clear(); *script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL; return true; } }; } CScript GetScriptForDestination(const CTxDestination& dest) { CScript script; boost::apply_visitor(CScriptVisitor(&script), dest); return script; } CScript GetScriptForRawPubKey(const CPubKey& pubKey) { return CScript() << std::vector<unsigned char>(pubKey.begin(), pubKey.end()) << OP_CHECKSIG; } CScript GetScriptForStakeDelegation(const CKeyID& stakingKey, const CKeyID& spendingKey) { CScript script; script << OP_DUP << OP_HASH160 << OP_ROT << OP_IF << OP_CHECKCOLDSTAKEVERIFY << ToByteVector(stakingKey) << OP_ELSE << ToByteVector(spendingKey) << OP_ENDIF << OP_EQUALVERIFY << OP_CHECKSIG; return script; } CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys) { CScript script; script << CScript::EncodeOP_N(nRequired); for (const CPubKey& key : keys) script << ToByteVector(key); script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG; return script; } bool IsValidDestination(const CTxDestination& dest) { return dest.which() != 0; } <commit_msg>Solver return false for empty scripts.<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2017-2020 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "script/standard.h" #include "pubkey.h" #include "script/script.h" #include "util.h" #include "utilstrencodings.h" typedef std::vector<unsigned char> valtype; unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY; CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {} const char* GetTxnOutputType(txnouttype t) { switch (t) { case TX_NONSTANDARD: return "nonstandard"; case TX_PUBKEY: return "pubkey"; case TX_PUBKEYHASH: return "pubkeyhash"; case TX_SCRIPTHASH: return "scripthash"; case TX_MULTISIG: return "multisig"; case TX_COLDSTAKE: return "coldstake"; case TX_NULL_DATA: return "nulldata"; case TX_ZEROCOINMINT: return "zerocoinmint"; } return NULL; } static bool MatchPayToPubkey(const CScript& script, valtype& pubkey) { if (script.size() == CPubKey::PUBLIC_KEY_SIZE + 2 && script[0] == CPubKey::PUBLIC_KEY_SIZE && script.back() == OP_CHECKSIG) { pubkey = valtype(script.begin() + 1, script.begin() + CPubKey::PUBLIC_KEY_SIZE + 1); return CPubKey::ValidSize(pubkey); } if (script.size() == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 2 && script[0] == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE && script.back() == OP_CHECKSIG) { pubkey = valtype(script.begin() + 1, script.begin() + CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 1); return CPubKey::ValidSize(pubkey); } return false; } static bool MatchPayToPubkeyHash(const CScript& script, valtype& pubkeyhash) { if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160 && script[2] == 20 && script[23] == OP_EQUALVERIFY && script[24] == OP_CHECKSIG) { pubkeyhash = valtype(script.begin () + 3, script.begin() + 23); return true; } return false; } static bool MatchPayToColdStaking(const CScript& script, valtype& stakerPubKeyHash, valtype& ownerPubKeyHash) { if (script.IsPayToColdStaking()) { stakerPubKeyHash = valtype(script.begin () + 6, script.begin() + 26); ownerPubKeyHash = valtype(script.begin () + 28, script.begin() + 48); return true; } return false; } /** Test for "small positive integer" script opcodes - OP_1 through OP_16. */ static constexpr bool IsSmallInteger(opcodetype opcode) { return opcode >= OP_1 && opcode <= OP_16; } static bool MatchMultisig(const CScript& script, unsigned int& required, std::vector<valtype>& pubkeys) { opcodetype opcode; valtype data; CScript::const_iterator it = script.begin(); if (script.size() < 1 || script.back() != OP_CHECKMULTISIG) return false; if (!script.GetOp(it, opcode, data) || !IsSmallInteger(opcode)) return false; required = CScript::DecodeOP_N(opcode); while (script.GetOp(it, opcode, data) && CPubKey::ValidSize(data)) { pubkeys.emplace_back(std::move(data)); } if (!IsSmallInteger(opcode)) return false; unsigned int keys = CScript::DecodeOP_N(opcode); if (pubkeys.size() != keys || keys < required) return false; return (it + 1 == script.end()); } /** * Return public keys or hashes from scriptPubKey, for 'standard' transaction types. */ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet) { if (scriptPubKey.empty()) return false; vSolutionsRet.clear(); // Shortcut for pay-to-script-hash, which are more constrained than the other types: // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL if (scriptPubKey.IsPayToScriptHash()) { typeRet = TX_SCRIPTHASH; std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22); vSolutionsRet.push_back(hashBytes); return true; } // Zerocoin if (scriptPubKey.IsZerocoinMint()) { typeRet = TX_ZEROCOINMINT; if(scriptPubKey.size() > 150) return false; std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.end()); vSolutionsRet.push_back(hashBytes); return true; } // Provably prunable, data-carrying output // // So long as script passes the IsUnspendable() test and all but the first // byte passes the IsPushOnly() test we don't care what exactly is in the // script. if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) { typeRet = TX_NULL_DATA; return true; } std::vector<unsigned char> data; if (MatchPayToPubkey(scriptPubKey, data)) { typeRet = TX_PUBKEY; vSolutionsRet.push_back(std::move(data)); return true; } if (MatchPayToPubkeyHash(scriptPubKey, data)) { typeRet = TX_PUBKEYHASH; vSolutionsRet.push_back(std::move(data)); return true; } std::vector<unsigned char> data1; if (MatchPayToColdStaking(scriptPubKey, data, data1)) { typeRet = TX_COLDSTAKE; vSolutionsRet.push_back(std::move(data)); vSolutionsRet.push_back(std::move(data1)); return true; } unsigned int required; std::vector<std::vector<unsigned char>> keys; if (MatchMultisig(scriptPubKey, required, keys)) { typeRet = TX_MULTISIG; vSolutionsRet.push_back({static_cast<unsigned char>(required)}); // safe as required is in range 1..16 vSolutionsRet.insert(vSolutionsRet.end(), keys.begin(), keys.end()); vSolutionsRet.push_back({static_cast<unsigned char>(keys.size())}); // safe as size is in range 1..16 return true; } vSolutionsRet.clear(); typeRet = TX_NONSTANDARD; return false; } int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions) { switch (t) { case TX_NONSTANDARD: case TX_NULL_DATA: case TX_ZEROCOINMINT: return -1; case TX_PUBKEY: return 1; case TX_PUBKEYHASH: return 2; case TX_COLDSTAKE: return 3; case TX_MULTISIG: if (vSolutions.size() < 1 || vSolutions[0].size() < 1) return -1; return vSolutions[0][0] + 1; case TX_SCRIPTHASH: return 1; // doesn't include args needed by the script } return -1; } bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet, bool fColdStake) { std::vector<valtype> vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { CPubKey pubKey(vSolutions[0]); if (!pubKey.IsValid()) return false; addressRet = pubKey.GetID(); return true; } else if (whichType == TX_PUBKEYHASH) { addressRet = CKeyID(uint160(vSolutions[0])); return true; } else if (whichType == TX_SCRIPTHASH) { addressRet = CScriptID(uint160(vSolutions[0])); return true; } else if (whichType == TX_COLDSTAKE) { addressRet = CKeyID(uint160(vSolutions[!fColdStake])); return true; } // Multisig txns have more than one address... return false; } bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet) { addressRet.clear(); typeRet = TX_NONSTANDARD; std::vector<valtype> vSolutions; if (!Solver(scriptPubKey, typeRet, vSolutions)) return false; if (typeRet == TX_NULL_DATA){ // This is data, not addresses return false; } if (typeRet == TX_MULTISIG) { nRequiredRet = vSolutions.front()[0]; for (unsigned int i = 1; i < vSolutions.size()-1; i++) { CPubKey pubKey(vSolutions[i]); if (!pubKey.IsValid()) continue; CTxDestination address = pubKey.GetID(); addressRet.push_back(address); } if (addressRet.empty()) return false; } else if (typeRet == TX_COLDSTAKE) { if (vSolutions.size() < 2) return false; nRequiredRet = 2; addressRet.push_back(CKeyID(uint160(vSolutions[0]))); addressRet.push_back(CKeyID(uint160(vSolutions[1]))); return true; } else { nRequiredRet = 1; CTxDestination address; if (!ExtractDestination(scriptPubKey, address)) return false; addressRet.push_back(address); } return true; } namespace { class CScriptVisitor : public boost::static_visitor<bool> { private: CScript *script; public: CScriptVisitor(CScript *scriptin) { script = scriptin; } bool operator()(const CNoDestination &dest) const { script->clear(); return false; } bool operator()(const CKeyID &keyID) const { script->clear(); *script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; return true; } bool operator()(const CScriptID &scriptID) const { script->clear(); *script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL; return true; } }; } CScript GetScriptForDestination(const CTxDestination& dest) { CScript script; boost::apply_visitor(CScriptVisitor(&script), dest); return script; } CScript GetScriptForRawPubKey(const CPubKey& pubKey) { return CScript() << std::vector<unsigned char>(pubKey.begin(), pubKey.end()) << OP_CHECKSIG; } CScript GetScriptForStakeDelegation(const CKeyID& stakingKey, const CKeyID& spendingKey) { CScript script; script << OP_DUP << OP_HASH160 << OP_ROT << OP_IF << OP_CHECKCOLDSTAKEVERIFY << ToByteVector(stakingKey) << OP_ELSE << ToByteVector(spendingKey) << OP_ENDIF << OP_EQUALVERIFY << OP_CHECKSIG; return script; } CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys) { CScript script; script << CScript::EncodeOP_N(nRequired); for (const CPubKey& key : keys) script << ToByteVector(key); script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG; return script; } bool IsValidDestination(const CTxDestination& dest) { return dest.which() != 0; } <|endoftext|>
<commit_before>#include "includes.h" #ifndef _WIN32 #include <sys/types.h> #include <dirent.h> #endif void prepare_logdir() { spdlog::drop_all(); #ifdef _WIN32 system("if not exist logs mkdir logs"); system("del /F /Q logs\\*"); #else auto rv = system("mkdir -p logs"); if (rv != 0) { throw std::runtime_error("Failed to mkdir -p logs"); } rv = system("rm -f logs/*"); if (rv != 0) { throw std::runtime_error("Failed to rm -f logs/*"); } #endif } std::string file_contents(const std::string &filename) { std::ifstream ifs(filename); if (!ifs) { throw std::runtime_error("Failed open file "); } return std::string((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); } std::size_t count_lines(const std::string &filename) { std::ifstream ifs(filename); if (!ifs) { throw std::runtime_error("Failed open file "); } std::string line; size_t counter = 0; while (std::getline(ifs, line)) counter++; return counter; } std::size_t get_filesize(const std::string &filename) { std::ifstream ifs(filename, std::ifstream::ate | std::ifstream::binary); if (!ifs) { throw std::runtime_error("Failed open file "); } return static_cast<std::size_t>(ifs.tellg()); } // source: https://stackoverflow.com/a/2072890/192001 bool ends_with(std::string const &value, std::string const &ending) { if (ending.size() > value.size()) { return false; } return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); } #ifdef _WIN32 // Based on: https://stackoverflow.com/a/37416569/192001 std::size_t count_files(const std::string &folder) { size_t counter = 0; WIN32_FIND_DATA ffd; // Start iterating over the files in the path directory. HANDLE hFind = ::FindFirstFileA((folder + "\\*").c_str(), &ffd); if (hFind != INVALID_HANDLE_VALUE) { do // Managed to locate and create an handle to that folder. { if (ffd.cFileName[0] != '.') counter++; } while (::FindNextFile(hFind, &ffd) != 0); ::FindClose(hFind); } else { throw std::runtime_error("Failed open folder " + folder); } return counter; } #else // Based on: https://stackoverflow.com/a/2802255/192001 std::size_t count_files(const std::string &folder) { size_t counter = 0; DIR *dp = opendir(folder.c_str()); if (dp == nullptr) { throw std::runtime_error("Failed open folder " + folder); } struct dirent *ep; while (ep = readdir(dp)) { if (ep->d_name[0] != '.') counter++; } (void)closedir(dp); return counter; } #endif <commit_msg>Update utils.cpp<commit_after>#include "includes.h" #ifndef _WIN32 #include <sys/types.h> #include <dirent.h> #endif void prepare_logdir() { spdlog::drop_all(); #ifdef _WIN32 system("if not exist logs mkdir logs"); system("del /F /Q logs\\*"); #else auto rv = system("mkdir -p logs"); if (rv != 0) { throw std::runtime_error("Failed to mkdir -p logs"); } rv = system("rm -f logs/*"); if (rv != 0) { throw std::runtime_error("Failed to rm -f logs/*"); } #endif } std::string file_contents(const std::string &filename) { std::ifstream ifs(filename); if (!ifs) { throw std::runtime_error("Failed open file "); } return std::string((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); } std::size_t count_lines(const std::string &filename) { std::ifstream ifs(filename); if (!ifs) { throw std::runtime_error("Failed open file "); } std::string line; size_t counter = 0; while (std::getline(ifs, line)) counter++; return counter; } std::size_t get_filesize(const std::string &filename) { std::ifstream ifs(filename, std::ifstream::ate | std::ifstream::binary); if (!ifs) { throw std::runtime_error("Failed open file "); } return static_cast<std::size_t>(ifs.tellg()); } // source: https://stackoverflow.com/a/2072890/192001 bool ends_with(std::string const &value, std::string const &ending) { if (ending.size() > value.size()) { return false; } return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); } #ifdef _WIN32 // Based on: https://stackoverflow.com/a/37416569/192001 std::size_t count_files(const std::string &folder) { size_t counter = 0; WIN32_FIND_DATA ffd; // Start iterating over the files in the folder directory. HANDLE hFind = ::FindFirstFileA((folder + "\\*").c_str(), &ffd); if (hFind != INVALID_HANDLE_VALUE) { do // Managed to locate and create an handle to that folder. { if (ffd.cFileName[0] != '.') counter++; } while (::FindNextFile(hFind, &ffd) != 0); ::FindClose(hFind); } else { throw std::runtime_error("Failed open folder " + folder); } return counter; } #else // Based on: https://stackoverflow.com/a/2802255/192001 std::size_t count_files(const std::string &folder) { size_t counter = 0; DIR *dp = opendir(folder.c_str()); if (dp == nullptr) { throw std::runtime_error("Failed open folder " + folder); } struct dirent *ep; while (ep = readdir(dp)) { if (ep->d_name[0] != '.') counter++; } (void)closedir(dp); return counter; } #endif <|endoftext|>
<commit_before>#include "apf.h" #include "apfMDS.h" #include "apfMesh2.h" #include "pcu_io.h" #include "pcu_byteorder.h" #include <cstdio> #include <cstring> #include <cassert> #include <cstdlib> /* read files in the AFLR3 format from Dave Marcum at Mississippi State -little-endian if file has suffix '.lb8.ugrid' -big-endian if file has suffix '.b8.ugrid' -integers are 4B -floats are 8B */ namespace { int faceTypeIdx(int type) { switch(type) { case apf::Mesh::TRIANGLE: return 0; case apf::Mesh::QUAD: return 1; default: { assert(false); return -1; } } } struct Reader { apf::Mesh2* mesh; FILE* file; std::map<long, apf::MeshEntity*> nodeMap; unsigned* faceVerts[2]; unsigned* faceTags[2]; bool swapBytes; }; struct header { unsigned nvtx, ntri, nquad, ntet, npyr, nprz, nhex; void print() { fprintf(stderr, "nvtx %u ntri %u nquad %u ntet %u npyr %u nprz %u nhex %u\n", nvtx,ntri,nquad,ntet,npyr,nprz,nhex); } }; void initReader(Reader* r, apf::Mesh2* m, const char* filename) { r->mesh = m; r->file = fopen(filename, "rb"); if (!r->file) { fprintf(stderr,"ERROR couldn't open ugrid file \"%s\"\n",filename); abort(); } unsigned endian = -1; if ( strstr(filename, ".b8.ugrid") ) { endian = PCU_BIG_ENDIAN; } else if ( strstr(filename, ".lb8.ugrid") ) { endian = PCU_LITTLE_ENDIAN; } else { fprintf(stderr, "ERROR file extension of \"%s\" is not supported\n", filename); exit(EXIT_FAILURE); } r->swapBytes = ( endian != PCU_HOST_ORDER ); } void readUnsigneds(FILE* f, unsigned* v, size_t cnt, bool swap) { assert(sizeof(unsigned)==4); size_t read = fread(v, sizeof(unsigned), cnt, f); assert(read == cnt); if ( swap ) pcu_swap_unsigneds(v,cnt); } void readDoubles(FILE* f, double* vals, size_t cnt, bool swap) { assert(sizeof(double)==8); size_t read = fread(vals, sizeof(double), cnt, f); assert(read == cnt); if ( swap ) pcu_swap_doubles(vals,cnt); } void readHeader(Reader* r, header* h) { const unsigned biggest = 100*1000*1000; unsigned headerVals[7]; readUnsigneds(r->file, headerVals, 7, r->swapBytes); for(unsigned i=0; i<7; i++) { assert(headerVals[i] < biggest); } h->nvtx = headerVals[0]; h->ntri = headerVals[1]; h->nquad = headerVals[2]; h->ntet = headerVals[3]; h->npyr = headerVals[4]; h->nprz = headerVals[5]; h->nhex = headerVals[6]; } apf::MeshEntity* makeVtx(Reader* r, apf::Vector3& pt, apf::ModelEntity* g) { apf::MeshEntity* v = r->mesh->createVert(g); r->mesh->setPoint(v, 0, pt); return v; } apf::MeshEntity* lookupVert(Reader* r, long ftnNodeId) { const long cNodeId = ftnNodeId - 1; assert(r->nodeMap.count(cNodeId)); return r->nodeMap[cNodeId]; } void readNodes(Reader* r, header* h) { const unsigned dim = 3; size_t cnt = h->nvtx*dim; double* xyz = (double*) calloc(cnt,sizeof(double)); readDoubles(r->file, xyz, cnt, r->swapBytes); for(long id=0; id<h->nvtx; id++) { apf::Vector3 p; for(unsigned j=0; j<dim; j++) p[j] = xyz[id*dim+j]; r->nodeMap[id] = makeVtx(r,p,0); } free(xyz); fprintf(stderr, "read %d vtx\n", h->nvtx); } void setNodeIds(Reader* r, header* h) { apf::Mesh* m = r->mesh; apf::MeshTag* t = m->createLongTag("ugrid-vtx-ids",1); for(long id=0; id<h->nvtx; id++) m->setLongTag(r->nodeMap[id],t,&id); m->destroyTag(t); } void readFaces(Reader* r, unsigned nfaces, int apfType) { const unsigned nverts = apf::Mesh::adjacentCount[apfType][0]; size_t cnt = nfaces * nverts; unsigned* vtx = (unsigned*) calloc(cnt,sizeof(unsigned)); r->faceVerts[faceTypeIdx(apfType)] = vtx; readUnsigneds(r->file, vtx, cnt, r->swapBytes); } void readTags(Reader* r, unsigned nfaces, int apfType) { unsigned* tags = (unsigned*) calloc(nfaces,sizeof(unsigned)); r->faceTags[faceTypeIdx(apfType)] = tags; readUnsigneds(r->file, tags, nfaces, r->swapBytes); } void readFacesAndTags(Reader* r, header* h) { //read the face vertices and store them readFaces(r,h->ntri,apf::Mesh::TRIANGLE); readFaces(r,h->nquad,apf::Mesh::QUAD); //read the tags and store them readTags(r,h->ntri,apf::Mesh::TRIANGLE); readTags(r,h->nquad,apf::Mesh::QUAD); } void checkFilePos(Reader* r, header* h) { // seven headers, vtx coords, face vertex ids, and face tags long expected = h->nvtx*3*sizeof(double) + sizeof(unsigned)*(7 + h->ntri*3 + h->nquad*4 + (h->ntri+h->nquad)); long pos = ftell(r->file); assert( pos == expected ); } void setFaceTags(Reader* r, apf::MeshTag* t, unsigned nfaces, int apfType) { const unsigned nverts = apf::Mesh::adjacentCount[apfType][0]; unsigned* vtx = r->faceVerts[faceTypeIdx(apfType)]; unsigned* tags = r->faceTags[faceTypeIdx(apfType)]; for(unsigned id=0; id<nfaces; id++) { apf::Downward verts; for(unsigned j=0; j<nverts; j++) { verts[j] = lookupVert(r, vtx[id*nverts+j]); } apf::MeshEntity* f = apf::findElement(r->mesh, apfType, verts); assert(f); int val = tags[id]; r->mesh->setIntTag(f, t, &val); } free(vtx); free(tags); fprintf(stderr, "set %d %s face tags\n", nfaces, apf::Mesh::typeName[apfType]); } void setFaceTags(Reader* r, header* h) { apf::MeshTag* t = r->mesh->createIntTag("ugrid-face-tag", 1); setFaceTags(r,t,h->ntri,apf::Mesh::TRIANGLE); setFaceTags(r,t,h->nquad,apf::Mesh::QUAD); } inline unsigned ugridToMdsElmIdx(int apfType, int ugridIdx) { static int ugrid_to_mds_verts[4][8] = { {0, 1, 2, 3, -1, -1, -1, -1}, //tet {0, 1, 2, 3, 4, 5, 6, 7}, //hex {0, 1, 2, 3, 4, 5, -1, -1}, //prism {3, 2, 4, 0, 1, -1, -1, -1} //pyramid }; assert(apfType >= 4); return ugrid_to_mds_verts[apfType-4][ugridIdx]; } void readElms(Reader* r, unsigned nelms, int apfType) { const unsigned nverts = apf::Mesh::adjacentCount[apfType][0]; apf::ModelEntity* g = r->mesh->findModelEntity(3, 0); size_t cnt = nelms*nverts; unsigned* vtx = (unsigned*) calloc(cnt,sizeof(unsigned)); readUnsigneds(r->file, vtx, cnt, r->swapBytes); for(unsigned i=0; i<nelms; i++) { apf::Downward verts; for(unsigned j=0; j<nverts; j++) { const unsigned mdsIdx = ugridToMdsElmIdx(apfType,j); verts[mdsIdx] = lookupVert(r, vtx[i*nverts+j]); } apf::MeshEntity* elm = apf::buildElement(r->mesh, g, apfType, verts); assert(elm); } free(vtx); fprintf(stderr, "read %d %s\n", nelms, apf::Mesh::typeName[apfType]); } void readElms(Reader* r, header* h) { readElms(r,h->ntet,apf::Mesh::TET); readElms(r,h->npyr,apf::Mesh::PYRAMID); readElms(r,h->nprz,apf::Mesh::PRISM); readElms(r,h->nhex,apf::Mesh::HEX); } void freeReader(Reader* r) { fclose(r->file); } void readUgrid(apf::Mesh2* m, const char* filename) { header hdr; Reader r; initReader(&r, m, filename); readHeader(&r, &hdr); hdr.print(); readNodes(&r, &hdr); setNodeIds(&r, &hdr); readFacesAndTags(&r,&hdr); checkFilePos(&r,&hdr); readElms(&r,&hdr); setFaceTags(&r,&hdr); freeReader(&r); m->acceptChanges(); } } namespace apf { Mesh2* loadMdsFromUgrid(gmi_model* g, const char* filename) { Mesh2* m = makeEmptyMdsMesh(g, 0, false); apf::changeMdsDimension(m, 3); readUgrid(m, filename); fprintf(stderr,"vtx %lu edge %lu face %lu rgn %lu\n", m->count(0), m->count(1), m->count(2), m->count(3)); return m; } } <commit_msg>long tags are not written, don't destroy the tag<commit_after>#include "apf.h" #include "apfMDS.h" #include "apfMesh2.h" #include "pcu_io.h" #include "pcu_byteorder.h" #include <cstdio> #include <cstring> #include <cassert> #include <cstdlib> /* read files in the AFLR3 format from Dave Marcum at Mississippi State -little-endian if file has suffix '.lb8.ugrid' -big-endian if file has suffix '.b8.ugrid' -integers are 4B -floats are 8B */ namespace { int faceTypeIdx(int type) { switch(type) { case apf::Mesh::TRIANGLE: return 0; case apf::Mesh::QUAD: return 1; default: { assert(false); return -1; } } } struct Reader { apf::Mesh2* mesh; FILE* file; std::map<long, apf::MeshEntity*> nodeMap; unsigned* faceVerts[2]; unsigned* faceTags[2]; bool swapBytes; }; struct header { unsigned nvtx, ntri, nquad, ntet, npyr, nprz, nhex; void print() { fprintf(stderr, "nvtx %u ntri %u nquad %u ntet %u npyr %u nprz %u nhex %u\n", nvtx,ntri,nquad,ntet,npyr,nprz,nhex); } }; void initReader(Reader* r, apf::Mesh2* m, const char* filename) { r->mesh = m; r->file = fopen(filename, "rb"); if (!r->file) { fprintf(stderr,"ERROR couldn't open ugrid file \"%s\"\n",filename); abort(); } unsigned endian = -1; if ( strstr(filename, ".b8.ugrid") ) { endian = PCU_BIG_ENDIAN; } else if ( strstr(filename, ".lb8.ugrid") ) { endian = PCU_LITTLE_ENDIAN; } else { fprintf(stderr, "ERROR file extension of \"%s\" is not supported\n", filename); exit(EXIT_FAILURE); } r->swapBytes = ( endian != PCU_HOST_ORDER ); } void readUnsigneds(FILE* f, unsigned* v, size_t cnt, bool swap) { assert(sizeof(unsigned)==4); size_t read = fread(v, sizeof(unsigned), cnt, f); assert(read == cnt); if ( swap ) pcu_swap_unsigneds(v,cnt); } void readDoubles(FILE* f, double* vals, size_t cnt, bool swap) { assert(sizeof(double)==8); size_t read = fread(vals, sizeof(double), cnt, f); assert(read == cnt); if ( swap ) pcu_swap_doubles(vals,cnt); } void readHeader(Reader* r, header* h) { const unsigned biggest = 100*1000*1000; unsigned headerVals[7]; readUnsigneds(r->file, headerVals, 7, r->swapBytes); for(unsigned i=0; i<7; i++) { assert(headerVals[i] < biggest); } h->nvtx = headerVals[0]; h->ntri = headerVals[1]; h->nquad = headerVals[2]; h->ntet = headerVals[3]; h->npyr = headerVals[4]; h->nprz = headerVals[5]; h->nhex = headerVals[6]; } apf::MeshEntity* makeVtx(Reader* r, apf::Vector3& pt, apf::ModelEntity* g) { apf::MeshEntity* v = r->mesh->createVert(g); r->mesh->setPoint(v, 0, pt); return v; } apf::MeshEntity* lookupVert(Reader* r, long ftnNodeId) { const long cNodeId = ftnNodeId - 1; assert(r->nodeMap.count(cNodeId)); return r->nodeMap[cNodeId]; } void readNodes(Reader* r, header* h) { const unsigned dim = 3; size_t cnt = h->nvtx*dim; double* xyz = (double*) calloc(cnt,sizeof(double)); readDoubles(r->file, xyz, cnt, r->swapBytes); for(long id=0; id<h->nvtx; id++) { apf::Vector3 p; for(unsigned j=0; j<dim; j++) p[j] = xyz[id*dim+j]; r->nodeMap[id] = makeVtx(r,p,0); } free(xyz); fprintf(stderr, "read %d vtx\n", h->nvtx); } void setNodeIds(Reader* r, header* h) { apf::Mesh* m = r->mesh; apf::MeshTag* t = m->createIntTag("ugrid-vtx-ids",1); for(long lid=0; lid<h->nvtx; lid++) { int iid = lid; m->setIntTag(r->nodeMap[lid],t,&iid); } } void readFaces(Reader* r, unsigned nfaces, int apfType) { const unsigned nverts = apf::Mesh::adjacentCount[apfType][0]; size_t cnt = nfaces * nverts; unsigned* vtx = (unsigned*) calloc(cnt,sizeof(unsigned)); r->faceVerts[faceTypeIdx(apfType)] = vtx; readUnsigneds(r->file, vtx, cnt, r->swapBytes); } void readTags(Reader* r, unsigned nfaces, int apfType) { unsigned* tags = (unsigned*) calloc(nfaces,sizeof(unsigned)); r->faceTags[faceTypeIdx(apfType)] = tags; readUnsigneds(r->file, tags, nfaces, r->swapBytes); } void readFacesAndTags(Reader* r, header* h) { //read the face vertices and store them readFaces(r,h->ntri,apf::Mesh::TRIANGLE); readFaces(r,h->nquad,apf::Mesh::QUAD); //read the tags and store them readTags(r,h->ntri,apf::Mesh::TRIANGLE); readTags(r,h->nquad,apf::Mesh::QUAD); } void checkFilePos(Reader* r, header* h) { // seven headers, vtx coords, face vertex ids, and face tags long expected = h->nvtx*3*sizeof(double) + sizeof(unsigned)*(7 + h->ntri*3 + h->nquad*4 + (h->ntri+h->nquad)); long pos = ftell(r->file); assert( pos == expected ); } void setFaceTags(Reader* r, apf::MeshTag* t, unsigned nfaces, int apfType) { const unsigned nverts = apf::Mesh::adjacentCount[apfType][0]; unsigned* vtx = r->faceVerts[faceTypeIdx(apfType)]; unsigned* tags = r->faceTags[faceTypeIdx(apfType)]; for(unsigned id=0; id<nfaces; id++) { apf::Downward verts; for(unsigned j=0; j<nverts; j++) { verts[j] = lookupVert(r, vtx[id*nverts+j]); } apf::MeshEntity* f = apf::findElement(r->mesh, apfType, verts); assert(f); int val = tags[id]; r->mesh->setIntTag(f, t, &val); } free(vtx); free(tags); fprintf(stderr, "set %d %s face tags\n", nfaces, apf::Mesh::typeName[apfType]); } void setFaceTags(Reader* r, header* h) { apf::MeshTag* t = r->mesh->createIntTag("ugrid-face-tag", 1); setFaceTags(r,t,h->ntri,apf::Mesh::TRIANGLE); setFaceTags(r,t,h->nquad,apf::Mesh::QUAD); } inline unsigned ugridToMdsElmIdx(int apfType, int ugridIdx) { static int ugrid_to_mds_verts[4][8] = { {0, 1, 2, 3, -1, -1, -1, -1}, //tet {0, 1, 2, 3, 4, 5, 6, 7}, //hex {0, 1, 2, 3, 4, 5, -1, -1}, //prism {3, 2, 4, 0, 1, -1, -1, -1} //pyramid }; assert(apfType >= 4); return ugrid_to_mds_verts[apfType-4][ugridIdx]; } void readElms(Reader* r, unsigned nelms, int apfType) { const unsigned nverts = apf::Mesh::adjacentCount[apfType][0]; apf::ModelEntity* g = r->mesh->findModelEntity(3, 0); size_t cnt = nelms*nverts; unsigned* vtx = (unsigned*) calloc(cnt,sizeof(unsigned)); readUnsigneds(r->file, vtx, cnt, r->swapBytes); for(unsigned i=0; i<nelms; i++) { apf::Downward verts; for(unsigned j=0; j<nverts; j++) { const unsigned mdsIdx = ugridToMdsElmIdx(apfType,j); verts[mdsIdx] = lookupVert(r, vtx[i*nverts+j]); } apf::MeshEntity* elm = apf::buildElement(r->mesh, g, apfType, verts); assert(elm); } free(vtx); fprintf(stderr, "read %d %s\n", nelms, apf::Mesh::typeName[apfType]); } void readElms(Reader* r, header* h) { readElms(r,h->ntet,apf::Mesh::TET); readElms(r,h->npyr,apf::Mesh::PYRAMID); readElms(r,h->nprz,apf::Mesh::PRISM); readElms(r,h->nhex,apf::Mesh::HEX); } void freeReader(Reader* r) { fclose(r->file); } void readUgrid(apf::Mesh2* m, const char* filename) { header hdr; Reader r; initReader(&r, m, filename); readHeader(&r, &hdr); hdr.print(); readNodes(&r, &hdr); setNodeIds(&r, &hdr); readFacesAndTags(&r,&hdr); checkFilePos(&r,&hdr); readElms(&r,&hdr); setFaceTags(&r,&hdr); freeReader(&r); m->acceptChanges(); } } namespace apf { Mesh2* loadMdsFromUgrid(gmi_model* g, const char* filename) { Mesh2* m = makeEmptyMdsMesh(g, 0, false); apf::changeMdsDimension(m, 3); readUgrid(m, filename); fprintf(stderr,"vtx %lu edge %lu face %lu rgn %lu\n", m->count(0), m->count(1), m->count(2), m->count(3)); return m; } } <|endoftext|>
<commit_before>/* Copyright 2015 Realm Inc - All Rights Reserved * Proprietary and Confidential */ #include <realm.hpp> #include <realm/lang_bind_helper.hpp> #include "error_handling.hpp" #include "realm_export_decls.hpp" #include "marshalling.hpp" #include "object-store/src/shared_realm.hpp" #include "object-store/src/schema.hpp" #include "object-store/src/binding_context.hpp" #include <list> #ifdef REALM_PLATFORM_ANDROID #include "object-store/src/impl/android/weak_realm_notifier.hpp" #endif using namespace realm; using namespace realm::binding; using NotifyRealmChangedT = void(*)(void* managed_realm_handle); NotifyRealmChangedT notify_realm_changed = nullptr; namespace realm { namespace binding { class CSharpBindingContext: public BindingContext { public: CSharpBindingContext(void* managed_realm_handle) : m_managed_realm_handle(managed_realm_handle) {} void did_change(std::vector<ObserverState> const&, std::vector<void*> const&) override { notify_realm_changed(m_managed_realm_handle); } private: void* m_managed_realm_handle; }; } } extern "C" { REALM_EXPORT void register_notify_realm_changed(NotifyRealmChangedT notifier) { notify_realm_changed = notifier; } REALM_EXPORT SharedRealm* shared_realm_open(Schema* schema, uint16_t* path, size_t path_len, bool read_only, SharedGroup::DurabilityLevel durability, uint8_t* encryption_key, uint64_t schemaVersion) { return handle_errors([&]() { Utf16StringAccessor pathStr(path, path_len); Realm::Config config; config.path = pathStr.to_string(); config.read_only = read_only; config.in_memory = durability != SharedGroup::durability_Full; // by definition the key is only allowwed to be 64 bytes long, enforced by C# code if (encryption_key == nullptr) config.encryption_key = std::vector<char>(); else config.encryption_key = std::vector<char>(encryption_key, encryption_key+64); config.schema.reset(schema); config.schema_version = schemaVersion; return new SharedRealm{Realm::get_shared_realm(config)}; }); } REALM_EXPORT void shared_realm_bind_to_managed_realm_handle(SharedRealm* realm, void* managed_realm_handle) { handle_errors([&]() { (*realm)->m_binding_context = std::unique_ptr<realm::BindingContext>(new CSharpBindingContext(managed_realm_handle)); }); } REALM_EXPORT void shared_realm_destroy(SharedRealm* realm) { handle_errors([&]() { (*realm)->close(); delete realm; }); } REALM_EXPORT size_t shared_realm_has_table(SharedRealm* realm, uint16_t* table_name, size_t table_name_len) { return handle_errors([&]() { Group* g = (*realm)->read_group(); Utf16StringAccessor str(table_name, table_name_len); return bool_to_size_t(g->has_table(str)); }); } REALM_EXPORT Table* shared_realm_get_table(SharedRealm* realm, uint16_t* table_name, size_t table_name_len) { return handle_errors([&]() { Group* g = (*realm)->read_group(); Utf16StringAccessor str(table_name, table_name_len); bool dummy; // get_or_add_table sets this to true if the table was added. return LangBindHelper::get_or_add_table(*g, str, &dummy); }); } REALM_EXPORT uint64_t shared_realm_get_schema_version(SharedRealm* realm) { return handle_errors([&]() { return (*realm)->config().schema_version; }); } REALM_EXPORT void shared_realm_begin_transaction(SharedRealm* realm) { handle_errors([&]() { (*realm)->begin_transaction(); }); } REALM_EXPORT void shared_realm_commit_transaction(SharedRealm* realm) { handle_errors([&]() { (*realm)->commit_transaction(); }); } REALM_EXPORT void shared_realm_cancel_transaction(SharedRealm* realm) { handle_errors([&]() { (*realm)->cancel_transaction(); }); } REALM_EXPORT size_t shared_realm_is_in_transaction(SharedRealm* realm) { return handle_errors([&]() { return bool_to_size_t((*realm)->is_in_transaction()); }); } REALM_EXPORT size_t shared_realm_is_same_instance(SharedRealm* lhs, SharedRealm* rhs) { return handle_errors([&]() { return *lhs == *rhs; // just compare raw pointers inside the smart pointers }); } REALM_EXPORT size_t shared_realm_refresh(SharedRealm* realm) { return handle_errors([&]() { return bool_to_size_t((*realm)->refresh()); }); } #ifdef REALM_PLATFORM_ANDROID REALM_EXPORT void bind_handler_functions(realm::_impl::create_handler_function create_function, realm::_impl::notify_handler_function notify_function, realm::_impl::destroy_handler_function destroy_function) { handle_errors([&]() { realm::_impl::create_handler_for_current_thread = create_function; realm::_impl::notify_handler = notify_function; realm::_impl::destroy_handler = destroy_function; }); } REALM_EXPORT void notify_realm(Realm* realm) { handle_errors([&]() { realm->notify(); }); } #endif } <commit_msg>Make notify_realm accept a pointer to a weak_ptr<commit_after>/* Copyright 2015 Realm Inc - All Rights Reserved * Proprietary and Confidential */ #include <realm.hpp> #include <realm/lang_bind_helper.hpp> #include "error_handling.hpp" #include "realm_export_decls.hpp" #include "marshalling.hpp" #include "object-store/src/shared_realm.hpp" #include "object-store/src/schema.hpp" #include "object-store/src/binding_context.hpp" #include <list> #ifdef REALM_PLATFORM_ANDROID #include "object-store/src/impl/android/weak_realm_notifier.hpp" #endif using namespace realm; using namespace realm::binding; using NotifyRealmChangedT = void(*)(void* managed_realm_handle); NotifyRealmChangedT notify_realm_changed = nullptr; namespace realm { namespace binding { class CSharpBindingContext: public BindingContext { public: CSharpBindingContext(void* managed_realm_handle) : m_managed_realm_handle(managed_realm_handle) {} void did_change(std::vector<ObserverState> const&, std::vector<void*> const&) override { notify_realm_changed(m_managed_realm_handle); } private: void* m_managed_realm_handle; }; } } extern "C" { REALM_EXPORT void register_notify_realm_changed(NotifyRealmChangedT notifier) { notify_realm_changed = notifier; } REALM_EXPORT SharedRealm* shared_realm_open(Schema* schema, uint16_t* path, size_t path_len, bool read_only, SharedGroup::DurabilityLevel durability, uint8_t* encryption_key, uint64_t schemaVersion) { return handle_errors([&]() { Utf16StringAccessor pathStr(path, path_len); Realm::Config config; config.path = pathStr.to_string(); config.read_only = read_only; config.in_memory = durability != SharedGroup::durability_Full; // by definition the key is only allowwed to be 64 bytes long, enforced by C# code if (encryption_key == nullptr) config.encryption_key = std::vector<char>(); else config.encryption_key = std::vector<char>(encryption_key, encryption_key+64); config.schema.reset(schema); config.schema_version = schemaVersion; return new SharedRealm{Realm::get_shared_realm(config)}; }); } REALM_EXPORT void shared_realm_bind_to_managed_realm_handle(SharedRealm* realm, void* managed_realm_handle) { handle_errors([&]() { (*realm)->m_binding_context = std::unique_ptr<realm::BindingContext>(new CSharpBindingContext(managed_realm_handle)); }); } REALM_EXPORT void shared_realm_destroy(SharedRealm* realm) { handle_errors([&]() { (*realm)->close(); delete realm; }); } REALM_EXPORT size_t shared_realm_has_table(SharedRealm* realm, uint16_t* table_name, size_t table_name_len) { return handle_errors([&]() { Group* g = (*realm)->read_group(); Utf16StringAccessor str(table_name, table_name_len); return bool_to_size_t(g->has_table(str)); }); } REALM_EXPORT Table* shared_realm_get_table(SharedRealm* realm, uint16_t* table_name, size_t table_name_len) { return handle_errors([&]() { Group* g = (*realm)->read_group(); Utf16StringAccessor str(table_name, table_name_len); bool dummy; // get_or_add_table sets this to true if the table was added. return LangBindHelper::get_or_add_table(*g, str, &dummy); }); } REALM_EXPORT uint64_t shared_realm_get_schema_version(SharedRealm* realm) { return handle_errors([&]() { return (*realm)->config().schema_version; }); } REALM_EXPORT void shared_realm_begin_transaction(SharedRealm* realm) { handle_errors([&]() { (*realm)->begin_transaction(); }); } REALM_EXPORT void shared_realm_commit_transaction(SharedRealm* realm) { handle_errors([&]() { (*realm)->commit_transaction(); }); } REALM_EXPORT void shared_realm_cancel_transaction(SharedRealm* realm) { handle_errors([&]() { (*realm)->cancel_transaction(); }); } REALM_EXPORT size_t shared_realm_is_in_transaction(SharedRealm* realm) { return handle_errors([&]() { return bool_to_size_t((*realm)->is_in_transaction()); }); } REALM_EXPORT size_t shared_realm_is_same_instance(SharedRealm* lhs, SharedRealm* rhs) { return handle_errors([&]() { return *lhs == *rhs; // just compare raw pointers inside the smart pointers }); } REALM_EXPORT size_t shared_realm_refresh(SharedRealm* realm) { return handle_errors([&]() { return bool_to_size_t((*realm)->refresh()); }); } #ifdef REALM_PLATFORM_ANDROID REALM_EXPORT void bind_handler_functions(realm::_impl::create_handler_function create_function, realm::_impl::notify_handler_function notify_function, realm::_impl::destroy_handler_function destroy_function) { handle_errors([&]() { realm::_impl::create_handler_for_current_thread = create_function; realm::_impl::notify_handler = notify_function; realm::_impl::destroy_handler = destroy_function; }); } REALM_EXPORT void notify_realm(std::weak_ptr<Realm>* realm) { handle_errors([&]() { if (auto realm_ptr = realm->lock()) { if (!realm_ptr->is_closed()) realm_ptr->notify(); } delete realm; }); } #endif } <|endoftext|>
<commit_before>/* * Copyright 2016 WebAssembly Community Group participants * * 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. */ // // Optimize combinations of instructions // #include <algorithm> #include <wasm.h> #include <pass.h> #include <wasm-s-parser.h> #include <support/threads.h> #include <ast_utils.h> namespace wasm { Name I32_EXPR = "i32.expr", I64_EXPR = "i64.expr", F32_EXPR = "f32.expr", F64_EXPR = "f64.expr", ANY_EXPR = "any.expr"; // A pattern struct Pattern { Expression* input; Expression* output; Pattern(Expression* input, Expression* output) : input(input), output(output) {} }; // Database of patterns struct PatternDatabase { Module wasm; char* input; std::map<Expression::Id, std::vector<Pattern>> patternMap; // root expression id => list of all patterns for it TODO optimize more PatternDatabase() { // TODO: do this on first use, with a lock, to avoid startup pause // generate module input = strdup( #include "OptimizeInstructions.wast.processed" ); SExpressionParser parser(input); Element& root = *parser.root; SExpressionWasmBuilder builder(wasm, *root[0]); // parse module form auto* func = wasm.getFunction("patterns"); auto* body = func->body->cast<Block>(); for (auto* item : body->list) { auto* pair = item->cast<Block>(); patternMap[pair->list[0]->_id].emplace_back(pair->list[0], pair->list[1]); } } ~PatternDatabase() { free(input); }; }; static PatternDatabase* database = nullptr; static void ensureDatabase() { if (!database) { // we must only ever create one database static OnlyOnce onlyOnce; onlyOnce.verify(); database = new PatternDatabase; } } // Check for matches and apply them struct Match { Module& wasm; Pattern& pattern; Match(Module& wasm, Pattern& pattern) : wasm(wasm), pattern(pattern) {} std::vector<Expression*> wildcards; // id in i32.any(id) etc. => the expression it represents in this match // Comparing/checking // Check if we can match to this pattern, updating ourselves with the info if so bool check(Expression* seen) { // compare seen to the pattern input, doing a special operation for our "wildcards" assert(wildcards.size() == 0); return ExpressionAnalyzer::flexibleEqual(pattern.input, seen, *this); } bool compare(Expression* subInput, Expression* subSeen) { CallImport* call = subInput->dynCast<CallImport>(); if (!call || call->operands.size() != 1 || call->operands[0]->type != i32 || !call->operands[0]->is<Const>()) return false; Index index = call->operands[0]->cast<Const>()->value.geti32(); // handle our special functions auto checkMatch = [&](WasmType type) { if (type != none && subSeen->type != type) return false; while (index >= wildcards.size()) { wildcards.push_back(nullptr); } if (!wildcards[index]) { // new wildcard wildcards[index] = subSeen; // NB: no need to copy return true; } else { // We are seeing this index for a second or later time, check it matches return ExpressionAnalyzer::equal(subSeen, wildcards[index]); }; }; if (call->target == I32_EXPR) { if (checkMatch(i32)) return true; } else if (call->target == I64_EXPR) { if (checkMatch(i64)) return true; } else if (call->target == F32_EXPR) { if (checkMatch(f32)) return true; } else if (call->target == F64_EXPR) { if (checkMatch(f64)) return true; } else if (call->target == ANY_EXPR) { if (checkMatch(none)) return true; } return false; } // Applying/copying // Apply the match, generate an output expression from the matched input, performing substitutions as necessary Expression* apply() { return ExpressionManipulator::flexibleCopy(pattern.output, wasm, *this); } // When copying a wildcard, perform the substitution. // TODO: we can reuse nodes, not copying a wildcard when it appears just once, and we can reuse other individual nodes when they are discarded anyhow. Expression* copy(Expression* curr) { CallImport* call = curr->dynCast<CallImport>(); if (!call || call->operands.size() != 1 || call->operands[0]->type != i32 || !call->operands[0]->is<Const>()) return nullptr; Index index = call->operands[0]->cast<Const>()->value.geti32(); // handle our special functions if (call->target == I32_EXPR || call->target == I64_EXPR || call->target == F32_EXPR || call->target == F64_EXPR || call->target == ANY_EXPR) { return ExpressionManipulator::copy(wildcards.at(index), wasm); } return nullptr; } }; // Main pass class struct OptimizeInstructions : public WalkerPass<PostWalker<OptimizeInstructions, UnifiedExpressionVisitor<OptimizeInstructions>>> { bool isFunctionParallel() override { return true; } Pass* create() override { return new OptimizeInstructions; } OptimizeInstructions() { ensureDatabase(); } void visitExpression(Expression* curr) { // we may be able to apply multiple patterns, one may open opportunities that look deeper NB: patterns must not have cycles while (1) { auto* handOptimized = handOptimize(curr); if (handOptimized) { curr = handOptimized; replaceCurrent(curr); } auto iter = database->patternMap.find(curr->_id); if (iter == database->patternMap.end()) return; auto& patterns = iter->second; bool more = false; for (auto& pattern : patterns) { Match match(*getModule(), pattern); if (match.check(curr)) { curr = match.apply(); replaceCurrent(curr); more = true; break; // exit pattern for loop, return to main while loop } } if (!more) break; } } // Optimizations that don't yet fit in the pattern DSL, but could be eventually maybe Expression* handOptimize(Expression* curr) { if (auto* binary = curr->dynCast<Binary>()) { // pattern match a load of 8 bits and a sign extend using a shl of 24 then shr_s of 24 as well, etc. if (binary->op == BinaryOp::ShrSInt32 && binary->right->is<Const>()) { auto shifts = binary->right->cast<Const>()->value.geti32(); if (shifts == 24 || shifts == 16) { auto* left = binary->left->dynCast<Binary>(); if (left && left->op == ShlInt32 && left->right->is<Const>() && left->right->cast<Const>()->value.geti32() == shifts) { auto* load = left->left->dynCast<Load>(); if (load && ((load->bytes == 1 && shifts == 24) || (load->bytes == 2 && shifts == 16))) { load->signed_ = true; return load; } } } } } else if (auto* set = curr->dynCast<SetGlobal>()) { // optimize out a set of a get auto* get = set->value->dynCast<GetGlobal>(); if (get && get->name == set->name) { ExpressionManipulator::nop(curr); } } else if (auto* iff = curr->dynCast<If>()) { iff->condition = optimizeBoolean(iff->condition); } else if (auto* select = curr->dynCast<Select>()) { select->condition = optimizeBoolean(select->condition); auto* condition = select->condition->dynCast<Unary>(); if (condition && condition->op == EqZInt32) { // flip select to remove eqz, if we can reorder EffectAnalyzer ifTrue(select->ifTrue); EffectAnalyzer ifFalse(select->ifFalse); if (!ifTrue.invalidates(ifFalse)) { select->condition = condition->value; std::swap(select->ifTrue, select->ifFalse); } } } else if (auto* br = curr->dynCast<Break>()) { if (br->condition) { br->condition = optimizeBoolean(br->condition); } } return nullptr; } private: Expression* optimizeBoolean(Expression* boolean) { auto* condition = boolean->dynCast<Unary>(); if (condition && condition->op == EqZInt32) { auto* condition2 = condition->value->dynCast<Unary>(); if (condition2 && condition2->op == EqZInt32) { // double eqz return condition2->value; } } return boolean; } }; Pass *createOptimizeInstructionsPass() { return new OptimizeInstructions(); } } // namespace wasm <commit_msg>clean up database-ensuring code using the new prepareToRun method<commit_after>/* * Copyright 2016 WebAssembly Community Group participants * * 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. */ // // Optimize combinations of instructions // #include <algorithm> #include <wasm.h> #include <pass.h> #include <wasm-s-parser.h> #include <support/threads.h> #include <ast_utils.h> namespace wasm { Name I32_EXPR = "i32.expr", I64_EXPR = "i64.expr", F32_EXPR = "f32.expr", F64_EXPR = "f64.expr", ANY_EXPR = "any.expr"; // A pattern struct Pattern { Expression* input; Expression* output; Pattern(Expression* input, Expression* output) : input(input), output(output) {} }; // Database of patterns struct PatternDatabase { Module wasm; char* input; std::map<Expression::Id, std::vector<Pattern>> patternMap; // root expression id => list of all patterns for it TODO optimize more PatternDatabase() { // generate module input = strdup( #include "OptimizeInstructions.wast.processed" ); SExpressionParser parser(input); Element& root = *parser.root; SExpressionWasmBuilder builder(wasm, *root[0]); // parse module form auto* func = wasm.getFunction("patterns"); auto* body = func->body->cast<Block>(); for (auto* item : body->list) { auto* pair = item->cast<Block>(); patternMap[pair->list[0]->_id].emplace_back(pair->list[0], pair->list[1]); } } ~PatternDatabase() { free(input); }; }; static PatternDatabase* database = nullptr; struct DatabaseEnsurer { DatabaseEnsurer() { assert(!database); database = new PatternDatabase; } }; // Check for matches and apply them struct Match { Module& wasm; Pattern& pattern; Match(Module& wasm, Pattern& pattern) : wasm(wasm), pattern(pattern) {} std::vector<Expression*> wildcards; // id in i32.any(id) etc. => the expression it represents in this match // Comparing/checking // Check if we can match to this pattern, updating ourselves with the info if so bool check(Expression* seen) { // compare seen to the pattern input, doing a special operation for our "wildcards" assert(wildcards.size() == 0); return ExpressionAnalyzer::flexibleEqual(pattern.input, seen, *this); } bool compare(Expression* subInput, Expression* subSeen) { CallImport* call = subInput->dynCast<CallImport>(); if (!call || call->operands.size() != 1 || call->operands[0]->type != i32 || !call->operands[0]->is<Const>()) return false; Index index = call->operands[0]->cast<Const>()->value.geti32(); // handle our special functions auto checkMatch = [&](WasmType type) { if (type != none && subSeen->type != type) return false; while (index >= wildcards.size()) { wildcards.push_back(nullptr); } if (!wildcards[index]) { // new wildcard wildcards[index] = subSeen; // NB: no need to copy return true; } else { // We are seeing this index for a second or later time, check it matches return ExpressionAnalyzer::equal(subSeen, wildcards[index]); }; }; if (call->target == I32_EXPR) { if (checkMatch(i32)) return true; } else if (call->target == I64_EXPR) { if (checkMatch(i64)) return true; } else if (call->target == F32_EXPR) { if (checkMatch(f32)) return true; } else if (call->target == F64_EXPR) { if (checkMatch(f64)) return true; } else if (call->target == ANY_EXPR) { if (checkMatch(none)) return true; } return false; } // Applying/copying // Apply the match, generate an output expression from the matched input, performing substitutions as necessary Expression* apply() { return ExpressionManipulator::flexibleCopy(pattern.output, wasm, *this); } // When copying a wildcard, perform the substitution. // TODO: we can reuse nodes, not copying a wildcard when it appears just once, and we can reuse other individual nodes when they are discarded anyhow. Expression* copy(Expression* curr) { CallImport* call = curr->dynCast<CallImport>(); if (!call || call->operands.size() != 1 || call->operands[0]->type != i32 || !call->operands[0]->is<Const>()) return nullptr; Index index = call->operands[0]->cast<Const>()->value.geti32(); // handle our special functions if (call->target == I32_EXPR || call->target == I64_EXPR || call->target == F32_EXPR || call->target == F64_EXPR || call->target == ANY_EXPR) { return ExpressionManipulator::copy(wildcards.at(index), wasm); } return nullptr; } }; // Main pass class struct OptimizeInstructions : public WalkerPass<PostWalker<OptimizeInstructions, UnifiedExpressionVisitor<OptimizeInstructions>>> { bool isFunctionParallel() override { return true; } Pass* create() override { return new OptimizeInstructions; } void prepareToRun(PassRunner* runner, Module* module) override { static DatabaseEnsurer ensurer; } void visitExpression(Expression* curr) { // we may be able to apply multiple patterns, one may open opportunities that look deeper NB: patterns must not have cycles while (1) { auto* handOptimized = handOptimize(curr); if (handOptimized) { curr = handOptimized; replaceCurrent(curr); } auto iter = database->patternMap.find(curr->_id); if (iter == database->patternMap.end()) return; auto& patterns = iter->second; bool more = false; for (auto& pattern : patterns) { Match match(*getModule(), pattern); if (match.check(curr)) { curr = match.apply(); replaceCurrent(curr); more = true; break; // exit pattern for loop, return to main while loop } } if (!more) break; } } // Optimizations that don't yet fit in the pattern DSL, but could be eventually maybe Expression* handOptimize(Expression* curr) { if (auto* binary = curr->dynCast<Binary>()) { // pattern match a load of 8 bits and a sign extend using a shl of 24 then shr_s of 24 as well, etc. if (binary->op == BinaryOp::ShrSInt32 && binary->right->is<Const>()) { auto shifts = binary->right->cast<Const>()->value.geti32(); if (shifts == 24 || shifts == 16) { auto* left = binary->left->dynCast<Binary>(); if (left && left->op == ShlInt32 && left->right->is<Const>() && left->right->cast<Const>()->value.geti32() == shifts) { auto* load = left->left->dynCast<Load>(); if (load && ((load->bytes == 1 && shifts == 24) || (load->bytes == 2 && shifts == 16))) { load->signed_ = true; return load; } } } } } else if (auto* set = curr->dynCast<SetGlobal>()) { // optimize out a set of a get auto* get = set->value->dynCast<GetGlobal>(); if (get && get->name == set->name) { ExpressionManipulator::nop(curr); } } else if (auto* iff = curr->dynCast<If>()) { iff->condition = optimizeBoolean(iff->condition); } else if (auto* select = curr->dynCast<Select>()) { select->condition = optimizeBoolean(select->condition); auto* condition = select->condition->dynCast<Unary>(); if (condition && condition->op == EqZInt32) { // flip select to remove eqz, if we can reorder EffectAnalyzer ifTrue(select->ifTrue); EffectAnalyzer ifFalse(select->ifFalse); if (!ifTrue.invalidates(ifFalse)) { select->condition = condition->value; std::swap(select->ifTrue, select->ifFalse); } } } else if (auto* br = curr->dynCast<Break>()) { if (br->condition) { br->condition = optimizeBoolean(br->condition); } } return nullptr; } private: Expression* optimizeBoolean(Expression* boolean) { auto* condition = boolean->dynCast<Unary>(); if (condition && condition->op == EqZInt32) { auto* condition2 = condition->value->dynCast<Unary>(); if (condition2 && condition2->op == EqZInt32) { // double eqz return condition2->value; } } return boolean; } }; Pass *createOptimizeInstructionsPass() { return new OptimizeInstructions(); } } // namespace wasm <|endoftext|>
<commit_before>#pragma once #include "../../types.hpp" #include "../base.hpp" #include "counter.hpp" #include <nlohmann/json.hpp> #include <pqrs/dispatcher.hpp> namespace krbn { namespace manipulator { namespace manipulators { namespace mouse_motion_to_scroll { class mouse_motion_to_scroll final : public base, public pqrs::dispatcher::extra::dispatcher_client { public: mouse_motion_to_scroll(const nlohmann::json& json, const core_configuration::details::complex_modifications_parameters& parameters) : base(), dispatcher_client() { try { if (!json.is_object()) { throw pqrs::json::unmarshal_error(fmt::format("json must be object, but is `{0}`", json.dump())); } for (const auto& [key, value] : json.items()) { if (key == "from") { if (!value.is_object()) { throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be object, but is `{1}`", key, value.dump())); } for (const auto& [k, v] : value.items()) { if (k == "modifiers") { try { from_modifiers_definition_ = v.get<from_modifiers_definition>(); } catch (const pqrs::json::unmarshal_error& e) { throw pqrs::json::unmarshal_error(fmt::format("`{0}.{1}` error: {2}", key, k, e.what())); } } } } else if (key == "options") { for (const auto& [k, v] : value.items()) { if (k == "threshold") { // (secret parameter) counter_parameters_.set_threshold(v.get<int>()); } else if (k == "recent_time_duration") { counter_parameters_.recent_time_duration = pqrs::osx::chrono::make_absolute_time_duration( std::chrono::milliseconds(v.get<int>())); } else if (k == "value_scale") { counter_parameters_.value_scale = v.get<double>(); } else if (k == "momentum_minus") { counter_parameters_.momentum_minus = v.get<int>(); } } } else if (key == "description" || key == "conditions" || key == "parameters" || key == "type") { // Do nothing } else { throw pqrs::json::unmarshal_error(fmt::format("unknown key `{0}` in `{1}`", key, json.dump())); } } counter_ = std::make_unique<counter>(weak_dispatcher_, counter_parameters_); counter_->scroll_event_arrived.connect([this](auto&& pointing_motion) { post_events(pointing_motion); }); } catch (...) { detach_from_dispatcher([this] { counter_ = nullptr; }); throw; } } virtual ~mouse_motion_to_scroll(void) { detach_from_dispatcher([this] { counter_ = nullptr; }); } virtual bool already_manipulated(const event_queue::entry& front_input_event) { return false; } virtual manipulate_result manipulate(event_queue::entry& front_input_event, const event_queue::queue& input_event_queue, const std::shared_ptr<event_queue::queue>& output_event_queue, absolute_time_point now) { if (output_event_queue) { // ---------------------------------------- if (!front_input_event.get_valid()) { return manipulate_result::passed; } if (!valid_) { return manipulate_result::passed; } // ---------------------------------------- auto from_mandatory_modifiers = test_conditions(front_input_event, output_event_queue); if (!from_mandatory_modifiers) { counter_->async_reset(); } else { if (auto m = front_input_event.get_event().find<pointing_motion>()) { front_input_event.set_valid(false); counter_->update(*m, front_input_event.get_event_time_stamp().get_time_stamp()); from_mandatory_modifiers_ = *from_mandatory_modifiers; device_id_ = front_input_event.get_device_id(); original_event_ = front_input_event.get_original_event(); weak_output_event_queue_ = output_event_queue; return manipulate_result::manipulated; } } } return manipulate_result::passed; } virtual bool active(void) const { return false; } virtual bool needs_virtual_hid_pointing(void) const { return true; } virtual void handle_device_keys_and_pointing_buttons_are_released_event(const event_queue::entry& front_input_event, event_queue::queue& output_event_queue) { } virtual void handle_device_ungrabbed_event(device_id device_id, const event_queue::queue& output_event_queue, absolute_time_point time_stamp) { } virtual void handle_pointing_device_event_from_event_tap(const event_queue::entry& front_input_event, event_queue::queue& output_event_queue) { } private: std::optional<std::unordered_set<modifier_flag>> test_conditions(const event_queue::entry& front_input_event, const std::shared_ptr<event_queue::queue>& output_event_queue) const { if (!condition_manager_.is_fulfilled(front_input_event, output_event_queue->get_manipulator_environment())) { return std::nullopt; } return from_modifiers_definition_.test_modifiers(output_event_queue->get_modifier_flag_manager()); } void post_events(const pointing_motion& pointing_motion) { if (auto output_event_queue = weak_output_event_queue_.lock()) { event_queue::event_time_stamp event_time_stamp(pqrs::osx::chrono::mach_absolute_time_point()); absolute_time_duration time_stamp_delay(0); // Post from_mandatory_modifiers key_up base::post_lazy_modifier_key_events(from_mandatory_modifiers_, event_type::key_up, device_id_, event_time_stamp, time_stamp_delay, original_event_, *output_event_queue); // Post new event { auto t = event_time_stamp; t.set_time_stamp(t.get_time_stamp() + time_stamp_delay++); output_event_queue->emplace_back_entry(device_id_, t, event_queue::event(pointing_motion), event_type::single, original_event_); } // Post from_mandatory_modifiers key_down base::post_lazy_modifier_key_events(from_mandatory_modifiers_, event_type::key_down, device_id_, event_time_stamp, time_stamp_delay, original_event_, *output_event_queue); krbn_notification_center::get_instance().enqueue_input_event_arrived(*this); } } from_modifiers_definition from_modifiers_definition_; counter_parameters counter_parameters_; std::unique_ptr<counter> counter_; std::unordered_set<modifier_flag> from_mandatory_modifiers_; device_id device_id_; event_queue::event original_event_; std::weak_ptr<event_queue::queue> weak_output_event_queue_; }; } // namespace mouse_motion_to_scroll } // namespace manipulators } // namespace manipulator } // namespace krbn <commit_msg>update error messages<commit_after>#pragma once #include "../../types.hpp" #include "../base.hpp" #include "counter.hpp" #include "krbn_notification_center.hpp" #include <nlohmann/json.hpp> #include <pqrs/dispatcher.hpp> namespace krbn { namespace manipulator { namespace manipulators { namespace mouse_motion_to_scroll { class mouse_motion_to_scroll final : public base, public pqrs::dispatcher::extra::dispatcher_client { public: mouse_motion_to_scroll(const nlohmann::json& json, const core_configuration::details::complex_modifications_parameters& parameters) : base(), dispatcher_client() { try { if (!json.is_object()) { throw pqrs::json::unmarshal_error(fmt::format("json must be object, but is `{0}`", json.dump())); } for (const auto& [key, value] : json.items()) { if (key == "from") { if (!value.is_object()) { throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be object, but is `{1}`", key, value.dump())); } for (const auto& [k, v] : value.items()) { if (k == "modifiers") { try { from_modifiers_definition_ = v.get<from_modifiers_definition>(); } catch (const pqrs::json::unmarshal_error& e) { throw pqrs::json::unmarshal_error(fmt::format("`{0}.{1}` error: {2}", key, k, e.what())); } } else { throw pqrs::json::unmarshal_error(fmt::format("`{0}` error: unknown key `{1}` in `{2}`", key, k, value.dump())); } } } else if (key == "options") { if (!value.is_object()) { throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be object, but is `{1}`", key, value.dump())); } for (const auto& [k, v] : value.items()) { if (k == "threshold") { // (secret parameter) counter_parameters_.set_threshold(v.get<int>()); } else if (k == "recent_time_duration") { counter_parameters_.recent_time_duration = pqrs::osx::chrono::make_absolute_time_duration( std::chrono::milliseconds(v.get<int>())); } else if (k == "value_scale") { counter_parameters_.value_scale = v.get<double>(); } else if (k == "momentum_minus") { counter_parameters_.momentum_minus = v.get<int>(); } } } else if (key == "description" || key == "conditions" || key == "parameters" || key == "type") { // Do nothing } else { throw pqrs::json::unmarshal_error(fmt::format("unknown key `{0}` in `{1}`", key, json.dump())); } } counter_ = std::make_unique<counter>(weak_dispatcher_, counter_parameters_); counter_->scroll_event_arrived.connect([this](auto&& pointing_motion) { post_events(pointing_motion); }); } catch (...) { detach_from_dispatcher([this] { counter_ = nullptr; }); throw; } } virtual ~mouse_motion_to_scroll(void) { detach_from_dispatcher([this] { counter_ = nullptr; }); } virtual bool already_manipulated(const event_queue::entry& front_input_event) { return false; } virtual manipulate_result manipulate(event_queue::entry& front_input_event, const event_queue::queue& input_event_queue, const std::shared_ptr<event_queue::queue>& output_event_queue, absolute_time_point now) { if (output_event_queue) { // ---------------------------------------- if (!front_input_event.get_valid()) { return manipulate_result::passed; } if (!valid_) { return manipulate_result::passed; } // ---------------------------------------- auto from_mandatory_modifiers = test_conditions(front_input_event, output_event_queue); if (!from_mandatory_modifiers) { counter_->async_reset(); } else { if (auto m = front_input_event.get_event().find<pointing_motion>()) { front_input_event.set_valid(false); counter_->update(*m, front_input_event.get_event_time_stamp().get_time_stamp()); from_mandatory_modifiers_ = *from_mandatory_modifiers; device_id_ = front_input_event.get_device_id(); original_event_ = front_input_event.get_original_event(); weak_output_event_queue_ = output_event_queue; return manipulate_result::manipulated; } } } return manipulate_result::passed; } virtual bool active(void) const { return false; } virtual bool needs_virtual_hid_pointing(void) const { return true; } virtual void handle_device_keys_and_pointing_buttons_are_released_event(const event_queue::entry& front_input_event, event_queue::queue& output_event_queue) { } virtual void handle_device_ungrabbed_event(device_id device_id, const event_queue::queue& output_event_queue, absolute_time_point time_stamp) { } virtual void handle_pointing_device_event_from_event_tap(const event_queue::entry& front_input_event, event_queue::queue& output_event_queue) { } private: std::optional<std::unordered_set<modifier_flag>> test_conditions(const event_queue::entry& front_input_event, const std::shared_ptr<event_queue::queue>& output_event_queue) const { if (!condition_manager_.is_fulfilled(front_input_event, output_event_queue->get_manipulator_environment())) { return std::nullopt; } return from_modifiers_definition_.test_modifiers(output_event_queue->get_modifier_flag_manager()); } void post_events(const pointing_motion& pointing_motion) { if (auto output_event_queue = weak_output_event_queue_.lock()) { event_queue::event_time_stamp event_time_stamp(pqrs::osx::chrono::mach_absolute_time_point()); absolute_time_duration time_stamp_delay(0); // Post from_mandatory_modifiers key_up base::post_lazy_modifier_key_events(from_mandatory_modifiers_, event_type::key_up, device_id_, event_time_stamp, time_stamp_delay, original_event_, *output_event_queue); // Post new event { auto t = event_time_stamp; t.set_time_stamp(t.get_time_stamp() + time_stamp_delay++); output_event_queue->emplace_back_entry(device_id_, t, event_queue::event(pointing_motion), event_type::single, original_event_); } // Post from_mandatory_modifiers key_down base::post_lazy_modifier_key_events(from_mandatory_modifiers_, event_type::key_down, device_id_, event_time_stamp, time_stamp_delay, original_event_, *output_event_queue); krbn_notification_center::get_instance().enqueue_input_event_arrived(*this); } } from_modifiers_definition from_modifiers_definition_; counter_parameters counter_parameters_; std::unique_ptr<counter> counter_; std::unordered_set<modifier_flag> from_mandatory_modifiers_; device_id device_id_; event_queue::event original_event_; std::weak_ptr<event_queue::queue> weak_output_event_queue_; }; } // namespace mouse_motion_to_scroll } // namespace manipulators } // namespace manipulator } // namespace krbn <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2009 by Miguel Chavez Gamboa * * miguel@lemonpos.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. * ***************************************************************************/ #include "mibitdialog.h" #include <QPixmap> #include <QString> #include <QLabel> #include <QHBoxLayout> #include <QVBoxLayout> #include <QTimeLine> #include <QPushButton> #include <QDebug> MibitDialog::MibitDialog( QWidget *parent, const QString &msg, const QString &file, const QPixmap &icon, AnimationType animation ) : QSvgWidget( parent ) { if (file != 0) setSVG(file); m_parent = parent; animType = animation; setMinimumHeight(150); setFixedSize(0,0); //until show we grow it setMaxHeight(maxH); //default sizes setMaxWidth(maxW); animRate = 500; //default animation speed (half second rate). img = new QLabel(); hLayout = new QHBoxLayout(); vLayout = new QVBoxLayout(); text = new QLabel(msg); btnClose = new QPushButton("Close"); ///TODO: what about translations??? img->setPixmap(icon); img->setMaximumHeight(48); //the icon size is hardcoded now. img->setMaximumWidth(48); img->setAlignment(Qt::AlignLeft); btnClose->setMaximumWidth(120); btnClose->setShortcut(Qt::Key_Escape); setLayout(vLayout); text->setWordWrap(true); text->setMargin(5); hLayout->addWidget(img,0,Qt::AlignLeft); hLayout->addWidget(text,0,Qt::AlignLeft); vLayout->addLayout(hLayout,0); vLayout->addWidget(btnClose,0,Qt::AlignCenter); timeLine = new QTimeLine(animRate, this); //1 second animation, check later. connect(timeLine, SIGNAL(frameChanged(int)), this, SLOT(animate(int))); connect(btnClose,SIGNAL(clicked()),this, SLOT(hideDialog())); connect(timeLine,SIGNAL(finished()), this, SLOT(onAnimationFinished())); } MibitDialog::~MibitDialog() { } void MibitDialog::showDialog(const QString &msg, AnimationType animation ) { //set default msg if the sent is empty. Also set the animation -the same way-. if (msg.isEmpty()) setMessage(text->text()); else setMessage( msg ); if (animation == 0) setAnimationType( atSlideDown ); else setAnimationType( animation ); show(); //update steps for animation, now that the window is showing. int maxStep; int minStep = 0; if ( animType == atSlideDown ) { maxStep = (m_parent->geometry().height()/2)-(maxHeight/2); minStep = -maxHeight; //timeLine->setCurveShape(QTimeLine::EaseOutCurve); //QTimeLine::SineCurve: Hacerlo criticamente amortiguado } else if (animType == atSlideUp ) { maxStep = (m_parent->geometry().height()/2)-(maxHeight/2); minStep = maxHeight + m_parent->geometry().height(); } else if ( animType == atGrowCenterH ) maxStep = maxWidth; else maxStep=maxHeight; timeLine->setFrameRange(minStep,maxStep); //make it grow timeLine->setDirection(QTimeLine::Forward); timeLine->start(); btnClose->setFocus(); } void MibitDialog::animate(int step) { //get some sizes... int textW = text->width(); int textH = text->height(); int btnH = btnClose->height(); QRect windowGeom = m_parent->geometry(); int midPointX = (windowGeom.width()/2); int midPointY = (windowGeom.height()/2); int newY; int newX; if ((midPointX-(maxWidth/2)) < 0) newX = 0; else newX = midPointX - maxWidth/2; if ((midPointY-(maxHeight/2)) < 0) newY = 0; else newY = midPointY - maxHeight/2; QRect dRect; switch (animType) { case atGrowCenterV: // Grow from Center Vertically.. to up and down break; case atGrowCenterH: // Grow from Center Horizontally... from left to right break; case atSlideDown: // slide Up case atSlideUp: // Slide down dRect.setX(newX); dRect.setY(step); dRect.setWidth(maxWidth); dRect.setHeight(maxHeight); setGeometry(dRect); setFixedHeight(maxHeight); setFixedWidth(maxWidth); break; default: break; } } void MibitDialog::hideDialog() { timeLine->toggleDirection();//reverse! timeLine->start(); } void MibitDialog::onAnimationFinished() { if (timeLine->direction() == QTimeLine::Backward) { close(); //qDebug()<<"Animation finished and it was in backward direction"; } } void MibitDialog::setSVG(const QString &file) { load(file); } void MibitDialog::setIcon(const QPixmap &icon) { img->setPixmap(icon); } void MibitDialog::setMessage(const QString &msg) { text->setText(msg); } <commit_msg>Completed all animation types<commit_after>/*************************************************************************** * Copyright (C) 2009 by Miguel Chavez Gamboa * * miguel@lemonpos.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. * ***************************************************************************/ #include "mibitdialog.h" #include <QPixmap> #include <QString> #include <QLabel> #include <QHBoxLayout> #include <QVBoxLayout> #include <QTimeLine> #include <QPushButton> #include <QDebug> MibitDialog::MibitDialog( QWidget *parent, const QString &msg, const QString &file, const QPixmap &icon, AnimationType animation ) : QSvgWidget( parent ) { if (file != 0) setSVG(file); m_parent = parent; animType = animation; setMinimumHeight(150); setFixedSize(0,0); //until show we grow it setMaxHeight(maxH); //default sizes setMaxWidth(maxW); animRate = 500; //default animation speed (half second rate). img = new QLabel(); hLayout = new QHBoxLayout(); vLayout = new QVBoxLayout(); text = new QLabel(msg); btnClose = new QPushButton("Close"); ///TODO: what about translations??? img->setPixmap(icon); img->setMaximumHeight(48); //the icon size is hardcoded now. img->setMaximumWidth(48); img->setAlignment(Qt::AlignLeft); btnClose->setMaximumWidth(120); btnClose->setShortcut(Qt::Key_Escape); setLayout(vLayout); text->setWordWrap(true); text->setMargin(5); hLayout->addWidget(img,0,Qt::AlignLeft); hLayout->addWidget(text,0,Qt::AlignLeft); vLayout->addLayout(hLayout,0); vLayout->addWidget(btnClose,0,Qt::AlignCenter); timeLine = new QTimeLine(animRate, this); connect(timeLine, SIGNAL(frameChanged(int)), this, SLOT(animate(int))); connect(btnClose,SIGNAL(clicked()),this, SLOT(hideDialog())); connect(timeLine,SIGNAL(finished()), this, SLOT(onAnimationFinished())); } MibitDialog::~MibitDialog() { } void MibitDialog::showDialog(const QString &msg, AnimationType animation ) { //set default msg if the sent is empty. Also set the animation -the same way-. if (msg.isEmpty()) setMessage(text->text()); else setMessage( msg ); if (animation == 0) setAnimationType( atSlideDown ); else setAnimationType( animation ); show(); //update steps for animation, now that the window is showing. int maxStep; int minStep = 0; switch (animType) { case atSlideDown: maxStep = (m_parent->geometry().height()/2)-(maxHeight/2); minStep = -maxHeight; break; case atSlideUp: maxStep = (m_parent->geometry().height()/2)-(maxHeight/2); minStep = maxHeight + m_parent->geometry().height(); break; case atGrowCenterH: maxStep = maxWidth; minStep = 0; break; case atGrowCenterV: maxStep= maxHeight; minStep = 0; break; } //timeLine->setCurveShape(QTimeLine::EaseOutCurve); //QTimeLine::SineCurve: Hacerlo criticamente amortiguado timeLine->setFrameRange(minStep,maxStep); //make it grow timeLine->setDirection(QTimeLine::Forward); timeLine->start(); btnClose->setFocus(); } void MibitDialog::animate(int step) { //get some sizes... int textW = text->width(); int textH = text->height(); int btnH = btnClose->height(); QRect windowGeom = m_parent->geometry(); int midPointX = (windowGeom.width()/2); int midPointY = (windowGeom.height()/2); int newY; int newX; //if ((midPointX-(maxWidth/2)) < 0) newX = 0; else newX = midPointX - maxWidth/2; //if ((midPointY-(maxHeight/2)) < 0) newY = 0; else newY = midPointY - maxHeight/2; QRect dRect; switch (animType) { case atGrowCenterV: // Grow from Center Vertically.. to up and down if ((midPointY - step/2) < 0 ) newY = 0; else newY = midPointY - step/2; if ((midPointX-(maxWidth/2)) < 0) newX = 0; else newX = midPointX - maxWidth/2; dRect.setX(newX); dRect.setY(newY); dRect.setWidth(step); dRect.setHeight(maxHeight); setGeometry(dRect); setFixedHeight(step); setFixedWidth(maxWidth); break; case atGrowCenterH: // Grow from Center Horizontally... from left to right if ((midPointX - step/2) < 0 ) newX = 0; else newX = midPointX - step/2; if ((midPointY-(maxHeight/2)) < 0) newY = 0; else newY = midPointY - maxHeight/2; dRect.setX(newX); dRect.setY(newY); dRect.setWidth(maxWidth); dRect.setHeight(step); setGeometry(dRect); setFixedHeight(maxHeight); setFixedWidth(step); break; case atSlideDown: // slide Up case atSlideUp: // Slide down if ((midPointX-(maxWidth/2)) < 0) newX = 0; else newX = midPointX - maxWidth/2; dRect.setX(newX); dRect.setY(step); dRect.setWidth(maxWidth); dRect.setHeight(maxHeight); setGeometry(dRect); setFixedHeight(maxHeight); setFixedWidth(maxWidth); break; default: break; } } void MibitDialog::hideDialog() { timeLine->toggleDirection();//reverse! timeLine->start(); } void MibitDialog::onAnimationFinished() { if (timeLine->direction() == QTimeLine::Backward) { close(); } } void MibitDialog::setSVG(const QString &file) { load(file); } void MibitDialog::setIcon(const QPixmap &icon) { img->setPixmap(icon); } void MibitDialog::setMessage(const QString &msg) { text->setText(msg); } <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXDE-Qt - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2012 Razor team * Authors: * Johannes Zellner <webmaster@nebulon.de> * * This program or 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 * * END_COMMON_COPYRIGHT_HEADER */ #include "pulseaudioengine.h" #include "audiodevice.h" #include <QMetaType> #include <QtDebug> //#define PULSEAUDIO_ENGINE_DEBUG static void sinkInfoCallback(pa_context *context, const pa_sink_info *info, int isLast, void *userdata) { PulseAudioEngine *pulseEngine = static_cast<PulseAudioEngine*>(userdata); QMap<pa_sink_state, QString> stateMap; stateMap[PA_SINK_INVALID_STATE] = "n/a"; stateMap[PA_SINK_RUNNING] = "RUNNING"; stateMap[PA_SINK_IDLE] = "IDLE"; stateMap[PA_SINK_SUSPENDED] = "SUSPENDED"; if (isLast < 0) { pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); qWarning() << QString("Failed to get sink information: %1").arg(pa_strerror(pa_context_errno(context))); return; } if (isLast) { pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); return; } pulseEngine->addOrUpdateSink(info); } static void contextEventCallback(pa_context *context, const char *name, pa_proplist *p, void *userdata) { #ifdef PULSEAUDIO_ENGINE_DEBUG qWarning("event received %s", name); #endif } static void contextStateCallback(pa_context *context, void *userdata) { PulseAudioEngine *pulseEngine = reinterpret_cast<PulseAudioEngine*>(userdata); // update internal state pa_context_state_t state = pa_context_get_state(context); pulseEngine->setContextState(state); #ifdef PULSEAUDIO_ENGINE_DEBUG switch (state) { case PA_CONTEXT_UNCONNECTED: qWarning("context unconnected"); break; case PA_CONTEXT_CONNECTING: qWarning("context connecting"); break; case PA_CONTEXT_AUTHORIZING: qWarning("context authorizing"); break; case PA_CONTEXT_SETTING_NAME: qWarning("context setting name"); break; case PA_CONTEXT_READY: qWarning("context ready"); break; case PA_CONTEXT_FAILED: qWarning("context failed"); break; case PA_CONTEXT_TERMINATED: qWarning("context terminated"); break; default: qWarning("we should never hit this state"); } #endif pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); } static void contextSuccessCallback(pa_context *context, int success, void *userdata) { Q_UNUSED(context); Q_UNUSED(success); Q_UNUSED(userdata); PulseAudioEngine *pulseEngine = reinterpret_cast<PulseAudioEngine*>(userdata); pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); } static void contextSubscriptionCallback(pa_context *context, pa_subscription_event_type_t t, uint32_t idx, void *userdata) { PulseAudioEngine *pulseEngine = reinterpret_cast<PulseAudioEngine*>(userdata); if (PA_SUBSCRIPTION_EVENT_REMOVE == t) pulseEngine->removeSink(idx); else pulseEngine->requestSinkInfoUpdate(idx); } PulseAudioEngine::PulseAudioEngine(QObject *parent) : AudioEngine(parent), m_context(0), m_contextState(PA_CONTEXT_UNCONNECTED), m_ready(false), m_maximumVolume(PA_VOLUME_UI_MAX) { qRegisterMetaType<pa_context_state_t>("pa_context_state_t"); m_reconnectionTimer.setSingleShot(true); m_reconnectionTimer.setInterval(100); connect(&m_reconnectionTimer, SIGNAL(timeout()), this, SLOT(connectContext())); m_mainLoop = pa_threaded_mainloop_new(); if (m_mainLoop == 0) { qWarning("Unable to create pulseaudio mainloop"); return; } if (pa_threaded_mainloop_start(m_mainLoop) != 0) { qWarning("Unable to start pulseaudio mainloop"); pa_threaded_mainloop_free(m_mainLoop); m_mainLoop = 0; return; } m_mainLoopApi = pa_threaded_mainloop_get_api(m_mainLoop); connect(this, SIGNAL(contextStateChanged(pa_context_state_t)), this, SLOT(handleContextStateChanged())); connectContext(); } PulseAudioEngine::~PulseAudioEngine() { if (m_context) { pa_context_unref(m_context); m_context = 0; } if (m_mainLoop) { pa_threaded_mainloop_free(m_mainLoop); m_mainLoop = 0; } } void PulseAudioEngine::removeSink(uint32_t idx) { auto dev_i = std::find_if(m_sinks.begin(), m_sinks.end(), [idx] (AudioDevice * dev) { return dev->index() == idx; }); if (m_sinks.end() == dev_i) return; QScopedPointer<AudioDevice> dev{*dev_i}; m_cVolumeMap.remove(dev.data()); m_sinks.erase(dev_i); emit sinkListChanged(); } void PulseAudioEngine::addOrUpdateSink(const pa_sink_info *info) { AudioDevice *dev = 0; bool newSink = false; QString name = QString::fromUtf8(info->name); foreach (AudioDevice *device, m_sinks) { if (device->name() == name) { dev = device; break; } } if (!dev) { dev = new AudioDevice(Sink, this); newSink = true; } dev->setName(name); dev->setIndex(info->index); dev->setDescription(QString::fromUtf8(info->description)); dev->setMuteNoCommit(info->mute); // TODO: save separately? alsa does not have it m_cVolumeMap.insert(dev, info->volume); pa_volume_t v = pa_cvolume_avg(&(info->volume)); // convert real volume to percentage dev->setVolumeNoCommit(((double)v * 100.0) / m_maximumVolume); if (newSink) { //keep the sinks sorted by index() m_sinks.insert( std::lower_bound(m_sinks.begin(), m_sinks.end(), dev, [] (AudioDevice const * const a, AudioDevice const * const b) { return a->name() < b->name(); }) , dev ); emit sinkListChanged(); } } void PulseAudioEngine::requestSinkInfoUpdate(uint32_t idx) { emit sinkInfoChanged(idx); } void PulseAudioEngine::commitDeviceVolume(AudioDevice *device) { if (!device || !m_ready) return; // convert from percentage to real volume value pa_volume_t v = ((double)device->volume() / 100.0) * m_maximumVolume; pa_cvolume tmpVolume = m_cVolumeMap.value(device); pa_cvolume *volume = pa_cvolume_set(&tmpVolume, tmpVolume.channels, v); // qDebug() << "PulseAudioEngine::commitDeviceVolume" << v; pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; if (device->type() == Sink) operation = pa_context_set_sink_volume_by_index(m_context, device->index(), volume, contextSuccessCallback, this); else operation = pa_context_set_source_volume_by_index(m_context, device->index(), volume, contextSuccessCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::retrieveSinks() { if (!m_ready) return; pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; operation = pa_context_get_sink_info_list(m_context, sinkInfoCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::setupSubscription() { if (!m_ready) return; connect(this, &PulseAudioEngine::sinkInfoChanged, this, &PulseAudioEngine::retrieveSinkInfo, Qt::QueuedConnection); pa_context_set_subscribe_callback(m_context, contextSubscriptionCallback, this); pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; operation = pa_context_subscribe(m_context, PA_SUBSCRIPTION_MASK_SINK, contextSuccessCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::handleContextStateChanged() { if (m_contextState == PA_CONTEXT_FAILED || m_contextState == PA_CONTEXT_TERMINATED) { qWarning("LXQt-Volume: Context connection failed or terminated lets try to reconnect"); m_reconnectionTimer.start(); } } void PulseAudioEngine::connectContext() { bool keepGoing = true; bool ok = false; m_reconnectionTimer.stop(); if (!m_mainLoop) return; pa_threaded_mainloop_lock(m_mainLoop); if (m_context) { pa_context_unref(m_context); m_context = 0; } m_context = pa_context_new(m_mainLoopApi, "lxqt-volume"); pa_context_set_state_callback(m_context, contextStateCallback, this); pa_context_set_event_callback(m_context, contextEventCallback, this); if (!m_context) { pa_threaded_mainloop_unlock(m_mainLoop); m_reconnectionTimer.start(); return; } if (pa_context_connect(m_context, NULL, (pa_context_flags_t)0, NULL) < 0) { pa_threaded_mainloop_unlock(m_mainLoop); m_reconnectionTimer.start(); return; } while (keepGoing) { switch (m_contextState) { case PA_CONTEXT_CONNECTING: case PA_CONTEXT_AUTHORIZING: case PA_CONTEXT_SETTING_NAME: break; case PA_CONTEXT_READY: keepGoing = false; ok = true; break; case PA_CONTEXT_TERMINATED: keepGoing = false; break; case PA_CONTEXT_FAILED: default: qWarning() << QString("Connection failure: %1").arg(pa_strerror(pa_context_errno(m_context))); keepGoing = false; } if (keepGoing) pa_threaded_mainloop_wait(m_mainLoop); } pa_threaded_mainloop_unlock(m_mainLoop); if (ok) { retrieveSinks(); setupSubscription(); } else { m_reconnectionTimer.start(); } } void PulseAudioEngine::retrieveSinkInfo(uint32_t idx) { if (!m_ready) return; pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; operation = pa_context_get_sink_info_by_index(m_context, idx, sinkInfoCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::setMute(AudioDevice *device, bool state) { if (!m_ready) return; pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; operation = pa_context_set_sink_mute_by_index(m_context, device->index(), state, contextSuccessCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::setContextState(pa_context_state_t state) { if (m_contextState == state) return; m_contextState = state; // update ready member as it depends on state if (m_ready == (m_contextState == PA_CONTEXT_READY)) return; m_ready = (m_contextState == PA_CONTEXT_READY); emit contextStateChanged(m_contextState); emit readyChanged(m_ready); } void PulseAudioEngine::setIgnoreMaxVolume(bool ignore) { if (ignore) m_maximumVolume = PA_VOLUME_UI_MAX; else m_maximumVolume = pa_sw_volume_from_dB(0); } <commit_msg>volume: Fix reporting of pulse volume<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXDE-Qt - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2012 Razor team * Authors: * Johannes Zellner <webmaster@nebulon.de> * * This program or 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 * * END_COMMON_COPYRIGHT_HEADER */ #include "pulseaudioengine.h" #include "audiodevice.h" #include <QMetaType> #include <QtDebug> //#define PULSEAUDIO_ENGINE_DEBUG static void sinkInfoCallback(pa_context *context, const pa_sink_info *info, int isLast, void *userdata) { PulseAudioEngine *pulseEngine = static_cast<PulseAudioEngine*>(userdata); QMap<pa_sink_state, QString> stateMap; stateMap[PA_SINK_INVALID_STATE] = "n/a"; stateMap[PA_SINK_RUNNING] = "RUNNING"; stateMap[PA_SINK_IDLE] = "IDLE"; stateMap[PA_SINK_SUSPENDED] = "SUSPENDED"; if (isLast < 0) { pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); qWarning() << QString("Failed to get sink information: %1").arg(pa_strerror(pa_context_errno(context))); return; } if (isLast) { pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); return; } pulseEngine->addOrUpdateSink(info); } static void contextEventCallback(pa_context *context, const char *name, pa_proplist *p, void *userdata) { #ifdef PULSEAUDIO_ENGINE_DEBUG qWarning("event received %s", name); #endif } static void contextStateCallback(pa_context *context, void *userdata) { PulseAudioEngine *pulseEngine = reinterpret_cast<PulseAudioEngine*>(userdata); // update internal state pa_context_state_t state = pa_context_get_state(context); pulseEngine->setContextState(state); #ifdef PULSEAUDIO_ENGINE_DEBUG switch (state) { case PA_CONTEXT_UNCONNECTED: qWarning("context unconnected"); break; case PA_CONTEXT_CONNECTING: qWarning("context connecting"); break; case PA_CONTEXT_AUTHORIZING: qWarning("context authorizing"); break; case PA_CONTEXT_SETTING_NAME: qWarning("context setting name"); break; case PA_CONTEXT_READY: qWarning("context ready"); break; case PA_CONTEXT_FAILED: qWarning("context failed"); break; case PA_CONTEXT_TERMINATED: qWarning("context terminated"); break; default: qWarning("we should never hit this state"); } #endif pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); } static void contextSuccessCallback(pa_context *context, int success, void *userdata) { Q_UNUSED(context); Q_UNUSED(success); Q_UNUSED(userdata); PulseAudioEngine *pulseEngine = reinterpret_cast<PulseAudioEngine*>(userdata); pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); } static void contextSubscriptionCallback(pa_context *context, pa_subscription_event_type_t t, uint32_t idx, void *userdata) { PulseAudioEngine *pulseEngine = reinterpret_cast<PulseAudioEngine*>(userdata); if (PA_SUBSCRIPTION_EVENT_REMOVE == t) pulseEngine->removeSink(idx); else pulseEngine->requestSinkInfoUpdate(idx); } PulseAudioEngine::PulseAudioEngine(QObject *parent) : AudioEngine(parent), m_context(0), m_contextState(PA_CONTEXT_UNCONNECTED), m_ready(false), m_maximumVolume(PA_VOLUME_UI_MAX) { qRegisterMetaType<pa_context_state_t>("pa_context_state_t"); m_reconnectionTimer.setSingleShot(true); m_reconnectionTimer.setInterval(100); connect(&m_reconnectionTimer, SIGNAL(timeout()), this, SLOT(connectContext())); m_mainLoop = pa_threaded_mainloop_new(); if (m_mainLoop == 0) { qWarning("Unable to create pulseaudio mainloop"); return; } if (pa_threaded_mainloop_start(m_mainLoop) != 0) { qWarning("Unable to start pulseaudio mainloop"); pa_threaded_mainloop_free(m_mainLoop); m_mainLoop = 0; return; } m_mainLoopApi = pa_threaded_mainloop_get_api(m_mainLoop); connect(this, SIGNAL(contextStateChanged(pa_context_state_t)), this, SLOT(handleContextStateChanged())); connectContext(); } PulseAudioEngine::~PulseAudioEngine() { if (m_context) { pa_context_unref(m_context); m_context = 0; } if (m_mainLoop) { pa_threaded_mainloop_free(m_mainLoop); m_mainLoop = 0; } } void PulseAudioEngine::removeSink(uint32_t idx) { auto dev_i = std::find_if(m_sinks.begin(), m_sinks.end(), [idx] (AudioDevice * dev) { return dev->index() == idx; }); if (m_sinks.end() == dev_i) return; QScopedPointer<AudioDevice> dev{*dev_i}; m_cVolumeMap.remove(dev.data()); m_sinks.erase(dev_i); emit sinkListChanged(); } void PulseAudioEngine::addOrUpdateSink(const pa_sink_info *info) { AudioDevice *dev = 0; bool newSink = false; QString name = QString::fromUtf8(info->name); foreach (AudioDevice *device, m_sinks) { if (device->name() == name) { dev = device; break; } } if (!dev) { dev = new AudioDevice(Sink, this); newSink = true; } dev->setName(name); dev->setIndex(info->index); dev->setDescription(QString::fromUtf8(info->description)); dev->setMuteNoCommit(info->mute); // TODO: save separately? alsa does not have it m_cVolumeMap.insert(dev, info->volume); pa_volume_t v = pa_cvolume_avg(&(info->volume)); // convert real volume to percentage dev->setVolumeNoCommit(qRound((static_cast<double>(v) * 100.0) / m_maximumVolume)); if (newSink) { //keep the sinks sorted by index() m_sinks.insert( std::lower_bound(m_sinks.begin(), m_sinks.end(), dev, [] (AudioDevice const * const a, AudioDevice const * const b) { return a->name() < b->name(); }) , dev ); emit sinkListChanged(); } } void PulseAudioEngine::requestSinkInfoUpdate(uint32_t idx) { emit sinkInfoChanged(idx); } void PulseAudioEngine::commitDeviceVolume(AudioDevice *device) { if (!device || !m_ready) return; // convert from percentage to real volume value pa_volume_t v = ((double)device->volume() / 100.0) * m_maximumVolume; pa_cvolume tmpVolume = m_cVolumeMap.value(device); pa_cvolume *volume = pa_cvolume_set(&tmpVolume, tmpVolume.channels, v); // qDebug() << "PulseAudioEngine::commitDeviceVolume" << v; pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; if (device->type() == Sink) operation = pa_context_set_sink_volume_by_index(m_context, device->index(), volume, contextSuccessCallback, this); else operation = pa_context_set_source_volume_by_index(m_context, device->index(), volume, contextSuccessCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::retrieveSinks() { if (!m_ready) return; pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; operation = pa_context_get_sink_info_list(m_context, sinkInfoCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::setupSubscription() { if (!m_ready) return; connect(this, &PulseAudioEngine::sinkInfoChanged, this, &PulseAudioEngine::retrieveSinkInfo, Qt::QueuedConnection); pa_context_set_subscribe_callback(m_context, contextSubscriptionCallback, this); pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; operation = pa_context_subscribe(m_context, PA_SUBSCRIPTION_MASK_SINK, contextSuccessCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::handleContextStateChanged() { if (m_contextState == PA_CONTEXT_FAILED || m_contextState == PA_CONTEXT_TERMINATED) { qWarning("LXQt-Volume: Context connection failed or terminated lets try to reconnect"); m_reconnectionTimer.start(); } } void PulseAudioEngine::connectContext() { bool keepGoing = true; bool ok = false; m_reconnectionTimer.stop(); if (!m_mainLoop) return; pa_threaded_mainloop_lock(m_mainLoop); if (m_context) { pa_context_unref(m_context); m_context = 0; } m_context = pa_context_new(m_mainLoopApi, "lxqt-volume"); pa_context_set_state_callback(m_context, contextStateCallback, this); pa_context_set_event_callback(m_context, contextEventCallback, this); if (!m_context) { pa_threaded_mainloop_unlock(m_mainLoop); m_reconnectionTimer.start(); return; } if (pa_context_connect(m_context, NULL, (pa_context_flags_t)0, NULL) < 0) { pa_threaded_mainloop_unlock(m_mainLoop); m_reconnectionTimer.start(); return; } while (keepGoing) { switch (m_contextState) { case PA_CONTEXT_CONNECTING: case PA_CONTEXT_AUTHORIZING: case PA_CONTEXT_SETTING_NAME: break; case PA_CONTEXT_READY: keepGoing = false; ok = true; break; case PA_CONTEXT_TERMINATED: keepGoing = false; break; case PA_CONTEXT_FAILED: default: qWarning() << QString("Connection failure: %1").arg(pa_strerror(pa_context_errno(m_context))); keepGoing = false; } if (keepGoing) pa_threaded_mainloop_wait(m_mainLoop); } pa_threaded_mainloop_unlock(m_mainLoop); if (ok) { retrieveSinks(); setupSubscription(); } else { m_reconnectionTimer.start(); } } void PulseAudioEngine::retrieveSinkInfo(uint32_t idx) { if (!m_ready) return; pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; operation = pa_context_get_sink_info_by_index(m_context, idx, sinkInfoCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::setMute(AudioDevice *device, bool state) { if (!m_ready) return; pa_threaded_mainloop_lock(m_mainLoop); pa_operation *operation; operation = pa_context_set_sink_mute_by_index(m_context, device->index(), state, contextSuccessCallback, this); while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); pa_threaded_mainloop_unlock(m_mainLoop); } void PulseAudioEngine::setContextState(pa_context_state_t state) { if (m_contextState == state) return; m_contextState = state; // update ready member as it depends on state if (m_ready == (m_contextState == PA_CONTEXT_READY)) return; m_ready = (m_contextState == PA_CONTEXT_READY); emit contextStateChanged(m_contextState); emit readyChanged(m_ready); } void PulseAudioEngine::setIgnoreMaxVolume(bool ignore) { if (ignore) m_maximumVolume = PA_VOLUME_UI_MAX; else m_maximumVolume = pa_sw_volume_from_dB(0); } <|endoftext|>
<commit_before>#include <catch2/catch.hpp> #include "types.hpp" #include <set> TEST_CASE("momentary_switch_event") { { krbn::momentary_switch_event e(krbn::key_code::keyboard_a); REQUIRE(e.make_modifier_flag() == std::nullopt); REQUIRE(e.modifier_flag() == false); REQUIRE(e.pointing_button() == false); REQUIRE(nlohmann::json(e).get<krbn::momentary_switch_event>() == e); } { krbn::momentary_switch_event e(krbn::key_code::keyboard_left_shift); REQUIRE(e.make_modifier_flag() == krbn::modifier_flag::left_shift); REQUIRE(e.modifier_flag() == true); REQUIRE(e.pointing_button() == false); REQUIRE(nlohmann::json(e).get<krbn::momentary_switch_event>() == e); } { krbn::momentary_switch_event e(krbn::consumer_key_code::mute); REQUIRE(e.make_modifier_flag() == std::nullopt); REQUIRE(e.modifier_flag() == false); REQUIRE(e.pointing_button() == false); REQUIRE(nlohmann::json(e).get<krbn::momentary_switch_event>() == e); } { krbn::momentary_switch_event e(krbn::apple_vendor_keyboard_key_code::expose_all); REQUIRE(e.make_modifier_flag() == std::nullopt); REQUIRE(e.modifier_flag() == false); REQUIRE(e.pointing_button() == false); REQUIRE(nlohmann::json(e).get<krbn::momentary_switch_event>() == e); } { krbn::momentary_switch_event e(krbn::apple_vendor_keyboard_key_code::function); REQUIRE(e.make_modifier_flag() == krbn::modifier_flag::fn); REQUIRE(e.modifier_flag() == true); REQUIRE(e.pointing_button() == false); REQUIRE(nlohmann::json(e).get<krbn::momentary_switch_event>() == e); } { krbn::momentary_switch_event e(krbn::apple_vendor_top_case_key_code::brightness_down); REQUIRE(e.make_modifier_flag() == std::nullopt); REQUIRE(e.modifier_flag() == false); REQUIRE(e.pointing_button() == false); REQUIRE(nlohmann::json(e).get<krbn::momentary_switch_event>() == e); } { krbn::momentary_switch_event e(krbn::apple_vendor_top_case_key_code::keyboard_fn); REQUIRE(e.make_modifier_flag() == krbn::modifier_flag::fn); REQUIRE(e.modifier_flag() == true); REQUIRE(e.pointing_button() == false); REQUIRE(nlohmann::json(e).get<krbn::momentary_switch_event>() == e); } { krbn::momentary_switch_event e(krbn::pointing_button::button1); REQUIRE(e.make_modifier_flag() == std::nullopt); REQUIRE(e.modifier_flag() == false); REQUIRE(e.pointing_button() == true); REQUIRE(nlohmann::json(e).get<krbn::momentary_switch_event>() == e); } { std::set<krbn::momentary_switch_event> map; map.insert(krbn::momentary_switch_event(krbn::consumer_key_code::mute)); map.insert(krbn::momentary_switch_event(krbn::key_code::keyboard_b)); map.insert(krbn::momentary_switch_event(krbn::key_code::keyboard_a)); map.insert(krbn::momentary_switch_event(krbn::key_code::keyboard_c)); map.insert(krbn::momentary_switch_event(krbn::pointing_button::button2)); map.insert(krbn::momentary_switch_event(krbn::pointing_button::button1)); int i = 0; for (const auto& m : map) { switch (i++) { case 0: REQUIRE(m == krbn::momentary_switch_event(krbn::key_code::keyboard_a)); break; case 1: REQUIRE(m == krbn::momentary_switch_event(krbn::key_code::keyboard_b)); break; case 2: REQUIRE(m == krbn::momentary_switch_event(krbn::key_code::keyboard_c)); break; case 3: REQUIRE(m == krbn::momentary_switch_event(krbn::consumer_key_code::mute)); break; case 4: REQUIRE(m == krbn::momentary_switch_event(krbn::pointing_button::button1)); break; case 5: REQUIRE(m == krbn::momentary_switch_event(krbn::pointing_button::button2)); break; } } } } <commit_msg>Update tests<commit_after>#include <catch2/catch.hpp> #include "types.hpp" #include <set> TEST_CASE("momentary_switch_event") { { krbn::momentary_switch_event e(krbn::key_code::keyboard_a); REQUIRE(e.make_modifier_flag() == std::nullopt); REQUIRE(e.modifier_flag() == false); REQUIRE(e.pointing_button() == false); REQUIRE(nlohmann::json(e).get<krbn::momentary_switch_event>() == e); } { krbn::momentary_switch_event e(krbn::key_code::keyboard_left_shift); REQUIRE(e.make_modifier_flag() == krbn::modifier_flag::left_shift); REQUIRE(e.modifier_flag() == true); REQUIRE(e.pointing_button() == false); REQUIRE(nlohmann::json(e).get<krbn::momentary_switch_event>() == e); } { krbn::momentary_switch_event e(krbn::consumer_key_code::mute); REQUIRE(e.make_modifier_flag() == std::nullopt); REQUIRE(e.modifier_flag() == false); REQUIRE(e.pointing_button() == false); REQUIRE(nlohmann::json(e).get<krbn::momentary_switch_event>() == e); } { krbn::momentary_switch_event e(krbn::apple_vendor_keyboard_key_code::expose_all); REQUIRE(e.make_modifier_flag() == std::nullopt); REQUIRE(e.modifier_flag() == false); REQUIRE(e.pointing_button() == false); REQUIRE(nlohmann::json(e).get<krbn::momentary_switch_event>() == e); } { krbn::momentary_switch_event e(krbn::apple_vendor_keyboard_key_code::function); REQUIRE(e.make_modifier_flag() == krbn::modifier_flag::fn); REQUIRE(e.modifier_flag() == true); REQUIRE(e.pointing_button() == false); REQUIRE(nlohmann::json(e).get<krbn::momentary_switch_event>() == e); } { krbn::momentary_switch_event e(krbn::apple_vendor_top_case_key_code::brightness_down); REQUIRE(e.make_modifier_flag() == std::nullopt); REQUIRE(e.modifier_flag() == false); REQUIRE(e.pointing_button() == false); REQUIRE(nlohmann::json(e).get<krbn::momentary_switch_event>() == e); } { krbn::momentary_switch_event e(krbn::apple_vendor_top_case_key_code::keyboard_fn); REQUIRE(e.make_modifier_flag() == krbn::modifier_flag::fn); REQUIRE(e.modifier_flag() == true); REQUIRE(e.pointing_button() == false); REQUIRE(nlohmann::json(e).get<krbn::momentary_switch_event>() == e); } { krbn::momentary_switch_event e(krbn::pointing_button::button1); REQUIRE(e.make_modifier_flag() == std::nullopt); REQUIRE(e.modifier_flag() == false); REQUIRE(e.pointing_button() == true); REQUIRE(nlohmann::json(e).get<krbn::momentary_switch_event>() == e); } { std::set<krbn::momentary_switch_event> map; map.insert(krbn::momentary_switch_event(krbn::consumer_key_code::mute)); map.insert(krbn::momentary_switch_event(krbn::key_code::keyboard_b)); map.insert(krbn::momentary_switch_event(krbn::key_code::keyboard_a)); map.insert(krbn::momentary_switch_event(krbn::key_code::keyboard_c)); map.insert(krbn::momentary_switch_event(krbn::pointing_button::button2)); map.insert(krbn::momentary_switch_event(krbn::pointing_button::button1)); int i = 0; for (const auto& m : map) { switch (i++) { case 0: REQUIRE(m == krbn::momentary_switch_event(krbn::key_code::keyboard_a)); break; case 1: REQUIRE(m == krbn::momentary_switch_event(krbn::key_code::keyboard_b)); break; case 2: REQUIRE(m == krbn::momentary_switch_event(krbn::key_code::keyboard_c)); break; case 3: REQUIRE(m == krbn::momentary_switch_event(krbn::consumer_key_code::mute)); break; case 4: REQUIRE(m == krbn::momentary_switch_event(krbn::pointing_button::button1)); break; case 5: REQUIRE(m == krbn::momentary_switch_event(krbn::pointing_button::button2)); break; } } } } TEST_CASE("momentary_switch_event json") { { std::string expected("{\"pointing_button\":\"button1\"}"); nlohmann::json actual = krbn::momentary_switch_event(pqrs::hid::usage_page::button, pqrs::hid::usage::button::button_1); REQUIRE(actual.dump() == expected); } { std::string expected("{\"pointing_button\":\"(number:1234)\"}"); nlohmann::json actual = krbn::momentary_switch_event(pqrs::hid::usage_page::button, pqrs::hid::usage::value_t(1234)); REQUIRE(actual.dump() == expected); } } <|endoftext|>
<commit_before>#ifndef _DATA_TYPES #define _DATA_TYPES #include <iostream> struct dimension { dimension(void); dimension(unsigned int w, unsigned int h); unsigned int width, height; }; struct position { position(void); position(int x, int y); int x, y; }; struct rectangle { rectangle(void); rectangle(position pos, dimension dim); rectangle(int x, int y, unsigned int width, unsigned int height); int & x(void); int const & x(void) const; int & y(void); int const & y(void) const; unsigned int & width(void); unsigned int const & width(void) const; unsigned int & height(void); unsigned int const & height(void) const; position _position; dimension _dimension; }; std::ostream & operator<<(std::ostream & os, const rectangle & rect); #endif <commit_msg>Data types for xft cpp adapter<commit_after>#ifndef _DATA_TYPES #define _DATA_TYPES #include <iostream> struct dimension { dimension(void); dimension(unsigned int w, unsigned int h); unsigned int width, height; }; struct position { position(void); position(int x, int y); int x, y; }; struct rectangle { rectangle(void); rectangle(position pos, dimension dim); rectangle(int x, int y, unsigned int width, unsigned int height); int & x(void); int const & x(void) const; int & y(void); int const & y(void) const; unsigned int & width(void); unsigned int const & width(void) const; unsigned int & height(void); unsigned int const & height(void) const; position _position; dimension _dimension; }; std::ostream & operator<<(std::ostream & os, const rectangle & rect); namespace x { namespace type { namespace generic { class name { public: name(const std::string & name) : m_name(name) {} std::string & operator*(void) { return m_name; } const std::string & operator*(void) const { return m_name; } std::string * const operator->(void) { return &m_name; } const std::string * const operator->(void) const { return &m_name; } private: std::string m_name; }; // class name }; // namespace generic class colorname : public generic::name { using generic::name::name; }; class fontname : public generic::name { using generic::name::name; }; }; // namespace type }; // namespace x #endif <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file QBigInt.cpp * @author Yann yann@ethdev.com * @date 2015 */ #include <boost/variant/multivisitors.hpp> #include <boost/variant.hpp> #include <libethcore/CommonJS.h> #include "QBigInt.h" using namespace dev; using namespace dev::mix; QString QBigInt::value() const { std::ostringstream s; s << m_internalValue; return QString::fromStdString(s.str()); } QBigInt* QBigInt::subtract(QBigInt* const& _value) const { BigIntVariant toSubtract = _value->internalValue(); return new QBigInt(boost::apply_visitor(mix::subtract(), m_internalValue, toSubtract)); } QBigInt* QBigInt::add(QBigInt* const& _value) const { BigIntVariant toAdd = _value->internalValue(); return new QBigInt(boost::apply_visitor(mix::add(), m_internalValue, toAdd)); } QBigInt* QBigInt::multiply(QBigInt* const& _value) const { BigIntVariant toMultiply = _value->internalValue(); return new QBigInt(boost::apply_visitor(mix::multiply(), m_internalValue, toMultiply)); } QBigInt* QBigInt::divide(QBigInt* const& _value) const { BigIntVariant toDivide = _value->internalValue(); return new QBigInt(boost::apply_visitor(mix::divide(), m_internalValue, toDivide)); } QVariantMap QBigInt::checkAgainst(QString const& _type) const { QVariantMap ret; QString type = _type; QString capacity = type.replace("uint", "").replace("int", ""); if (capacity.isEmpty()) capacity = "256"; bigint range = 256^(capacity.toInt() / 8); bigint value = boost::get<bigint>(this->internalValue()); ret.insert("valid", true); if (_type.startsWith("uint") && value > range - 1) { ret.insert("minValue", "0"); std::ostringstream s; s << range - 1; ret.insert("maxValue", QString::fromStdString(s.str())); if (value > range) ret["valid"] = false; } else if (_type.startsWith("int")) { range = range / 2; std::ostringstream s; s << -range; ret.insert("minValue", QString::fromStdString(s.str())); s.str(""); s.clear(); s << range - 1; ret.insert("maxValue", QString::fromStdString(s.str())); if (-range > value || value > range - 1) ret["valid"] = false; } return ret; } <commit_msg>bug fix: #2020<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file QBigInt.cpp * @author Yann yann@ethdev.com * @date 2015 */ #include <boost/variant/multivisitors.hpp> #include <boost/variant.hpp> #include <libethcore/CommonJS.h> #include "QBigInt.h" using namespace dev; using namespace dev::mix; QString QBigInt::value() const { std::ostringstream s; s << m_internalValue; return QString::fromStdString(s.str()); } QBigInt* QBigInt::subtract(QBigInt* const& _value) const { BigIntVariant toSubtract = _value->internalValue(); return new QBigInt(boost::apply_visitor(mix::subtract(), m_internalValue, toSubtract)); } QBigInt* QBigInt::add(QBigInt* const& _value) const { BigIntVariant toAdd = _value->internalValue(); return new QBigInt(boost::apply_visitor(mix::add(), m_internalValue, toAdd)); } QBigInt* QBigInt::multiply(QBigInt* const& _value) const { BigIntVariant toMultiply = _value->internalValue(); return new QBigInt(boost::apply_visitor(mix::multiply(), m_internalValue, toMultiply)); } QBigInt* QBigInt::divide(QBigInt* const& _value) const { BigIntVariant toDivide = _value->internalValue(); return new QBigInt(boost::apply_visitor(mix::divide(), m_internalValue, toDivide)); } QVariantMap QBigInt::checkAgainst(QString const& _type) const { QVariantMap ret; QString type = _type; QString capacity = type.replace("uint", "").replace("int", ""); if (capacity.isEmpty()) capacity = "256"; bigint range = 1; for (int k = 0; k < capacity.toInt() / 8; ++k) range = range * 256; bigint value = boost::get<bigint>(this->internalValue()); ret.insert("valid", true); if (_type.startsWith("uint") && value > range - 1) { ret.insert("minValue", "0"); std::ostringstream s; s << range - 1; ret.insert("maxValue", QString::fromStdString(s.str())); if (value > range) ret["valid"] = false; } else if (_type.startsWith("int")) { range = range / 2; std::ostringstream s; s << -range; ret.insert("minValue", QString::fromStdString(s.str())); s.str(""); s.clear(); s << range - 1; ret.insert("maxValue", QString::fromStdString(s.str())); if (-range > value || value > range - 1) ret["valid"] = false; } return ret; } <|endoftext|>
<commit_before><commit_msg>[NFC] Fix warnings in RHist.hxx<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2010 The WebM 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. // // Implements two reader subclasses: MkvReaderQT and MkvBufferedReaderQT // that can be passed to the mkvparser object for its use in reading WebM data. // See www.webmproject.org for more info. // #include "mkvreaderqt.hpp" extern "C" { #include "log.h" } static void ReadCompletion(Ptr request, long refcon, OSErr readErr); //-------------------------------------------------------------------------------- MkvReaderQT::MkvReaderQT() : m_length(0), m_dataRef(NULL), m_dataHandler(NULL) { } //-------------------------------------------------------------------------------- MkvReaderQT::~MkvReaderQT() { Close(); } //-------------------------------------------------------------------------------- int MkvReaderQT::Open(Handle dataRef, OSType dataRefType) { if (dataRef == NULL) return -11; if ((m_dataRef) || (m_dataHandler)) return -2; m_dataRef = dataRef; long fileSize = 0; // Retrieve the best data handler component to use with the given data reference, for read purpoases. // Then open the returned component using standard Component Manager calls. OSType err; ComponentInstance dataHandler = 0; err = OpenAComponent(GetDataHandler(dataRef, dataRefType, kDataHCanRead), &dataHandler); if (err) return -3; // Provide a data reference to the data handler. // Then you may start reading and/or writing // movie data from that data reference. err = DataHSetDataRef(dataHandler, dataRef); if (err) return -4; // Open a read path to the current data reference. // You need to do this before your component can read data using a data handler component. err = DataHOpenForRead(dataHandler); if (err) return -5; // Get the size, in bytes, of the current data reference. // This is functionally equivalent to the File Manager's GetEOF function. err = DataHGetFileSize(dataHandler, &fileSize); if (err) return -6; m_length = fileSize; #if 0 Boolean buffersReads; Boolean buffersWrites; DataHDoesBuffer(dataHandler, &buffersReads, &buffersWrites); dbg_printf("DataHDoesBuffer() buffersReads = %d\n", buffersReads); long blockSize = 0; DataHGetPreferredBlockSize(dataHandler, &blockSize); dbg_printf("DataHGetPreferredBlockSize() is %ld\n", blockSize); #endif // dbg_printf("[WebM Import] DataHGetFileSize = %d\n", fileSize); // dbg_printf("[WebM Import] sizeof Header %d\n", sizeof(header)); m_dataHandler = dataHandler; return 0; } //-------------------------------------------------------------------------------- void MkvReaderQT::Close() { // **** } //-------------------------------------------------------------------------------- int MkvReaderQT::Read(long long position, long length, unsigned char* buffer) { // sanity checks if ((m_dataRef == NULL) || (position < 0) || (length < 0) || (position >= m_length)) return -1; if (length == 0) return 0; if (length != 1) dbg_printf("MkvReaderQT::Read() len = %ld\n", length); // DatHGetPreferredBlockSize() // MovieImportSetIdleManager(store, store->idleManager) // seek and read // This function provides both a synchronous and an asynchronous read interface. Synchronous read operations // work like the DataHGetData function--the data handler component returns control to the client program only // after it has serviced the read request. Asynchronous read operations allow client programs to schedule read // requests in the context of a specified QuickTime time base. The DataHandler queues the request and immediately // returns control to the caller. After the component actually reads the data, it calls the completion function - // calling of the completion will occurs in DataHTask. Not all data handlers support scheduling, if they don't // they'll complete synchronously and then call the completion function. Additionally as a note, some DataHandlers // support 64-bit file offsets, for example DataHScheduleData64, we're not using this call here but you could use // 64-bit versions first, and if they fail fall back to the older calls. OSType err; err = DataHScheduleData(m_dataHandler, // DataHandler Component Instance (Ptr)buffer, // Specifies the location in memory that is to receive the data position, // Offset in the data reference from which you want to read length, // The number of bytes to read 0, // refCon NULL, // pointer to a schedule record - NULL for Synchronous operation NULL); // pointer to a data-handler completion function - NULL for Syncronous operation if (err) return -2; // if we read less than what caller asked for, then return error. //if (size < size_t(length)) // return -1; return 0; } //-------------------------------------------------------------------------------- int MkvReaderQT::Length(long long* total, long long* available) { if (total) *total = m_length; if (available) *available = m_length; return 0; } //-------------------------------------------------------------------------------- // MkvBufferedReaderQT::MkvBufferedReaderQT() : bufDataSize(0), bufStartFilePos(0), bufCurFilePos(0), bufEndFilePos(0), m_PendingReadSize(0) { bufDataMax = sizeof(buf); m_previousReadPos = 0; } //-------------------------------------------------------------------------------- MkvBufferedReaderQT::~MkvBufferedReaderQT() { // **** } //-------------------------------------------------------------------------------- // int MkvBufferedReaderQT::Read(long long requestedPos, long requestedLen, unsigned char* outbuf) { // **** NOTE - any dbg_print() in this function has big impact on runtime performance. //dbg_printf("MkvBufferedReaderQT::Read() - requestedPos = %lld, requestedLen = %ld\n", requestedPos, requestedLen); //dbg_printf("\tbufStartFilePos = %lld, m_buffer.size = %lu\n", bufStartFilePos, m_buffer.size()); // dbg_printf("ReadPos\t%c\t%ld\tdelta=%ld\n", (requestedPos > m_previousReadPos)?'+':'-', requestedPos, (requestedPos-m_previousReadPos)); m_previousReadPos = requestedPos; if ((requestedPos < bufStartFilePos) || (requestedPos > bufEndFilePos) || ((requestedPos + requestedLen - 1) > bufEndFilePos)) { // m_bufHeadPos+m_buffer.size())) { // non-contiguous read, miss dbg_printf("\tNON-CONTIGUOUS READ, CACHE MISS requestedPos = %lld, requestedLen = %ld [%ld - %ld - %ld]\n", requestedPos, requestedLen, bufStartFilePos, bufCurFilePos, bufEndFilePos); int err = this->MkvReaderQT::Read(requestedPos, requestedLen, outbuf); return err; } //dbg_printf("\tm_bufpos=%lld, requestedLen=%ld, m_buffer.size() = %lu\n", m_bufpos, requestedLen, m_buffer.size()); #if 0 // contiguous read (or empty buffer) // is the request larger than what we already have in buffer? if ((requestedPos + requestedLen - 1) > bufEndFilePos) { // (m_bufHeadPos + m_buffer.size() - 1)) { dbg_printf("\tNOT ENOUGH IN BUFFER, read from file.\n"); // not enough in buffer... // read from data handler (file) size_t growSize = (requestedLen < m_chunksize) ? m_chunksize : requestedLen; // grow buffer by chunksize or requestedLen, whichever is greater. unsigned char* tempBuf = (unsigned char*)malloc(growSize); int err = this->MkvReaderQT::Read(requestedPos, growSize, tempBuf); if (err != 0) { free(tempBuf); return err; } // append to existing buffer for (long i=0; i < growSize; i++) { m_buffer.push_back(tempBuf[i]); } free(tempBuf); } #endif //dbg_printf("\tm_buffer.front = %1x\n", m_buffer.front()); // read from buffer if (requestedLen > 0) { for (long i=0; i < requestedLen; i++) { outbuf[i] = buf[requestedPos - bufStartFilePos + i]; //outbuf[i] = m_buffer[requestedPos - bufStartFilePos + i]; //.front(); //m_buffer.pop(); //m_bufpos++; } // **** dbg_printf("BUF CACHE HIT!\n"); bufCurFilePos = (requestedPos + requestedLen); } //dbg_printf("\toutbuf[0]=%1x\n", outbuf[0]); //dbg_printf("MkvBufferedReaderQT::Read() return.\n"); //dbg_printf("\n"); return 0; } //-------------------------------------------------------------------------------- void MkvBufferedReaderQT::ReadAsync(MkvBufferedReaderQT* reader, long requestedLen) { if (reader->m_PendingReadSize != 0) { // if an async read is already pending, nop and return now. return; } dbg_printf("ReadAsync...\n"); dbg_printf("MkvBufferedReaderQT::buf %ld [%ld - %ld - %ld] %ld\n", reader->bufDataSize, reader->bufStartFilePos, reader->bufCurFilePos, reader->bufEndFilePos, reader->bufDataMax); if (reader->read_completion_cb == NULL) reader->read_completion_cb = NewDataHCompletionUPP(ReadCompletion); // if requested size wouldn't fit into available space in buffer, and currently consumed more than 3/4 of data in buffer, then compact the buffer. if ((reader->bufDataSize + requestedLen > reader->bufDataMax) && ((reader->bufCurFilePos - reader->bufStartFilePos) > (reader->bufEndFilePos - reader->bufStartFilePos) * 0.75)) { reader->CompactBuffer(requestedLen); } if (reader->bufDataSize + requestedLen <= reader->bufDataMax) { wide ofst; ofst.hi = 0; ofst.lo = reader->bufEndFilePos; reader->m_PendingReadSize = requestedLen; reader->readErr = DataHReadAsync(reader->m_dataHandler, reader->buf + reader->bufDataSize, requestedLen, &ofst, reader->read_completion_cb, (long)reader); } else { dbg_printf("MkvBufferedReaderQT::ReadAsync() FAIL - BUFFER FULL. bufDataSize=%ld, consumed=%ld\n", reader->bufDataSize, (reader->bufCurFilePos - reader->bufStartFilePos)); reader->m_PendingReadSize = 0; DataHTask(reader->m_dataHandler); //ReadCompletion(NULL, (long)reader, noErr); // **** maybe wait, and then call comletion, just to keep pump going... } } //-------------------------------------------------------------------------------- void MkvBufferedReaderQT::InitBuffer() { if ((m_PendingReadSize == 0) && (bufDataSize == 0) && (bufEndFilePos == 0)) { dbg_printf("InitBuffer (sync) ..."); long requestedLen = kReadChunkSize * 16; // **** try larger initial chunk m_PendingReadSize = requestedLen; int err = this->MkvReaderQT::Read(0, requestedLen, buf); ReadCompletion(NULL, (long)this, err); } else { dbg_printf("InitBuffer FAIL."); } } //-------------------------------------------------------------------------------- static void ReadCompletion(Ptr request, long refcon, OSErr readErr) { MkvBufferedReaderQT* reader = (MkvBufferedReaderQT*)refcon; reader->readErr = readErr; reader->bufEndFilePos += reader->m_PendingReadSize; // incr file position by amount that was just read into buf reader->bufDataSize += reader->m_PendingReadSize; // incr size of data in buf reader->m_PendingReadSize = 0; dbg_printf("...ReadCompletion (filePos=%ld)\n", reader->bufEndFilePos); long readSize = kReadChunkSize; // MkvBufferedReaderQT::kDefaultChunkSize; MkvBufferedReaderQT::ReadAsync(reader); // , readSize); use default arg } //-------------------------------------------------------------------------------- void MkvBufferedReaderQT::CompactBuffer(long requestedSize) { long remainingDataSize = (bufDataMax - bufDataSize); long consumedDataSize = (bufCurFilePos - bufStartFilePos); long killDataSize = (consumedDataSize > kReadChunkSize) ? (consumedDataSize - kReadChunkSize) : (consumedDataSize * 0.50); //* 0.5; // 0.66; // / 2; if (requestedSize > remainingDataSize) { if (killDataSize > (requestedSize - remainingDataSize)) { dbg_printf("CompactBuffer() consumedDataSize=%ld, killDataSize=%ld\n", consumedDataSize, killDataSize); memmove(&buf[0], &buf[killDataSize], (bufDataSize - killDataSize)); bufDataSize -= killDataSize; bufStartFilePos += killDataSize; } else { dbg_printf("CompactBuffer() FAIL. Wait for more data to be consumed.\n"); } } else dbg_printf("CompactBuffer() NOP, don't need to compact at this time.\n"); } <commit_msg>Fix off-by-one bug in the importer's reader.<commit_after>// Copyright (c) 2010 The WebM 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. // // Implements two reader subclasses: MkvReaderQT and MkvBufferedReaderQT // that can be passed to the mkvparser object for its use in reading WebM data. // See www.webmproject.org for more info. // #include "mkvreaderqt.hpp" extern "C" { #include "log.h" } static void ReadCompletion(Ptr request, long refcon, OSErr readErr); //-------------------------------------------------------------------------------- MkvReaderQT::MkvReaderQT() : m_length(0), m_dataRef(NULL), m_dataHandler(NULL) { } //-------------------------------------------------------------------------------- MkvReaderQT::~MkvReaderQT() { Close(); } //-------------------------------------------------------------------------------- int MkvReaderQT::Open(Handle dataRef, OSType dataRefType) { if (dataRef == NULL) return -11; if ((m_dataRef) || (m_dataHandler)) return -2; m_dataRef = dataRef; long fileSize = 0; // Retrieve the best data handler component to use with the given data reference, for read purpoases. // Then open the returned component using standard Component Manager calls. OSType err; ComponentInstance dataHandler = 0; err = OpenAComponent(GetDataHandler(dataRef, dataRefType, kDataHCanRead), &dataHandler); if (err) return -3; // Provide a data reference to the data handler. // Then you may start reading and/or writing // movie data from that data reference. err = DataHSetDataRef(dataHandler, dataRef); if (err) return -4; // Open a read path to the current data reference. // You need to do this before your component can read data using a data handler component. err = DataHOpenForRead(dataHandler); if (err) return -5; // Get the size, in bytes, of the current data reference. // This is functionally equivalent to the File Manager's GetEOF function. err = DataHGetFileSize(dataHandler, &fileSize); if (err) return -6; m_length = fileSize; #if 0 Boolean buffersReads; Boolean buffersWrites; DataHDoesBuffer(dataHandler, &buffersReads, &buffersWrites); dbg_printf("DataHDoesBuffer() buffersReads = %d\n", buffersReads); long blockSize = 0; DataHGetPreferredBlockSize(dataHandler, &blockSize); dbg_printf("DataHGetPreferredBlockSize() is %ld\n", blockSize); #endif // dbg_printf("[WebM Import] DataHGetFileSize = %d\n", fileSize); // dbg_printf("[WebM Import] sizeof Header %d\n", sizeof(header)); m_dataHandler = dataHandler; return 0; } //-------------------------------------------------------------------------------- void MkvReaderQT::Close() { // **** } //-------------------------------------------------------------------------------- int MkvReaderQT::Read(long long position, long length, unsigned char* buffer) { // sanity checks if ((m_dataRef == NULL) || (position < 0) || (length < 0) || (position >= m_length)) return -1; if (length == 0) return 0; if (length != 1) dbg_printf("MkvReaderQT::Read() len = %ld\n", length); // DatHGetPreferredBlockSize() // MovieImportSetIdleManager(store, store->idleManager) // seek and read // This function provides both a synchronous and an asynchronous read interface. Synchronous read operations // work like the DataHGetData function--the data handler component returns control to the client program only // after it has serviced the read request. Asynchronous read operations allow client programs to schedule read // requests in the context of a specified QuickTime time base. The DataHandler queues the request and immediately // returns control to the caller. After the component actually reads the data, it calls the completion function - // calling of the completion will occurs in DataHTask. Not all data handlers support scheduling, if they don't // they'll complete synchronously and then call the completion function. Additionally as a note, some DataHandlers // support 64-bit file offsets, for example DataHScheduleData64, we're not using this call here but you could use // 64-bit versions first, and if they fail fall back to the older calls. OSType err; err = DataHScheduleData(m_dataHandler, // DataHandler Component Instance (Ptr)buffer, // Specifies the location in memory that is to receive the data position, // Offset in the data reference from which you want to read length, // The number of bytes to read 0, // refCon NULL, // pointer to a schedule record - NULL for Synchronous operation NULL); // pointer to a data-handler completion function - NULL for Syncronous operation if (err) return -2; // if we read less than what caller asked for, then return error. //if (size < size_t(length)) // return -1; return 0; } //-------------------------------------------------------------------------------- int MkvReaderQT::Length(long long* total, long long* available) { if (total) *total = m_length; if (available) *available = m_length; return 0; } //-------------------------------------------------------------------------------- // MkvBufferedReaderQT::MkvBufferedReaderQT() : bufDataSize(0), bufStartFilePos(0), bufCurFilePos(0), bufEndFilePos(0), m_PendingReadSize(0) { bufDataMax = sizeof(buf); m_previousReadPos = 0; } //-------------------------------------------------------------------------------- MkvBufferedReaderQT::~MkvBufferedReaderQT() { // **** } //-------------------------------------------------------------------------------- // int MkvBufferedReaderQT::Read(long long requestedPos, long requestedLen, unsigned char* outbuf) { // **** NOTE - any dbg_print() in this function has big impact on runtime performance. //dbg_printf("MkvBufferedReaderQT::Read() - requestedPos = %lld, requestedLen = %ld\n", requestedPos, requestedLen); //dbg_printf("\tbufStartFilePos = %lld, m_buffer.size = %lu\n", bufStartFilePos, m_buffer.size()); // dbg_printf("ReadPos\t%c\t%ld\tdelta=%ld\n", (requestedPos > m_previousReadPos)?'+':'-', requestedPos, (requestedPos-m_previousReadPos)); m_previousReadPos = requestedPos; if ((requestedPos < bufStartFilePos) || (requestedPos >= bufEndFilePos) || ((requestedPos + requestedLen) > bufEndFilePos)) { // m_bufHeadPos+m_buffer.size())) { // non-contiguous read, miss dbg_printf("\tNON-CONTIGUOUS READ, CACHE MISS requestedPos = %lld, requestedLen = %ld [%ld - %ld - %ld]\n", requestedPos, requestedLen, bufStartFilePos, bufCurFilePos, bufEndFilePos); int err = this->MkvReaderQT::Read(requestedPos, requestedLen, outbuf); return err; } //dbg_printf("\tm_bufpos=%lld, requestedLen=%ld, m_buffer.size() = %lu\n", m_bufpos, requestedLen, m_buffer.size()); #if 0 // contiguous read (or empty buffer) // is the request larger than what we already have in buffer? if ((requestedPos + requestedLen - 1) > bufEndFilePos) { // (m_bufHeadPos + m_buffer.size() - 1)) { dbg_printf("\tNOT ENOUGH IN BUFFER, read from file.\n"); // not enough in buffer... // read from data handler (file) size_t growSize = (requestedLen < m_chunksize) ? m_chunksize : requestedLen; // grow buffer by chunksize or requestedLen, whichever is greater. unsigned char* tempBuf = (unsigned char*)malloc(growSize); int err = this->MkvReaderQT::Read(requestedPos, growSize, tempBuf); if (err != 0) { free(tempBuf); return err; } // append to existing buffer for (long i=0; i < growSize; i++) { m_buffer.push_back(tempBuf[i]); } free(tempBuf); } #endif //dbg_printf("\tm_buffer.front = %1x\n", m_buffer.front()); // read from buffer if (requestedLen > 0) { for (long i=0; i < requestedLen; i++) { outbuf[i] = buf[requestedPos - bufStartFilePos + i]; //outbuf[i] = m_buffer[requestedPos - bufStartFilePos + i]; //.front(); //m_buffer.pop(); //m_bufpos++; } // **** dbg_printf("BUF CACHE HIT!\n"); bufCurFilePos = (requestedPos + requestedLen); } //dbg_printf("\toutbuf[0]=%1x\n", outbuf[0]); //dbg_printf("MkvBufferedReaderQT::Read() return.\n"); //dbg_printf("\n"); return 0; } //-------------------------------------------------------------------------------- void MkvBufferedReaderQT::ReadAsync(MkvBufferedReaderQT* reader, long requestedLen) { if (reader->m_PendingReadSize != 0) { // if an async read is already pending, nop and return now. return; } dbg_printf("ReadAsync...\n"); dbg_printf("MkvBufferedReaderQT::buf %ld [%ld - %ld - %ld] %ld\n", reader->bufDataSize, reader->bufStartFilePos, reader->bufCurFilePos, reader->bufEndFilePos, reader->bufDataMax); if (reader->read_completion_cb == NULL) reader->read_completion_cb = NewDataHCompletionUPP(ReadCompletion); // if requested size wouldn't fit into available space in buffer, and currently consumed more than 3/4 of data in buffer, then compact the buffer. if ((reader->bufDataSize + requestedLen > reader->bufDataMax) && ((reader->bufCurFilePos - reader->bufStartFilePos) > (reader->bufEndFilePos - reader->bufStartFilePos) * 0.75)) { reader->CompactBuffer(requestedLen); } if (reader->bufDataSize + requestedLen <= reader->bufDataMax) { wide ofst; ofst.hi = 0; ofst.lo = reader->bufEndFilePos; reader->m_PendingReadSize = requestedLen; reader->readErr = DataHReadAsync(reader->m_dataHandler, reader->buf + reader->bufDataSize, requestedLen, &ofst, reader->read_completion_cb, (long)reader); } else { dbg_printf("MkvBufferedReaderQT::ReadAsync() FAIL - BUFFER FULL. bufDataSize=%ld, consumed=%ld\n", reader->bufDataSize, (reader->bufCurFilePos - reader->bufStartFilePos)); reader->m_PendingReadSize = 0; DataHTask(reader->m_dataHandler); //ReadCompletion(NULL, (long)reader, noErr); // **** maybe wait, and then call comletion, just to keep pump going... } } //-------------------------------------------------------------------------------- void MkvBufferedReaderQT::InitBuffer() { if ((m_PendingReadSize == 0) && (bufDataSize == 0) && (bufEndFilePos == 0)) { dbg_printf("InitBuffer (sync) ..."); long requestedLen = kReadChunkSize * 16; // **** try larger initial chunk m_PendingReadSize = requestedLen; int err = this->MkvReaderQT::Read(0, requestedLen, buf); ReadCompletion(NULL, (long)this, err); } else { dbg_printf("InitBuffer FAIL."); } } //-------------------------------------------------------------------------------- static void ReadCompletion(Ptr request, long refcon, OSErr readErr) { MkvBufferedReaderQT* reader = (MkvBufferedReaderQT*)refcon; reader->readErr = readErr; reader->bufEndFilePos += reader->m_PendingReadSize; // incr file position by amount that was just read into buf reader->bufDataSize += reader->m_PendingReadSize; // incr size of data in buf reader->m_PendingReadSize = 0; dbg_printf("...ReadCompletion (filePos=%ld)\n", reader->bufEndFilePos); long readSize = kReadChunkSize; // MkvBufferedReaderQT::kDefaultChunkSize; MkvBufferedReaderQT::ReadAsync(reader); // , readSize); use default arg } //-------------------------------------------------------------------------------- void MkvBufferedReaderQT::CompactBuffer(long requestedSize) { long remainingDataSize = (bufDataMax - bufDataSize); long consumedDataSize = (bufCurFilePos - bufStartFilePos); long killDataSize = (consumedDataSize > kReadChunkSize) ? (consumedDataSize - kReadChunkSize) : (consumedDataSize * 0.50); //* 0.5; // 0.66; // / 2; if (requestedSize > remainingDataSize) { if (killDataSize > (requestedSize - remainingDataSize)) { dbg_printf("CompactBuffer() consumedDataSize=%ld, killDataSize=%ld\n", consumedDataSize, killDataSize); memmove(&buf[0], &buf[killDataSize], (bufDataSize - killDataSize)); bufDataSize -= killDataSize; bufStartFilePos += killDataSize; } else { dbg_printf("CompactBuffer() FAIL. Wait for more data to be consumed.\n"); } } else dbg_printf("CompactBuffer() NOP, don't need to compact at this time.\n"); } <|endoftext|>
<commit_before>/********************************************************************* * * Condor ClassAd library * Copyright (C) 1990-2001, CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, WI, and Rajesh Raman. * * This library is free software; you can redistribute it and/or * modify it under the terms of version 2.1 of the 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * *********************************************************************/ #include "common.h" #include "lexer.h" #include "exprTree.h" #include "collection.h" #include "collectionBase.h" #include "classad.h" BEGIN_NAMESPACE( classad ) //-------------classad templates -------------- template map<string, bool>; // function table template map<string, void*, CaseIgnLTStr>; template map<string, void*, CaseIgnLTStr>::iterator; // XML attributes template map<string, string>; template map<string, string>::iterator; // attribute list template hash_map<string, ExprTree*, StringCaseIgnHash, CaseIgnEqStr>; template hash_map<string, ExprTree*, StringCaseIgnHash, CaseIgnEqStr>::iterator; template hash_map<string, ExprTree*, StringCaseIgnHash, CaseIgnEqStr>::const_iterator; // expr evaluation cache template hash_map<const ExprTree*, Value, ExprHash >; template hash_map<const ExprTree*, Value, ExprHash >::iterator; // component stuff template vector< pair<string, ExprTree*> >; template vector<ExprTree*>; template map<string, ClassAd *>; template map<string, ClassAdCollection *>; #ifdef CLASSAD_DISTRIBUTION template vector<string>; #include "transaction.h" #include "view.h" // view content template multiset<ViewMember, ViewMemberLT>; template multiset<ViewMember, ViewMemberLT>::iterator; // list of sub-views template slist<View*>; // view registry template hash_map<string,View*,StringHash>; template hash_map<string,View*,StringHash>::iterator; // index template hash_map<string,multiset<ViewMember,ViewMemberLT>::iterator, StringHash>::iterator; template hash_map<string,multiset<ViewMember,ViewMemberLT>::iterator, StringHash>; // main classad table template hash_map<string, ClassAdProxy, StringHash>; template hash_map<string, ClassAdProxy, StringHash>::iterator; // index file template map<string, int>; template hash_map<string,int,StringHash>; template hash_map<string,int,StringHash>::iterator; // transaction registry template hash_map<string, ServerTransaction*, StringHash>; template hash_map<string, ServerTransaction*, StringHash>::iterator; // operations in transaction template list<XactionRecord>; #endif class _ClassAdInit { public: _ClassAdInit( ) { tzset( ); } } __ClassAdInit; END_NAMESPACE <commit_msg>Change for standalone to compile with GCC 3.0. It was a goofy thing: we need to define an operator+. Francesco Giacomini figured it out for us a while ago, and I only just added it. Also added "using namespace std" for the standalong to compile well with GCC 3.0<commit_after>/********************************************************************* * * Condor ClassAd library * Copyright (C) 1990-2001, CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, WI, and Rajesh Raman. * * This library is free software; you can redistribute it and/or * modify it under the terms of version 2.1 of the 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * *********************************************************************/ #include "common.h" #include "lexer.h" #include "exprTree.h" #include "collection.h" #include "collectionBase.h" #include "classad.h" using namespace std; BEGIN_NAMESPACE( classad ) //-------------classad templates -------------- template map<string, bool>; // function table template map<string, void*, CaseIgnLTStr>; template map<string, void*, CaseIgnLTStr>::iterator; // XML attributes template map<string, string>; template map<string, string>::iterator; // attribute list template hash_map<string, ExprTree*, StringCaseIgnHash, CaseIgnEqStr>; template hash_map<string, ExprTree*, StringCaseIgnHash, CaseIgnEqStr>::iterator; template hash_map<string, ExprTree*, StringCaseIgnHash, CaseIgnEqStr>::const_iterator; // expr evaluation cache template hash_map<const ExprTree*, Value, ExprHash >; template hash_map<const ExprTree*, Value, ExprHash >::iterator; // component stuff template vector< pair<string, ExprTree*> >; template vector<ExprTree*>; template map<string, ClassAd *>; template map<string, ClassAdCollection *>; #ifdef CLASSAD_DISTRIBUTION template vector<string>; #include "transaction.h" #include "view.h" // view content template multiset<ViewMember, ViewMemberLT>; template multiset<ViewMember, ViewMemberLT>::iterator; // list of sub-views template slist<View*>; // view registry template hash_map<string,View*,StringHash>; template hash_map<string,View*,StringHash>::iterator; // index template hash_map<string,multiset<ViewMember,ViewMemberLT>::iterator, StringHash>::iterator; template hash_map<string,multiset<ViewMember,ViewMemberLT>::iterator, StringHash>; // main classad table template hash_map<string, ClassAdProxy, StringHash>; template hash_map<string, ClassAdProxy, StringHash>::iterator; // index file template map<string, int>; template hash_map<string,int,StringHash>; template hash_map<string,int,StringHash>::iterator; // transaction registry template hash_map<string, ServerTransaction*, StringHash>; template hash_map<string, ServerTransaction*, StringHash>::iterator; // operations in transaction template list<XactionRecord>; #if (__GNUC__>=3) template string std::operator+<char, std::char_traits<char>, std::allocator<char> >(const string&, const string&); #endif #endif class _ClassAdInit { public: _ClassAdInit( ) { tzset( ); } } __ClassAdInit; END_NAMESPACE <|endoftext|>
<commit_before>/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "src/core/lib/channel/channel_tracer.h" #include <grpc/grpc.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/string_util.h> #include <grpc/support/useful.h> #include <stdlib.h> #include <string.h> #include "src/core/lib/channel/object_registry.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/memory.h" #include "src/core/lib/iomgr/error.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/surface/channel.h" #include "src/core/lib/transport/connectivity_state.h" namespace grpc_core { class TraceEvent { public: TraceEvent(grpc_slice data, grpc_error* error, grpc_connectivity_state connectivity_state, ChannelTracer* referenced_tracer) : data_(data), error_(error), connectivity_state_(connectivity_state), next_(nullptr) { referenced_tracer_ = referenced_tracer ? referenced_tracer->Ref() : nullptr; time_created_ = gpr_now(GPR_CLOCK_REALTIME); } private: friend class ChannelTracer; friend class ChannelTracerRenderer; grpc_slice data_; grpc_error* error_; gpr_timespec time_created_; grpc_connectivity_state connectivity_state_; TraceEvent* next_; // the tracer object for the (sub)channel that this trace node refers to. ChannelTracer* referenced_tracer_; }; ChannelTracer::ChannelTracer(size_t max_nodes) : channel_uuid_(-1), num_nodes_logged_(0), num_children_seen_(0), list_size_(0), max_list_size_(max_nodes), head_trace_(0), tail_trace_(0) { if (!max_list_size_) return; // tracing is disabled if max_nodes == 0 gpr_mu_init(&tracer_mu_); gpr_ref_init(&refs_, 1); channel_uuid_ = grpc_object_registry_register_object( this, GRPC_OBJECT_REGISTRY_CHANNEL_TRACER); max_list_size_ = max_nodes; time_created_ = gpr_now(GPR_CLOCK_REALTIME); } ChannelTracer* ChannelTracer::Ref() { if (!max_list_size_) return nullptr; // tracing is disabled if max_nodes == 0 gpr_ref(&refs_); return this; } void ChannelTracer::FreeNode(TraceEvent* node) { GRPC_ERROR_UNREF(node->error_); if (node->referenced_tracer_) { node->referenced_tracer_->Unref(); } grpc_slice_unref_internal(node->data_); gpr_free(node); } void ChannelTracer::Unref() { if (!max_list_size_) return; // tracing is disabled if max_nodes == 0 if (gpr_unref(&refs_)) { TraceEvent* it = head_trace_; while (it != nullptr) { TraceEvent* to_free = it; it = it->next_; FreeNode(to_free); } gpr_mu_destroy(&tracer_mu_); } } intptr_t ChannelTracer::GetUuid() { return channel_uuid_; } void ChannelTracer::AddTrace(grpc_slice data, grpc_error* error, grpc_connectivity_state connectivity_state, ChannelTracer* referenced_tracer) { if (!max_list_size_) return; // tracing is disabled if max_nodes == 0 ++num_nodes_logged_; if (referenced_tracer != nullptr) ++num_children_seen_; // create and fill up the new node TraceEvent* new_trace_node = New<TraceEvent>(data, error, connectivity_state, referenced_tracer); // first node case if (head_trace_ == nullptr) { head_trace_ = tail_trace_ = new_trace_node; } // regular node add case else { tail_trace_->next_ = new_trace_node; tail_trace_ = tail_trace_->next_; } ++list_size_; // maybe garbage collect the end if (list_size_ > max_list_size_) { TraceEvent* to_free = head_trace_; head_trace_ = head_trace_->next_; FreeNode(to_free); --list_size_; } } // returns an allocated string that represents tm according to RFC-3339. static char* fmt_time(gpr_timespec tm) { char buffer[35]; struct tm* tm_info = localtime((const time_t*)&tm.tv_sec); strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%S", tm_info); char* full_time_str; gpr_asprintf(&full_time_str, "%s.%09dZ", buffer, tm.tv_nsec); return full_time_str; } // Helper class that is responsible for walking the tree of ChannelTracer // objects and rendering the trace as JSON according to: // https://github.com/grpc/proposal/pull/7 // The rendered JSON should be of this format: // { // "channelData": { // "uuid": string, // "numNodesLogged": number, // "startTime": timestamp string, // "nodes": [ // { // "data": string, // "error": string, // "time": timestamp string, // // can only be one of the states in connectivity_state.h // "state": enum string, // // uuid of referenced subchannel. // // Optional, only present if this event refers to a child object. // // and example of a referenced child would be a trace event for a // // subchannel being created. // "child_uuid": string // }, // ] // }, // // Optional, only present if this channel has children // "childData": [ // // List of child data, which is of the exact same format as the // ] // } class ChannelTracerRenderer { public: // If recursive==true, then the entire tree of trace will be rendered. // If not, then only the top level data will be. ChannelTracerRenderer(ChannelTracer* tracer, bool recursive) : current_tracer_(tracer), recursive_(recursive), seen_tracers_(nullptr), size_(0), cap_(0) {} // Renders the trace and returns an allocated char* with the formatted JSON char* Run() { grpc_json* json = grpc_json_create(GRPC_JSON_OBJECT); AddSeenTracer(current_tracer_); RecursivelyPopulateJson(json); gpr_free(seen_tracers_); char* json_str = grpc_json_dump_to_string(json, 0); grpc_json_destroy(json); return json_str; } private: // tracks that a tracer has already been rendered to avoid infinite // recursion. void AddSeenTracer(ChannelTracer* newly_seen) { if (size_ >= cap_) { cap_ = GPR_MAX(5 * sizeof(newly_seen), 3 * cap_ / 2); seen_tracers_ = (ChannelTracer**)gpr_realloc(seen_tracers_, cap_); } seen_tracers_[size_++] = newly_seen; } // Checks if a tracer has already been seen. bool TracerAlreadySeen(ChannelTracer* tracer) { for (size_t i = 0; i < size_; ++i) { if (seen_tracers_[i] == tracer) return true; } return false; } // Recursively fills up json by walking over all of the trace of // current_tracer_. Starts at the top level, by creating the fields // channelData, and childData. void RecursivelyPopulateJson(grpc_json* json) { grpc_json* channel_data = grpc_json_create_child( nullptr, json, "channelData", nullptr, GRPC_JSON_OBJECT, false); grpc_json* children = nullptr; if (recursive_) { children = grpc_json_create_child(channel_data, json, "childData", nullptr, GRPC_JSON_ARRAY, false); } PopulateChannelData(channel_data, children); } // Fills up the channelData object. If children is not null, it will // recursively populate each referenced child as it passes that node. void PopulateChannelData(grpc_json* channel_data, grpc_json* children) { grpc_json* child = nullptr; char* uuid_str; gpr_asprintf(&uuid_str, "%" PRIdPTR, current_tracer_->channel_uuid_); child = grpc_json_create_child(child, channel_data, "uuid", uuid_str, GRPC_JSON_NUMBER, true); char* num_nodes_logged_str; gpr_asprintf(&num_nodes_logged_str, "%" PRId64, current_tracer_->num_nodes_logged_); child = grpc_json_create_child(child, channel_data, "numNodesLogged", num_nodes_logged_str, GRPC_JSON_NUMBER, true); child = grpc_json_create_child(child, channel_data, "startTime", fmt_time(current_tracer_->time_created_), GRPC_JSON_STRING, true); child = grpc_json_create_child(child, channel_data, "nodes", nullptr, GRPC_JSON_ARRAY, false); PopulateNodeList(child, children); } // Iterated over the list of TraceEvents and populates their data. void PopulateNodeList(grpc_json* nodes, grpc_json* children) { grpc_json* child = nullptr; TraceEvent* it = current_tracer_->head_trace_; while (it != nullptr) { child = grpc_json_create_child(child, nodes, nullptr, nullptr, GRPC_JSON_OBJECT, false); PopulateNode(it, child, children); it = it->next_; } } // Fills in all the data for a single TraceEvent. If children is not null // and the TraceEvent refers to a child Tracer object and recursive_ is true, // then that child object will be rendered into the trace. void PopulateNode(TraceEvent* node, grpc_json* json, grpc_json* children) { grpc_json* child = nullptr; child = grpc_json_create_child(child, json, "data", grpc_slice_to_c_string(node->data_), GRPC_JSON_STRING, true); if (node->error_ != GRPC_ERROR_NONE) { child = grpc_json_create_child( child, json, "error", gpr_strdup(grpc_error_string(node->error_)), GRPC_JSON_STRING, true); } child = grpc_json_create_child(child, json, "time", fmt_time(node->time_created_), GRPC_JSON_STRING, true); child = grpc_json_create_child( child, json, "state", grpc_connectivity_state_name(node->connectivity_state_), GRPC_JSON_STRING, false); if (node->referenced_tracer_ != nullptr) { char* uuid_str; gpr_asprintf(&uuid_str, "%" PRIdPTR, node->referenced_tracer_->channel_uuid_); child = grpc_json_create_child(child, json, "uuid", uuid_str, GRPC_JSON_NUMBER, true); // If we are recursively populating everything, and this node // references a tracer we haven't seen yet, we render that tracer // in full, adding it to the parent JSON's "children" field. if (children && !TracerAlreadySeen(node->referenced_tracer_)) { grpc_json* referenced_tracer = grpc_json_create_child( nullptr, children, nullptr, nullptr, GRPC_JSON_OBJECT, false); AddSeenTracer(node->referenced_tracer_); ChannelTracer* saved = current_tracer_; current_tracer_ = node->referenced_tracer_; RecursivelyPopulateJson(referenced_tracer); current_tracer_ = saved; } } } // Tracks the current tracer we are rendering as we walk the tree of tracers. ChannelTracer* current_tracer_; // If true, we will render the data of all of this tracer's children. bool recursive_; // These members are used to track tracers we have already rendered. This is // a dynamically growing array that is deallocated when the rendering is done. ChannelTracer** seen_tracers_; size_t size_; size_t cap_; }; char* ChannelTracer::RenderTrace(bool recursive) { if (!max_list_size_) return nullptr; // tracing is disabled if max_nodes == 0 ChannelTracerRenderer renderer(this, recursive); return renderer.Run(); } char* ChannelTracer::GetChannelTraceFromUuid(intptr_t uuid, bool recursive) { void* object; grpc_object_registry_type type = grpc_object_registry_get_object(uuid, &object); GPR_ASSERT(type == GRPC_OBJECT_REGISTRY_CHANNEL_TRACER); return static_cast<ChannelTracer*>(object)->RenderTrace(recursive); } } // namespace grpc_core <commit_msg>Fix clang tidy<commit_after>/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "src/core/lib/channel/channel_tracer.h" #include <grpc/grpc.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/string_util.h> #include <grpc/support/useful.h> #include <stdlib.h> #include <string.h> #include "src/core/lib/channel/object_registry.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/memory.h" #include "src/core/lib/iomgr/error.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/surface/channel.h" #include "src/core/lib/transport/connectivity_state.h" namespace grpc_core { class TraceEvent { public: TraceEvent(grpc_slice data, grpc_error* error, grpc_connectivity_state connectivity_state, ChannelTracer* referenced_tracer) : data_(data), error_(error), connectivity_state_(connectivity_state), next_(nullptr) { referenced_tracer_ = referenced_tracer ? referenced_tracer->Ref() : nullptr; time_created_ = gpr_now(GPR_CLOCK_REALTIME); } private: friend class ChannelTracer; friend class ChannelTracerRenderer; grpc_slice data_; grpc_error* error_; gpr_timespec time_created_; grpc_connectivity_state connectivity_state_; TraceEvent* next_; // the tracer object for the (sub)channel that this trace node refers to. ChannelTracer* referenced_tracer_; }; ChannelTracer::ChannelTracer(size_t max_nodes) : channel_uuid_(-1), num_nodes_logged_(0), num_children_seen_(0), list_size_(0), max_list_size_(max_nodes), head_trace_(nullptr), tail_trace_(nullptr) { if (!max_list_size_) return; // tracing is disabled if max_nodes == 0 gpr_mu_init(&tracer_mu_); gpr_ref_init(&refs_, 1); channel_uuid_ = grpc_object_registry_register_object( this, GRPC_OBJECT_REGISTRY_CHANNEL_TRACER); max_list_size_ = max_nodes; time_created_ = gpr_now(GPR_CLOCK_REALTIME); } ChannelTracer* ChannelTracer::Ref() { if (!max_list_size_) return nullptr; // tracing is disabled if max_nodes == 0 gpr_ref(&refs_); return this; } void ChannelTracer::FreeNode(TraceEvent* node) { GRPC_ERROR_UNREF(node->error_); if (node->referenced_tracer_) { node->referenced_tracer_->Unref(); } grpc_slice_unref_internal(node->data_); gpr_free(node); } void ChannelTracer::Unref() { if (!max_list_size_) return; // tracing is disabled if max_nodes == 0 if (gpr_unref(&refs_)) { TraceEvent* it = head_trace_; while (it != nullptr) { TraceEvent* to_free = it; it = it->next_; FreeNode(to_free); } gpr_mu_destroy(&tracer_mu_); } } intptr_t ChannelTracer::GetUuid() { return channel_uuid_; } void ChannelTracer::AddTrace(grpc_slice data, grpc_error* error, grpc_connectivity_state connectivity_state, ChannelTracer* referenced_tracer) { if (!max_list_size_) return; // tracing is disabled if max_nodes == 0 ++num_nodes_logged_; if (referenced_tracer != nullptr) ++num_children_seen_; // create and fill up the new node TraceEvent* new_trace_node = New<TraceEvent>(data, error, connectivity_state, referenced_tracer); // first node case if (head_trace_ == nullptr) { head_trace_ = tail_trace_ = new_trace_node; } // regular node add case else { tail_trace_->next_ = new_trace_node; tail_trace_ = tail_trace_->next_; } ++list_size_; // maybe garbage collect the end if (list_size_ > max_list_size_) { TraceEvent* to_free = head_trace_; head_trace_ = head_trace_->next_; FreeNode(to_free); --list_size_; } } // returns an allocated string that represents tm according to RFC-3339. static char* fmt_time(gpr_timespec tm) { char buffer[35]; struct tm* tm_info = localtime((const time_t*)&tm.tv_sec); strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%S", tm_info); char* full_time_str; gpr_asprintf(&full_time_str, "%s.%09dZ", buffer, tm.tv_nsec); return full_time_str; } // Helper class that is responsible for walking the tree of ChannelTracer // objects and rendering the trace as JSON according to: // https://github.com/grpc/proposal/pull/7 // The rendered JSON should be of this format: // { // "channelData": { // "uuid": string, // "numNodesLogged": number, // "startTime": timestamp string, // "nodes": [ // { // "data": string, // "error": string, // "time": timestamp string, // // can only be one of the states in connectivity_state.h // "state": enum string, // // uuid of referenced subchannel. // // Optional, only present if this event refers to a child object. // // and example of a referenced child would be a trace event for a // // subchannel being created. // "child_uuid": string // }, // ] // }, // // Optional, only present if this channel has children // "childData": [ // // List of child data, which is of the exact same format as the // ] // } class ChannelTracerRenderer { public: // If recursive==true, then the entire tree of trace will be rendered. // If not, then only the top level data will be. ChannelTracerRenderer(ChannelTracer* tracer, bool recursive) : current_tracer_(tracer), recursive_(recursive), seen_tracers_(nullptr), size_(0), cap_(0) {} // Renders the trace and returns an allocated char* with the formatted JSON char* Run() { grpc_json* json = grpc_json_create(GRPC_JSON_OBJECT); AddSeenTracer(current_tracer_); RecursivelyPopulateJson(json); gpr_free(seen_tracers_); char* json_str = grpc_json_dump_to_string(json, 0); grpc_json_destroy(json); return json_str; } private: // tracks that a tracer has already been rendered to avoid infinite // recursion. void AddSeenTracer(ChannelTracer* newly_seen) { if (size_ >= cap_) { cap_ = GPR_MAX(5 * sizeof(newly_seen), 3 * cap_ / 2); seen_tracers_ = (ChannelTracer**)gpr_realloc(seen_tracers_, cap_); } seen_tracers_[size_++] = newly_seen; } // Checks if a tracer has already been seen. bool TracerAlreadySeen(ChannelTracer* tracer) { for (size_t i = 0; i < size_; ++i) { if (seen_tracers_[i] == tracer) return true; } return false; } // Recursively fills up json by walking over all of the trace of // current_tracer_. Starts at the top level, by creating the fields // channelData, and childData. void RecursivelyPopulateJson(grpc_json* json) { grpc_json* channel_data = grpc_json_create_child( nullptr, json, "channelData", nullptr, GRPC_JSON_OBJECT, false); grpc_json* children = nullptr; if (recursive_) { children = grpc_json_create_child(channel_data, json, "childData", nullptr, GRPC_JSON_ARRAY, false); } PopulateChannelData(channel_data, children); } // Fills up the channelData object. If children is not null, it will // recursively populate each referenced child as it passes that node. void PopulateChannelData(grpc_json* channel_data, grpc_json* children) { grpc_json* child = nullptr; char* uuid_str; gpr_asprintf(&uuid_str, "%" PRIdPTR, current_tracer_->channel_uuid_); child = grpc_json_create_child(child, channel_data, "uuid", uuid_str, GRPC_JSON_NUMBER, true); char* num_nodes_logged_str; gpr_asprintf(&num_nodes_logged_str, "%" PRId64, current_tracer_->num_nodes_logged_); child = grpc_json_create_child(child, channel_data, "numNodesLogged", num_nodes_logged_str, GRPC_JSON_NUMBER, true); child = grpc_json_create_child(child, channel_data, "startTime", fmt_time(current_tracer_->time_created_), GRPC_JSON_STRING, true); child = grpc_json_create_child(child, channel_data, "nodes", nullptr, GRPC_JSON_ARRAY, false); PopulateNodeList(child, children); } // Iterated over the list of TraceEvents and populates their data. void PopulateNodeList(grpc_json* nodes, grpc_json* children) { grpc_json* child = nullptr; TraceEvent* it = current_tracer_->head_trace_; while (it != nullptr) { child = grpc_json_create_child(child, nodes, nullptr, nullptr, GRPC_JSON_OBJECT, false); PopulateNode(it, child, children); it = it->next_; } } // Fills in all the data for a single TraceEvent. If children is not null // and the TraceEvent refers to a child Tracer object and recursive_ is true, // then that child object will be rendered into the trace. void PopulateNode(TraceEvent* node, grpc_json* json, grpc_json* children) { grpc_json* child = nullptr; child = grpc_json_create_child(child, json, "data", grpc_slice_to_c_string(node->data_), GRPC_JSON_STRING, true); if (node->error_ != GRPC_ERROR_NONE) { child = grpc_json_create_child( child, json, "error", gpr_strdup(grpc_error_string(node->error_)), GRPC_JSON_STRING, true); } child = grpc_json_create_child(child, json, "time", fmt_time(node->time_created_), GRPC_JSON_STRING, true); child = grpc_json_create_child( child, json, "state", grpc_connectivity_state_name(node->connectivity_state_), GRPC_JSON_STRING, false); if (node->referenced_tracer_ != nullptr) { char* uuid_str; gpr_asprintf(&uuid_str, "%" PRIdPTR, node->referenced_tracer_->channel_uuid_); child = grpc_json_create_child(child, json, "uuid", uuid_str, GRPC_JSON_NUMBER, true); // If we are recursively populating everything, and this node // references a tracer we haven't seen yet, we render that tracer // in full, adding it to the parent JSON's "children" field. if (children && !TracerAlreadySeen(node->referenced_tracer_)) { grpc_json* referenced_tracer = grpc_json_create_child( nullptr, children, nullptr, nullptr, GRPC_JSON_OBJECT, false); AddSeenTracer(node->referenced_tracer_); ChannelTracer* saved = current_tracer_; current_tracer_ = node->referenced_tracer_; RecursivelyPopulateJson(referenced_tracer); current_tracer_ = saved; } } } // Tracks the current tracer we are rendering as we walk the tree of tracers. ChannelTracer* current_tracer_; // If true, we will render the data of all of this tracer's children. bool recursive_; // These members are used to track tracers we have already rendered. This is // a dynamically growing array that is deallocated when the rendering is done. ChannelTracer** seen_tracers_; size_t size_; size_t cap_; }; char* ChannelTracer::RenderTrace(bool recursive) { if (!max_list_size_) return nullptr; // tracing is disabled if max_nodes == 0 ChannelTracerRenderer renderer(this, recursive); return renderer.Run(); } char* ChannelTracer::GetChannelTraceFromUuid(intptr_t uuid, bool recursive) { void* object; grpc_object_registry_type type = grpc_object_registry_get_object(uuid, &object); GPR_ASSERT(type == GRPC_OBJECT_REGISTRY_CHANNEL_TRACER); return static_cast<ChannelTracer*>(object)->RenderTrace(recursive); } } // namespace grpc_core <|endoftext|>
<commit_before>// definition of necessary units static const double cm=1; static const double cm3=cm*cm*cm; static const double volt=1; static const double C=1; // Coulomb static const double Qe=-1.6e-19*C; // eletron charge static const double epsilon0=8.854187817e-14*C/volt/cm; // vacuum permittivity // https://link.springer.com/chapter/10.1007/10832182_519 static const double epsilonGe=15.8; // Ge dielectric constant //______________________________________________________________________________ // V"(x)=a, https://www.wolframalpha.com/input/?i=V%27%27(x)%3Da double V(double *coordinates, double *parameters) { double x = coordinates[0]; // there is no y and z dependence double x0= 0*cm; // lower electrode double x1= parameters[0]; // upper electrode double v0= 0*volt; // lower voltage double v1= parameters[1]; // upper voltage double rho=parameters[2]*Qe;// space charge density [C/cm3] double a =-rho/epsilon0/epsilonGe; double c2= (v1-v0)/(x1-x0) - a/2*(x1+x0); double c1= (v0*x1-v1*x0)/(x1-x0) + a/2*x0*x1; return a*x*x/2 + c2*x + c1; } //______________________________________________________________________________ // search for depletion voltage of a planar detector given impurity & thickness double GetVdep(double impurity, double thickness, double vupper) { if (impurity==0) return 0; // nothing to deplete TF1 *det=new TF1("det", V, 0, thickness, 3); // potential distr. double bias, vlower=0*volt; // range of search while (abs(vupper-vlower)>1e-3*volt) { // binary search bias=(vupper+vlower)/2; // bias voltage det->SetParameters(thickness, bias, impurity); if (det->Derivative(0)*det->Derivative(thickness)<0) vlower=bias; else vupper=bias; } return bias; } //______________________________________________________________________________ // draw results void getVd(int type=1, double thickness=1*cm) { const int n=10; // number of points double impurity[n]={1e9/cm3, 2e9/cm3, 4e9/cm3, 8e9/cm3, 1e10/cm3, 2e10/cm3, 4e10/cm3, 8e10/cm3, 1e11/cm3, 1.2e11/cm3}; // p-type if (type==-1) for (int i=0; i<n; i++) impurity[i]*=type; // n-type double absi[n], vdep[n]; for (int i=0; i<n; i++) { vdep[i] = GetVdep(impurity[i], thickness, type*-2e4*volt); absi[i] = abs(impurity[i]); } gROOT->SetStyle("Plain"); // pick up a good default drawing style // modify the default style gStyle->SetLegendBorderSize(0); gStyle->SetLegendFont(132); gStyle->SetLabelFont(132,"XY"); gStyle->SetTitleFont(132,"XY"); gStyle->SetLabelSize(0.05,"XY"); gStyle->SetTitleSize(0.05,"XY"); gStyle->SetTitleOffset(1.1,"XY"); gStyle->SetPadRightMargin(0.01); gStyle->SetPadLeftMargin(0.11); gStyle->SetPadTopMargin(0.01); gStyle->SetPadBottomMargin(0.12); // Vdep VS impurity TGraph *g = new TGraph(n,absi,vdep); g->SetTitle(";Net Impurity [cm^{-3}];Depletion Voltage [V]"); g->Draw("apc"); TText *t1 = new TText(2e9, 6000, Form( "%.0f cm thick planar detector", thickness/cm)); t1->Draw(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy(); gPad->Print("depleted.png"); // voltage VS thickness TCanvas *c = new TCanvas; double bias = -1000*volt; // p-type if(type==-1) bias = 1000*volt; // n-type // over depleted TF1 *fvo=new TF1("fvo", V, 0, thickness, 3); fvo->SetParameters(thickness, vdep[6]+bias, impurity[6]); fvo->SetTitle(";Thickness [cm]; Voltage [V]"); fvo->SetLineColor(kMagenta); fvo->SetLineStyle(2); fvo->GetXaxis()->SetTitleOffset(1.1); fvo->Draw(); // depleted TF1 *fvd=new TF1("fvd", V, 0, thickness, 3); fvd->SetParameters(thickness, vdep[6], impurity[6]); fvd->Draw("same"); // undepleted TF1 *fvu=new TF1("fvu", V, 0, thickness, 3); fvu->SetParameters(thickness, bias, impurity[6]); fvu->SetLineColor(kRed); fvu->SetLineStyle(3); fvu->Draw("same"); // potential due to bias alone TF1 *fvb=new TF1("fvb", V, 0, thickness, 3); fvb->SetParameters(thickness, bias, 0/cm3); fvb->SetLineColor(kBlue); fvb->SetLineStyle(4); fvb->Draw("same"); // potential due to space charges alone TF1 *fvc=new TF1("fvc", V, 0, thickness, 3); fvc->SetParameters(thickness, 0*volt, impurity[6]); fvc->SetLineColor(kGreen); fvc->SetLineStyle(5); fvc->Draw("same"); if (type==-1) { // draw lines and texts for n-type TLine *l1 = new TLine(0,bias/volt,thickness/cm,bias/volt); l1->SetLineStyle(kDashed); l1->Draw(); TLine *l2 = new TLine(0,vdep[6]/volt,thickness/cm,vdep[6]/volt); l2->SetLineStyle(kDashed); l2->Draw(); TLine *l3=new TLine(0,(vdep[6]+bias)/volt,thickness/cm,(vdep[6]+bias)/volt); l3->SetLineStyle(kDashed); l3->Draw(); TText *t2 = new TText(0.04,bias/volt+20,Form("%.0f V", bias/volt)); t2->SetTextFont(132); t2->Draw(); TText *t3 = new TText(0.04,vdep[6]/volt+20, Form("%.0f V", vdep[6]/volt)); t3->SetTextFont(132); t3->Draw(); TText *t4 = new TText(0.04,(vdep[6]+bias)/volt+20, Form("%.0f V", (vdep[6]+bias)/volt)); t4->Draw(); TText *t5 = new TText(0.5, 2800, "over depleted"); t5->SetTextFont(132); t5->SetTextColor(kMagenta); t5->Draw(); TText *t6 = new TText(0.8, 2310, "just depleted"); t6->SetTextFont(132); t6->Draw(); TText *t7 = new TText(0.65, 1250, "undepleted"); t7->SetTextFont(132); t7->SetTextColor(kRed); t7->Draw(); TText *t8 = new TText(0.65, 800, "bias alone"); t8->SetTextFont(132); t8->SetTextColor(kBlue); t8->Draw(); TText *t9 = new TText(0.55, 200, "space charges alone"); t9->SetTextFont(132); t9->SetTextColor(kGreen); t9->Draw(); TLatex *t10 = new TLatex(0.1, 2700, Form("Impurity: %.0e/cm^{3}",impurity[6]/cm3)); t10->SetTextFont(132); t10->Draw(); } else { // draw lines and texts for p-type TLine *l0 = new TLine(0,0,thickness/cm,0); l0->SetLineStyle(kDashed); l0->Draw(); TLine *l1 = new TLine(0,bias/volt,thickness/cm,bias/volt); l1->SetLineStyle(kDashed); l1->Draw(); TLine *l2 = new TLine(0,vdep[6]/volt,thickness/cm,vdep[6]/volt); l2->SetLineStyle(kDashed); l2->Draw(); TLine *l3=new TLine(0,(vdep[6]+bias)/volt,thickness/cm,(vdep[6]+bias)/volt); l3->SetLineStyle(kDashed); l3->Draw(); TText *t2 = new TText(0.04,bias/volt+20,Form("%.0f V", bias/volt)); t2->SetTextFont(132); t2->Draw(); TText *t3 = new TText(0.04,vdep[6]/volt+20, Form("%.0f V", vdep[6]/volt)); t3->SetTextFont(132); t3->Draw(); TText *t4 = new TText(0.04,(vdep[6]+bias)/volt+20, Form("%.0f V", (vdep[6]+bias)/volt)); t4->SetTextFont(132); t4->Draw(); TText *t5 = new TText(0.5, -3100, "over depleted"); t5->SetTextFont(132); t5->SetTextColor(kMagenta); t5->Draw(); TText *t6 = new TText(0.76, -2500, "just depleted"); t6->SetTextFont(132); t6->Draw(); TText *t7 = new TText(0.65, -1400, "undepleted"); t7->SetTextFont(132); t7->SetTextColor(kRed); t7->Draw(); TText *t8 = new TText(0.6, -900, "bias alone"); t8->SetTextFont(132); t8->SetTextColor(kBlue); t8->Draw(); TText *t9 = new TText(0.5, -200, "space charges alone"); t9->SetTextFont(132); t9->SetTextColor(kGreen); t9->Draw(); TLatex *t10 = new TLatex(0.1, -2700, Form("Impurity: %.0e/cm^{3}",impurity[6]/cm3)); t10->SetTextFont(132); t10->Draw(); } c->Print("undepleted.png"); } <commit_msg>fine tuned text position<commit_after>// definition of necessary units static const double cm=1; static const double cm3=cm*cm*cm; static const double volt=1; static const double C=1; // Coulomb static const double Qe=-1.6e-19*C; // eletron charge static const double epsilon0=8.854187817e-14*C/volt/cm; // vacuum permittivity // https://link.springer.com/chapter/10.1007/10832182_519 static const double epsilonGe=15.8; // Ge dielectric constant //______________________________________________________________________________ // V"(x)=a, https://www.wolframalpha.com/input/?i=V%27%27(x)%3Da double V(double *coordinates, double *parameters) { double x = coordinates[0]; // there is no y and z dependence double x0= 0*cm; // lower electrode double x1= parameters[0]; // upper electrode double v0= 0*volt; // lower voltage double v1= parameters[1]; // upper voltage double rho=parameters[2]*Qe;// space charge density [C/cm3] double a =-rho/epsilon0/epsilonGe; double c2= (v1-v0)/(x1-x0) - a/2*(x1+x0); double c1= (v0*x1-v1*x0)/(x1-x0) + a/2*x0*x1; return a*x*x/2 + c2*x + c1; } //______________________________________________________________________________ // search for depletion voltage of a planar detector given impurity & thickness double GetVdep(double impurity, double thickness, double vupper) { if (impurity==0) return 0; // nothing to deplete TF1 *det=new TF1("det", V, 0, thickness, 3); // potential distr. double bias, vlower=0*volt; // range of search while (abs(vupper-vlower)>1e-3*volt) { // binary search bias=(vupper+vlower)/2; // bias voltage det->SetParameters(thickness, bias, impurity); if (det->Derivative(0)*det->Derivative(thickness)<0) vlower=bias; else vupper=bias; } return bias; } //______________________________________________________________________________ // draw results void getVd(int type=1, double thickness=1*cm) { const int n=10; // number of points double impurity[n]={1e9/cm3, 2e9/cm3, 4e9/cm3, 8e9/cm3, 1e10/cm3, 2e10/cm3, 4e10/cm3, 8e10/cm3, 1e11/cm3, 1.2e11/cm3}; // p-type if (type==-1) for (int i=0; i<n; i++) impurity[i]*=type; // n-type double absi[n], vdep[n]; for (int i=0; i<n; i++) { vdep[i] = GetVdep(impurity[i], thickness, type*-2e4*volt); absi[i] = abs(impurity[i]); } gROOT->SetStyle("Plain"); // pick up a good default drawing style to modify // modify the default style gStyle->SetLegendBorderSize(0); gStyle->SetLegendFont(132); gStyle->SetLabelFont(132,"XY"); gStyle->SetTitleFont(132,"XY"); gStyle->SetLabelSize(0.05,"XY"); gStyle->SetTitleSize(0.05,"XY"); gStyle->SetTitleOffset(1.1,"XY"); gStyle->SetPadRightMargin(0.01); gStyle->SetPadLeftMargin(0.11); gStyle->SetPadTopMargin(0.01); gStyle->SetPadBottomMargin(0.12); // Vdep VS impurity TGraph *g = new TGraph(n,absi,vdep); g->SetTitle(";Net Impurity [cm^{-3}];Depletion Voltage [V]"); g->Draw("apc"); TText *t1 = new TText(2e9, 6000, Form("%.0f cm thick planar detector", thickness/cm)); t1->Draw(); gPad->SetLogx(); gPad->SetGridx(); gPad->SetGridy(); gPad->Print("depleted.png"); // voltage VS thickness double bias = -1000*volt*type; TCanvas *c = new TCanvas; // over depleted TF1 *fvo=new TF1("fvo", V, 0, thickness, 3); fvo->SetParameters(thickness, vdep[6]+bias, impurity[6]); fvo->SetTitle(";Thickness [cm]; Voltage [V]"); fvo->SetLineColor(kMagenta); fvo->SetLineStyle(2); fvo->GetXaxis()->SetTitleOffset(1.1); fvo->Draw(); // depleted TF1 *fvd=new TF1("fvd", V, 0, thickness, 3); fvd->SetParameters(thickness, vdep[6], impurity[6]); fvd->Draw("same"); // undepleted TF1 *fvu=new TF1("fvu", V, 0, thickness, 3); fvu->SetParameters(thickness, bias, impurity[6]); fvu->SetLineColor(kRed); fvu->SetLineStyle(3); fvu->Draw("same"); // potential due to bias alone TF1 *fvb=new TF1("fvb", V, 0, thickness, 3); fvb->SetParameters(thickness, bias, 0/cm3); fvb->SetLineColor(kBlue); fvb->SetLineStyle(4); fvb->Draw("same"); // potential due to space charges alone TF1 *fvc=new TF1("fvc", V, 0, thickness, 3); fvc->SetParameters(thickness, 0*volt, impurity[6]); fvc->SetLineColor(kGreen); fvc->SetLineStyle(5); fvc->Draw("same"); if (type==-1) { // draw lines and texts for n-type TLine *l1 = new TLine(0,bias/volt,thickness/cm,bias/volt); l1->SetLineStyle(kDashed); l1->Draw(); TLine *l2 = new TLine(0,vdep[6]/volt,thickness/cm,vdep[6]/volt); l2->SetLineStyle(kDashed); l2->Draw(); TLine *l3=new TLine(0,(vdep[6]+bias)/volt,thickness/cm,(vdep[6]+bias)/volt); l3->SetLineStyle(kDashed); l3->Draw(); TText *t2 = new TText(0.04,bias/volt+20,Form("%.0f V", bias/volt)); t2->SetTextFont(132); t2->Draw(); TText *t3 = new TText(0.04,vdep[6]/volt+20, Form("%.0f V", vdep[6]/volt)); t3->SetTextFont(132); t3->Draw(); TText *t4 = new TText(0.04,(vdep[6]+bias)/volt+20, Form("%.0f V", (vdep[6]+bias)/volt)); t4->Draw(); TText *t5 = new TText(0.5, 2800, "over depleted"); t5->SetTextFont(132); t5->SetTextColor(kMagenta); t5->Draw(); TText *t6 = new TText(0.8, 2310, "just depleted"); t6->SetTextFont(132); t6->Draw(); TText *t7 = new TText(0.65, 1250, "undepleted"); t7->SetTextFont(132); t7->SetTextColor(kRed); t7->Draw(); TText *t8 = new TText(0.65, 800, "bias alone"); t8->SetTextFont(132); t8->SetTextColor(kBlue); t8->Draw(); TText *t9 = new TText(0.55, 200, "space charges alone"); t9->SetTextFont(132); t9->SetTextColor(kGreen); t9->Draw(); TLatex *t10 = new TLatex(0.1, 2700, Form("Impurity: %.0e/cm^{3}",impurity[6]/cm3)); t10->SetTextFont(132); t10->Draw(); } else { // draw lines and texts for p-type TLine *l0 = new TLine(0,0,thickness/cm,0); l0->SetLineStyle(kDashed); l0->Draw(); TLine *l1 = new TLine(0,bias/volt,thickness/cm,bias/volt); l1->SetLineStyle(kDashed); l1->Draw(); TLine *l2 = new TLine(0,vdep[6]/volt,thickness/cm,vdep[6]/volt); l2->SetLineStyle(kDashed); l2->Draw(); TLine *l3=new TLine(0,(vdep[6]+bias)/volt,thickness/cm,(vdep[6]+bias)/volt); l3->SetLineStyle(kDashed); l3->Draw(); TText *t2 = new TText(0.04,bias/volt+20,Form("%.0f V", bias/volt)); t2->SetTextFont(132); t2->Draw(); TText *t3 = new TText(0.04,vdep[6]/volt+20, Form("%.0f V", vdep[6]/volt)); t3->SetTextFont(132); t3->Draw(); TText *t4 = new TText(0.04,(vdep[6]+bias)/volt+20, Form("%.0f V", (vdep[6]+bias)/volt)); t4->SetTextFont(132); t4->Draw(); TText *t5 = new TText(0.76, -2850, "over depleted"); t5->SetTextFont(132); t5->SetTextAngle(-19); t5->SetTextColor(kMagenta); t5->Draw(); TText *t6 = new TText(0.8, -2120, "just depleted"); t6->SetTextFont(132); t6->SetTextAngle(-9); t6->Draw(); TText *t7 = new TText(0.65, -1350, "undepleted"); t7->SetTextFont(132); t7->SetTextColor(kRed); t7->Draw(); TText *t8 = new TText(0.75, -700, "bias alone"); t8->SetTextFont(132); t8->SetTextAngle(-11.5); t8->SetTextColor(kBlue); t8->Draw(); TText *t9 = new TText(0.65, -450, "space charges alone"); t9->SetTextFont(132); t9->SetTextAngle(12.5); t9->SetTextColor(kGreen); t9->Draw(); TLatex *t10 = new TLatex(0.15, -2800, Form("Impurity: %.0e/cm^{3}",impurity[6]/cm3)); t10->SetTextFont(132); t10->Draw(); } c->Print("undepleted.png"); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ndole.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: kz $ $Date: 2004-10-04 18:59:21 $ * * 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 _NDOLE_HXX #define _NDOLE_HXX #ifndef _NDNOTXT_HXX #include <ndnotxt.hxx> #endif #include <svtools/embedhlp.hxx> class SwGrfFmtColl; class SwDoc; class SwOLENode; class SwOLELink; class SwOLELRUCache; class SwOLEListener_Impl; class SwOLEObj { friend class SwOLENode; static SwOLELRUCache* pOLELRU_Cache; const SwOLENode* pOLENd; SwOLEListener_Impl* pListener; //Entweder Ref oder Name sind bekannt, wenn nur der Name bekannt ist, wird //dir Ref bei Anforderung durch GetOleRef() vom Sfx besorgt. svt::EmbeddedObjectRef xOLERef; //com::sun::star::uno::Reference < com::sun::star::embed::XEmbeddedObject > xOLERef; String aName; SwOLEObj( const SwOLEObj& rObj ); //nicht erlaubt. SwOLEObj(); void SetNode( SwOLENode* pNode ); public: SwOLEObj( const svt::EmbeddedObjectRef& pObj ); SwOLEObj( const String &rName ); ~SwOLEObj(); BOOL RemovedFromLRU(); String GetDescription(); #ifndef _FESHVIEW_ONLY_INLINE_NEEDED com::sun::star::uno::Reference < com::sun::star::embed::XEmbeddedObject > GetOleRef(); svt::EmbeddedObjectRef& GetObject(); // const String &GetName() const { return aName; } const String& GetCurrentPersistName() const { return aName; } BOOL IsOleRef() const; //Damit das Objekt nicht unnoetig geladen werden muss. #endif }; // -------------------- // SwOLENode // -------------------- class SwOLENode: public SwNoTxtNode { friend class SwNodes; mutable SwOLEObj aOLEObj; Graphic* pGraphic; sal_Int64 nViewAspect; String sChartTblName; // bei Chart Objecten: Name der ref. Tabelle BOOL bOLESizeInvalid; //Soll beim SwDoc::PrtOLENotify beruecksichtig //werden (zum Beispiel kopiert). Ist nicht //Persistent. SwOLENode( const SwNodeIndex &rWhere, const svt::EmbeddedObjectRef&, SwGrfFmtColl *pGrfColl, SwAttrSet* pAutoAttr = 0 ); SwOLENode( const SwNodeIndex &rWhere, const String &rName, SwGrfFmtColl *pGrfColl, SwAttrSet* pAutoAttr = 0 ); // aOLEObj besitzt einen privaten Copy-CTOR, wir brauchen auch einen: SwOLENode( const SwOLENode & ); public: const SwOLEObj& GetOLEObj() const { return aOLEObj; } SwOLEObj& GetOLEObj() { return aOLEObj; } ~SwOLENode(); virtual SwCntntNode *SplitNode( const SwPosition & ); // steht in ndcopy.cxx virtual SwCntntNode* MakeCopy( SwDoc*, const SwNodeIndex& ) const; virtual Size GetTwipSize() const; Graphic* GetGraphic(); void GetNewReplacement(); virtual BOOL SavePersistentData(); virtual BOOL RestorePersistentData(); BOOL IsInGlobalDocSection() const; BOOL IsOLEObjectDeleted() const; BOOL IsOLESizeInvalid() const { return bOLESizeInvalid; } void SetOLESizeInvalid( BOOL b ){ bOLESizeInvalid = b; } sal_Int64 GetAspect() const { return nViewAspect; } void SetAspect( sal_Int64 nAspect) { nViewAspect = nAspect; } // OLE-Object aus dem "Speicher" entfernen // inline void Unload() { aOLEObj.Unload(); } String GetDescription() const { return aOLEObj.GetDescription(); } #ifndef _FESHVIEW_ONLY_INLINE_NEEDED const String& GetChartTblName() const { return sChartTblName; } void SetChartTblName( const String& rNm ) { sChartTblName = rNm; } #endif }; // Inline Metoden aus Node.hxx - erst hier ist der TxtNode bekannt !! inline SwOLENode *SwNode::GetOLENode() { return ND_OLENODE == nNodeType ? (SwOLENode*)this : 0; } inline const SwOLENode *SwNode::GetOLENode() const { return ND_OLENODE == nNodeType ? (const SwOLENode*)this : 0; } #endif // _NDOLE_HXX <commit_msg>INTEGRATION: CWS leanobjects (1.8.122); FILE MERGED 2004/11/18 11:08:20 mba 1.8.122.1: #i37278#: make objects loadable on demand<commit_after>/************************************************************************* * * $RCSfile: ndole.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2004-11-26 16:25:39 $ * * 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 _NDOLE_HXX #define _NDOLE_HXX #ifndef _NDNOTXT_HXX #include <ndnotxt.hxx> #endif #include <svtools/embedhlp.hxx> class SwGrfFmtColl; class SwDoc; class SwOLENode; class SwOLELink; class SwOLEListener_Impl; class SwOLEObj { friend class SwOLENode; const SwOLENode* pOLENd; SwOLEListener_Impl* pListener; //Entweder Ref oder Name sind bekannt, wenn nur der Name bekannt ist, wird //dir Ref bei Anforderung durch GetOleRef() vom Sfx besorgt. svt::EmbeddedObjectRef xOLERef; String aName; SwOLEObj( const SwOLEObj& rObj ); //nicht erlaubt. SwOLEObj(); void SetNode( SwOLENode* pNode ); public: SwOLEObj( const svt::EmbeddedObjectRef& pObj ); SwOLEObj( const String &rName ); ~SwOLEObj(); BOOL UnloadObject(); String GetDescription(); #ifndef _FESHVIEW_ONLY_INLINE_NEEDED com::sun::star::uno::Reference < com::sun::star::embed::XEmbeddedObject > GetOleRef(); svt::EmbeddedObjectRef& GetObject(); const String& GetCurrentPersistName() const { return aName; } BOOL IsOleRef() const; //Damit das Objekt nicht unnoetig geladen werden muss. #endif }; // -------------------- // SwOLENode // -------------------- class SwOLENode: public SwNoTxtNode { friend class SwNodes; mutable SwOLEObj aOLEObj; Graphic* pGraphic; sal_Int64 nViewAspect; String sChartTblName; // bei Chart Objecten: Name der ref. Tabelle BOOL bOLESizeInvalid; //Soll beim SwDoc::PrtOLENotify beruecksichtig //werden (zum Beispiel kopiert). Ist nicht //Persistent. SwOLENode( const SwNodeIndex &rWhere, const svt::EmbeddedObjectRef&, SwGrfFmtColl *pGrfColl, SwAttrSet* pAutoAttr = 0 ); SwOLENode( const SwNodeIndex &rWhere, const String &rName, SwGrfFmtColl *pGrfColl, SwAttrSet* pAutoAttr = 0 ); // aOLEObj besitzt einen privaten Copy-CTOR, wir brauchen auch einen: SwOLENode( const SwOLENode & ); public: const SwOLEObj& GetOLEObj() const { return aOLEObj; } SwOLEObj& GetOLEObj() { return aOLEObj; } ~SwOLENode(); virtual SwCntntNode *SplitNode( const SwPosition & ); // steht in ndcopy.cxx virtual SwCntntNode* MakeCopy( SwDoc*, const SwNodeIndex& ) const; virtual Size GetTwipSize() const; Graphic* GetGraphic(); void GetNewReplacement(); virtual BOOL SavePersistentData(); virtual BOOL RestorePersistentData(); BOOL IsInGlobalDocSection() const; BOOL IsOLEObjectDeleted() const; BOOL IsOLESizeInvalid() const { return bOLESizeInvalid; } void SetOLESizeInvalid( BOOL b ){ bOLESizeInvalid = b; } sal_Int64 GetAspect() const { return nViewAspect; } void SetAspect( sal_Int64 nAspect) { nViewAspect = nAspect; } // OLE-Object aus dem "Speicher" entfernen // inline void Unload() { aOLEObj.Unload(); } String GetDescription() const { return aOLEObj.GetDescription(); } #ifndef _FESHVIEW_ONLY_INLINE_NEEDED const String& GetChartTblName() const { return sChartTblName; } void SetChartTblName( const String& rNm ) { sChartTblName = rNm; } #endif }; // Inline Metoden aus Node.hxx - erst hier ist der TxtNode bekannt !! inline SwOLENode *SwNode::GetOLENode() { return ND_OLENODE == nNodeType ? (SwOLENode*)this : 0; } inline const SwOLENode *SwNode::GetOLENode() const { return ND_OLENODE == nNodeType ? (const SwOLENode*)this : 0; } #endif // _NDOLE_HXX <|endoftext|>
<commit_before>// Catch #include <catch.hpp> // C++ Standard Library #include <memory> // Mantella #include <mantella> class TestHillClimbing : public mant::HillClimbing { public: TestHillClimbing( const std::shared_ptr<mant::OptimisationProblem> optimisationProblem) : mant::HillClimbing(optimisationProblem), neighboursIndex_(0){ } void setVelocitys(arma::mat neighbours){ neighbours_ = neighbours; } protected: arma::Col<double> getRandomNeighbour(const arma::Col<double>& parameter, const double minimalDistance, const double maximalDistance) override { return neighbours_.col(neighboursIndex_++); } unsigned int neighboursIndex_; arma::mat neighbours_; }; TEST_CASE("HillClimbing", "") { SECTION(".setMaximalStepSize") { std::shared_ptr<mant::OptimisationProblem> optimisationProblem(new mant::bbob::SphereFunction(2)); mant::HillClimbing hillClimbing(optimisationProblem); SECTION("Test default value"){ //TODO } SECTION("Test with parameter") { //TODO } } SECTION(".optimise") { // TODO } SECTION("Exception tests") { std::shared_ptr<mant::OptimisationProblem> optimisationProblem(new mant::bbob::SphereFunction(2)); mant::HillClimbing hillClimbing(optimisationProblem); SECTION("Throws an exception, if the MaximalStepSize zero") { // CHECK_THROWS_AS(hillClimbing.setMaximalStepSize({0, 0}), std::logic_error); } SECTION("Throws an exception, if the size of MaximalStepSize is not equal to the number of dimension of the problem") { // CHECK_THROWS_AS(hillClimbing.setMaximalStepSize({100, 100, 100}), std::logic_error); // CHECK_THROWS_AS(hillClimbing.setMaximalStepSize({100}), std::logic_error); } } SECTION(".toString") { SECTION("Returns the expected class name.") { std::shared_ptr<mant::OptimisationProblem> optimisationProblem(new mant::bbob::SphereFunction(2)); CHECK(mant::HillClimbing(optimisationProblem).toString() == "hill_climbing"); } } } <commit_msg>Minor code style fixes<commit_after>// Catch #include <catch.hpp> // C++ Standard Library #include <memory> // Mantella #include <mantella> class TestHillClimbing : public mant::HillClimbing { public: TestHillClimbing( const std::shared_ptr<mant::OptimisationProblem> optimisationProblem) : mant::HillClimbing(optimisationProblem), neighboursIndex_(0){ } void setVelocitys( const arma::Mat<double>& neighbours){ neighbours_ = neighbours; } protected: arma::Col<double> getRandomNeighbour(const arma::Col<double>& parameter, const double minimalDistance, const double maximalDistance) override { return neighbours_.col(neighboursIndex_++); } unsigned int neighboursIndex_; arma::mat neighbours_; }; TEST_CASE("HillClimbing", "") { SECTION(".setMaximalStepSize") { std::shared_ptr<mant::OptimisationProblem> optimisationProblem(new mant::bbob::SphereFunction(2)); mant::HillClimbing hillClimbing(optimisationProblem); SECTION("Test default value"){ //TODO } SECTION("Test with parameter") { //TODO } } SECTION(".optimise") { // TODO } SECTION("Exception tests") { std::shared_ptr<mant::OptimisationProblem> optimisationProblem(new mant::bbob::SphereFunction(2)); mant::HillClimbing hillClimbing(optimisationProblem); SECTION("Throws an exception, if the MaximalStepSize zero") { // CHECK_THROWS_AS(hillClimbing.setMaximalStepSize({0, 0}), std::logic_error); } SECTION("Throws an exception, if the size of MaximalStepSize is not equal to the number of dimension of the problem") { // CHECK_THROWS_AS(hillClimbing.setMaximalStepSize({100, 100, 100}), std::logic_error); // CHECK_THROWS_AS(hillClimbing.setMaximalStepSize({100}), std::logic_error); } } SECTION(".toString") { SECTION("Returns the expected class name.") { std::shared_ptr<mant::OptimisationProblem> optimisationProblem(new mant::bbob::SphereFunction(2)); CHECK(mant::HillClimbing(optimisationProblem).toString() == "hill_climbing"); } } } <|endoftext|>
<commit_before>#ifdef ENABLE_MPI #include "CellCommunicator.h" /*! * \param sysdef System definition * \param cl MPCD cell list */ mpcd::CellCommunicator::CellCommunicator(std::shared_ptr<SystemDefinition> sysdef, std::shared_ptr<mpcd::CellList> cl) : m_sysdef(sysdef), m_pdata(sysdef->getParticleData()), m_exec_conf(m_pdata->getExecConf()), m_mpi_comm(m_exec_conf->getMPICommunicator()), m_decomposition(m_pdata->getDomainDecomposition()), m_cl(cl), m_communicating(false), m_send_buf(m_exec_conf), m_recv_buf(m_exec_conf), m_needs_init(true) { m_exec_conf->msg->notice(5) << "Constructing MPCD CellCommunicator" << std::endl; #ifdef ENABLE_CUDA if (m_exec_conf->isCUDAEnabled()) { m_tuner_pack.reset(new Autotuner(32, 1024, 32, 5, 100000, "mpcd_cell_comm_pack", m_exec_conf)); m_tuner_unpack.reset(new Autotuner(32, 1024, 32, 5, 100000, "mpcd_cell_comm_unpack", m_exec_conf)); } #endif // ENABLE_CUDA m_cl->getSizeChangeSignal().connect<mpcd::CellCommunicator, &mpcd::CellCommunicator::slotInit>(this); } mpcd::CellCommunicator::~CellCommunicator() { m_exec_conf->msg->notice(5) << "Destroying MPCD CellCommunicator" << std::endl; m_cl->getSizeChangeSignal().disconnect<mpcd::CellCommunicator, &mpcd::CellCommunicator::slotInit>(this); } namespace mpcd { namespace detail { //! Unary operator to wrap global cell indexes into the local domain struct LocalCellWrapOp { LocalCellWrapOp(std::shared_ptr<mpcd::CellList> cl_) : cl(cl_), ci(cl_->getCellIndexer()), gci(cl_->getGlobalCellIndexer()) { } //! Transform the global 1D cell index into a local 1D cell index inline unsigned int operator()(unsigned int cell_idx) { // convert the 1D global cell index to a global cell tuple const uint3 cell = gci.getTriple(cell_idx); // convert the global cell tuple to a local cell tuple int3 local_cell = cl->getLocalCell(make_int3(cell.x, cell.y, cell.z)); // wrap the local cell through the global boundaries, which should work for all reasonable cell comms. if (local_cell.x >= (int)gci.getW()) local_cell.x -= gci.getW(); else if (local_cell.x < 0) local_cell.x += gci.getW(); if (local_cell.y >= (int)gci.getH()) local_cell.y -= gci.getH(); else if (local_cell.y < 0) local_cell.y += gci.getH(); if (local_cell.z >= (int)gci.getD()) local_cell.z -= gci.getD(); else if (local_cell.z < 0) local_cell.z += gci.getD(); // convert the local cell tuple back to an index return ci(local_cell.x, local_cell.y, local_cell.z); } std::shared_ptr<mpcd::CellList> cl; //!< Cell list const Index3D ci; //!< Cell indexer const Index3D gci; //!< Global cell indexer }; } // end namespace detail } // end namespace mpcd void mpcd::CellCommunicator::initialize() { // obtain domain decomposition const Index3D& di = m_decomposition->getDomainIndexer(); ArrayHandle<unsigned int> h_cart_ranks(m_decomposition->getCartRanks(), access_location::host, access_mode::read); const uint3 my_pos = m_decomposition->getGridPos(); // use the cell list to compute the bounds const Index3D& ci = m_cl->getCellIndexer(); const Index3D& global_ci = m_cl->getGlobalCellIndexer(); auto num_comm_cells = m_cl->getNComm(); const uint3 max_lo = make_uint3(num_comm_cells[static_cast<unsigned int>(mpcd::detail::face::west)], num_comm_cells[static_cast<unsigned int>(mpcd::detail::face::south)], num_comm_cells[static_cast<unsigned int>(mpcd::detail::face::down)]); const uint3 min_hi = make_uint3(ci.getW() - num_comm_cells[static_cast<unsigned int>(mpcd::detail::face::east)], ci.getH() - num_comm_cells[static_cast<unsigned int>(mpcd::detail::face::north)], ci.getD() - num_comm_cells[static_cast<unsigned int>(mpcd::detail::face::up)]); // check to make sure box is not overdecomposed { const unsigned int nextra = m_cl->getNExtraCells(); unsigned int err = ((max_lo.x + nextra) > min_hi.x || (max_lo.y + nextra) > min_hi.y || (max_lo.z + nextra) > min_hi.z); MPI_Allreduce(MPI_IN_PLACE, &err, 1, MPI_UNSIGNED, MPI_MAX, m_mpi_comm); if (err) { m_exec_conf->msg->error() << "mpcd: Simulation box is overdecomposed, decrease the number of ranks." << std::endl; throw std::runtime_error("Simulation box is overdecomposed for MPCD"); } } // loop over all cells in the grid and determine where to send them std::multimap<unsigned int, unsigned int> send_map; std::set<unsigned int> neighbors; for (unsigned int k=0; k < ci.getD(); ++k) { for (unsigned int j=0; j < ci.getH(); ++j) { for (unsigned int i=0; i < ci.getW(); ++i) { // skip any cells interior to the grid, which will not be communicated // this is wasteful loop logic, but initialize will only be called rarely if (i >= max_lo.x && i < min_hi.x && j >= max_lo.y && j < min_hi.y && k >= max_lo.z && k < min_hi.z) continue; // obtain the 1D global index of this cell const int3 global_cell = m_cl->getGlobalCell(make_int3(i,j,k)); const unsigned int global_cell_idx = global_ci(global_cell.x, global_cell.y, global_cell.z); // check which direction the cell lies off rank in x,y,z std::vector<int> dx = {0}; if (i < max_lo.x) dx.push_back(-1); else if (i >= min_hi.x) dx.push_back(1); std::vector<int> dy = {0}; if (j < max_lo.y) dy.push_back(-1); else if (j >= min_hi.y) dy.push_back(1); std::vector<int> dz = {0}; if (k < max_lo.z) dz.push_back(-1); else if (k >= min_hi.z) dz.push_back(1); // generate all permutations of these neighbors for the cell for (auto ddx = dx.begin(); ddx != dx.end(); ++ddx) { for (auto ddy = dy.begin(); ddy != dy.end(); ++ddy) { for (auto ddz = dz.begin(); ddz != dz.end(); ++ddz) { // skip self if (*ddx == 0 && *ddy == 0 && *ddz == 0) continue; // get neighbor rank tuple int3 neigh = make_int3((int)my_pos.x + *ddx, (int)my_pos.y + *ddy, (int)my_pos.z + *ddz); // wrap neighbor through the boundaries if (neigh.x < 0) neigh.x += di.getW(); else if (neigh.x >= (int)di.getW()) neigh.x -= di.getW(); if (neigh.y < 0) neigh.y += di.getH(); else if (neigh.y >= (int)di.getH()) neigh.y -= di.getH(); if (neigh.z < 0) neigh.z += di.getD(); else if (neigh.z >= (int)di.getD()) neigh.z -= di.getD(); // convert neighbor to a linear rank and push it into the unique neighbor set const unsigned int neigh_rank = h_cart_ranks.data[di(neigh.x,neigh.y,neigh.z)]; neighbors.insert(neigh_rank); send_map.insert(std::make_pair(neigh_rank, global_cell_idx)); } // ddz } // ddy } // ddx } // i } // j } // k // allocate send / receive index arrays { GPUArray<unsigned int> send_idx(send_map.size(), m_exec_conf); m_send_idx.swap(send_idx); } // fill the send indexes with the global values // flood the array of unique neighbors and count the number to send { ArrayHandle<unsigned int> h_send_idx(m_send_idx, access_location::host, access_mode::overwrite); unsigned int idx = 0; for (auto it = send_map.begin(); it != send_map.end(); ++it) { h_send_idx.data[idx++] = it->second; } m_neighbors.resize(neighbors.size()); m_begin.resize(m_neighbors.size()); m_num_send.resize(m_neighbors.size()); idx = 0; for (auto it = neighbors.begin(); it != neighbors.end(); ++it) { auto lower = send_map.lower_bound(*it); auto upper = send_map.upper_bound(*it); m_neighbors[idx] = *it; m_begin[idx] = std::distance(send_map.begin(), lower); m_num_send[idx] = std::distance(lower, upper); ++idx; } } // send / receive the global cell indexes to be communicated with neighbors std::vector<unsigned int> recv_idx(m_send_idx.getNumElements()); { ArrayHandle<unsigned int> h_send_idx(m_send_idx, access_location::host, access_mode::read); m_reqs.resize(2*m_neighbors.size()); for (unsigned int idx=0; idx < m_neighbors.size(); ++idx) { const unsigned int offset = m_begin[idx]; MPI_Isend(h_send_idx.data + offset, m_num_send[idx], MPI_INT, m_neighbors[idx], 0, m_mpi_comm, &m_reqs[2*idx]); MPI_Irecv(recv_idx.data() + offset, m_num_send[idx], MPI_INT, m_neighbors[idx], 0, m_mpi_comm, &m_reqs[2*idx+1]); } MPI_Waitall(m_reqs.size(), m_reqs.data(), MPI_STATUSES_IGNORE); } // transform all of the global cell indexes back into local cell indexes { ArrayHandle<unsigned int> h_send_idx(m_send_idx, access_location::host, access_mode::readwrite); mpcd::detail::LocalCellWrapOp wrapper(m_cl); std::transform(h_send_idx.data, h_send_idx.data + m_send_idx.getNumElements(), h_send_idx.data, wrapper); std::transform(recv_idx.begin(), recv_idx.end(), recv_idx.begin(), wrapper); } // map the received cells from a rank-basis to a cell-basis { std::multimap<unsigned int, unsigned int> cell_map; std::set<unsigned int> unique_cells; for (unsigned int idx=0; idx < recv_idx.size(); ++idx) { const unsigned int cell = recv_idx[idx]; unique_cells.insert(cell); cell_map.insert(std::make_pair(cell, idx)); } m_num_cells = unique_cells.size(); /* * Allocate auxiliary memory for receiving cell reordering */ { GPUArray<unsigned int> recv(recv_idx.size(), m_exec_conf); m_recv.swap(recv); GPUArray<unsigned int> cells(m_num_cells, m_exec_conf); m_cells.swap(cells); GPUArray<unsigned int> recv_begin(m_num_cells, m_exec_conf); m_recv_begin.swap(recv_begin); GPUArray<unsigned int> recv_end(m_num_cells, m_exec_conf); m_recv_end.swap(recv_end); } /* * Write out the resorted cells from the map, and determine the range of data belonging to each received cell */ ArrayHandle<unsigned int> h_recv(m_recv, access_location::host, access_mode::overwrite); unsigned int idx = 0; for (auto it = cell_map.begin(); it != cell_map.end(); ++it) { h_recv.data[idx++] = it->second; } ArrayHandle<unsigned int> h_cells(m_cells, access_location::host, access_mode::overwrite); ArrayHandle<unsigned int> h_recv_begin(m_recv_begin, access_location::host, access_mode::overwrite); ArrayHandle<unsigned int> h_recv_end(m_recv_end, access_location::host, access_mode::overwrite); idx = 0; for (auto it = unique_cells.begin(); it != unique_cells.end(); ++it) { auto lower = cell_map.lower_bound(*it); auto upper = cell_map.upper_bound(*it); h_cells.data[idx] = *it; h_recv_begin.data[idx] = std::distance(cell_map.begin(), lower); h_recv_end.data[idx] = std::distance(cell_map.begin(), upper); ++idx; } } } #endif // ENABLE_MPI <commit_msg>Use a linear search on the map for performance<commit_after>#ifdef ENABLE_MPI #include "CellCommunicator.h" /*! * \param sysdef System definition * \param cl MPCD cell list */ mpcd::CellCommunicator::CellCommunicator(std::shared_ptr<SystemDefinition> sysdef, std::shared_ptr<mpcd::CellList> cl) : m_sysdef(sysdef), m_pdata(sysdef->getParticleData()), m_exec_conf(m_pdata->getExecConf()), m_mpi_comm(m_exec_conf->getMPICommunicator()), m_decomposition(m_pdata->getDomainDecomposition()), m_cl(cl), m_communicating(false), m_send_buf(m_exec_conf), m_recv_buf(m_exec_conf), m_needs_init(true) { m_exec_conf->msg->notice(5) << "Constructing MPCD CellCommunicator" << std::endl; #ifdef ENABLE_CUDA if (m_exec_conf->isCUDAEnabled()) { m_tuner_pack.reset(new Autotuner(32, 1024, 32, 5, 100000, "mpcd_cell_comm_pack", m_exec_conf)); m_tuner_unpack.reset(new Autotuner(32, 1024, 32, 5, 100000, "mpcd_cell_comm_unpack", m_exec_conf)); } #endif // ENABLE_CUDA m_cl->getSizeChangeSignal().connect<mpcd::CellCommunicator, &mpcd::CellCommunicator::slotInit>(this); } mpcd::CellCommunicator::~CellCommunicator() { m_exec_conf->msg->notice(5) << "Destroying MPCD CellCommunicator" << std::endl; m_cl->getSizeChangeSignal().disconnect<mpcd::CellCommunicator, &mpcd::CellCommunicator::slotInit>(this); } namespace mpcd { namespace detail { //! Unary operator to wrap global cell indexes into the local domain struct LocalCellWrapOp { LocalCellWrapOp(std::shared_ptr<mpcd::CellList> cl_) : cl(cl_), ci(cl_->getCellIndexer()), gci(cl_->getGlobalCellIndexer()) { } //! Transform the global 1D cell index into a local 1D cell index inline unsigned int operator()(unsigned int cell_idx) { // convert the 1D global cell index to a global cell tuple const uint3 cell = gci.getTriple(cell_idx); // convert the global cell tuple to a local cell tuple int3 local_cell = cl->getLocalCell(make_int3(cell.x, cell.y, cell.z)); // wrap the local cell through the global boundaries, which should work for all reasonable cell comms. if (local_cell.x >= (int)gci.getW()) local_cell.x -= gci.getW(); else if (local_cell.x < 0) local_cell.x += gci.getW(); if (local_cell.y >= (int)gci.getH()) local_cell.y -= gci.getH(); else if (local_cell.y < 0) local_cell.y += gci.getH(); if (local_cell.z >= (int)gci.getD()) local_cell.z -= gci.getD(); else if (local_cell.z < 0) local_cell.z += gci.getD(); // convert the local cell tuple back to an index return ci(local_cell.x, local_cell.y, local_cell.z); } std::shared_ptr<mpcd::CellList> cl; //!< Cell list const Index3D ci; //!< Cell indexer const Index3D gci; //!< Global cell indexer }; } // end namespace detail } // end namespace mpcd void mpcd::CellCommunicator::initialize() { // obtain domain decomposition const Index3D& di = m_decomposition->getDomainIndexer(); ArrayHandle<unsigned int> h_cart_ranks(m_decomposition->getCartRanks(), access_location::host, access_mode::read); const uint3 my_pos = m_decomposition->getGridPos(); // use the cell list to compute the bounds const Index3D& ci = m_cl->getCellIndexer(); const Index3D& global_ci = m_cl->getGlobalCellIndexer(); auto num_comm_cells = m_cl->getNComm(); const uint3 max_lo = make_uint3(num_comm_cells[static_cast<unsigned int>(mpcd::detail::face::west)], num_comm_cells[static_cast<unsigned int>(mpcd::detail::face::south)], num_comm_cells[static_cast<unsigned int>(mpcd::detail::face::down)]); const uint3 min_hi = make_uint3(ci.getW() - num_comm_cells[static_cast<unsigned int>(mpcd::detail::face::east)], ci.getH() - num_comm_cells[static_cast<unsigned int>(mpcd::detail::face::north)], ci.getD() - num_comm_cells[static_cast<unsigned int>(mpcd::detail::face::up)]); // check to make sure box is not overdecomposed { const unsigned int nextra = m_cl->getNExtraCells(); unsigned int err = ((max_lo.x + nextra) > min_hi.x || (max_lo.y + nextra) > min_hi.y || (max_lo.z + nextra) > min_hi.z); MPI_Allreduce(MPI_IN_PLACE, &err, 1, MPI_UNSIGNED, MPI_MAX, m_mpi_comm); if (err) { m_exec_conf->msg->error() << "mpcd: Simulation box is overdecomposed, decrease the number of ranks." << std::endl; throw std::runtime_error("Simulation box is overdecomposed for MPCD"); } } // loop over all cells in the grid and determine where to send them std::multimap<unsigned int, unsigned int> send_map; std::set<unsigned int> neighbors; for (unsigned int k=0; k < ci.getD(); ++k) { for (unsigned int j=0; j < ci.getH(); ++j) { for (unsigned int i=0; i < ci.getW(); ++i) { // skip any cells interior to the grid, which will not be communicated // this is wasteful loop logic, but initialize will only be called rarely if (i >= max_lo.x && i < min_hi.x && j >= max_lo.y && j < min_hi.y && k >= max_lo.z && k < min_hi.z) continue; // obtain the 1D global index of this cell const int3 global_cell = m_cl->getGlobalCell(make_int3(i,j,k)); const unsigned int global_cell_idx = global_ci(global_cell.x, global_cell.y, global_cell.z); // check which direction the cell lies off rank in x,y,z std::vector<int> dx = {0}; if (i < max_lo.x) dx.push_back(-1); else if (i >= min_hi.x) dx.push_back(1); std::vector<int> dy = {0}; if (j < max_lo.y) dy.push_back(-1); else if (j >= min_hi.y) dy.push_back(1); std::vector<int> dz = {0}; if (k < max_lo.z) dz.push_back(-1); else if (k >= min_hi.z) dz.push_back(1); // generate all permutations of these neighbors for the cell for (auto ddx = dx.begin(); ddx != dx.end(); ++ddx) { for (auto ddy = dy.begin(); ddy != dy.end(); ++ddy) { for (auto ddz = dz.begin(); ddz != dz.end(); ++ddz) { // skip self if (*ddx == 0 && *ddy == 0 && *ddz == 0) continue; // get neighbor rank tuple int3 neigh = make_int3((int)my_pos.x + *ddx, (int)my_pos.y + *ddy, (int)my_pos.z + *ddz); // wrap neighbor through the boundaries if (neigh.x < 0) neigh.x += di.getW(); else if (neigh.x >= (int)di.getW()) neigh.x -= di.getW(); if (neigh.y < 0) neigh.y += di.getH(); else if (neigh.y >= (int)di.getH()) neigh.y -= di.getH(); if (neigh.z < 0) neigh.z += di.getD(); else if (neigh.z >= (int)di.getD()) neigh.z -= di.getD(); // convert neighbor to a linear rank and push it into the unique neighbor set const unsigned int neigh_rank = h_cart_ranks.data[di(neigh.x,neigh.y,neigh.z)]; neighbors.insert(neigh_rank); send_map.insert(std::make_pair(neigh_rank, global_cell_idx)); } // ddz } // ddy } // ddx } // i } // j } // k // allocate send / receive index arrays { GPUArray<unsigned int> send_idx(send_map.size(), m_exec_conf); m_send_idx.swap(send_idx); } // fill the send indexes with the global values // flood the array of unique neighbors and count the number to send { ArrayHandle<unsigned int> h_send_idx(m_send_idx, access_location::host, access_mode::overwrite); unsigned int idx = 0; for (auto it = send_map.begin(); it != send_map.end(); ++it) { h_send_idx.data[idx++] = it->second; } m_neighbors.resize(neighbors.size()); m_begin.resize(m_neighbors.size()); m_num_send.resize(m_neighbors.size()); idx = 0; for (auto it = neighbors.begin(); it != neighbors.end(); ++it) { auto lower = send_map.lower_bound(*it); auto upper = send_map.upper_bound(*it); m_neighbors[idx] = *it; m_begin[idx] = std::distance(send_map.begin(), lower); m_num_send[idx] = std::distance(lower, upper); ++idx; } } // send / receive the global cell indexes to be communicated with neighbors std::vector<unsigned int> recv_idx(m_send_idx.getNumElements()); { ArrayHandle<unsigned int> h_send_idx(m_send_idx, access_location::host, access_mode::read); m_reqs.resize(2*m_neighbors.size()); for (unsigned int idx=0; idx < m_neighbors.size(); ++idx) { const unsigned int offset = m_begin[idx]; MPI_Isend(h_send_idx.data + offset, m_num_send[idx], MPI_INT, m_neighbors[idx], 0, m_mpi_comm, &m_reqs[2*idx]); MPI_Irecv(recv_idx.data() + offset, m_num_send[idx], MPI_INT, m_neighbors[idx], 0, m_mpi_comm, &m_reqs[2*idx+1]); } MPI_Waitall(m_reqs.size(), m_reqs.data(), MPI_STATUSES_IGNORE); } // transform all of the global cell indexes back into local cell indexes { ArrayHandle<unsigned int> h_send_idx(m_send_idx, access_location::host, access_mode::readwrite); mpcd::detail::LocalCellWrapOp wrapper(m_cl); std::transform(h_send_idx.data, h_send_idx.data + m_send_idx.getNumElements(), h_send_idx.data, wrapper); std::transform(recv_idx.begin(), recv_idx.end(), recv_idx.begin(), wrapper); } // map the received cells from a rank-basis to a cell-basis { std::multimap<unsigned int, unsigned int> cell_map; std::set<unsigned int> unique_cells; for (unsigned int idx=0; idx < recv_idx.size(); ++idx) { const unsigned int cell = recv_idx[idx]; unique_cells.insert(cell); cell_map.insert(std::make_pair(cell, idx)); } m_num_cells = unique_cells.size(); /* * Allocate auxiliary memory for receiving cell reordering */ { GPUArray<unsigned int> recv(recv_idx.size(), m_exec_conf); m_recv.swap(recv); GPUArray<unsigned int> cells(m_num_cells, m_exec_conf); m_cells.swap(cells); GPUArray<unsigned int> recv_begin(m_num_cells, m_exec_conf); m_recv_begin.swap(recv_begin); GPUArray<unsigned int> recv_end(m_num_cells, m_exec_conf); m_recv_end.swap(recv_end); } /* * Generate the compacted list of unique cells */ ArrayHandle<unsigned int> h_cells(m_cells, access_location::host, access_mode::overwrite); idx = 0; for (auto it = unique_cells.begin(); it != unique_cells.end(); ++it) { h_cells.data[idx++] = *it; } /* * Loop over the cell map to do run-length encoding on the keys. This * determines the range of data belonging to each received cell. */ ArrayHandle<unsigned int> h_recv_begin(m_recv_begin, access_location::host, access_mode::overwrite); ArrayHandle<unsigned int> h_recv_end(m_recv_end, access_location::host, access_mode::overwrite); unsigned int last_cell = UINT_MAX; unsigned int cell_idx = 0; idx = 0; h_recv_begin.data[cell_idx] = idx; for (auto it = cell_map.begin(); it != cell_map.end(); ++it) { // record the sorted receive index h_recv.data[idx] = it->second; // if not very first pass and the current cell does not match the // last cell, then we are on a new cell, and need to demark an end / begin if (last_cell != UINT_MAX && it->first != last_cell) { h_recv_end.data[cell_idx] = idx; h_recv_begin.data[++cell_idx] = idx; } last_cell = it->first; ++idx; } h_recv_end.data[cell_idx] = idx; } } #endif // ENABLE_MPI <|endoftext|>
<commit_before>// // @author @Yue Wang @shbling @Soyn @Yue Wang // // Exercise 10.24: // Use bind and check_size to find the first element in a vector of ints that has a value greater // than the length of a specified string value. // // Discussion over this exercise on StackOverflow // http://stackoverflow.com/questions/20539406/what-type-does-stdfind-if-not-return // #include <iostream> #include <string> #include <vector> #include <algorithm> #include <functional> using std::cout; using std::endl; using std::string; using std::vector; using std::find_if; using std::bind; inline auto check_size(string const& s, string::size_type sz) -> bool { return s.size() < sz; } inline auto find_first_greater(vector<int> const& v, string const& s) -> vector<int>::const_iterator { auto lambda = [&](int i){ return i >= 0 && bind(check_size, s, i)(); }; return find_if(v.cbegin(), v.cend(), lambda); } int main() { vector<int> v{ -1, -2, 3, 4, 5, 6, 7 }; string s("test"); cout << *find_first_greater(v, s) << endl; return 0; } <commit_msg>fix : #345 with C++14 syntax<commit_after>// // @author @Yue Wang @shbling @Soyn @Yue Wang // // Exercise 10.24: // Use bind and check_size to find the first element in a vector of ints that has a value greater // than the length of a specified string value. // // Discussion over this exercise on StackOverflow // http://stackoverflow.com/questions/20539406/what-type-does-stdfind-if-not-return // #include <iostream> #include <vector> #include <algorithm> #include <functional> using std::cout; using std::endl; using std::string; using std::vector; using std::find_if; using std::bind; using std::size_t; auto check_size(string const& str, size_t sz) { return str.size() < sz; } auto find_first_greater(vector<int> const& v, string const& str) { auto predicate = [&](int i){ return bind(check_size, str, i)(); }; return find_if(v.cbegin(), v.cend(), predicate); } int main() { vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 }; string str("123456"); auto result = find_first_greater(vec, str); if (result != vec.cend()) cout << *result << endl; else cout << "Not found" << endl; return 0; } <|endoftext|>
<commit_before>#include "dcdsupport.h" #include "dlangdebughelper.h" #include <dlangoptionspage.h> #include <stdexcept> #include <QProcess> #include <QTextStream> #include <QDebug> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/project.h> #include <cpptools/cppmodelmanager.h> using namespace Dcd; DcdClient::DcdClient(const QString &projectName, const QString &processName, int port, QObject *parent) : QObject(parent), m_projectName(projectName), m_port(port), m_processName(processName) { m_portArguments << QLatin1String("--port") << QString::number(port); } const QString &DcdClient::projectName() const { return m_projectName; } void DcdClient::setOutputFile(const QString &filePath) { m_filePath = filePath; } void startProcess(QProcess &p, const QString &processName, const QStringList &args, const QString &filePath, QIODevice::OpenMode mode = QIODevice::ReadWrite) { if (p.state() != QProcess::NotRunning) { throw std::runtime_error("process is already running"); } if (!filePath.isEmpty()) { p.setStandardOutputFile(filePath, QIODevice::Append | QIODevice::Unbuffered); p.setStandardErrorFile(filePath, QIODevice::Append | QIODevice::Unbuffered); } p.start(processName, args, mode); if (!p.waitForStarted(1000)) { throw std::runtime_error("process start timeout"); } } void waitForFinished(QProcess &p) { if (!p.waitForFinished(1000)) { throw std::runtime_error("process finish timeout"); } if (p.exitStatus() != QProcess::NormalExit || p.exitCode() != 0) { throw std::runtime_error(p.readAllStandardError().data()); } } void DcdClient::complete(const QString &filePath, int position, CompletionList &result) { DEBUG_GUARD(""); QStringList args = m_portArguments; args << QLatin1String("-c") + QString::number(position) << filePath; QProcess process; startProcess(process, m_processName, args, m_filePath); waitForFinished(process); QByteArray array(process.readAllStandardOutput()); return parseOutput(array, result); } void DcdClient::completeFromArray(const QString &array, int position, DcdClient::CompletionList &result) { DEBUG_GUARD(QString::number(position)); QStringList args = m_portArguments; args << QLatin1String("-c") + QString::number(position); QProcess process; startProcess(process, m_processName, args, m_filePath); process.write(array.toLatin1()); if (!process.waitForBytesWritten(5000)) { throw std::runtime_error("process writing data timeout"); } process.closeWriteChannel(); waitForFinished(process); QByteArray output(process.readAllStandardOutput()); return parseOutput(output, result); } void DcdClient::appendIncludePath(const QString &includePath) { DEBUG_GUARD(""); QStringList args = m_portArguments; args << QLatin1String("-I") + includePath; QProcess process; startProcess(process, m_processName, args, m_filePath); waitForFinished(process); } void DcdClient::findSymbolLocation(const QString &array, int position, DcdClient::Location &result) { DEBUG_GUARD(QString::number(position)); QStringList args = m_portArguments; args << QLatin1String("-c") + QString::number(position) << "-l"; QProcess process; startProcess(process, m_processName, args, m_filePath); process.write(array.toLatin1()); if (!process.waitForBytesWritten(2000)) { throw std::runtime_error("process writing data timeout"); } process.closeWriteChannel(); waitForFinished(process); QString str(process.readAllStandardOutput()); QStringList list = str.split('\t'); result = list.size() == 2 ? Location(list.front(), list.back().toInt()) : Location(QString(), 0); } void DcdClient::getDocumentationComments(const QString &array, int position, QStringList &result) { DEBUG_GUARD(QString::number(position)); QStringList args = m_portArguments; args << QLatin1String("-c") + QString::number(position) << "-d"; QProcess process; startProcess(process, m_processName, args, m_filePath); process.write(array.toLatin1()); if (!process.waitForBytesWritten(2000)) { throw std::runtime_error("process writing data timeout"); } process.closeWriteChannel(); waitForFinished(process); QString str(process.readAllStandardOutput()); result = str.split('\n'); } void DcdClient::parseOutput(const QByteArray &output, DcdClient::CompletionList &result) { result.list.clear(); result.type = DCD_BAD_TYPE; QTextStream stream(output); QString line = stream.readLine(); if (line == QLatin1String("identifiers")) { return parseIdentifiers(stream, result); } else if (line == QLatin1String("calltips")) { return parseCalltips(stream, result); } else if (line.isEmpty()) { return; } else { throw std::runtime_error("unknown output type"); } } void DcdClient::parseIdentifiers(QTextStream &stream, DcdClient::CompletionList &result) { QString line; do { line = stream.readLine(); if (line.isNull() || line.isEmpty()) break; QStringList tokens = line.split(QLatin1Char('\t')); if (tokens.size() != 2) { throw std::runtime_error("Failed to parse identifiers"); } result.type = DCD_IDENTIFIER; result.list.push_back(DcdCompletion()); result.list.back().data = tokens.front(); result.list.back().type = DcdCompletion::fromString(tokens.back()); } while (stream.status() == QTextStream::Ok); } void DcdClient::parseCalltips(QTextStream &stream, DcdClient::CompletionList &result) { QString line; do { line = stream.readLine(); if (line.isNull() || line.isEmpty()) break; result.type = DCD_CALLTIP; result.list.push_back(DcdCompletion()); result.list.back().data = line; result.list.back().type = DcdCompletion::DCD_NO_TYPE; } while (stream.status() == QTextStream::Ok); } DcdCompletion::IdentifierType DcdCompletion::fromString(const QString &name) { char c = name.at(0).toLatin1(); switch (c) { case 'c': return DCD_CLASS; case 'i': return DCD_INTERFACE; case 's': return DCD_STRUCT; case 'u': return DCD_UNION; case 'v': return DCD_VAR; case 'm': return DCD_MEMBER_VAR; case 'k': return DCD_KEYWORD; case 'f': return DCD_FUNCTION; case 'g': return DCD_ENUM_NAME; case 'e': return DCD_ENUM_VAR; case 'P': return DCD_PACKAGE; case 'M': return DCD_MODULE; case 'a': return DCD_ARRAY; case 'A': return DCD_ASSOC_ARRAY; case 'l': return DCD_ALIAS; case 't': return DCD_TEMPLATE; case 'T': return DCD_MIXIN; default: return DCD_NO_TYPE; } return DCD_NO_TYPE; } DcdServer::DcdServer(const QString& projectName, const QString &processName, int port, QObject *parent) : QObject(parent), m_projectName(projectName), m_port(port), m_processName(processName) { m_process = new QProcess(this); connect(m_process, SIGNAL(finished(int)), this, SLOT(onFinished(int))); connect(m_process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(onError(QProcess::ProcessError))); } DcdServer::~DcdServer() { DEBUG_GUARD(""); stop(); m_process->waitForFinished(10000); } int DcdServer::port() const { return m_port; } const QString &DcdServer::projectName() const { return m_projectName; } void DcdServer::setOutputFile(const QString &filePath) { m_filePath = filePath; } void DcdServer::start() { startProcess(*m_process, m_processName, QStringList() << QLatin1String("--port") << QString::number(m_port), m_filePath); } void DcdServer::stop() { m_process->kill(); } bool DcdServer::isRunning() const { return (m_process && m_process->state() == QProcess::Running); } void DcdServer::onFinished(int errorCode) { qDebug() << "DCD server finished"; if (errorCode != 0) { emit error(tr("DCD server process has been terminated with exit code %1").arg(errorCode)); qWarning("DCD server: %s", static_cast<QProcess*>(sender())->readAllStandardError().data()); } } void DcdServer::onError(QProcess::ProcessError error) { qDebug() << "DCD server error"; switch (error) { case QProcess::FailedToStart: emit this->error(tr("DCD server failed to start")); break; case QProcess::Crashed: emit this->error(tr("DCD server crashed")); break; case QProcess::Timedout: emit this->error(tr("DCD server starting timeout")); break; default: emit this->error(tr("DCD server unknown error")); break; } stop(); } // Factory DcdFactory::ClientPointer DcdFactory::client(const QString &projectName) { try { MapString::iterator it = mapChannels.find(projectName); if (it == mapChannels.end()) { int port = m_firstPort + currentPortOffset % (m_lastPort - m_firstPort + 1); ServerPointer server(new Dcd::DcdServer(projectName, DlangEditor::DlangOptionsPage::dcdServerExecutable(), port, this)); server->setOutputFile(DlangEditor::DlangOptionsPage::dcdServerLogPath()); server->start(); connect(server.data(), SIGNAL(error(QString)), this, SLOT(onError(QString))); ClientPointer client(new Dcd::DcdClient(projectName, DlangEditor::DlangOptionsPage::dcdClientExecutable(), port, this)); appendIncludePaths(client); it = mapChannels.insert(projectName, qMakePair(client, server)); ++currentPortOffset; } else { if (!it.value().second->isRunning()) { it.value().second->stop(); mapChannels.erase(it); return ClientPointer(); } } return it.value().first; } catch (std::exception &ex) { qDebug("Client exception: %s", ex.what()); } catch (...) { qDebug("Client exception: unknown"); } return ClientPointer(); } void DcdFactory::appendIncludePaths(ClientPointer client) { // append default include paths from options page QStringList list = DlangEditor::DlangOptionsPage::includePaths(); // append include paths from project settings CppTools::CppModelManager *modelmanager = CppTools::CppModelManager::instance(); if (modelmanager) { ProjectExplorer::Project *currentProject = ProjectExplorer::ProjectExplorerPlugin::currentProject(); if (currentProject) { CppTools::ProjectInfo pinfo = modelmanager->projectInfo(currentProject); if (pinfo.isValid()) { foreach (const CppTools::ProjectPart::HeaderPath &header, pinfo.headerPaths()) { if (header.isValid()) { list.push_back(header.path); } } } } } list.removeDuplicates(); foreach (const QString& l, list) { client->appendIncludePath(l); } } void DcdFactory::setPortRange(int first, int last) { m_firstPort = first; m_lastPort = std::max(last, first); } QPair<int, int> DcdFactory::portRange() const { return qMakePair(m_firstPort, m_lastPort); } DcdFactory *DcdFactory::instance() { static DcdFactory inst(DlangEditor::DlangOptionsPage::portsRange()); return &inst; } void DcdFactory::onError(QString error) { qDebug("DcdFactory::onError: %s", error.toStdString().data()); qWarning("DcdFactory::onError: %s", error.toStdString().data()); Dcd::DcdServer *server = qobject_cast<Dcd::DcdServer*>(sender()); server->stop(); mapChannels.remove(server->projectName()); } DcdFactory::DcdFactory(QPair<int, int> range) : currentPortOffset(0) { setPortRange(range.first, range.second); } <commit_msg>Dcd processes extra logging *Process arguments logging<commit_after>#include "dcdsupport.h" #include "dlangdebughelper.h" #include <dlangoptionspage.h> #include <stdexcept> #include <QProcess> #include <QTextStream> #include <QDebug> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/project.h> #include <cpptools/cppmodelmanager.h> using namespace Dcd; DcdClient::DcdClient(const QString &projectName, const QString &processName, int port, QObject *parent) : QObject(parent), m_projectName(projectName), m_port(port), m_processName(processName) { m_portArguments << QLatin1String("--port") << QString::number(port); } const QString &DcdClient::projectName() const { return m_projectName; } void DcdClient::setOutputFile(const QString &filePath) { m_filePath = filePath; } void startProcess(QProcess &p, const QString &processName, const QStringList &args, const QString &filePath, QIODevice::OpenMode mode = QIODevice::ReadWrite) { if (p.state() != QProcess::NotRunning) { throw std::runtime_error("process is already running"); } if (!filePath.isEmpty()) { p.setStandardOutputFile(filePath, QIODevice::Append | QIODevice::Unbuffered); p.setStandardErrorFile(filePath, QIODevice::Append | QIODevice::Unbuffered); } qDebug() << processName << " process " << args; p.start(processName, args, mode); if (!p.waitForStarted(1000)) { throw std::runtime_error("process start timeout"); } } void waitForFinished(QProcess &p) { if (!p.waitForFinished(1000)) { throw std::runtime_error("process finish timeout"); } if (p.exitStatus() != QProcess::NormalExit || p.exitCode() != 0) { throw std::runtime_error(p.readAllStandardError().data()); } } void DcdClient::complete(const QString &filePath, int position, CompletionList &result) { DEBUG_GUARD(""); QStringList args = m_portArguments; args << QLatin1String("-c") + QString::number(position) << filePath; qDebug() << "dcd-client process " << args; QProcess process; startProcess(process, m_processName, args, m_filePath); waitForFinished(process); QByteArray array(process.readAllStandardOutput()); return parseOutput(array, result); } void DcdClient::completeFromArray(const QString &array, int position, DcdClient::CompletionList &result) { DEBUG_GUARD(QString::number(position)); QStringList args = m_portArguments; args << QLatin1String("-c") + QString::number(position); QProcess process; startProcess(process, m_processName, args, m_filePath); process.write(array.toLatin1()); if (!process.waitForBytesWritten(5000)) { throw std::runtime_error("process writing data timeout"); } process.closeWriteChannel(); waitForFinished(process); QByteArray output(process.readAllStandardOutput()); return parseOutput(output, result); } void DcdClient::appendIncludePath(const QString &includePath) { DEBUG_GUARD(""); QStringList args = m_portArguments; args << QLatin1String("-I") + includePath; qDebug() << "dcd-client process " << args; QProcess process; startProcess(process, m_processName, args, m_filePath); waitForFinished(process); } void DcdClient::findSymbolLocation(const QString &array, int position, DcdClient::Location &result) { DEBUG_GUARD(QString::number(position)); QStringList args = m_portArguments; args << QLatin1String("-c") + QString::number(position) << "-l"; qDebug() << "dcd-client process " << args; QProcess process; startProcess(process, m_processName, args, m_filePath); process.write(array.toLatin1()); if (!process.waitForBytesWritten(2000)) { throw std::runtime_error("process writing data timeout"); } process.closeWriteChannel(); waitForFinished(process); QString str(process.readAllStandardOutput()); QStringList list = str.split('\t'); result = list.size() == 2 ? Location(list.front(), list.back().toInt()) : Location(QString(), 0); } void DcdClient::getDocumentationComments(const QString &array, int position, QStringList &result) { DEBUG_GUARD(QString::number(position)); QStringList args = m_portArguments; args << QLatin1String("-c") + QString::number(position) << "-d"; qDebug() << "dcd-client process " << args; QProcess process; startProcess(process, m_processName, args, m_filePath); process.write(array.toLatin1()); if (!process.waitForBytesWritten(2000)) { throw std::runtime_error("process writing data timeout"); } process.closeWriteChannel(); waitForFinished(process); QString str(process.readAllStandardOutput()); result = str.split('\n'); } void DcdClient::parseOutput(const QByteArray &output, DcdClient::CompletionList &result) { result.list.clear(); result.type = DCD_BAD_TYPE; QTextStream stream(output); QString line = stream.readLine(); if (line == QLatin1String("identifiers")) { return parseIdentifiers(stream, result); } else if (line == QLatin1String("calltips")) { return parseCalltips(stream, result); } else if (line.isEmpty()) { return; } else { throw std::runtime_error("unknown output type"); } } void DcdClient::parseIdentifiers(QTextStream &stream, DcdClient::CompletionList &result) { QString line; do { line = stream.readLine(); if (line.isNull() || line.isEmpty()) break; QStringList tokens = line.split(QLatin1Char('\t')); if (tokens.size() != 2) { throw std::runtime_error("Failed to parse identifiers"); } result.type = DCD_IDENTIFIER; result.list.push_back(DcdCompletion()); result.list.back().data = tokens.front(); result.list.back().type = DcdCompletion::fromString(tokens.back()); } while (stream.status() == QTextStream::Ok); } void DcdClient::parseCalltips(QTextStream &stream, DcdClient::CompletionList &result) { QString line; do { line = stream.readLine(); if (line.isNull() || line.isEmpty()) break; result.type = DCD_CALLTIP; result.list.push_back(DcdCompletion()); result.list.back().data = line; result.list.back().type = DcdCompletion::DCD_NO_TYPE; } while (stream.status() == QTextStream::Ok); } DcdCompletion::IdentifierType DcdCompletion::fromString(const QString &name) { char c = name.at(0).toLatin1(); switch (c) { case 'c': return DCD_CLASS; case 'i': return DCD_INTERFACE; case 's': return DCD_STRUCT; case 'u': return DCD_UNION; case 'v': return DCD_VAR; case 'm': return DCD_MEMBER_VAR; case 'k': return DCD_KEYWORD; case 'f': return DCD_FUNCTION; case 'g': return DCD_ENUM_NAME; case 'e': return DCD_ENUM_VAR; case 'P': return DCD_PACKAGE; case 'M': return DCD_MODULE; case 'a': return DCD_ARRAY; case 'A': return DCD_ASSOC_ARRAY; case 'l': return DCD_ALIAS; case 't': return DCD_TEMPLATE; case 'T': return DCD_MIXIN; default: return DCD_NO_TYPE; } return DCD_NO_TYPE; } DcdServer::DcdServer(const QString& projectName, const QString &processName, int port, QObject *parent) : QObject(parent), m_projectName(projectName), m_port(port), m_processName(processName) { m_process = new QProcess(this); connect(m_process, SIGNAL(finished(int)), this, SLOT(onFinished(int))); connect(m_process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(onError(QProcess::ProcessError))); } DcdServer::~DcdServer() { DEBUG_GUARD(""); stop(); m_process->waitForFinished(10000); } int DcdServer::port() const { return m_port; } const QString &DcdServer::projectName() const { return m_projectName; } void DcdServer::setOutputFile(const QString &filePath) { m_filePath = filePath; } void DcdServer::start() { startProcess(*m_process, m_processName, QStringList() << QLatin1String("--port") << QString::number(m_port), m_filePath); } void DcdServer::stop() { m_process->kill(); } bool DcdServer::isRunning() const { return (m_process && m_process->state() == QProcess::Running); } void DcdServer::onFinished(int errorCode) { qDebug() << "DCD server finished"; if (errorCode != 0) { emit error(tr("DCD server process has been terminated with exit code %1").arg(errorCode)); qWarning("DCD server: %s", static_cast<QProcess*>(sender())->readAllStandardError().data()); } } void DcdServer::onError(QProcess::ProcessError error) { qDebug() << "DCD server error"; switch (error) { case QProcess::FailedToStart: emit this->error(tr("DCD server failed to start")); break; case QProcess::Crashed: emit this->error(tr("DCD server crashed")); break; case QProcess::Timedout: emit this->error(tr("DCD server starting timeout")); break; default: emit this->error(tr("DCD server unknown error")); break; } stop(); } // Factory DcdFactory::ClientPointer DcdFactory::client(const QString &projectName) { try { MapString::iterator it = mapChannels.find(projectName); if (it == mapChannels.end()) { int port = m_firstPort + currentPortOffset % (m_lastPort - m_firstPort + 1); ServerPointer server(new Dcd::DcdServer(projectName, DlangEditor::DlangOptionsPage::dcdServerExecutable(), port, this)); server->setOutputFile(DlangEditor::DlangOptionsPage::dcdServerLogPath()); server->start(); connect(server.data(), SIGNAL(error(QString)), this, SLOT(onError(QString))); ClientPointer client(new Dcd::DcdClient(projectName, DlangEditor::DlangOptionsPage::dcdClientExecutable(), port, this)); appendIncludePaths(client); it = mapChannels.insert(projectName, qMakePair(client, server)); ++currentPortOffset; } else { if (!it.value().second->isRunning()) { it.value().second->stop(); mapChannels.erase(it); return ClientPointer(); } } return it.value().first; } catch (std::exception &ex) { qDebug("Client exception: %s", ex.what()); } catch (...) { qDebug("Client exception: unknown"); } return ClientPointer(); } void DcdFactory::appendIncludePaths(ClientPointer client) { // append default include paths from options page QStringList list = DlangEditor::DlangOptionsPage::includePaths(); // append include paths from project settings CppTools::CppModelManager *modelmanager = CppTools::CppModelManager::instance(); if (modelmanager) { ProjectExplorer::Project *currentProject = ProjectExplorer::ProjectExplorerPlugin::currentProject(); if (currentProject) { CppTools::ProjectInfo pinfo = modelmanager->projectInfo(currentProject); if (pinfo.isValid()) { foreach (const CppTools::ProjectPart::HeaderPath &header, pinfo.headerPaths()) { if (header.isValid()) { list.push_back(header.path); } } } } } list.removeDuplicates(); foreach (const QString& l, list) { client->appendIncludePath(l); } } void DcdFactory::setPortRange(int first, int last) { m_firstPort = first; m_lastPort = std::max(last, first); } QPair<int, int> DcdFactory::portRange() const { return qMakePair(m_firstPort, m_lastPort); } DcdFactory *DcdFactory::instance() { static DcdFactory inst(DlangEditor::DlangOptionsPage::portsRange()); return &inst; } void DcdFactory::onError(QString error) { qDebug("DcdFactory::onError: %s", error.toStdString().data()); qWarning("DcdFactory::onError: %s", error.toStdString().data()); Dcd::DcdServer *server = qobject_cast<Dcd::DcdServer*>(sender()); server->stop(); mapChannels.remove(server->projectName()); } DcdFactory::DcdFactory(QPair<int, int> range) : currentPortOffset(0) { setPortRange(range.first, range.second); } <|endoftext|>
<commit_before>#ifdef _WIN32 #include <assert.h> #include "win_fsnotifier.h" using namespace std; // // WatchPoint // WatchPoint::WatchPoint(Server* server, const u16string& path) : path(path) { wstring pathW(path.begin(), path.end()); HANDLE directoryHandle = CreateFileW( pathW.c_str(), // pointer to the file name FILE_LIST_DIRECTORY, // access (read/write) mode CREATE_SHARE, // share mode NULL, // security descriptor OPEN_EXISTING, // how to create CREATE_FLAGS, // file attributes NULL // file with attributes to copy ); if (directoryHandle == INVALID_HANDLE_VALUE) { throw FileWatcherException("Couldn't add watch:", path, GetLastError()); } this->directoryHandle = directoryHandle; this->server = server; this->buffer.reserve(EVENT_BUFFER_SIZE); ZeroMemory(&this->overlapped, sizeof(OVERLAPPED)); this->overlapped.hEvent = this; listen(); } WatchPoint::~WatchPoint() { BOOL ret = CloseHandle(directoryHandle); if (!ret) { log_severe(server->getThreadEnv(), "Couldn't close handle %p for '%ls': %d", directoryHandle, path.c_str(), GetLastError()); } } void WatchPoint::close() { BOOL ret = CancelIo(directoryHandle); if (!ret) { log_severe(server->getThreadEnv(), "Couldn't cancel I/O %p for '%ls': %d", directoryHandle, path.c_str(), GetLastError()); } // Force the processing of the ERROR_OPERATION_ABORTED event generated by CancelIO() (see handleEventCallback()) // Without this the abort event is handled after close() returns // Which means we'll unlock the calling thread before the watch point is truly cleaned up SleepEx(0, true); } static void CALLBACK handleEventCallback(DWORD errorCode, DWORD bytesTransferred, LPOVERLAPPED overlapped) { WatchPoint* watchPoint = (WatchPoint*) overlapped->hEvent; watchPoint->handleEventsInBuffer(errorCode, bytesTransferred); } void WatchPoint::listen() { BOOL success = ReadDirectoryChangesW( directoryHandle, // handle to directory &buffer[0], // read results buffer EVENT_BUFFER_SIZE, // length of buffer TRUE, // include children EVENT_MASK, // filter conditions NULL, // bytes returned &overlapped, // overlapped buffer &handleEventCallback // completion routine ); if (!success) { throw FileWatcherException("Couldn't start watching", path, GetLastError()); } } void WatchPoint::handleEventsInBuffer(DWORD errorCode, DWORD bytesTransferred) { server->handleEvents(this, errorCode, buffer, bytesTransferred); } void Server::handleEvents(WatchPoint* watchPoint, DWORD errorCode, const vector<BYTE>& buffer, DWORD bytesTransferred) { JNIEnv* env = getThreadEnv(); const u16string& path = watchPoint->path; try { if (errorCode == ERROR_OPERATION_ABORTED) { log_fine(env, "Finished watching '%s'", utf16ToUtf8String(path).c_str()); reportFinished(path); return; } // TODO Handle other error codes if (bytesTransferred == 0) { // Got a buffer overflow => current changes lost => send INVALIDATE on root log_info(env, "Detected overflow for %s", utf16ToUtf8String(path).c_str()); reportChange(env, FILE_EVENT_INVALIDATE, path); } else { int index = 0; for (;;) { FILE_NOTIFY_INFORMATION* current = (FILE_NOTIFY_INFORMATION*) &buffer[index]; handleEvent(env, path, current); if (current->NextEntryOffset == 0) { break; } index += current->NextEntryOffset; } } watchPoint->listen(); } catch (const exception& ex) { reportError(env, ex); reportFinished(path); } } bool isAbsoluteLocalPath(const u16string& path) { if (path.length() < 3) { return false; } return ((u'a' <= path[0] && path[0] <= u'z') || (u'A' <= path[0] && path[0] <= u'Z')) && path[1] == u':' && path[2] == u'\\'; } bool isAbsoluteUncPath(const u16string& path) { if (path.length() < 3) { return false; } return path[0] == u'\\' && path[1] == u'\\'; } bool isLongPath(const u16string& path) { return path.length() >= 4 && path.substr(0, 4) == u"\\\\?\\"; } bool isUncLongPath(const u16string& path) { return path.length() >= 8 && path.substr(0, 8) == u"\\\\?\\UNC\\"; } // TODO How can this be done nicer, wihtout both unnecessary copy and in-place mutation? void convertToLongPathIfNeeded(u16string& path) { // Technically, this should be MAX_PATH (i.e. 260), except some Win32 API related // to working with directory paths are actually limited to 240. It is just // safer/simpler to cover both cases in one code path. if (path.length() <= 240) { return; } // It is already a long path, nothing to do here if (isLongPath(path)) { return; } if (isAbsoluteLocalPath(path)) { // Format: C:\... -> \\?\C:\... path.insert(0, u"\\\\?\\"); } else if (isAbsoluteUncPath(path)) { // In this case, we need to skip the first 2 characters: // Format: \\server\share\... -> \\?\UNC\server\share\... path.erase(0, 2); path.insert(0, u"\\\\?\\UNC\\"); } else { // It is some sort of unknown format, don't mess with it } } void Server::handleEvent(JNIEnv* env, const u16string& path, FILE_NOTIFY_INFORMATION* info) { wstring changedPathW = wstring(info->FileName, 0, info->FileNameLength / sizeof(wchar_t)); u16string changedPath(changedPathW.begin(), changedPathW.end()); // TODO Do we ever get an empty path? if (!changedPath.empty()) { changedPath.insert(0, 1, u'\\'); changedPath.insert(0, path); } // TODO Remove long prefix for path once? if (isLongPath(changedPath)) { if (isUncLongPath(changedPath)) { changedPath.erase(0, 8).insert(0, u"\\\\"); } else { changedPath.erase(0, 4); } } log_fine(env, "Change detected: 0x%x '%ls'", info->Action, changedPathW.c_str()); jint type; if (info->Action == FILE_ACTION_ADDED || info->Action == FILE_ACTION_RENAMED_NEW_NAME) { type = FILE_EVENT_CREATED; } else if (info->Action == FILE_ACTION_REMOVED || info->Action == FILE_ACTION_RENAMED_OLD_NAME) { type = FILE_EVENT_REMOVED; } else if (info->Action == FILE_ACTION_MODIFIED) { type = FILE_EVENT_MODIFIED; } else { log_warning(env, "Unknown event 0x%x for %ls", info->Action, changedPathW.c_str()); type = FILE_EVENT_UNKNOWN; } reportChange(env, type, changedPath); } // // Server // Server::Server(JNIEnv* env, jobject watcherCallback) : AbstractServer(env, watcherCallback) { startThread(); // TODO Error handling SetThreadPriority(this->watcherThread.native_handle(), THREAD_PRIORITY_ABOVE_NORMAL); } void Server::terminate() { terminated = true; } Server::~Server() { list<u16string> paths; for (auto& watchPoint : watchPoints) { paths.push_back(watchPoint.first); } for (auto& path : paths) { executeOnThread(shared_ptr<Command>(new UnregisterPathCommand(path))); } executeOnThread(shared_ptr<Command>(new TerminateCommand())); if (watcherThread.joinable()) { watcherThread.join(); } } void Server::runLoop(JNIEnv* env, function<void(exception_ptr)> notifyStarted) { notifyStarted(nullptr); while (!terminated || watchPoints.size() > 0) { SleepEx(INFINITE, true); } } static void CALLBACK processCommandsCallback(_In_ ULONG_PTR info) { Server* server = (Server*) info; server->processCommands(); } void Server::processCommandsOnThread() { QueueUserAPC(processCommandsCallback, watcherThread.native_handle(), (ULONG_PTR) this); } void Server::registerPath(const u16string& path) { u16string longPath = path; convertToLongPathIfNeeded(longPath); if (watchPoints.find(longPath) != watchPoints.end()) { throw FileWatcherException("Already watching path", path); } watchPoints.emplace(piecewise_construct, forward_as_tuple(longPath), forward_as_tuple(this, longPath)); } void Server::unregisterPath(const u16string& path) { u16string longPath = path; convertToLongPathIfNeeded(longPath); auto it = watchPoints.find(longPath); if (it == watchPoints.end()) { log_fine(getThreadEnv(), "Path is not watched: %s", utf16ToUtf8String(path).c_str()); return; } it->second.close(); } void Server::reportFinished(const u16string path) { watchPoints.erase(path); } // // JNI calls // JNIEXPORT jobject JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_startWatcher(JNIEnv* env, jclass target, jobject javaCallback) { return wrapServer(env, [env, javaCallback]() { return new Server(env, javaCallback); }); } #endif <commit_msg>Win: Handle all OS errors during event handling<commit_after>#ifdef _WIN32 #include <assert.h> #include "win_fsnotifier.h" using namespace std; // // WatchPoint // WatchPoint::WatchPoint(Server* server, const u16string& path) : path(path) { wstring pathW(path.begin(), path.end()); HANDLE directoryHandle = CreateFileW( pathW.c_str(), // pointer to the file name FILE_LIST_DIRECTORY, // access (read/write) mode CREATE_SHARE, // share mode NULL, // security descriptor OPEN_EXISTING, // how to create CREATE_FLAGS, // file attributes NULL // file with attributes to copy ); if (directoryHandle == INVALID_HANDLE_VALUE) { throw FileWatcherException("Couldn't add watch:", path, GetLastError()); } this->directoryHandle = directoryHandle; this->server = server; this->buffer.reserve(EVENT_BUFFER_SIZE); ZeroMemory(&this->overlapped, sizeof(OVERLAPPED)); this->overlapped.hEvent = this; listen(); } WatchPoint::~WatchPoint() { BOOL ret = CloseHandle(directoryHandle); if (!ret) { log_severe(server->getThreadEnv(), "Couldn't close handle %p for '%ls': %d", directoryHandle, path.c_str(), GetLastError()); } } void WatchPoint::close() { BOOL ret = CancelIo(directoryHandle); if (!ret) { log_severe(server->getThreadEnv(), "Couldn't cancel I/O %p for '%ls': %d", directoryHandle, path.c_str(), GetLastError()); } // Force the processing of the ERROR_OPERATION_ABORTED event generated by CancelIO() (see handleEventCallback()) // Without this the abort event is handled after close() returns // Which means we'll unlock the calling thread before the watch point is truly cleaned up SleepEx(0, true); } static void CALLBACK handleEventCallback(DWORD errorCode, DWORD bytesTransferred, LPOVERLAPPED overlapped) { WatchPoint* watchPoint = (WatchPoint*) overlapped->hEvent; watchPoint->handleEventsInBuffer(errorCode, bytesTransferred); } void WatchPoint::listen() { BOOL success = ReadDirectoryChangesW( directoryHandle, // handle to directory &buffer[0], // read results buffer EVENT_BUFFER_SIZE, // length of buffer TRUE, // include children EVENT_MASK, // filter conditions NULL, // bytes returned &overlapped, // overlapped buffer &handleEventCallback // completion routine ); if (!success) { throw FileWatcherException("Couldn't start watching", path, GetLastError()); } } void WatchPoint::handleEventsInBuffer(DWORD errorCode, DWORD bytesTransferred) { server->handleEvents(this, errorCode, buffer, bytesTransferred); } void Server::handleEvents(WatchPoint* watchPoint, DWORD errorCode, const vector<BYTE>& buffer, DWORD bytesTransferred) { JNIEnv* env = getThreadEnv(); const u16string& path = watchPoint->path; try { switch (errorCode) { case ERROR_SUCCESS: break; case ERROR_OPERATION_ABORTED: log_fine(env, "Finished watching '%s'", utf16ToUtf8String(path).c_str()); reportFinished(path); return; default: throw FileWatcherException("Error received when handling events", errorCode); } if (bytesTransferred == 0) { // Got a buffer overflow => current changes lost => send INVALIDATE on root log_info(env, "Detected overflow for %s", utf16ToUtf8String(path).c_str()); reportChange(env, FILE_EVENT_INVALIDATE, path); } else { int index = 0; for (;;) { FILE_NOTIFY_INFORMATION* current = (FILE_NOTIFY_INFORMATION*) &buffer[index]; handleEvent(env, path, current); if (current->NextEntryOffset == 0) { break; } index += current->NextEntryOffset; } } watchPoint->listen(); } catch (const exception& ex) { reportError(env, ex); reportFinished(path); } } bool isAbsoluteLocalPath(const u16string& path) { if (path.length() < 3) { return false; } return ((u'a' <= path[0] && path[0] <= u'z') || (u'A' <= path[0] && path[0] <= u'Z')) && path[1] == u':' && path[2] == u'\\'; } bool isAbsoluteUncPath(const u16string& path) { if (path.length() < 3) { return false; } return path[0] == u'\\' && path[1] == u'\\'; } bool isLongPath(const u16string& path) { return path.length() >= 4 && path.substr(0, 4) == u"\\\\?\\"; } bool isUncLongPath(const u16string& path) { return path.length() >= 8 && path.substr(0, 8) == u"\\\\?\\UNC\\"; } // TODO How can this be done nicer, wihtout both unnecessary copy and in-place mutation? void convertToLongPathIfNeeded(u16string& path) { // Technically, this should be MAX_PATH (i.e. 260), except some Win32 API related // to working with directory paths are actually limited to 240. It is just // safer/simpler to cover both cases in one code path. if (path.length() <= 240) { return; } // It is already a long path, nothing to do here if (isLongPath(path)) { return; } if (isAbsoluteLocalPath(path)) { // Format: C:\... -> \\?\C:\... path.insert(0, u"\\\\?\\"); } else if (isAbsoluteUncPath(path)) { // In this case, we need to skip the first 2 characters: // Format: \\server\share\... -> \\?\UNC\server\share\... path.erase(0, 2); path.insert(0, u"\\\\?\\UNC\\"); } else { // It is some sort of unknown format, don't mess with it } } void Server::handleEvent(JNIEnv* env, const u16string& path, FILE_NOTIFY_INFORMATION* info) { wstring changedPathW = wstring(info->FileName, 0, info->FileNameLength / sizeof(wchar_t)); u16string changedPath(changedPathW.begin(), changedPathW.end()); // TODO Do we ever get an empty path? if (!changedPath.empty()) { changedPath.insert(0, 1, u'\\'); changedPath.insert(0, path); } // TODO Remove long prefix for path once? if (isLongPath(changedPath)) { if (isUncLongPath(changedPath)) { changedPath.erase(0, 8).insert(0, u"\\\\"); } else { changedPath.erase(0, 4); } } log_fine(env, "Change detected: 0x%x '%ls'", info->Action, changedPathW.c_str()); jint type; if (info->Action == FILE_ACTION_ADDED || info->Action == FILE_ACTION_RENAMED_NEW_NAME) { type = FILE_EVENT_CREATED; } else if (info->Action == FILE_ACTION_REMOVED || info->Action == FILE_ACTION_RENAMED_OLD_NAME) { type = FILE_EVENT_REMOVED; } else if (info->Action == FILE_ACTION_MODIFIED) { type = FILE_EVENT_MODIFIED; } else { log_warning(env, "Unknown event 0x%x for %ls", info->Action, changedPathW.c_str()); type = FILE_EVENT_UNKNOWN; } reportChange(env, type, changedPath); } // // Server // Server::Server(JNIEnv* env, jobject watcherCallback) : AbstractServer(env, watcherCallback) { startThread(); // TODO Error handling SetThreadPriority(this->watcherThread.native_handle(), THREAD_PRIORITY_ABOVE_NORMAL); } void Server::terminate() { terminated = true; } Server::~Server() { list<u16string> paths; for (auto& watchPoint : watchPoints) { paths.push_back(watchPoint.first); } for (auto& path : paths) { executeOnThread(shared_ptr<Command>(new UnregisterPathCommand(path))); } executeOnThread(shared_ptr<Command>(new TerminateCommand())); if (watcherThread.joinable()) { watcherThread.join(); } } void Server::runLoop(JNIEnv* env, function<void(exception_ptr)> notifyStarted) { notifyStarted(nullptr); while (!terminated || watchPoints.size() > 0) { SleepEx(INFINITE, true); } } static void CALLBACK processCommandsCallback(_In_ ULONG_PTR info) { Server* server = (Server*) info; server->processCommands(); } void Server::processCommandsOnThread() { QueueUserAPC(processCommandsCallback, watcherThread.native_handle(), (ULONG_PTR) this); } void Server::registerPath(const u16string& path) { u16string longPath = path; convertToLongPathIfNeeded(longPath); if (watchPoints.find(longPath) != watchPoints.end()) { throw FileWatcherException("Already watching path", path); } watchPoints.emplace(piecewise_construct, forward_as_tuple(longPath), forward_as_tuple(this, longPath)); } void Server::unregisterPath(const u16string& path) { u16string longPath = path; convertToLongPathIfNeeded(longPath); auto it = watchPoints.find(longPath); if (it == watchPoints.end()) { log_fine(getThreadEnv(), "Path is not watched: %s", utf16ToUtf8String(path).c_str()); return; } it->second.close(); } void Server::reportFinished(const u16string path) { watchPoints.erase(path); } // // JNI calls // JNIEXPORT jobject JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_startWatcher(JNIEnv* env, jclass target, jobject javaCallback) { return wrapServer(env, [env, javaCallback]() { return new Server(env, javaCallback); }); } #endif <|endoftext|>
<commit_before>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2020 Hugo Beauzée-Luyssen, Videolabs, VideoLAN * * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr> * * 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.1 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "filesystem/libvlc/DeviceLister.h" #include "utils/VLCInstance.h" #include "utils/Filename.h" #include "utils/Url.h" #include "filesystem/libvlc/Device.h" #include "logging/Logger.h" namespace medialibrary { namespace fs { namespace libvlc { DeviceLister::DeviceLister( const std::string &protocol ) : m_protocol( protocol ) , m_cb( nullptr ) { } void DeviceLister::refresh() { /* * We are continuously refreshing through libvlc's discoverer so there's * nothing particular to do here */ } bool DeviceLister::start( IDeviceListerCb *cb ) { assert( m_cb == nullptr ); m_cb = cb; auto started = false; for ( auto& sd : m_sds ) { if ( sd.name == "upnp" || sd.name == "sap" ) continue; auto& em = sd.discoverer.mediaList()->eventManager(); em.onItemAdded( [this]( VLC::MediaPtr m, int ) { onDeviceAdded( std::move( m ) ); } ); em.onItemDeleted( [this]( VLC::MediaPtr m, int ) { onDeviceRemoved( std::move( m ) ); } ); LOG_DEBUG( "Starting Service Discovery ", sd.name ); if ( sd.discoverer.start() == false ) LOG_WARN( "Failed to start SD ", sd.name ); else if ( started == false ) started = true; } return started; } void DeviceLister::stop() { for ( auto& sd : m_sds ) { if ( sd.discoverer.isRunning() == true ) sd.discoverer.stop(); } } void DeviceLister::addSD( const std::string& name ) { m_sds.push_back( SD{ name, VLC::MediaDiscoverer{ VLCInstance::get(), name } } ); } void DeviceLister::onDeviceAdded( VLC::MediaPtr media ) { const auto& mrl = media->mrl(); if ( utils::url::scheme( mrl ) != m_protocol ) return; auto uuid = media->meta( libvlc_meta_Title ); LOG_DEBUG( "Mountpoint added: ", mrl, " from device ", uuid ); m_cb->onDeviceMounted( uuid, utils::file::toFolderPath( mrl ), true ); } void DeviceLister::onDeviceRemoved( VLC::MediaPtr media ) { const auto& mrl = media->mrl(); if ( utils::url::scheme( mrl ) != m_protocol ) return; auto uuid = media->meta( libvlc_meta_Title ); LOG_DEBUG( "Mountpoint removed: ", mrl, " from device ", uuid ); m_cb->onDeviceUnmounted( uuid, utils::file::toFolderPath( mrl ) ); } } } } <commit_msg>libvlc: DeviceLister: Log when stopping a SD<commit_after>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2020 Hugo Beauzée-Luyssen, Videolabs, VideoLAN * * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr> * * 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.1 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "filesystem/libvlc/DeviceLister.h" #include "utils/VLCInstance.h" #include "utils/Filename.h" #include "utils/Url.h" #include "filesystem/libvlc/Device.h" #include "logging/Logger.h" namespace medialibrary { namespace fs { namespace libvlc { DeviceLister::DeviceLister( const std::string &protocol ) : m_protocol( protocol ) , m_cb( nullptr ) { } void DeviceLister::refresh() { /* * We are continuously refreshing through libvlc's discoverer so there's * nothing particular to do here */ } bool DeviceLister::start( IDeviceListerCb *cb ) { assert( m_cb == nullptr ); m_cb = cb; auto started = false; for ( auto& sd : m_sds ) { if ( sd.name == "upnp" || sd.name == "sap" ) continue; auto& em = sd.discoverer.mediaList()->eventManager(); em.onItemAdded( [this]( VLC::MediaPtr m, int ) { onDeviceAdded( std::move( m ) ); } ); em.onItemDeleted( [this]( VLC::MediaPtr m, int ) { onDeviceRemoved( std::move( m ) ); } ); LOG_DEBUG( "Starting Service Discovery ", sd.name ); if ( sd.discoverer.start() == false ) LOG_WARN( "Failed to start SD ", sd.name ); else if ( started == false ) started = true; } return started; } void DeviceLister::stop() { for ( auto& sd : m_sds ) { if ( sd.discoverer.isRunning() == true ) { LOG_DEBUG( "Stopping Service Discovery ", sd.name ); sd.discoverer.stop(); } } } void DeviceLister::addSD( const std::string& name ) { m_sds.push_back( SD{ name, VLC::MediaDiscoverer{ VLCInstance::get(), name } } ); } void DeviceLister::onDeviceAdded( VLC::MediaPtr media ) { const auto& mrl = media->mrl(); if ( utils::url::scheme( mrl ) != m_protocol ) return; auto uuid = media->meta( libvlc_meta_Title ); LOG_DEBUG( "Mountpoint added: ", mrl, " from device ", uuid ); m_cb->onDeviceMounted( uuid, utils::file::toFolderPath( mrl ), true ); } void DeviceLister::onDeviceRemoved( VLC::MediaPtr media ) { const auto& mrl = media->mrl(); if ( utils::url::scheme( mrl ) != m_protocol ) return; auto uuid = media->meta( libvlc_meta_Title ); LOG_DEBUG( "Mountpoint removed: ", mrl, " from device ", uuid ); m_cb->onDeviceUnmounted( uuid, utils::file::toFolderPath( mrl ) ); } } } } <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/notifications/sync_notifier/notification_bitmap_fetcher.h" #include "base/compiler_specific.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_utils.h" #include "net/http/http_status_code.h" #include "net/url_request/test_url_fetcher_factory.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_request_status.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/size.h" #include "ui/gfx/skia_util.h" namespace { const bool kAsyncCall = true; const bool kSyncCall = false; } // namespace namespace notifier { // Class to catch events from the NotificationBitmapFetcher for testing. class NotificationBitmapFetcherTestDelegate : public NotificationBitmapFetcherDelegate { public: explicit NotificationBitmapFetcherTestDelegate(bool async) : called_(false), success_(false), async_(async) {} virtual ~NotificationBitmapFetcherTestDelegate() { EXPECT_TRUE(called_); } // Method inherited from NotificationBitmapFetcherDelegate. virtual void OnFetchComplete(const GURL url, const SkBitmap* bitmap) OVERRIDE { called_ = true; url_ = url; if (NULL != bitmap) { success_ = true; bitmap->deepCopyTo(&bitmap_, bitmap->getConfig()); } // For async calls, we need to quit the message loop so the test can // continue. if (async_) { base::MessageLoop::current()->Quit(); } } GURL url() const { return url_; } bool success() const { return success_; } const SkBitmap& bitmap() const { return bitmap_; } private: bool called_; GURL url_; bool success_; bool async_; SkBitmap bitmap_; DISALLOW_COPY_AND_ASSIGN(NotificationBitmapFetcherTestDelegate); }; class NotificationBitmapFetcherBrowserTest : public InProcessBrowserTest { public: virtual void SetUp() OVERRIDE { url_fetcher_factory_.reset(new net::FakeURLFetcherFactory(NULL)); InProcessBrowserTest::SetUp(); } protected: scoped_ptr<net::FakeURLFetcherFactory> url_fetcher_factory_; }; #if defined(OS_WIN) #define MAYBE_StartTest DISABLED_StartTest #else #define MAYBE_StartTest StartTest #endif // WARNING: These tests work with --single_process, but not // --single-process. The reason is that the sandbox does not get created // for us by the test process if --single-process is used. IN_PROC_BROWSER_TEST_F(NotificationBitmapFetcherBrowserTest, MAYBE_StartTest) { GURL url("http://example.com/this-should-work"); // Put some realistic looking bitmap data into the url_fetcher. SkBitmap image; // Put a real bitmap into "image". 2x2 bitmap of green 32 bit pixels. image.setConfig(SkBitmap::kARGB_8888_Config, 2, 2); image.allocPixels(); image.eraseColor(SK_ColorGREEN); // Encode the bits as a PNG. std::vector<unsigned char> compressed; ASSERT_TRUE(gfx::PNGCodec::EncodeBGRASkBitmap(image, true, &compressed)); // Copy the bits into the string, and put them into the FakeURLFetcher. std::string image_string(compressed.begin(), compressed.end()); // Set up a delegate to wait for the callback. NotificationBitmapFetcherTestDelegate delegate(kAsyncCall); NotificationBitmapFetcher fetcher(url, &delegate); url_fetcher_factory_->SetFakeResponse(url, image_string, net::HTTP_OK, net::URLRequestStatus::SUCCESS); // We expect that the image decoder will get called and return // an image in a callback to OnImageDecoded(). fetcher.Start(browser()->profile()); // Blocks until test delegate is notified via a callback. content::RunMessageLoop(); ASSERT_TRUE(delegate.success()); // Make sure we get back the bitmap we expect. const SkBitmap& found_image = delegate.bitmap(); EXPECT_TRUE(gfx::BitmapsAreEqual(image, found_image)); } IN_PROC_BROWSER_TEST_F(NotificationBitmapFetcherBrowserTest, OnImageDecodedTest) { GURL url("http://example.com/this-should-work-as-well"); SkBitmap image; // Put a real bitmap into "image". 2x2 bitmap of green 16 bit pixels. image.setConfig(SkBitmap::kARGB_8888_Config, 2, 2); image.allocPixels(); image.eraseColor(SK_ColorGREEN); NotificationBitmapFetcherTestDelegate delegate(kSyncCall); NotificationBitmapFetcher fetcher(url, &delegate); fetcher.OnImageDecoded(NULL, image); // Ensure image is marked as succeeded. EXPECT_TRUE(delegate.success()); // Test that the image is what we expect. EXPECT_TRUE(gfx::BitmapsAreEqual(image, delegate.bitmap())); } IN_PROC_BROWSER_TEST_F(NotificationBitmapFetcherBrowserTest, OnURLFetchFailureTest) { GURL url("http://example.com/this-should-be-fetch-failure"); // We intentionally put no data into the bitmap to simulate a failure. // Set up a delegate to wait for the callback. NotificationBitmapFetcherTestDelegate delegate(kAsyncCall); NotificationBitmapFetcher fetcher(url, &delegate); url_fetcher_factory_->SetFakeResponse(url, std::string(), net::HTTP_INTERNAL_SERVER_ERROR, net::URLRequestStatus::FAILED); fetcher.Start(browser()->profile()); // Blocks until test delegate is notified via a callback. content::RunMessageLoop(); EXPECT_FALSE(delegate.success()); } IN_PROC_BROWSER_TEST_F(NotificationBitmapFetcherBrowserTest, HandleImageFailedTest) { GURL url("http://example.com/this-should-be-a-decode-failure"); NotificationBitmapFetcherTestDelegate delegate(kAsyncCall); NotificationBitmapFetcher fetcher(url, &delegate); url_fetcher_factory_->SetFakeResponse( url, std::string("Not a real bitmap"), net::HTTP_OK, net::URLRequestStatus::SUCCESS); fetcher.Start(browser()->profile()); // Blocks until test delegate is notified via a callback. content::RunMessageLoop(); EXPECT_FALSE(delegate.success()); } } // namespace notifier <commit_msg>Disabled flaky NotificationBitmapFetcherBrowserTest.HandleImageFailedTest on Windows Debug.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/notifications/sync_notifier/notification_bitmap_fetcher.h" #include "base/compiler_specific.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_utils.h" #include "net/http/http_status_code.h" #include "net/url_request/test_url_fetcher_factory.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_request_status.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/size.h" #include "ui/gfx/skia_util.h" namespace { const bool kAsyncCall = true; const bool kSyncCall = false; } // namespace namespace notifier { // Class to catch events from the NotificationBitmapFetcher for testing. class NotificationBitmapFetcherTestDelegate : public NotificationBitmapFetcherDelegate { public: explicit NotificationBitmapFetcherTestDelegate(bool async) : called_(false), success_(false), async_(async) {} virtual ~NotificationBitmapFetcherTestDelegate() { EXPECT_TRUE(called_); } // Method inherited from NotificationBitmapFetcherDelegate. virtual void OnFetchComplete(const GURL url, const SkBitmap* bitmap) OVERRIDE { called_ = true; url_ = url; if (NULL != bitmap) { success_ = true; bitmap->deepCopyTo(&bitmap_, bitmap->getConfig()); } // For async calls, we need to quit the message loop so the test can // continue. if (async_) { base::MessageLoop::current()->Quit(); } } GURL url() const { return url_; } bool success() const { return success_; } const SkBitmap& bitmap() const { return bitmap_; } private: bool called_; GURL url_; bool success_; bool async_; SkBitmap bitmap_; DISALLOW_COPY_AND_ASSIGN(NotificationBitmapFetcherTestDelegate); }; class NotificationBitmapFetcherBrowserTest : public InProcessBrowserTest { public: virtual void SetUp() OVERRIDE { url_fetcher_factory_.reset(new net::FakeURLFetcherFactory(NULL)); InProcessBrowserTest::SetUp(); } protected: scoped_ptr<net::FakeURLFetcherFactory> url_fetcher_factory_; }; #if defined(OS_WIN) #define MAYBE_StartTest DISABLED_StartTest #else #define MAYBE_StartTest StartTest #endif // WARNING: These tests work with --single_process, but not // --single-process. The reason is that the sandbox does not get created // for us by the test process if --single-process is used. IN_PROC_BROWSER_TEST_F(NotificationBitmapFetcherBrowserTest, MAYBE_StartTest) { GURL url("http://example.com/this-should-work"); // Put some realistic looking bitmap data into the url_fetcher. SkBitmap image; // Put a real bitmap into "image". 2x2 bitmap of green 32 bit pixels. image.setConfig(SkBitmap::kARGB_8888_Config, 2, 2); image.allocPixels(); image.eraseColor(SK_ColorGREEN); // Encode the bits as a PNG. std::vector<unsigned char> compressed; ASSERT_TRUE(gfx::PNGCodec::EncodeBGRASkBitmap(image, true, &compressed)); // Copy the bits into the string, and put them into the FakeURLFetcher. std::string image_string(compressed.begin(), compressed.end()); // Set up a delegate to wait for the callback. NotificationBitmapFetcherTestDelegate delegate(kAsyncCall); NotificationBitmapFetcher fetcher(url, &delegate); url_fetcher_factory_->SetFakeResponse(url, image_string, net::HTTP_OK, net::URLRequestStatus::SUCCESS); // We expect that the image decoder will get called and return // an image in a callback to OnImageDecoded(). fetcher.Start(browser()->profile()); // Blocks until test delegate is notified via a callback. content::RunMessageLoop(); ASSERT_TRUE(delegate.success()); // Make sure we get back the bitmap we expect. const SkBitmap& found_image = delegate.bitmap(); EXPECT_TRUE(gfx::BitmapsAreEqual(image, found_image)); } IN_PROC_BROWSER_TEST_F(NotificationBitmapFetcherBrowserTest, OnImageDecodedTest) { GURL url("http://example.com/this-should-work-as-well"); SkBitmap image; // Put a real bitmap into "image". 2x2 bitmap of green 16 bit pixels. image.setConfig(SkBitmap::kARGB_8888_Config, 2, 2); image.allocPixels(); image.eraseColor(SK_ColorGREEN); NotificationBitmapFetcherTestDelegate delegate(kSyncCall); NotificationBitmapFetcher fetcher(url, &delegate); fetcher.OnImageDecoded(NULL, image); // Ensure image is marked as succeeded. EXPECT_TRUE(delegate.success()); // Test that the image is what we expect. EXPECT_TRUE(gfx::BitmapsAreEqual(image, delegate.bitmap())); } IN_PROC_BROWSER_TEST_F(NotificationBitmapFetcherBrowserTest, OnURLFetchFailureTest) { GURL url("http://example.com/this-should-be-fetch-failure"); // We intentionally put no data into the bitmap to simulate a failure. // Set up a delegate to wait for the callback. NotificationBitmapFetcherTestDelegate delegate(kAsyncCall); NotificationBitmapFetcher fetcher(url, &delegate); url_fetcher_factory_->SetFakeResponse(url, std::string(), net::HTTP_INTERNAL_SERVER_ERROR, net::URLRequestStatus::FAILED); fetcher.Start(browser()->profile()); // Blocks until test delegate is notified via a callback. content::RunMessageLoop(); EXPECT_FALSE(delegate.success()); } // Flaky on Win XP Debug: crbug.com/316488 #if defined(OS_WIN) && !defined(NDEBUG) #define MAYBE_HandleImageFailedTest DISABLED_HandleImageFailedTest #else #define MAYBE_HandleImageFailedTest HandleImageFailedTest #endif IN_PROC_BROWSER_TEST_F(NotificationBitmapFetcherBrowserTest, MAYBE_HandleImageFailedTest) { GURL url("http://example.com/this-should-be-a-decode-failure"); NotificationBitmapFetcherTestDelegate delegate(kAsyncCall); NotificationBitmapFetcher fetcher(url, &delegate); url_fetcher_factory_->SetFakeResponse( url, std::string("Not a real bitmap"), net::HTTP_OK, net::URLRequestStatus::SUCCESS); fetcher.Start(browser()->profile()); // Blocks until test delegate is notified via a callback. content::RunMessageLoop(); EXPECT_FALSE(delegate.success()); } } // namespace notifier <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <algorithm> #include <iterator> #include <map> #include <string> #include "caf/string_view.hpp" namespace caf { /// Maps strings to values of type `V`, but unlike `std::map<std::string, V>` /// accepts `string_view` for looking up keys efficiently. template <class V> class dictionary { public: // -- member types ---------------------------------------------------------- using map_type = std::map<std::string, V>; using key_type = typename map_type::key_type; using mapped_type = typename map_type::mapped_type; using value_type = typename map_type::value_type; using allocator_type = typename map_type::allocator_type; using size_type = typename map_type::size_type; using difference_type = typename map_type::difference_type; using reference = typename map_type::reference; using const_reference = typename map_type::const_reference; using pointer = typename map_type::pointer; using const_pointer = typename map_type::const_pointer; using iterator = typename map_type::iterator; using const_iterator = typename map_type::const_iterator; using reverse_iterator = typename map_type::reverse_iterator; using const_reverse_iterator = typename map_type::const_reverse_iterator; using iterator_bool_pair = std::pair<iterator, bool>; struct mapped_type_less { inline bool operator()(const value_type& x, string_view y) const { return x.first < y; } inline bool operator()(const value_type& x, const value_type& y) const { return x.first < y.first; } inline bool operator()(string_view x, const value_type& y) const { return x < y.first; } }; // -- constructors, destructors, and assignment operators ------------------- dictionary() = default; dictionary(dictionary&&) = default; dictionary(const dictionary&) = default; dictionary(std::initializer_list<value_type> xs) : xs_(xs) { // nop } template <class InputIterator> dictionary(InputIterator first, InputIterator last) : xs_(first, last) { // nop } dictionary& operator=(dictionary&&) = default; dictionary& operator=(const dictionary&) = default; // -- iterator access -------------------------------------------------------- iterator begin() noexcept { return xs_.begin(); } const_iterator begin() const noexcept { return xs_.begin(); } const_iterator cbegin() const noexcept { return begin(); } reverse_iterator rbegin() noexcept { return xs_.rbegin(); } const_reverse_iterator rbegin() const noexcept { return xs_.rbegin(); } const_reverse_iterator crbegin() const noexcept { return rbegin(); } iterator end() noexcept { return xs_.end(); } const_iterator end() const noexcept { return xs_.end(); } const_iterator cend() const noexcept { return end(); } reverse_iterator rend() noexcept { return xs_.rend(); } const_reverse_iterator rend() const noexcept { return xs_.rend(); } const_reverse_iterator crend() const noexcept { return rend(); } // -- size ------------------------------------------------------------------- bool empty() const noexcept { return xs_.empty(); } size_type size() const noexcept { return xs_.size(); } // -- access to members ------------------------------------------------------ /// Gives raw access to the underlying container. map_type& container() noexcept { return xs_; } /// Gives raw access to the underlying container. const map_type& container() const noexcept { return xs_; } // -- modifiers ------------------------------------------------------------- void clear() noexcept { return xs_.clear(); } void swap(dictionary& other) { xs_.swap(other.xs_); } // -- insertion -------------------------------------------------------------- template <class K, class T> iterator_bool_pair emplace(K&& key, T&& value) { auto i = lower_bound(key); if (i == end()) return xs_.emplace(copy(std::forward<K>(key)), V{std::forward<T>(value)}); if (i->first == key) return {i, false}; return {xs_.emplace_hint(i, copy(std::forward<K>(key)), V{std::forward<T>(value)}), true}; } iterator_bool_pair insert(value_type kvp) { return emplace(kvp.first, std::move(kvp.second)); } iterator insert(iterator hint, value_type kvp) { return emplace_hint(hint, kvp.first, std::move(kvp.second)); } template <class T> iterator_bool_pair insert(string_view key, T&& value) { return emplace(key, V{std::forward<T>(value)}); } template <class K, class T> iterator emplace_hint(iterator hint, K&& key, T&& value) { if (hint == end() || hint->first > key) return xs_.emplace(copy(std::forward<K>(key)), V{std::forward<T>(value)}) .first; if (hint->first == key) return hint; return xs_.emplace_hint(hint, copy(std::forward<K>(key)), V{std::forward<T>(value)}); } template <class T> iterator insert(iterator hint, string_view key, T&& value) { return emplace_hint(hint, key, std::forward<T>(value)); } void insert(const_iterator first, const_iterator last) { xs_.insert(first, last); } template <class T> iterator_bool_pair insert_or_assign(string_view key, T&& value) { auto i = lower_bound(key); if (i == end()) return xs_.emplace(copy(key), V{std::forward<T>(value)}); if (i->first == key) { i->second = V{std::forward<T>(value)}; return {i, false}; } return {xs_.emplace_hint(i, copy(key), V{std::forward<T>(value)}), true}; } template <class T> iterator insert_or_assign(iterator hint, string_view key, T&& value) { if (hint == end() || hint->first > key) return insert_or_assign(key, std::forward<T>(value)).first; hint = lower_bound(hint, key); if (hint != end() && hint->first == key) { hint->second = std::forward<T>(value); return hint; } return xs_.emplace_hint(hint, copy(key), V{std::forward<T>(value)}); } // -- lookup ----------------------------------------------------------------- bool contains(string_view key) const noexcept { auto i = lower_bound(key); return !(i == end() || i->first != key); } size_t count(string_view key) const noexcept { return contains(key) ? 1u : 0u; } iterator find(string_view key) noexcept { auto i = lower_bound(key); return i != end() && i->first == key ? i : end(); } const_iterator find(string_view key) const noexcept { auto i = lower_bound(key); return i != end() && i->first == key ? i : end(); } iterator lower_bound(string_view key) { return lower_bound(begin(), key); } const_iterator lower_bound(string_view key) const { return lower_bound(begin(), key); } iterator upper_bound(string_view key) { mapped_type_less cmp; return std::upper_bound(begin(), end(), key, cmp); } const_iterator upper_bound(string_view key) const { mapped_type_less cmp; return std::upper_bound(begin(), end(), key, cmp); } // -- element access --------------------------------------------------------- mapped_type& operator[](string_view key) { return insert(key, mapped_type{}).first->second; } private: iterator lower_bound(iterator from, string_view key) { mapped_type_less cmp; return std::lower_bound(from, end(), key, cmp); } const_iterator lower_bound(const_iterator from, string_view key) const { mapped_type_less cmp; return std::lower_bound(from, end(), key, cmp); } template <size_t N> static inline std::string copy(const char (&str)[N]) { return std::string{str}; } // Copies the content of `str` into a new string. static inline std::string copy(string_view str) { return std::string{str.begin(), str.end()}; } // Moves the content of `str` into a new string. static inline std::string copy(std::string str) { return str; } map_type xs_; }; // @relates dictionary template <class T> bool operator==(const dictionary<T>& xs, const dictionary<T>& ys) { return xs.container() == ys.container(); } // @relates dictionary template <class T> bool operator!=(const dictionary<T>& xs, const dictionary<T>& ys) { return xs.container() != ys.container(); } // @relates dictionary template <class T> bool operator<(const dictionary<T>& xs, const dictionary<T>& ys) { return xs.container() < ys.container(); } // @relates dictionary template <class T> bool operator<=(const dictionary<T>& xs, const dictionary<T>& ys) { return xs.container() <= ys.container(); } // @relates dictionary template <class T> bool operator>(const dictionary<T>& xs, const dictionary<T>& ys) { return xs.container() > ys.container(); } // @relates dictionary template <class T> bool operator>=(const dictionary<T>& xs, const dictionary<T>& ys) { return xs.container() >= ys.container(); } } // namespace caf <commit_msg>Add free convenience function<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <algorithm> #include <iterator> #include <map> #include <string> #include "caf/string_view.hpp" namespace caf { /// Maps strings to values of type `V`, but unlike `std::map<std::string, V>` /// accepts `string_view` for looking up keys efficiently. template <class V> class dictionary { public: // -- member types ---------------------------------------------------------- using map_type = std::map<std::string, V>; using key_type = typename map_type::key_type; using mapped_type = typename map_type::mapped_type; using value_type = typename map_type::value_type; using allocator_type = typename map_type::allocator_type; using size_type = typename map_type::size_type; using difference_type = typename map_type::difference_type; using reference = typename map_type::reference; using const_reference = typename map_type::const_reference; using pointer = typename map_type::pointer; using const_pointer = typename map_type::const_pointer; using iterator = typename map_type::iterator; using const_iterator = typename map_type::const_iterator; using reverse_iterator = typename map_type::reverse_iterator; using const_reverse_iterator = typename map_type::const_reverse_iterator; using iterator_bool_pair = std::pair<iterator, bool>; struct mapped_type_less { inline bool operator()(const value_type& x, string_view y) const { return x.first < y; } inline bool operator()(const value_type& x, const value_type& y) const { return x.first < y.first; } inline bool operator()(string_view x, const value_type& y) const { return x < y.first; } }; // -- constructors, destructors, and assignment operators ------------------- dictionary() = default; dictionary(dictionary&&) = default; dictionary(const dictionary&) = default; dictionary(std::initializer_list<value_type> xs) : xs_(xs) { // nop } template <class InputIterator> dictionary(InputIterator first, InputIterator last) : xs_(first, last) { // nop } dictionary& operator=(dictionary&&) = default; dictionary& operator=(const dictionary&) = default; // -- iterator access -------------------------------------------------------- iterator begin() noexcept { return xs_.begin(); } const_iterator begin() const noexcept { return xs_.begin(); } const_iterator cbegin() const noexcept { return begin(); } reverse_iterator rbegin() noexcept { return xs_.rbegin(); } const_reverse_iterator rbegin() const noexcept { return xs_.rbegin(); } const_reverse_iterator crbegin() const noexcept { return rbegin(); } iterator end() noexcept { return xs_.end(); } const_iterator end() const noexcept { return xs_.end(); } const_iterator cend() const noexcept { return end(); } reverse_iterator rend() noexcept { return xs_.rend(); } const_reverse_iterator rend() const noexcept { return xs_.rend(); } const_reverse_iterator crend() const noexcept { return rend(); } // -- size ------------------------------------------------------------------- bool empty() const noexcept { return xs_.empty(); } size_type size() const noexcept { return xs_.size(); } // -- access to members ------------------------------------------------------ /// Gives raw access to the underlying container. map_type& container() noexcept { return xs_; } /// Gives raw access to the underlying container. const map_type& container() const noexcept { return xs_; } // -- modifiers ------------------------------------------------------------- void clear() noexcept { return xs_.clear(); } void swap(dictionary& other) { xs_.swap(other.xs_); } // -- insertion -------------------------------------------------------------- template <class K, class T> iterator_bool_pair emplace(K&& key, T&& value) { auto i = lower_bound(key); if (i == end()) return xs_.emplace(copy(std::forward<K>(key)), V{std::forward<T>(value)}); if (i->first == key) return {i, false}; return {xs_.emplace_hint(i, copy(std::forward<K>(key)), V{std::forward<T>(value)}), true}; } iterator_bool_pair insert(value_type kvp) { return emplace(kvp.first, std::move(kvp.second)); } iterator insert(iterator hint, value_type kvp) { return emplace_hint(hint, kvp.first, std::move(kvp.second)); } template <class T> iterator_bool_pair insert(string_view key, T&& value) { return emplace(key, V{std::forward<T>(value)}); } template <class K, class T> iterator emplace_hint(iterator hint, K&& key, T&& value) { if (hint == end() || hint->first > key) return xs_.emplace(copy(std::forward<K>(key)), V{std::forward<T>(value)}) .first; if (hint->first == key) return hint; return xs_.emplace_hint(hint, copy(std::forward<K>(key)), V{std::forward<T>(value)}); } template <class T> iterator insert(iterator hint, string_view key, T&& value) { return emplace_hint(hint, key, std::forward<T>(value)); } void insert(const_iterator first, const_iterator last) { xs_.insert(first, last); } template <class T> iterator_bool_pair insert_or_assign(string_view key, T&& value) { auto i = lower_bound(key); if (i == end()) return xs_.emplace(copy(key), V{std::forward<T>(value)}); if (i->first == key) { i->second = V{std::forward<T>(value)}; return {i, false}; } return {xs_.emplace_hint(i, copy(key), V{std::forward<T>(value)}), true}; } template <class T> iterator insert_or_assign(iterator hint, string_view key, T&& value) { if (hint == end() || hint->first > key) return insert_or_assign(key, std::forward<T>(value)).first; hint = lower_bound(hint, key); if (hint != end() && hint->first == key) { hint->second = std::forward<T>(value); return hint; } return xs_.emplace_hint(hint, copy(key), V{std::forward<T>(value)}); } // -- lookup ----------------------------------------------------------------- bool contains(string_view key) const noexcept { auto i = lower_bound(key); return !(i == end() || i->first != key); } size_t count(string_view key) const noexcept { return contains(key) ? 1u : 0u; } iterator find(string_view key) noexcept { auto i = lower_bound(key); return i != end() && i->first == key ? i : end(); } const_iterator find(string_view key) const noexcept { auto i = lower_bound(key); return i != end() && i->first == key ? i : end(); } iterator lower_bound(string_view key) { return lower_bound(begin(), key); } const_iterator lower_bound(string_view key) const { return lower_bound(begin(), key); } iterator upper_bound(string_view key) { mapped_type_less cmp; return std::upper_bound(begin(), end(), key, cmp); } const_iterator upper_bound(string_view key) const { mapped_type_less cmp; return std::upper_bound(begin(), end(), key, cmp); } // -- element access --------------------------------------------------------- mapped_type& operator[](string_view key) { return insert(key, mapped_type{}).first->second; } private: iterator lower_bound(iterator from, string_view key) { mapped_type_less cmp; return std::lower_bound(from, end(), key, cmp); } const_iterator lower_bound(const_iterator from, string_view key) const { mapped_type_less cmp; return std::lower_bound(from, end(), key, cmp); } template <size_t N> static inline std::string copy(const char (&str)[N]) { return std::string{str}; } // Copies the content of `str` into a new string. static inline std::string copy(string_view str) { return std::string{str.begin(), str.end()}; } // Moves the content of `str` into a new string. static inline std::string copy(std::string str) { return str; } map_type xs_; }; // -- operators ---------------------------------------------------------------- // @relates dictionary template <class T> bool operator==(const dictionary<T>& xs, const dictionary<T>& ys) { return xs.container() == ys.container(); } // @relates dictionary template <class T> bool operator!=(const dictionary<T>& xs, const dictionary<T>& ys) { return xs.container() != ys.container(); } // @relates dictionary template <class T> bool operator<(const dictionary<T>& xs, const dictionary<T>& ys) { return xs.container() < ys.container(); } // @relates dictionary template <class T> bool operator<=(const dictionary<T>& xs, const dictionary<T>& ys) { return xs.container() <= ys.container(); } // @relates dictionary template <class T> bool operator>(const dictionary<T>& xs, const dictionary<T>& ys) { return xs.container() > ys.container(); } // @relates dictionary template <class T> bool operator>=(const dictionary<T>& xs, const dictionary<T>& ys) { return xs.container() >= ys.container(); } // -- free functions ----------------------------------------------------------- /// Convenience function for calling `dict.insert_or_assign(key, value)`. // @relates dictionary template <class T> void put(dictionary<T>& dict, string_view key, T value) { dict.insert_or_assign(key, std::move(value)); } } // namespace caf <|endoftext|>
<commit_before>#include <mtp/ptp/Session.h> #include <mtp/ptp/Messages.h> #include <mtp/ptp/Container.h> #include <mtp/ptp/OperationRequest.h> namespace mtp { #define THROW_INVALID_RESPONSE void Session::Close() { OperationRequest req(OperationCode::CloseSession, 0, _sessionId); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(0, data, response); //HexDump("payload", data); } msg::ObjectHandles Session::GetObjectHandles(u32 storageId, u32 objectFormat, u32 parent) { u32 transaction = _transactionId++; OperationRequest req(OperationCode::GetObjectHandles, transaction, storageId, objectFormat, parent); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(transaction, data, response); InputStream stream(data, 8); //operation code + session id msg::ObjectHandles goh; goh.Read(stream); return goh; } msg::StorageIDs Session::GetStorageIDs() { u32 transaction = _transactionId++; OperationRequest req(OperationCode::GetStorageIDs, transaction, 0xffffffffu); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(transaction, data, response); InputStream stream(data, 8); //operation code + session id msg::StorageIDs gsi; gsi.Read(stream); return gsi; } msg::StorageInfo Session::GetStorageInfo(u32 storageId) { u32 transaction = _transactionId++; OperationRequest req(OperationCode::GetStorageInfo, transaction, storageId); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(transaction, data, response); InputStream stream(data, 8); //operation code + session id msg::StorageInfo gsi; gsi.Read(stream); return gsi; } msg::ObjectInfo Session::GetObjectInfo(u32 objectId) { u32 transaction = _transactionId++; OperationRequest req(OperationCode::GetObjectInfo, transaction, objectId); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(transaction, data, response); InputStream stream(data, 8); //operation code + session id msg::ObjectInfo goi; goi.Read(stream); return goi; } msg::ObjectPropsSupported Session::GetObjectPropsSupported(u32 objectId) { u32 transaction = _transactionId++; OperationRequest req(OperationCode::GetObjectPropsSupported, transaction, objectId); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(transaction, data, response); InputStream stream(data, 8); //operation code + session id msg::ObjectPropsSupported ops; ops.Read(stream); return ops; } ByteArray Session::GetObject(u32 objectId) { u32 transaction = _transactionId++; OperationRequest req(OperationCode::GetObject, transaction, objectId); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(transaction, data, response); return ByteArray(data.begin() + 8, data.end()); } Session::NewObjectInfo Session::SendObjectInfo(const msg::ObjectInfo &objectInfo, u32 storageId, u32 parentObject) { u32 transaction = _transactionId++; { OperationRequest req(OperationCode::SendObjectInfo, transaction, storageId, parentObject); Container container(req); _packeter.Write(container.Data); } { DataRequest req(OperationCode::SendObjectInfo, transaction); OutputStream stream(req.Data); objectInfo.Write(stream); Container container(req); _packeter.Write(container.Data); } ByteArray data, response; _packeter.Read(transaction, data, response); //HexDump("response", response); InputStream stream(response, 8); //operation code + session id NewObjectInfo noi; stream >> noi.StorageId; stream >> noi.ParentObjectId; stream >> noi.ObjectId; return noi; } void Session::SendObject(const ByteArray &object) { u32 transaction = _transactionId++; { OperationRequest req(OperationCode::SendObject, transaction); Container container(req); _packeter.Write(container.Data); } { DataRequest req(OperationCode::SendObject, transaction); req.Append(object); Container container(req); _packeter.Write(container.Data, 0); } ByteArray data, response; _packeter.Read(transaction, data, response); HexDump("response", response); } void Session::DeleteObject(u32 objectId) { u32 transaction = _transactionId++; OperationRequest req(OperationCode::DeleteObject, transaction, objectId); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(transaction, data, response); } } <commit_msg>added CHECK_RESPONSE macro, check every response<commit_after>#include <mtp/ptp/Session.h> #include <mtp/ptp/Messages.h> #include <mtp/ptp/Container.h> #include <mtp/ptp/OperationRequest.h> namespace mtp { #define CHECK_RESPONSE(RDATA) do { \ InputStream s(response); \ Response header(s);\ if (header.ResponseType != ResponseType::OK && header.ResponseType != ResponseType::SessionAlreadyOpen) \ throw InvalidResponseException(__func__, header.ResponseType); \ } while(false) void Session::Close() { OperationRequest req(OperationCode::CloseSession, 0, _sessionId); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(0, data, response); //HexDump("payload", data); } msg::ObjectHandles Session::GetObjectHandles(u32 storageId, u32 objectFormat, u32 parent) { u32 transaction = _transactionId++; OperationRequest req(OperationCode::GetObjectHandles, transaction, storageId, objectFormat, parent); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(transaction, data, response); CHECK_RESPONSE(response); InputStream stream(data, 8); //operation code + session id msg::ObjectHandles goh; goh.Read(stream); return goh; } msg::StorageIDs Session::GetStorageIDs() { u32 transaction = _transactionId++; OperationRequest req(OperationCode::GetStorageIDs, transaction, 0xffffffffu); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(transaction, data, response); CHECK_RESPONSE(response); InputStream stream(data, 8); //operation code + session id msg::StorageIDs gsi; gsi.Read(stream); return gsi; } msg::StorageInfo Session::GetStorageInfo(u32 storageId) { u32 transaction = _transactionId++; OperationRequest req(OperationCode::GetStorageInfo, transaction, storageId); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(transaction, data, response); CHECK_RESPONSE(response); InputStream stream(data, 8); //operation code + session id msg::StorageInfo gsi; gsi.Read(stream); return gsi; } msg::ObjectInfo Session::GetObjectInfo(u32 objectId) { u32 transaction = _transactionId++; OperationRequest req(OperationCode::GetObjectInfo, transaction, objectId); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(transaction, data, response); CHECK_RESPONSE(response); InputStream stream(data, 8); //operation code + session id msg::ObjectInfo goi; goi.Read(stream); return goi; } msg::ObjectPropsSupported Session::GetObjectPropsSupported(u32 objectId) { u32 transaction = _transactionId++; OperationRequest req(OperationCode::GetObjectPropsSupported, transaction, objectId); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(transaction, data, response); CHECK_RESPONSE(response); InputStream stream(data, 8); //operation code + session id msg::ObjectPropsSupported ops; ops.Read(stream); return ops; } ByteArray Session::GetObject(u32 objectId) { u32 transaction = _transactionId++; OperationRequest req(OperationCode::GetObject, transaction, objectId); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(transaction, data, response); CHECK_RESPONSE(response); return ByteArray(data.begin() + 8, data.end()); } Session::NewObjectInfo Session::SendObjectInfo(const msg::ObjectInfo &objectInfo, u32 storageId, u32 parentObject) { u32 transaction = _transactionId++; { OperationRequest req(OperationCode::SendObjectInfo, transaction, storageId, parentObject); Container container(req); _packeter.Write(container.Data); } { DataRequest req(OperationCode::SendObjectInfo, transaction); OutputStream stream(req.Data); objectInfo.Write(stream); Container container(req); _packeter.Write(container.Data); } ByteArray data, response; _packeter.Read(transaction, data, response); //HexDump("response", response); CHECK_RESPONSE(response); InputStream stream(response, 8); //operation code + session id NewObjectInfo noi; stream >> noi.StorageId; stream >> noi.ParentObjectId; stream >> noi.ObjectId; return noi; } void Session::SendObject(const ByteArray &object) { u32 transaction = _transactionId++; { OperationRequest req(OperationCode::SendObject, transaction); Container container(req); _packeter.Write(container.Data); } { DataRequest req(OperationCode::SendObject, transaction); req.Append(object); Container container(req); _packeter.Write(container.Data, 0); } ByteArray data, response; _packeter.Read(transaction, data, response); CHECK_RESPONSE(response); } void Session::DeleteObject(u32 objectId) { u32 transaction = _transactionId++; OperationRequest req(OperationCode::DeleteObject, transaction, objectId); Container container(req); _packeter.Write(container.Data); ByteArray data, response; _packeter.Read(transaction, data, response); CHECK_RESPONSE(response); } } <|endoftext|>
<commit_before>//===--- lib/CodeGen/DIE.cpp - DWARF Info Entries -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Data structures for DWARF info entries. // //===----------------------------------------------------------------------===// #include "DIE.h" #include "llvm/ADT/Twine.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/IR/DataLayout.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Format.h" #include "llvm/Support/FormattedStream.h" using namespace llvm; //===----------------------------------------------------------------------===// // DIEAbbrevData Implementation //===----------------------------------------------------------------------===// /// Profile - Used to gather unique data for the abbreviation folding set. /// void DIEAbbrevData::Profile(FoldingSetNodeID &ID) const { ID.AddInteger(Attribute); ID.AddInteger(Form); } //===----------------------------------------------------------------------===// // DIEAbbrev Implementation //===----------------------------------------------------------------------===// /// Profile - Used to gather unique data for the abbreviation folding set. /// void DIEAbbrev::Profile(FoldingSetNodeID &ID) const { ID.AddInteger(Tag); ID.AddInteger(ChildrenFlag); // For each attribute description. for (unsigned i = 0, N = Data.size(); i < N; ++i) Data[i].Profile(ID); } /// Emit - Print the abbreviation using the specified asm printer. /// void DIEAbbrev::Emit(AsmPrinter *AP) const { // Emit its Dwarf tag type. // FIXME: Doing work even in non-asm-verbose runs. AP->EmitULEB128(Tag, dwarf::TagString(Tag)); // Emit whether it has children DIEs. // FIXME: Doing work even in non-asm-verbose runs. AP->EmitULEB128(ChildrenFlag, dwarf::ChildrenString(ChildrenFlag)); // For each attribute description. for (unsigned i = 0, N = Data.size(); i < N; ++i) { const DIEAbbrevData &AttrData = Data[i]; // Emit attribute type. // FIXME: Doing work even in non-asm-verbose runs. AP->EmitULEB128(AttrData.getAttribute(), dwarf::AttributeString(AttrData.getAttribute())); // Emit form type. // FIXME: Doing work even in non-asm-verbose runs. AP->EmitULEB128(AttrData.getForm(), dwarf::FormEncodingString(AttrData.getForm())); } // Mark end of abbreviation. AP->EmitULEB128(0, "EOM(1)"); AP->EmitULEB128(0, "EOM(2)"); } #ifndef NDEBUG void DIEAbbrev::print(raw_ostream &O) { O << "Abbreviation @" << format("0x%lx", (long)(intptr_t)this) << " " << dwarf::TagString(Tag) << " " << dwarf::ChildrenString(ChildrenFlag) << '\n'; for (unsigned i = 0, N = Data.size(); i < N; ++i) { O << " " << dwarf::AttributeString(Data[i].getAttribute()) << " " << dwarf::FormEncodingString(Data[i].getForm()) << '\n'; } } void DIEAbbrev::dump() { print(dbgs()); } #endif //===----------------------------------------------------------------------===// // DIE Implementation //===----------------------------------------------------------------------===// DIE::~DIE() { for (unsigned i = 0, N = Children.size(); i < N; ++i) delete Children[i]; } /// Climb up the parent chain to get the compile unit DIE this DIE belongs to. DIE *DIE::getCompileUnit() const{ DIE *p = getParent(); while (p) { if (p->getTag() == dwarf::DW_TAG_compile_unit) return p; p = p->getParent(); } return NULL; } #ifndef NDEBUG void DIE::print(raw_ostream &O, unsigned IncIndent) { IndentCount += IncIndent; const std::string Indent(IndentCount, ' '); bool isBlock = Abbrev.getTag() == 0; if (!isBlock) { O << Indent << "Die: " << format("0x%lx", (long)(intptr_t)this) << ", Offset: " << Offset << ", Size: " << Size << "\n"; O << Indent << dwarf::TagString(Abbrev.getTag()) << " " << dwarf::ChildrenString(Abbrev.getChildrenFlag()) << "\n"; } else { O << "Size: " << Size << "\n"; } const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData(); IndentCount += 2; for (unsigned i = 0, N = Data.size(); i < N; ++i) { O << Indent; if (!isBlock) O << dwarf::AttributeString(Data[i].getAttribute()); else O << "Blk[" << i << "]"; O << " " << dwarf::FormEncodingString(Data[i].getForm()) << " "; Values[i]->print(O); O << "\n"; } IndentCount -= 2; for (unsigned j = 0, M = Children.size(); j < M; ++j) { Children[j]->print(O, 4); } if (!isBlock) O << "\n"; IndentCount -= IncIndent; } void DIE::dump() { print(dbgs()); } #endif void DIEValue::anchor() { } #ifndef NDEBUG void DIEValue::dump() { print(dbgs()); } #endif //===----------------------------------------------------------------------===// // DIEInteger Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit integer of appropriate size. /// void DIEInteger::EmitValue(AsmPrinter *Asm, unsigned Form) const { unsigned Size = ~0U; switch (Form) { case dwarf::DW_FORM_flag_present: // Emit something to keep the lines and comments in sync. // FIXME: Is there a better way to do this? if (Asm->OutStreamer.hasRawTextSupport()) Asm->OutStreamer.EmitRawText(StringRef("")); return; case dwarf::DW_FORM_flag: // Fall thru case dwarf::DW_FORM_ref1: // Fall thru case dwarf::DW_FORM_data1: Size = 1; break; case dwarf::DW_FORM_ref2: // Fall thru case dwarf::DW_FORM_data2: Size = 2; break; case dwarf::DW_FORM_sec_offset: // Fall thru case dwarf::DW_FORM_ref4: // Fall thru case dwarf::DW_FORM_data4: Size = 4; break; case dwarf::DW_FORM_ref8: // Fall thru case dwarf::DW_FORM_data8: Size = 8; break; case dwarf::DW_FORM_GNU_str_index: Asm->EmitULEB128(Integer); return; case dwarf::DW_FORM_GNU_addr_index: Asm->EmitULEB128(Integer); return; case dwarf::DW_FORM_udata: Asm->EmitULEB128(Integer); return; case dwarf::DW_FORM_sdata: Asm->EmitSLEB128(Integer); return; case dwarf::DW_FORM_addr: Size = Asm->getDataLayout().getPointerSize(); break; default: llvm_unreachable("DIE Value form not supported yet"); } Asm->OutStreamer.EmitIntValue(Integer, Size); } /// SizeOf - Determine size of integer value in bytes. /// unsigned DIEInteger::SizeOf(AsmPrinter *AP, unsigned Form) const { switch (Form) { case dwarf::DW_FORM_flag_present: return 0; case dwarf::DW_FORM_flag: // Fall thru case dwarf::DW_FORM_ref1: // Fall thru case dwarf::DW_FORM_data1: return sizeof(int8_t); case dwarf::DW_FORM_ref2: // Fall thru case dwarf::DW_FORM_data2: return sizeof(int16_t); case dwarf::DW_FORM_sec_offset: // Fall thru case dwarf::DW_FORM_ref4: // Fall thru case dwarf::DW_FORM_data4: return sizeof(int32_t); case dwarf::DW_FORM_ref8: // Fall thru case dwarf::DW_FORM_data8: return sizeof(int64_t); case dwarf::DW_FORM_GNU_str_index: return MCAsmInfo::getULEB128Size(Integer); case dwarf::DW_FORM_GNU_addr_index: return MCAsmInfo::getULEB128Size(Integer); case dwarf::DW_FORM_udata: return MCAsmInfo::getULEB128Size(Integer); case dwarf::DW_FORM_sdata: return MCAsmInfo::getSLEB128Size(Integer); case dwarf::DW_FORM_addr: return AP->getDataLayout().getPointerSize(); default: llvm_unreachable("DIE Value form not supported yet"); } } #ifndef NDEBUG void DIEInteger::print(raw_ostream &O) { O << "Int: " << (int64_t)Integer << " 0x"; O.write_hex(Integer); } #endif //===----------------------------------------------------------------------===// // DIELabel Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit label value. /// void DIELabel::EmitValue(AsmPrinter *AP, unsigned Form) const { AP->OutStreamer.EmitSymbolValue(Label, SizeOf(AP, Form)); } /// SizeOf - Determine size of label value in bytes. /// unsigned DIELabel::SizeOf(AsmPrinter *AP, unsigned Form) const { if (Form == dwarf::DW_FORM_data4) return 4; if (Form == dwarf::DW_FORM_sec_offset) return 4; if (Form == dwarf::DW_FORM_strp) return 4; return AP->getDataLayout().getPointerSize(); } #ifndef NDEBUG void DIELabel::print(raw_ostream &O) { O << "Lbl: " << Label->getName(); } #endif //===----------------------------------------------------------------------===// // DIEDelta Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit delta value. /// void DIEDelta::EmitValue(AsmPrinter *AP, unsigned Form) const { AP->EmitLabelDifference(LabelHi, LabelLo, SizeOf(AP, Form)); } /// SizeOf - Determine size of delta value in bytes. /// unsigned DIEDelta::SizeOf(AsmPrinter *AP, unsigned Form) const { if (Form == dwarf::DW_FORM_data4) return 4; if (Form == dwarf::DW_FORM_strp) return 4; return AP->getDataLayout().getPointerSize(); } #ifndef NDEBUG void DIEDelta::print(raw_ostream &O) { O << "Del: " << LabelHi->getName() << "-" << LabelLo->getName(); } #endif //===----------------------------------------------------------------------===// // DIEEntry Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit debug information entry offset. /// void DIEEntry::EmitValue(AsmPrinter *AP, unsigned Form) const { AP->EmitInt32(Entry->getOffset()); } #ifndef NDEBUG void DIEEntry::print(raw_ostream &O) { O << format("Die: 0x%lx", (long)(intptr_t)Entry); } #endif //===----------------------------------------------------------------------===// // DIEBlock Implementation //===----------------------------------------------------------------------===// /// ComputeSize - calculate the size of the block. /// unsigned DIEBlock::ComputeSize(AsmPrinter *AP) { if (!Size) { const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData(); for (unsigned i = 0, N = Values.size(); i < N; ++i) Size += Values[i]->SizeOf(AP, AbbrevData[i].getForm()); } return Size; } /// EmitValue - Emit block data. /// void DIEBlock::EmitValue(AsmPrinter *Asm, unsigned Form) const { switch (Form) { default: llvm_unreachable("Improper form for block"); case dwarf::DW_FORM_block1: Asm->EmitInt8(Size); break; case dwarf::DW_FORM_block2: Asm->EmitInt16(Size); break; case dwarf::DW_FORM_block4: Asm->EmitInt32(Size); break; case dwarf::DW_FORM_block: Asm->EmitULEB128(Size); break; } const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData(); for (unsigned i = 0, N = Values.size(); i < N; ++i) Values[i]->EmitValue(Asm, AbbrevData[i].getForm()); } /// SizeOf - Determine size of block data in bytes. /// unsigned DIEBlock::SizeOf(AsmPrinter *AP, unsigned Form) const { switch (Form) { case dwarf::DW_FORM_block1: return Size + sizeof(int8_t); case dwarf::DW_FORM_block2: return Size + sizeof(int16_t); case dwarf::DW_FORM_block4: return Size + sizeof(int32_t); case dwarf::DW_FORM_block: return Size + MCAsmInfo::getULEB128Size(Size); default: llvm_unreachable("Improper form for block"); } } #ifndef NDEBUG void DIEBlock::print(raw_ostream &O) { O << "Blk: "; DIE::print(O, 5); } #endif <commit_msg>No functionality change. Use unreachable in getCompileUnit.<commit_after>//===--- lib/CodeGen/DIE.cpp - DWARF Info Entries -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Data structures for DWARF info entries. // //===----------------------------------------------------------------------===// #include "DIE.h" #include "llvm/ADT/Twine.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/IR/DataLayout.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Format.h" #include "llvm/Support/FormattedStream.h" using namespace llvm; //===----------------------------------------------------------------------===// // DIEAbbrevData Implementation //===----------------------------------------------------------------------===// /// Profile - Used to gather unique data for the abbreviation folding set. /// void DIEAbbrevData::Profile(FoldingSetNodeID &ID) const { ID.AddInteger(Attribute); ID.AddInteger(Form); } //===----------------------------------------------------------------------===// // DIEAbbrev Implementation //===----------------------------------------------------------------------===// /// Profile - Used to gather unique data for the abbreviation folding set. /// void DIEAbbrev::Profile(FoldingSetNodeID &ID) const { ID.AddInteger(Tag); ID.AddInteger(ChildrenFlag); // For each attribute description. for (unsigned i = 0, N = Data.size(); i < N; ++i) Data[i].Profile(ID); } /// Emit - Print the abbreviation using the specified asm printer. /// void DIEAbbrev::Emit(AsmPrinter *AP) const { // Emit its Dwarf tag type. // FIXME: Doing work even in non-asm-verbose runs. AP->EmitULEB128(Tag, dwarf::TagString(Tag)); // Emit whether it has children DIEs. // FIXME: Doing work even in non-asm-verbose runs. AP->EmitULEB128(ChildrenFlag, dwarf::ChildrenString(ChildrenFlag)); // For each attribute description. for (unsigned i = 0, N = Data.size(); i < N; ++i) { const DIEAbbrevData &AttrData = Data[i]; // Emit attribute type. // FIXME: Doing work even in non-asm-verbose runs. AP->EmitULEB128(AttrData.getAttribute(), dwarf::AttributeString(AttrData.getAttribute())); // Emit form type. // FIXME: Doing work even in non-asm-verbose runs. AP->EmitULEB128(AttrData.getForm(), dwarf::FormEncodingString(AttrData.getForm())); } // Mark end of abbreviation. AP->EmitULEB128(0, "EOM(1)"); AP->EmitULEB128(0, "EOM(2)"); } #ifndef NDEBUG void DIEAbbrev::print(raw_ostream &O) { O << "Abbreviation @" << format("0x%lx", (long)(intptr_t)this) << " " << dwarf::TagString(Tag) << " " << dwarf::ChildrenString(ChildrenFlag) << '\n'; for (unsigned i = 0, N = Data.size(); i < N; ++i) { O << " " << dwarf::AttributeString(Data[i].getAttribute()) << " " << dwarf::FormEncodingString(Data[i].getForm()) << '\n'; } } void DIEAbbrev::dump() { print(dbgs()); } #endif //===----------------------------------------------------------------------===// // DIE Implementation //===----------------------------------------------------------------------===// DIE::~DIE() { for (unsigned i = 0, N = Children.size(); i < N; ++i) delete Children[i]; } /// Climb up the parent chain to get the compile unit DIE this DIE belongs to. DIE *DIE::getCompileUnit() const{ DIE *p = getParent(); while (p) { if (p->getTag() == dwarf::DW_TAG_compile_unit) return p; p = p->getParent(); } llvm_unreachable("We should not have orphaned DIEs."); } #ifndef NDEBUG void DIE::print(raw_ostream &O, unsigned IncIndent) { IndentCount += IncIndent; const std::string Indent(IndentCount, ' '); bool isBlock = Abbrev.getTag() == 0; if (!isBlock) { O << Indent << "Die: " << format("0x%lx", (long)(intptr_t)this) << ", Offset: " << Offset << ", Size: " << Size << "\n"; O << Indent << dwarf::TagString(Abbrev.getTag()) << " " << dwarf::ChildrenString(Abbrev.getChildrenFlag()) << "\n"; } else { O << "Size: " << Size << "\n"; } const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData(); IndentCount += 2; for (unsigned i = 0, N = Data.size(); i < N; ++i) { O << Indent; if (!isBlock) O << dwarf::AttributeString(Data[i].getAttribute()); else O << "Blk[" << i << "]"; O << " " << dwarf::FormEncodingString(Data[i].getForm()) << " "; Values[i]->print(O); O << "\n"; } IndentCount -= 2; for (unsigned j = 0, M = Children.size(); j < M; ++j) { Children[j]->print(O, 4); } if (!isBlock) O << "\n"; IndentCount -= IncIndent; } void DIE::dump() { print(dbgs()); } #endif void DIEValue::anchor() { } #ifndef NDEBUG void DIEValue::dump() { print(dbgs()); } #endif //===----------------------------------------------------------------------===// // DIEInteger Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit integer of appropriate size. /// void DIEInteger::EmitValue(AsmPrinter *Asm, unsigned Form) const { unsigned Size = ~0U; switch (Form) { case dwarf::DW_FORM_flag_present: // Emit something to keep the lines and comments in sync. // FIXME: Is there a better way to do this? if (Asm->OutStreamer.hasRawTextSupport()) Asm->OutStreamer.EmitRawText(StringRef("")); return; case dwarf::DW_FORM_flag: // Fall thru case dwarf::DW_FORM_ref1: // Fall thru case dwarf::DW_FORM_data1: Size = 1; break; case dwarf::DW_FORM_ref2: // Fall thru case dwarf::DW_FORM_data2: Size = 2; break; case dwarf::DW_FORM_sec_offset: // Fall thru case dwarf::DW_FORM_ref4: // Fall thru case dwarf::DW_FORM_data4: Size = 4; break; case dwarf::DW_FORM_ref8: // Fall thru case dwarf::DW_FORM_data8: Size = 8; break; case dwarf::DW_FORM_GNU_str_index: Asm->EmitULEB128(Integer); return; case dwarf::DW_FORM_GNU_addr_index: Asm->EmitULEB128(Integer); return; case dwarf::DW_FORM_udata: Asm->EmitULEB128(Integer); return; case dwarf::DW_FORM_sdata: Asm->EmitSLEB128(Integer); return; case dwarf::DW_FORM_addr: Size = Asm->getDataLayout().getPointerSize(); break; default: llvm_unreachable("DIE Value form not supported yet"); } Asm->OutStreamer.EmitIntValue(Integer, Size); } /// SizeOf - Determine size of integer value in bytes. /// unsigned DIEInteger::SizeOf(AsmPrinter *AP, unsigned Form) const { switch (Form) { case dwarf::DW_FORM_flag_present: return 0; case dwarf::DW_FORM_flag: // Fall thru case dwarf::DW_FORM_ref1: // Fall thru case dwarf::DW_FORM_data1: return sizeof(int8_t); case dwarf::DW_FORM_ref2: // Fall thru case dwarf::DW_FORM_data2: return sizeof(int16_t); case dwarf::DW_FORM_sec_offset: // Fall thru case dwarf::DW_FORM_ref4: // Fall thru case dwarf::DW_FORM_data4: return sizeof(int32_t); case dwarf::DW_FORM_ref8: // Fall thru case dwarf::DW_FORM_data8: return sizeof(int64_t); case dwarf::DW_FORM_GNU_str_index: return MCAsmInfo::getULEB128Size(Integer); case dwarf::DW_FORM_GNU_addr_index: return MCAsmInfo::getULEB128Size(Integer); case dwarf::DW_FORM_udata: return MCAsmInfo::getULEB128Size(Integer); case dwarf::DW_FORM_sdata: return MCAsmInfo::getSLEB128Size(Integer); case dwarf::DW_FORM_addr: return AP->getDataLayout().getPointerSize(); default: llvm_unreachable("DIE Value form not supported yet"); } } #ifndef NDEBUG void DIEInteger::print(raw_ostream &O) { O << "Int: " << (int64_t)Integer << " 0x"; O.write_hex(Integer); } #endif //===----------------------------------------------------------------------===// // DIELabel Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit label value. /// void DIELabel::EmitValue(AsmPrinter *AP, unsigned Form) const { AP->OutStreamer.EmitSymbolValue(Label, SizeOf(AP, Form)); } /// SizeOf - Determine size of label value in bytes. /// unsigned DIELabel::SizeOf(AsmPrinter *AP, unsigned Form) const { if (Form == dwarf::DW_FORM_data4) return 4; if (Form == dwarf::DW_FORM_sec_offset) return 4; if (Form == dwarf::DW_FORM_strp) return 4; return AP->getDataLayout().getPointerSize(); } #ifndef NDEBUG void DIELabel::print(raw_ostream &O) { O << "Lbl: " << Label->getName(); } #endif //===----------------------------------------------------------------------===// // DIEDelta Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit delta value. /// void DIEDelta::EmitValue(AsmPrinter *AP, unsigned Form) const { AP->EmitLabelDifference(LabelHi, LabelLo, SizeOf(AP, Form)); } /// SizeOf - Determine size of delta value in bytes. /// unsigned DIEDelta::SizeOf(AsmPrinter *AP, unsigned Form) const { if (Form == dwarf::DW_FORM_data4) return 4; if (Form == dwarf::DW_FORM_strp) return 4; return AP->getDataLayout().getPointerSize(); } #ifndef NDEBUG void DIEDelta::print(raw_ostream &O) { O << "Del: " << LabelHi->getName() << "-" << LabelLo->getName(); } #endif //===----------------------------------------------------------------------===// // DIEEntry Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit debug information entry offset. /// void DIEEntry::EmitValue(AsmPrinter *AP, unsigned Form) const { AP->EmitInt32(Entry->getOffset()); } #ifndef NDEBUG void DIEEntry::print(raw_ostream &O) { O << format("Die: 0x%lx", (long)(intptr_t)Entry); } #endif //===----------------------------------------------------------------------===// // DIEBlock Implementation //===----------------------------------------------------------------------===// /// ComputeSize - calculate the size of the block. /// unsigned DIEBlock::ComputeSize(AsmPrinter *AP) { if (!Size) { const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData(); for (unsigned i = 0, N = Values.size(); i < N; ++i) Size += Values[i]->SizeOf(AP, AbbrevData[i].getForm()); } return Size; } /// EmitValue - Emit block data. /// void DIEBlock::EmitValue(AsmPrinter *Asm, unsigned Form) const { switch (Form) { default: llvm_unreachable("Improper form for block"); case dwarf::DW_FORM_block1: Asm->EmitInt8(Size); break; case dwarf::DW_FORM_block2: Asm->EmitInt16(Size); break; case dwarf::DW_FORM_block4: Asm->EmitInt32(Size); break; case dwarf::DW_FORM_block: Asm->EmitULEB128(Size); break; } const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData(); for (unsigned i = 0, N = Values.size(); i < N; ++i) Values[i]->EmitValue(Asm, AbbrevData[i].getForm()); } /// SizeOf - Determine size of block data in bytes. /// unsigned DIEBlock::SizeOf(AsmPrinter *AP, unsigned Form) const { switch (Form) { case dwarf::DW_FORM_block1: return Size + sizeof(int8_t); case dwarf::DW_FORM_block2: return Size + sizeof(int16_t); case dwarf::DW_FORM_block4: return Size + sizeof(int32_t); case dwarf::DW_FORM_block: return Size + MCAsmInfo::getULEB128Size(Size); default: llvm_unreachable("Improper form for block"); } } #ifndef NDEBUG void DIEBlock::print(raw_ostream &O) { O << "Blk: "; DIE::print(O, 5); } #endif <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org> Copyright (C) 2002 Joseph Wenninger <jowenn@kde.org> Copyright (C) 2002 Anders Lund <anders.lund@lund.tdcadsl.dk> Copyright (C) 2007 Anders Lund <anders@alweb.dk> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kateconsole.h" #include <kiconloader.h> #include <klocalizedstring.h> #include <ktexteditor/document.h> #include <ktexteditor/view.h> #include <kde_terminal_interface.h> #include <kshell.h> #include <kparts/part.h> #include <QAction> #include <kactioncollection.h> #include <kmessagebox.h> #include <QApplication> #include <QStyle> #include <QIcon> #include <QShowEvent> #include <QLabel> #include <QCheckBox> #include <QVBoxLayout> #include <QFileInfo> #include <kpluginloader.h> #include <kservice.h> #include <kaboutdata.h> #include <kpluginfactory.h> #include <kauthorized.h> #include <KConfigGroup> #include <KXMLGUIFactory> K_PLUGIN_FACTORY_WITH_JSON (KateKonsolePluginFactory, "katekonsoleplugin.json", registerPlugin<KateKonsolePlugin>();) KateKonsolePlugin::KateKonsolePlugin( QObject* parent, const QList<QVariant>& ): KTextEditor::Plugin ( parent ) { m_previousEditorEnv=qgetenv("EDITOR"); if (!KAuthorized::authorizeKAction(QStringLiteral("shell_access"))) { KMessageBox::sorry(0, i18n ("You do not have enough karma to access a shell or terminal emulation")); } } KateKonsolePlugin::~KateKonsolePlugin() { ::setenv( "EDITOR", m_previousEditorEnv.data(), 1 ); } QObject *KateKonsolePlugin::createView (KTextEditor::MainWindow *mainWindow) { KateKonsolePluginView *view = new KateKonsolePluginView (this, mainWindow); return view; } KTextEditor::ConfigPage *KateKonsolePlugin::configPage (int number, QWidget *parent) { if (number != 0) return 0; return new KateKonsoleConfigPage(parent, this); } QString KateKonsolePlugin::configPageName (int number) const { if (number != 0) return QString(); return i18n("Terminal"); } QString KateKonsolePlugin::configPageFullName (int number) const { if (number != 0) return QString(); return i18n("Terminal Settings"); } QIcon KateKonsolePlugin::configPageIcon (int number) const { if (number != 0) return QIcon(); return QIcon::fromTheme(QStringLiteral("utilities-terminal")); } void KateKonsolePlugin::readConfig() { foreach ( KateKonsolePluginView *view, mViews ) view->readConfig(); } KateKonsolePluginView::KateKonsolePluginView (KateKonsolePlugin* plugin, KTextEditor::MainWindow *mainWindow) : QObject(mainWindow),m_plugin(plugin) { // init console QWidget *toolview = mainWindow->createToolView (plugin, QStringLiteral("kate_private_plugin_katekonsoleplugin"), KTextEditor::MainWindow::Bottom, SmallIcon(QStringLiteral("utilities-terminal")), i18n("Terminal")); m_console = new KateConsole(m_plugin, mainWindow, toolview); // register this view m_plugin->mViews.append ( this ); } KateKonsolePluginView::~KateKonsolePluginView () { // unregister this view m_plugin->mViews.removeAll (this); // cleanup, kill toolview + console QWidget *toolview = m_console->parentWidget(); delete m_console; delete toolview; } void KateKonsolePluginView::readConfig() { m_console->readConfig(); } KateConsole::KateConsole (KateKonsolePlugin* plugin, KTextEditor::MainWindow *mw, QWidget *parent) : QWidget (parent) , m_part (0) , m_mw (mw) , m_toolView (parent) , m_plugin(plugin) { KXMLGUIClient::setComponentName (QStringLiteral("katekonsole"), i18n ("Kate Terminal")); setXMLFile( QStringLiteral("ui.rc") ); // make sure we have a vertical layout new QVBoxLayout(this); QAction* a = actionCollection()->addAction(QStringLiteral("katekonsole_tools_pipe_to_terminal")); a->setIcon(QIcon::fromTheme(QStringLiteral("utilities-terminal"))); a->setText(i18nc("@action", "&Pipe to Terminal")); connect(a, SIGNAL(triggered()), this, SLOT(slotPipeToConsole())); a = actionCollection()->addAction(QStringLiteral("katekonsole_tools_sync")); a->setText(i18nc("@action", "S&ynchronize Terminal with Current Document")); connect(a, SIGNAL(triggered()), this, SLOT(slotManualSync())); a = actionCollection()->addAction(QStringLiteral("katekonsole_tools_toggle_focus")); a->setIcon(QIcon::fromTheme(QStringLiteral("utilities-terminal"))); a->setText(i18nc("@action", "&Focus Terminal")); connect(a, SIGNAL(triggered()), this, SLOT(slotToggleFocus())); m_mw->guiFactory()->addClient (this); readConfig(); } KateConsole::~KateConsole () { m_mw->guiFactory()->removeClient (this); if (m_part) disconnect ( m_part, SIGNAL(destroyed()), this, SLOT(slotDestroyed()) ); } void KateConsole::loadConsoleIfNeeded() { if (m_part) return; if (!window() || !parentWidget()) return; if (!window() || !isVisibleTo(window())) return; KPluginFactory* factory = 0; KService::Ptr service = KService::serviceByDesktopName(QStringLiteral("konsolepart")); if (service) { factory = KPluginLoader(service->library()).factory(); } if (!factory) return; m_part = static_cast<KParts::ReadOnlyPart *>(factory->create<QObject>(this, this)); if (!m_part) return; layout()->addWidget(m_part->widget()); // start the terminal qobject_cast<TerminalInterface*>(m_part)->showShellInDir( QString() ); // KGlobal::locale()->insertCatalog("konsole"); // FIXME KF5: insert catalog setFocusProxy(m_part->widget()); m_part->widget()->show(); connect ( m_part, SIGNAL(destroyed()), this, SLOT(slotDestroyed()) ); connect ( m_part, SIGNAL(overrideShortcut(QKeyEvent*,bool&)), this, SLOT(overrideShortcut(QKeyEvent*,bool&))); slotSync(); } void KateConsole::slotDestroyed () { m_part = 0; m_currentPath.clear (); // hide the dockwidget if (parentWidget()) { m_mw->hideToolView (m_toolView); } } void KateConsole::overrideShortcut (QKeyEvent *, bool &override) { /** * let konsole handle all shortcuts */ override = true; } void KateConsole::showEvent(QShowEvent *) { if (m_part) return; loadConsoleIfNeeded(); } void KateConsole::cd (const QString & path) { if (m_currentPath == path) return; if (!m_part) return; m_currentPath = path; sendInput(QStringLiteral("cd ") + KShell::quoteArg(m_currentPath) + QLatin1Char('\n')); } void KateConsole::sendInput( const QString& text ) { loadConsoleIfNeeded(); if (!m_part) return; TerminalInterface *t = qobject_cast<TerminalInterface *>(m_part); if (!t) return; t->sendInput (text); } void KateConsole::slotPipeToConsole () { if (KMessageBox::warningContinueCancel (m_mw->window() , i18n ("Do you really want to pipe the text to the console? This will execute any contained commands with your user rights.") , i18n ("Pipe to Terminal?") , KGuiItem(i18n("Pipe to Terminal")), KStandardGuiItem::cancel(), QStringLiteral("Pipe To Terminal Warning")) != KMessageBox::Continue) return; KTextEditor::View *v = m_mw->activeView(); if (!v) return; if (v->selection()) sendInput (v->selectionText()); else sendInput (v->document()->text()); } void KateConsole::slotSync(KTextEditor::View *) { if (m_mw->activeView() ) { QUrl u = m_mw->activeView()->document()->url(); if ( u.isValid() && u.isLocalFile() ) { QFileInfo fi(u.toLocalFile()); cd(fi.absoluteFilePath() ); } else if ( !u.isEmpty() ) { sendInput( QStringLiteral("### ") + i18n("Sorry, cannot cd into '%1'", u.toLocalFile() ) + QLatin1Char('\n') ); } } } void KateConsole::slotManualSync() { m_currentPath.clear (); slotSync(); if ( ! m_part || ! m_part->widget()->isVisible() ) m_mw->showToolView( parentWidget() ); } void KateConsole::slotToggleFocus() { QAction *action = actionCollection()->action(QStringLiteral("katekonsole_tools_toggle_focus")); if ( ! m_part ) { m_mw->showToolView( parentWidget() ); action->setText( i18n("Defocus Terminal") ); return; // this shows and focuses the konsole } if ( ! m_part ) return; if (m_part->widget()->hasFocus()) { if (m_mw->activeView()) m_mw->activeView()->setFocus(); action->setText( i18n("Focus Terminal") ); } else { // show the view if it is hidden if (parentWidget()->isHidden()) m_mw->showToolView( parentWidget() ); else // should focus the widget too! m_part->widget()->setFocus( Qt::OtherFocusReason ); action->setText( i18n("Defocus Terminal") ); } } void KateConsole::readConfig() { disconnect(m_mw, &KTextEditor::MainWindow::viewChanged, this, &KateConsole::slotSync); if ( KConfigGroup(KSharedConfig::openConfig(), "Konsole").readEntry("AutoSyncronize", false) ) { connect(m_mw, &KTextEditor::MainWindow::viewChanged, this, &KateConsole::slotSync); } if ( KConfigGroup(KSharedConfig::openConfig(), "Konsole").readEntry("SetEditor", false) ) ::setenv( "EDITOR", "kate -b",1); else ::setenv( "EDITOR", m_plugin->previousEditorEnv().data(), 1 ); } KateKonsoleConfigPage::KateKonsoleConfigPage( QWidget* parent, KateKonsolePlugin *plugin ) : KTextEditor::ConfigPage( parent ) , mPlugin( plugin ) { QVBoxLayout *lo = new QVBoxLayout( this ); lo->setSpacing(QApplication::style()->pixelMetric(QStyle::PM_DefaultLayoutSpacing)); cbAutoSyncronize = new QCheckBox( i18n("&Automatically synchronize the terminal with the current document when possible"), this ); lo->addWidget( cbAutoSyncronize ); cbSetEditor = new QCheckBox( i18n("Set &EDITOR environment variable to 'kate -b'"), this ); lo->addWidget( cbSetEditor ); QLabel *tmp = new QLabel(this); tmp->setText(i18n("Important: The document has to be closed to make the console application continue")); lo->addWidget(tmp); reset(); lo->addStretch(); connect( cbAutoSyncronize, SIGNAL(stateChanged(int)), SIGNAL(changed()) ); connect( cbSetEditor, SIGNAL(stateChanged(int)), SIGNAL(changed()) ); } void KateKonsoleConfigPage::apply() { KConfigGroup config(KSharedConfig::openConfig(), "Konsole"); config.writeEntry("AutoSyncronize", cbAutoSyncronize->isChecked()); config.writeEntry("SetEditor", cbSetEditor->isChecked()); config.sync(); mPlugin->readConfig(); } void KateKonsoleConfigPage::reset() { KConfigGroup config(KSharedConfig::openConfig(), "Konsole"); cbAutoSyncronize->setChecked(config.readEntry("AutoSyncronize", false)); cbSetEditor->setChecked(config.readEntry("SetEditor", false)); } #include "kateconsole.moc" // kate: space-indent on; indent-width 2; replace-tabs on; <commit_msg>absoluteFilePath() -> absolutePath()<commit_after>/* This file is part of the KDE project Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org> Copyright (C) 2002 Joseph Wenninger <jowenn@kde.org> Copyright (C) 2002 Anders Lund <anders.lund@lund.tdcadsl.dk> Copyright (C) 2007 Anders Lund <anders@alweb.dk> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kateconsole.h" #include <kiconloader.h> #include <klocalizedstring.h> #include <ktexteditor/document.h> #include <ktexteditor/view.h> #include <kde_terminal_interface.h> #include <kshell.h> #include <kparts/part.h> #include <QAction> #include <kactioncollection.h> #include <kmessagebox.h> #include <QApplication> #include <QStyle> #include <QIcon> #include <QShowEvent> #include <QLabel> #include <QCheckBox> #include <QVBoxLayout> #include <QFileInfo> #include <kpluginloader.h> #include <kservice.h> #include <kaboutdata.h> #include <kpluginfactory.h> #include <kauthorized.h> #include <KConfigGroup> #include <KXMLGUIFactory> K_PLUGIN_FACTORY_WITH_JSON (KateKonsolePluginFactory, "katekonsoleplugin.json", registerPlugin<KateKonsolePlugin>();) KateKonsolePlugin::KateKonsolePlugin( QObject* parent, const QList<QVariant>& ): KTextEditor::Plugin ( parent ) { m_previousEditorEnv=qgetenv("EDITOR"); if (!KAuthorized::authorizeKAction(QStringLiteral("shell_access"))) { KMessageBox::sorry(0, i18n ("You do not have enough karma to access a shell or terminal emulation")); } } KateKonsolePlugin::~KateKonsolePlugin() { ::setenv( "EDITOR", m_previousEditorEnv.data(), 1 ); } QObject *KateKonsolePlugin::createView (KTextEditor::MainWindow *mainWindow) { KateKonsolePluginView *view = new KateKonsolePluginView (this, mainWindow); return view; } KTextEditor::ConfigPage *KateKonsolePlugin::configPage (int number, QWidget *parent) { if (number != 0) return 0; return new KateKonsoleConfigPage(parent, this); } QString KateKonsolePlugin::configPageName (int number) const { if (number != 0) return QString(); return i18n("Terminal"); } QString KateKonsolePlugin::configPageFullName (int number) const { if (number != 0) return QString(); return i18n("Terminal Settings"); } QIcon KateKonsolePlugin::configPageIcon (int number) const { if (number != 0) return QIcon(); return QIcon::fromTheme(QStringLiteral("utilities-terminal")); } void KateKonsolePlugin::readConfig() { foreach ( KateKonsolePluginView *view, mViews ) view->readConfig(); } KateKonsolePluginView::KateKonsolePluginView (KateKonsolePlugin* plugin, KTextEditor::MainWindow *mainWindow) : QObject(mainWindow),m_plugin(plugin) { // init console QWidget *toolview = mainWindow->createToolView (plugin, QStringLiteral("kate_private_plugin_katekonsoleplugin"), KTextEditor::MainWindow::Bottom, SmallIcon(QStringLiteral("utilities-terminal")), i18n("Terminal")); m_console = new KateConsole(m_plugin, mainWindow, toolview); // register this view m_plugin->mViews.append ( this ); } KateKonsolePluginView::~KateKonsolePluginView () { // unregister this view m_plugin->mViews.removeAll (this); // cleanup, kill toolview + console QWidget *toolview = m_console->parentWidget(); delete m_console; delete toolview; } void KateKonsolePluginView::readConfig() { m_console->readConfig(); } KateConsole::KateConsole (KateKonsolePlugin* plugin, KTextEditor::MainWindow *mw, QWidget *parent) : QWidget (parent) , m_part (0) , m_mw (mw) , m_toolView (parent) , m_plugin(plugin) { KXMLGUIClient::setComponentName (QStringLiteral("katekonsole"), i18n ("Kate Terminal")); setXMLFile( QStringLiteral("ui.rc") ); // make sure we have a vertical layout new QVBoxLayout(this); QAction* a = actionCollection()->addAction(QStringLiteral("katekonsole_tools_pipe_to_terminal")); a->setIcon(QIcon::fromTheme(QStringLiteral("utilities-terminal"))); a->setText(i18nc("@action", "&Pipe to Terminal")); connect(a, SIGNAL(triggered()), this, SLOT(slotPipeToConsole())); a = actionCollection()->addAction(QStringLiteral("katekonsole_tools_sync")); a->setText(i18nc("@action", "S&ynchronize Terminal with Current Document")); connect(a, SIGNAL(triggered()), this, SLOT(slotManualSync())); a = actionCollection()->addAction(QStringLiteral("katekonsole_tools_toggle_focus")); a->setIcon(QIcon::fromTheme(QStringLiteral("utilities-terminal"))); a->setText(i18nc("@action", "&Focus Terminal")); connect(a, SIGNAL(triggered()), this, SLOT(slotToggleFocus())); m_mw->guiFactory()->addClient (this); readConfig(); } KateConsole::~KateConsole () { m_mw->guiFactory()->removeClient (this); if (m_part) disconnect ( m_part, SIGNAL(destroyed()), this, SLOT(slotDestroyed()) ); } void KateConsole::loadConsoleIfNeeded() { if (m_part) return; if (!window() || !parentWidget()) return; if (!window() || !isVisibleTo(window())) return; KPluginFactory* factory = 0; KService::Ptr service = KService::serviceByDesktopName(QStringLiteral("konsolepart")); if (service) { factory = KPluginLoader(service->library()).factory(); } if (!factory) return; m_part = static_cast<KParts::ReadOnlyPart *>(factory->create<QObject>(this, this)); if (!m_part) return; layout()->addWidget(m_part->widget()); // start the terminal qobject_cast<TerminalInterface*>(m_part)->showShellInDir( QString() ); // KGlobal::locale()->insertCatalog("konsole"); // FIXME KF5: insert catalog setFocusProxy(m_part->widget()); m_part->widget()->show(); connect ( m_part, SIGNAL(destroyed()), this, SLOT(slotDestroyed()) ); connect ( m_part, SIGNAL(overrideShortcut(QKeyEvent*,bool&)), this, SLOT(overrideShortcut(QKeyEvent*,bool&))); slotSync(); } void KateConsole::slotDestroyed () { m_part = 0; m_currentPath.clear (); // hide the dockwidget if (parentWidget()) { m_mw->hideToolView (m_toolView); } } void KateConsole::overrideShortcut (QKeyEvent *, bool &override) { /** * let konsole handle all shortcuts */ override = true; } void KateConsole::showEvent(QShowEvent *) { if (m_part) return; loadConsoleIfNeeded(); } void KateConsole::cd (const QString & path) { if (m_currentPath == path) return; if (!m_part) return; m_currentPath = path; sendInput(QStringLiteral("cd ") + KShell::quoteArg(m_currentPath) + QLatin1Char('\n')); } void KateConsole::sendInput( const QString& text ) { loadConsoleIfNeeded(); if (!m_part) return; TerminalInterface *t = qobject_cast<TerminalInterface *>(m_part); if (!t) return; t->sendInput (text); } void KateConsole::slotPipeToConsole () { if (KMessageBox::warningContinueCancel (m_mw->window() , i18n ("Do you really want to pipe the text to the console? This will execute any contained commands with your user rights.") , i18n ("Pipe to Terminal?") , KGuiItem(i18n("Pipe to Terminal")), KStandardGuiItem::cancel(), QStringLiteral("Pipe To Terminal Warning")) != KMessageBox::Continue) return; KTextEditor::View *v = m_mw->activeView(); if (!v) return; if (v->selection()) sendInput (v->selectionText()); else sendInput (v->document()->text()); } void KateConsole::slotSync(KTextEditor::View *) { if (m_mw->activeView()) { QUrl u = m_mw->activeView()->document()->url(); if (u.isValid() && u.isLocalFile()) { QFileInfo fi(u.toLocalFile()); cd(fi.absolutePath()); } else if (!u.isEmpty()) { sendInput( QStringLiteral("### ") + i18n("Sorry, cannot cd into '%1'", u.toLocalFile() ) + QLatin1Char('\n') ); } } } void KateConsole::slotManualSync() { m_currentPath.clear (); slotSync(); if ( ! m_part || ! m_part->widget()->isVisible() ) m_mw->showToolView( parentWidget() ); } void KateConsole::slotToggleFocus() { QAction *action = actionCollection()->action(QStringLiteral("katekonsole_tools_toggle_focus")); if ( ! m_part ) { m_mw->showToolView( parentWidget() ); action->setText( i18n("Defocus Terminal") ); return; // this shows and focuses the konsole } if ( ! m_part ) return; if (m_part->widget()->hasFocus()) { if (m_mw->activeView()) m_mw->activeView()->setFocus(); action->setText( i18n("Focus Terminal") ); } else { // show the view if it is hidden if (parentWidget()->isHidden()) m_mw->showToolView( parentWidget() ); else // should focus the widget too! m_part->widget()->setFocus( Qt::OtherFocusReason ); action->setText( i18n("Defocus Terminal") ); } } void KateConsole::readConfig() { disconnect(m_mw, &KTextEditor::MainWindow::viewChanged, this, &KateConsole::slotSync); if ( KConfigGroup(KSharedConfig::openConfig(), "Konsole").readEntry("AutoSyncronize", false) ) { connect(m_mw, &KTextEditor::MainWindow::viewChanged, this, &KateConsole::slotSync); } if ( KConfigGroup(KSharedConfig::openConfig(), "Konsole").readEntry("SetEditor", false) ) ::setenv( "EDITOR", "kate -b",1); else ::setenv( "EDITOR", m_plugin->previousEditorEnv().data(), 1 ); } KateKonsoleConfigPage::KateKonsoleConfigPage( QWidget* parent, KateKonsolePlugin *plugin ) : KTextEditor::ConfigPage( parent ) , mPlugin( plugin ) { QVBoxLayout *lo = new QVBoxLayout( this ); lo->setSpacing(QApplication::style()->pixelMetric(QStyle::PM_DefaultLayoutSpacing)); cbAutoSyncronize = new QCheckBox( i18n("&Automatically synchronize the terminal with the current document when possible"), this ); lo->addWidget( cbAutoSyncronize ); cbSetEditor = new QCheckBox( i18n("Set &EDITOR environment variable to 'kate -b'"), this ); lo->addWidget( cbSetEditor ); QLabel *tmp = new QLabel(this); tmp->setText(i18n("Important: The document has to be closed to make the console application continue")); lo->addWidget(tmp); reset(); lo->addStretch(); connect( cbAutoSyncronize, SIGNAL(stateChanged(int)), SIGNAL(changed()) ); connect( cbSetEditor, SIGNAL(stateChanged(int)), SIGNAL(changed()) ); } void KateKonsoleConfigPage::apply() { KConfigGroup config(KSharedConfig::openConfig(), "Konsole"); config.writeEntry("AutoSyncronize", cbAutoSyncronize->isChecked()); config.writeEntry("SetEditor", cbSetEditor->isChecked()); config.sync(); mPlugin->readConfig(); } void KateKonsoleConfigPage::reset() { KConfigGroup config(KSharedConfig::openConfig(), "Konsole"); cbAutoSyncronize->setChecked(config.readEntry("AutoSyncronize", false)); cbSetEditor->setChecked(config.readEntry("SetEditor", false)); } #include "kateconsole.moc" // kate: space-indent on; indent-width 2; replace-tabs on; <|endoftext|>
<commit_before><commit_msg>Fixed name for xapiand_max_time_delete<commit_after><|endoftext|>
<commit_before>/* * Copyright © 2012 Intel Corporation * * 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 (including the next * paragraph) 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 "main/core.h" #include "ir.h" #include "linker.h" #include "ir_uniform.h" #include "glsl_symbol_table.h" #include "program/hash_table.h" /* These functions are put in a "private" namespace instead of being marked * static so that the unit tests can access them. See * http://code.google.com/p/googletest/wiki/AdvancedGuide#Testing_Private_Code */ namespace linker { gl_uniform_storage * get_storage(gl_uniform_storage *storage, unsigned num_storage, const char *name) { for (unsigned int i = 0; i < num_storage; i++) { if (strcmp(name, storage[i].name) == 0) return &storage[i]; } return NULL; } void copy_constant_to_storage(union gl_constant_value *storage, const ir_constant *val, const enum glsl_base_type base_type, const unsigned int elements) { for (unsigned int i = 0; i < elements; i++) { switch (base_type) { case GLSL_TYPE_UINT: storage[i].u = val->value.u[i]; break; case GLSL_TYPE_INT: case GLSL_TYPE_SAMPLER: storage[i].i = val->value.i[i]; break; case GLSL_TYPE_FLOAT: storage[i].f = val->value.f[i]; break; case GLSL_TYPE_BOOL: storage[i].b = int(val->value.b[i]); break; case GLSL_TYPE_ARRAY: case GLSL_TYPE_STRUCT: case GLSL_TYPE_IMAGE: case GLSL_TYPE_ATOMIC_UINT: case GLSL_TYPE_INTERFACE: case GLSL_TYPE_VOID: case GLSL_TYPE_ERROR: /* All other types should have already been filtered by other * paths in the caller. */ assert(!"Should not get here."); break; } } } void set_uniform_binding(void *mem_ctx, gl_shader_program *prog, const char *name, const glsl_type *type, int binding) { struct gl_uniform_storage *const storage = get_storage(prog->UniformStorage, prog->NumUserUniformStorage, name); if (storage == NULL) { assert(storage != NULL); return; } if (storage->type->is_sampler()) { unsigned elements = MAX2(storage->array_elements, 1); /* From section 4.4.4 of the GLSL 4.20 specification: * "If the binding identifier is used with an array, the first element * of the array takes the specified unit and each subsequent element * takes the next consecutive unit." */ for (unsigned int i = 0; i < elements; i++) { storage->storage[i].i = binding + i; } for (int sh = 0; sh < MESA_SHADER_STAGES; sh++) { gl_shader *shader = prog->_LinkedShaders[sh]; if (shader && storage->sampler[sh].active) { for (unsigned i = 0; i < elements; i++) { unsigned index = storage->sampler[sh].index + i; shader->SamplerUnits[index] = storage->storage[i].i; } } } } else if (storage->block_index != -1) { /* This is a field of a UBO. val is the binding index. */ for (int i = 0; i < MESA_SHADER_STAGES; i++) { int stage_index = prog->UniformBlockStageIndex[i][storage->block_index]; if (stage_index != -1) { struct gl_shader *sh = prog->_LinkedShaders[i]; sh->UniformBlocks[stage_index].Binding = binding; } } } storage->initialized = true; } void set_uniform_initializer(void *mem_ctx, gl_shader_program *prog, const char *name, const glsl_type *type, ir_constant *val) { if (type->is_record()) { ir_constant *field_constant; field_constant = (ir_constant *)val->components.get_head(); for (unsigned int i = 0; i < type->length; i++) { const glsl_type *field_type = type->fields.structure[i].type; const char *field_name = ralloc_asprintf(mem_ctx, "%s.%s", name, type->fields.structure[i].name); set_uniform_initializer(mem_ctx, prog, field_name, field_type, field_constant); field_constant = (ir_constant *)field_constant->next; } return; } else if (type->is_array() && type->fields.array->is_record()) { const glsl_type *const element_type = type->fields.array; for (unsigned int i = 0; i < type->length; i++) { const char *element_name = ralloc_asprintf(mem_ctx, "%s[%d]", name, i); set_uniform_initializer(mem_ctx, prog, element_name, element_type, val->array_elements[i]); } return; } struct gl_uniform_storage *const storage = get_storage(prog->UniformStorage, prog->NumUserUniformStorage, name); if (storage == NULL) { assert(storage != NULL); return; } if (val->type->is_array()) { const enum glsl_base_type base_type = val->array_elements[0]->type->base_type; const unsigned int elements = val->array_elements[0]->type->components(); unsigned int idx = 0; assert(val->type->length >= storage->array_elements); for (unsigned int i = 0; i < storage->array_elements; i++) { copy_constant_to_storage(& storage->storage[idx], val->array_elements[i], base_type, elements); idx += elements; } } else { copy_constant_to_storage(storage->storage, val, val->type->base_type, val->type->components()); if (storage->type->is_sampler()) { for (int sh = 0; sh < MESA_SHADER_STAGES; sh++) { gl_shader *shader = prog->_LinkedShaders[sh]; if (shader && storage->sampler[sh].active) { unsigned index = storage->sampler[sh].index; shader->SamplerUnits[index] = storage->storage[0].i; } } } } storage->initialized = true; } } void link_set_uniform_initializers(struct gl_shader_program *prog) { void *mem_ctx = NULL; for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) { struct gl_shader *shader = prog->_LinkedShaders[i]; if (shader == NULL) continue; foreach_list(node, shader->ir) { ir_variable *const var = ((ir_instruction *) node)->as_variable(); if (!var || var->data.mode != ir_var_uniform) continue; if (!mem_ctx) mem_ctx = ralloc_context(NULL); if (var->data.explicit_binding) { linker::set_uniform_binding(mem_ctx, prog, var->name, var->type, var->data.binding); } else if (var->constant_value) { linker::set_uniform_initializer(mem_ctx, prog, var->name, var->type, var->constant_value); } } } ralloc_free(mem_ctx); } <commit_msg>linker: Split set_uniform_binding into separate functions for blocks and samplers<commit_after>/* * Copyright © 2012 Intel Corporation * * 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 (including the next * paragraph) 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 "main/core.h" #include "ir.h" #include "linker.h" #include "ir_uniform.h" #include "glsl_symbol_table.h" #include "program/hash_table.h" /* These functions are put in a "private" namespace instead of being marked * static so that the unit tests can access them. See * http://code.google.com/p/googletest/wiki/AdvancedGuide#Testing_Private_Code */ namespace linker { gl_uniform_storage * get_storage(gl_uniform_storage *storage, unsigned num_storage, const char *name) { for (unsigned int i = 0; i < num_storage; i++) { if (strcmp(name, storage[i].name) == 0) return &storage[i]; } return NULL; } void copy_constant_to_storage(union gl_constant_value *storage, const ir_constant *val, const enum glsl_base_type base_type, const unsigned int elements) { for (unsigned int i = 0; i < elements; i++) { switch (base_type) { case GLSL_TYPE_UINT: storage[i].u = val->value.u[i]; break; case GLSL_TYPE_INT: case GLSL_TYPE_SAMPLER: storage[i].i = val->value.i[i]; break; case GLSL_TYPE_FLOAT: storage[i].f = val->value.f[i]; break; case GLSL_TYPE_BOOL: storage[i].b = int(val->value.b[i]); break; case GLSL_TYPE_ARRAY: case GLSL_TYPE_STRUCT: case GLSL_TYPE_IMAGE: case GLSL_TYPE_ATOMIC_UINT: case GLSL_TYPE_INTERFACE: case GLSL_TYPE_VOID: case GLSL_TYPE_ERROR: /* All other types should have already been filtered by other * paths in the caller. */ assert(!"Should not get here."); break; } } } void set_sampler_binding(void *mem_ctx, gl_shader_program *prog, const char *name, const glsl_type *type, int binding) { struct gl_uniform_storage *const storage = get_storage(prog->UniformStorage, prog->NumUserUniformStorage, name); if (storage == NULL) { assert(storage != NULL); return; } { unsigned elements = MAX2(storage->array_elements, 1); /* From section 4.4.4 of the GLSL 4.20 specification: * "If the binding identifier is used with an array, the first element * of the array takes the specified unit and each subsequent element * takes the next consecutive unit." */ for (unsigned int i = 0; i < elements; i++) { storage->storage[i].i = binding + i; } for (int sh = 0; sh < MESA_SHADER_STAGES; sh++) { gl_shader *shader = prog->_LinkedShaders[sh]; if (shader && storage->sampler[sh].active) { for (unsigned i = 0; i < elements; i++) { unsigned index = storage->sampler[sh].index + i; shader->SamplerUnits[index] = storage->storage[i].i; } } } } storage->initialized = true; } void set_block_binding(void *mem_ctx, gl_shader_program *prog, const char *name, const glsl_type *type, int binding) { struct gl_uniform_storage *const storage = get_storage(prog->UniformStorage, prog->NumUserUniformStorage, name); if (storage == NULL) { assert(storage != NULL); return; } if (storage->block_index != -1) { /* This is a field of a UBO. val is the binding index. */ for (int i = 0; i < MESA_SHADER_STAGES; i++) { int stage_index = prog->UniformBlockStageIndex[i][storage->block_index]; if (stage_index != -1) { struct gl_shader *sh = prog->_LinkedShaders[i]; sh->UniformBlocks[stage_index].Binding = binding; } } } storage->initialized = true; } void set_uniform_binding(void *mem_ctx, gl_shader_program *prog, const char *name, const glsl_type *type, int binding) { struct gl_uniform_storage *const storage = get_storage(prog->UniformStorage, prog->NumUserUniformStorage, name); if (storage == NULL) { assert(storage != NULL); return; } if (storage->type->is_sampler()) { set_sampler_binding(mem_ctx, prog, name, type, binding); } else if (storage->block_index != -1) { set_block_binding(mem_ctx, prog, name, type, binding); } } void set_uniform_initializer(void *mem_ctx, gl_shader_program *prog, const char *name, const glsl_type *type, ir_constant *val) { if (type->is_record()) { ir_constant *field_constant; field_constant = (ir_constant *)val->components.get_head(); for (unsigned int i = 0; i < type->length; i++) { const glsl_type *field_type = type->fields.structure[i].type; const char *field_name = ralloc_asprintf(mem_ctx, "%s.%s", name, type->fields.structure[i].name); set_uniform_initializer(mem_ctx, prog, field_name, field_type, field_constant); field_constant = (ir_constant *)field_constant->next; } return; } else if (type->is_array() && type->fields.array->is_record()) { const glsl_type *const element_type = type->fields.array; for (unsigned int i = 0; i < type->length; i++) { const char *element_name = ralloc_asprintf(mem_ctx, "%s[%d]", name, i); set_uniform_initializer(mem_ctx, prog, element_name, element_type, val->array_elements[i]); } return; } struct gl_uniform_storage *const storage = get_storage(prog->UniformStorage, prog->NumUserUniformStorage, name); if (storage == NULL) { assert(storage != NULL); return; } if (val->type->is_array()) { const enum glsl_base_type base_type = val->array_elements[0]->type->base_type; const unsigned int elements = val->array_elements[0]->type->components(); unsigned int idx = 0; assert(val->type->length >= storage->array_elements); for (unsigned int i = 0; i < storage->array_elements; i++) { copy_constant_to_storage(& storage->storage[idx], val->array_elements[i], base_type, elements); idx += elements; } } else { copy_constant_to_storage(storage->storage, val, val->type->base_type, val->type->components()); if (storage->type->is_sampler()) { for (int sh = 0; sh < MESA_SHADER_STAGES; sh++) { gl_shader *shader = prog->_LinkedShaders[sh]; if (shader && storage->sampler[sh].active) { unsigned index = storage->sampler[sh].index; shader->SamplerUnits[index] = storage->storage[0].i; } } } } storage->initialized = true; } } void link_set_uniform_initializers(struct gl_shader_program *prog) { void *mem_ctx = NULL; for (unsigned int i = 0; i < MESA_SHADER_STAGES; i++) { struct gl_shader *shader = prog->_LinkedShaders[i]; if (shader == NULL) continue; foreach_list(node, shader->ir) { ir_variable *const var = ((ir_instruction *) node)->as_variable(); if (!var || var->data.mode != ir_var_uniform) continue; if (!mem_ctx) mem_ctx = ralloc_context(NULL); if (var->data.explicit_binding) { linker::set_uniform_binding(mem_ctx, prog, var->name, var->type, var->data.binding); } else if (var->constant_value) { linker::set_uniform_initializer(mem_ctx, prog, var->name, var->type, var->constant_value); } } } ralloc_free(mem_ctx); } <|endoftext|>
<commit_before>//===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass eliminates machine instruction PHI nodes by inserting copy // instructions. This destroys SSA information, but is the desired input for // some register allocators. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/SSARegMap.h" #include "llvm/CodeGen/LiveVariables.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "Support/DenseMap.h" #include "Support/STLExtras.h" using namespace llvm; namespace { struct PNE : public MachineFunctionPass { bool runOnMachineFunction(MachineFunction &Fn) { bool Changed = false; // Eliminate PHI instructions by inserting copies into predecessor blocks. // for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) Changed |= EliminatePHINodes(Fn, *I); //std::cerr << "AFTER PHI NODE ELIM:\n"; //Fn.dump(); return Changed; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addPreserved<LiveVariables>(); MachineFunctionPass::getAnalysisUsage(AU); } private: /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions /// in predecessor basic blocks. /// bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB); }; RegisterPass<PNE> X("phi-node-elimination", "Eliminate PHI nodes for register allocation"); } const PassInfo *llvm::PHIEliminationID = X.getPassInfo(); /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in /// predecessor basic blocks. /// bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) { if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI) return false; // Quick exit for normal case... LiveVariables *LV = getAnalysisToUpdate<LiveVariables>(); const TargetInstrInfo &MII = MF.getTarget().getInstrInfo(); const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo(); // VRegPHIUseCount - Keep track of the number of times each virtual register // is used by PHI nodes in this block. DenseMap<unsigned, VirtReg2IndexFunctor> VRegPHIUseCount; VRegPHIUseCount.grow(MF.getSSARegMap()->getLastVirtReg()); // Get an iterator to the first instruction after the last PHI node (this may // allso be the end of the basic block). While we are scanning the PHIs, // populate the VRegPHIUseCount map. MachineBasicBlock::iterator AfterPHIsIt = MBB.begin(); while (AfterPHIsIt != MBB.end() && AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI) { MachineInstr *PHI = AfterPHIsIt; for (unsigned i = 1, e = PHI->getNumOperands(); i < e; i += 2) VRegPHIUseCount[PHI->getOperand(i).getReg()]++; ++AfterPHIsIt; // Skip over all of the PHI nodes... } while (MBB.front().getOpcode() == TargetInstrInfo::PHI) { // Unlink the PHI node from the basic block... but don't delete the PHI yet MachineInstr *MI = MBB.remove(MBB.begin()); assert(MRegisterInfo::isVirtualRegister(MI->getOperand(0).getReg()) && "PHI node doesn't write virt reg?"); unsigned DestReg = MI->getOperand(0).getReg(); // Create a new register for the incoming PHI arguments const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg); unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC); // Insert a register to register copy in the top of the current block (but // after any remaining phi nodes) which copies the new incoming register // into the phi node destination. // RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC); // Update live variable information if there is any... if (LV) { MachineInstr *PHICopy = prior(AfterPHIsIt); // Add information to LiveVariables to know that the incoming value is // killed. Note that because the value is defined in several places (once // each for each incoming block), the "def" block and instruction fields // for the VarInfo is not filled in. // LV->addVirtualRegisterKilled(IncomingReg, &MBB, PHICopy); // Since we are going to be deleting the PHI node, if it is the last use // of any registers, or if the value itself is dead, we need to move this // information over to the new copy we just inserted... // std::pair<LiveVariables::killed_iterator, LiveVariables::killed_iterator> RKs = LV->killed_range(MI); std::vector<std::pair<MachineInstr*, unsigned> > Range; if (RKs.first != RKs.second) { // Copy the range into a vector... Range.assign(RKs.first, RKs.second); // Delete the range... LV->removeVirtualRegistersKilled(RKs.first, RKs.second); // Add all of the kills back, which will update the appropriate info... for (unsigned i = 0, e = Range.size(); i != e; ++i) LV->addVirtualRegisterKilled(Range[i].second, &MBB, PHICopy); } RKs = LV->dead_range(MI); if (RKs.first != RKs.second) { // Works as above... Range.assign(RKs.first, RKs.second); LV->removeVirtualRegistersDead(RKs.first, RKs.second); for (unsigned i = 0, e = Range.size(); i != e; ++i) LV->addVirtualRegisterDead(Range[i].second, &MBB, PHICopy); } } // Adjust the VRegPHIUseCount map to account for the removal of this PHI // node. for (unsigned i = 1; i != MI->getNumOperands(); i += 2) VRegPHIUseCount[MI->getOperand(i).getReg()]--; // Now loop over all of the incoming arguments, changing them to copy into // the IncomingReg register in the corresponding predecessor basic block. // for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) { MachineOperand &opVal = MI->getOperand(i-1); // Get the MachineBasicBlock equivalent of the BasicBlock that is the // source path the PHI. MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock(); MachineBasicBlock::iterator I = opBlock.getFirstTerminator(); // Check to make sure we haven't already emitted the copy for this block. // This can happen because PHI nodes may have multiple entries for the // same basic block. It doesn't matter which entry we use though, because // all incoming values are guaranteed to be the same for a particular bb. // // If we emitted a copy for this basic block already, it will be right // where we want to insert one now. Just check for a definition of the // register we are interested in! // bool HaveNotEmitted = true; if (I != opBlock.begin()) { MachineBasicBlock::iterator PrevInst = prior(I); for (unsigned i = 0, e = PrevInst->getNumOperands(); i != e; ++i) { MachineOperand &MO = PrevInst->getOperand(i); if (MO.isRegister() && MO.getReg() == IncomingReg) if (MO.isDef()) { HaveNotEmitted = false; break; } } } if (HaveNotEmitted) { // If the copy has not already been emitted, do it. assert(MRegisterInfo::isVirtualRegister(opVal.getReg()) && "Machine PHI Operands must all be virtual registers!"); unsigned SrcReg = opVal.getReg(); RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC); // Now update live variable information if we have it. if (LV) { // We want to be able to insert a kill of the register if this PHI // (aka, the copy we just inserted) is the last use of the source // value. Live variable analysis conservatively handles this by // saying that the value is live until the end of the block the PHI // entry lives in. If the value really is dead at the PHI copy, there // will be no successor blocks which have the value live-in. // // Check to see if the copy is the last use, and if so, update the // live variables information so that it knows the copy source // instruction kills the incoming value. // LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg); // Loop over all of the successors of the basic block, checking to see // if the value is either live in the block, or if it is killed in the // block. Also check to see if this register is in use by another PHI // node which has not yet been eliminated. If so, it will be killed // at an appropriate point later. // bool ValueIsLive = false; for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(), E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) { MachineBasicBlock *MBB = *SI; // Is it alive in this successor? unsigned SuccIdx = LV->getMachineBasicBlockIndex(MBB); if (SuccIdx < InRegVI.AliveBlocks.size() && InRegVI.AliveBlocks[SuccIdx]) { ValueIsLive = true; break; } // Is it killed in this successor? for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i) if (InRegVI.Kills[i].first == MBB) { ValueIsLive = true; break; } // Is it used by any PHI instructions in this block? if (!ValueIsLive) ValueIsLive = VRegPHIUseCount[SrcReg] != 0; } // Okay, if we now know that the value is not live out of the block, // we can add a kill marker to the copy we inserted saying that it // kills the incoming value! // if (!ValueIsLive) { MachineBasicBlock::iterator Prev = prior(I); LV->addVirtualRegisterKilled(SrcReg, &opBlock, Prev); } } } } // really delete the PHI instruction now! delete MI; } return true; } <commit_msg>Fix a really nasty bug from my changes on Monday to PHIElim. These changes broke obsequi and a lot of other things. It all boiled down to MBB being overloaded in an inner scope and me confusing it with the one in the outer scope. Ugh!<commit_after>//===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass eliminates machine instruction PHI nodes by inserting copy // instructions. This destroys SSA information, but is the desired input for // some register allocators. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/SSARegMap.h" #include "llvm/CodeGen/LiveVariables.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "Support/DenseMap.h" #include "Support/STLExtras.h" using namespace llvm; namespace { struct PNE : public MachineFunctionPass { bool runOnMachineFunction(MachineFunction &Fn) { bool Changed = false; // Eliminate PHI instructions by inserting copies into predecessor blocks. // for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) Changed |= EliminatePHINodes(Fn, *I); //std::cerr << "AFTER PHI NODE ELIM:\n"; //Fn.dump(); return Changed; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addPreserved<LiveVariables>(); MachineFunctionPass::getAnalysisUsage(AU); } private: /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions /// in predecessor basic blocks. /// bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB); }; RegisterPass<PNE> X("phi-node-elimination", "Eliminate PHI nodes for register allocation"); } const PassInfo *llvm::PHIEliminationID = X.getPassInfo(); /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in /// predecessor basic blocks. /// bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) { if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI) return false; // Quick exit for normal case... LiveVariables *LV = getAnalysisToUpdate<LiveVariables>(); const TargetInstrInfo &MII = MF.getTarget().getInstrInfo(); const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo(); // VRegPHIUseCount - Keep track of the number of times each virtual register // is used by PHI nodes in successors of this block. DenseMap<unsigned, VirtReg2IndexFunctor> VRegPHIUseCount; VRegPHIUseCount.grow(MF.getSSARegMap()->getLastVirtReg()); unsigned BBIsSuccOfPreds = 0; // Number of times MBB is a succ of preds for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin(), E = MBB.pred_end(); PI != E; ++PI) for (MachineBasicBlock::succ_iterator SI = (*PI)->succ_begin(), E = (*PI)->succ_end(); SI != E; ++SI) { BBIsSuccOfPreds += *SI == &MBB; for (MachineBasicBlock::iterator BBI = (*SI)->begin(); BBI !=(*SI)->end() && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI) for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) VRegPHIUseCount[BBI->getOperand(i).getReg()]++; } // Get an iterator to the first instruction after the last PHI node (this may // also be the end of the basic block). While we are scanning the PHIs, // populate the VRegPHIUseCount map. MachineBasicBlock::iterator AfterPHIsIt = MBB.begin(); while (AfterPHIsIt != MBB.end() && AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI) ++AfterPHIsIt; // Skip over all of the PHI nodes... while (MBB.front().getOpcode() == TargetInstrInfo::PHI) { // Unlink the PHI node from the basic block... but don't delete the PHI yet MachineInstr *MI = MBB.remove(MBB.begin()); assert(MRegisterInfo::isVirtualRegister(MI->getOperand(0).getReg()) && "PHI node doesn't write virt reg?"); unsigned DestReg = MI->getOperand(0).getReg(); // Create a new register for the incoming PHI arguments const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg); unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC); // Insert a register to register copy in the top of the current block (but // after any remaining phi nodes) which copies the new incoming register // into the phi node destination. // RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC); // Update live variable information if there is any... if (LV) { MachineInstr *PHICopy = prior(AfterPHIsIt); // Add information to LiveVariables to know that the incoming value is // killed. Note that because the value is defined in several places (once // each for each incoming block), the "def" block and instruction fields // for the VarInfo is not filled in. // LV->addVirtualRegisterKilled(IncomingReg, &MBB, PHICopy); // Since we are going to be deleting the PHI node, if it is the last use // of any registers, or if the value itself is dead, we need to move this // information over to the new copy we just inserted... // std::pair<LiveVariables::killed_iterator, LiveVariables::killed_iterator> RKs = LV->killed_range(MI); std::vector<std::pair<MachineInstr*, unsigned> > Range; if (RKs.first != RKs.second) { // Copy the range into a vector... Range.assign(RKs.first, RKs.second); // Delete the range... LV->removeVirtualRegistersKilled(RKs.first, RKs.second); // Add all of the kills back, which will update the appropriate info... for (unsigned i = 0, e = Range.size(); i != e; ++i) LV->addVirtualRegisterKilled(Range[i].second, &MBB, PHICopy); } RKs = LV->dead_range(MI); if (RKs.first != RKs.second) { // Works as above... Range.assign(RKs.first, RKs.second); LV->removeVirtualRegistersDead(RKs.first, RKs.second); for (unsigned i = 0, e = Range.size(); i != e; ++i) LV->addVirtualRegisterDead(Range[i].second, &MBB, PHICopy); } } // Adjust the VRegPHIUseCount map to account for the removal of this PHI // node. for (unsigned i = 1; i != MI->getNumOperands(); i += 2) VRegPHIUseCount[MI->getOperand(i).getReg()] -= BBIsSuccOfPreds; // Now loop over all of the incoming arguments, changing them to copy into // the IncomingReg register in the corresponding predecessor basic block. // for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) { MachineOperand &opVal = MI->getOperand(i-1); // Get the MachineBasicBlock equivalent of the BasicBlock that is the // source path the PHI. MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock(); MachineBasicBlock::iterator I = opBlock.getFirstTerminator(); // Check to make sure we haven't already emitted the copy for this block. // This can happen because PHI nodes may have multiple entries for the // same basic block. It doesn't matter which entry we use though, because // all incoming values are guaranteed to be the same for a particular bb. // // If we emitted a copy for this basic block already, it will be right // where we want to insert one now. Just check for a definition of the // register we are interested in! // bool HaveNotEmitted = true; if (I != opBlock.begin()) { MachineBasicBlock::iterator PrevInst = prior(I); for (unsigned i = 0, e = PrevInst->getNumOperands(); i != e; ++i) { MachineOperand &MO = PrevInst->getOperand(i); if (MO.isRegister() && MO.getReg() == IncomingReg) if (MO.isDef()) { HaveNotEmitted = false; break; } } } if (HaveNotEmitted) { // If the copy has not already been emitted, do it. assert(MRegisterInfo::isVirtualRegister(opVal.getReg()) && "Machine PHI Operands must all be virtual registers!"); unsigned SrcReg = opVal.getReg(); RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC); // Now update live variable information if we have it. if (LV) { // We want to be able to insert a kill of the register if this PHI // (aka, the copy we just inserted) is the last use of the source // value. Live variable analysis conservatively handles this by // saying that the value is live until the end of the block the PHI // entry lives in. If the value really is dead at the PHI copy, there // will be no successor blocks which have the value live-in. // // Check to see if the copy is the last use, and if so, update the // live variables information so that it knows the copy source // instruction kills the incoming value. // LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg); // Loop over all of the successors of the basic block, checking to see // if the value is either live in the block, or if it is killed in the // block. Also check to see if this register is in use by another PHI // node which has not yet been eliminated. If so, it will be killed // at an appropriate point later. // bool ValueIsLive = false; for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(), E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) { MachineBasicBlock *SuccMBB = *SI; // Is it alive in this successor? unsigned SuccIdx = LV->getMachineBasicBlockIndex(SuccMBB); if (SuccIdx < InRegVI.AliveBlocks.size() && InRegVI.AliveBlocks[SuccIdx]) { ValueIsLive = true; break; } // Is it killed in this successor? for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i) if (InRegVI.Kills[i].first == SuccMBB) { ValueIsLive = true; break; } // Is it used by any PHI instructions in this block? if (!ValueIsLive) ValueIsLive = VRegPHIUseCount[SrcReg] != 0; } // Okay, if we now know that the value is not live out of the block, // we can add a kill marker to the copy we inserted saying that it // kills the incoming value! // if (!ValueIsLive) { MachineBasicBlock::iterator Prev = prior(I); LV->addVirtualRegisterKilled(SrcReg, &opBlock, Prev); } } } } // really delete the PHI instruction now! delete MI; } return true; } <|endoftext|>
<commit_before><commit_msg>natpmp fix<commit_after><|endoftext|>
<commit_before>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: include/eos/render/normals.hpp * * Copyright 2014-2019 Patrik Huber * * 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 #ifndef EOS_RENDER_NORMALS_HPP #define EOS_RENDER_NORMALS_HPP #include "glm/vec3.hpp" #include "glm/geometric.hpp" #include "Eigen/Core" namespace eos { namespace render { /** * Calculates the normal of a face (or triangle), i.e. the * per-face normal. Return normal will be normalised. * Assumes the triangle is given in CCW order, i.e. vertices * in counterclockwise order on the screen are front-facing. * * @param[in] v0 First vertex. * @param[in] v1 Second vertex. * @param[in] v2 Third vertex. * @return The unit-length normal of the given triangle. */ inline Eigen::Vector3f compute_face_normal(const Eigen::Vector3f& v0, const Eigen::Vector3f& v1, const Eigen::Vector3f& v2) { Eigen::Vector3f n = (v1 - v0).cross(v2 - v0); // v0-to-v1 x v0-to-v2 return n.normalized(); }; // Todo: Doxygen. Actually this is the overload that's probably most used? inline Eigen::Vector3f compute_face_normal(const Eigen::Vector4f& v0, const Eigen::Vector4f& v1, const Eigen::Vector4f& v2) { Eigen::Vector4f n = (v1 - v0).cross3(v2 - v0); // v0-to-v1 x v0-to-v2 return n.head<3>().normalized(); }; /** * Computes the normal of a face (or triangle), i.e. the * per-face normal. Return normal will be normalised. * Assumes the triangle is given in CCW order, i.e. vertices * in counterclockwise order on the screen are front-facing. * * @param[in] v0 First vertex. * @param[in] v1 Second vertex. * @param[in] v2 Third vertex. * @return The unit-length normal of the given triangle. */ inline glm::vec3 compute_face_normal(const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2) { glm::vec3 n = glm::cross(v1 - v0, v2 - v0); // v0-to-v1 x v0-to-v2 n = glm::normalize(n); return n; }; } /* namespace render */ } /* namespace eos */ #endif /* EOS_RENDER_NORMALS_HPP */ <commit_msg>Run clang-format on normals.hpp<commit_after>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: include/eos/render/normals.hpp * * Copyright 2014-2019 Patrik Huber * * 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 #ifndef EOS_RENDER_NORMALS_HPP #define EOS_RENDER_NORMALS_HPP #include "glm/vec3.hpp" #include "glm/geometric.hpp" #include "Eigen/Core" namespace eos { namespace render { /** * Calculates the normal of a face (or triangle), i.e. the per-face normal. Returned normal will be unit * length. * * Assumes the triangle is given in CCW order, i.e. vertices in counterclockwise order on the screen are * front-facing. * * @param[in] v0 First vertex. * @param[in] v1 Second vertex. * @param[in] v2 Third vertex. * @return The unit-length normal of the given triangle. */ inline Eigen::Vector3f compute_face_normal(const Eigen::Vector3f& v0, const Eigen::Vector3f& v1, const Eigen::Vector3f& v2) { Eigen::Vector3f n = (v1 - v0).cross(v2 - v0); // v0-to-v1 x v0-to-v2 return n.normalized(); }; /** * Calculates the normal of a face (or triangle), i.e. the per-face normal. Returned normal will be unit * length. * * Assumes the triangle is given in CCW order, i.e. vertices in counterclockwise order on the screen are * front-facing. * * @param[in] v0 First vertex. * @param[in] v1 Second vertex. * @param[in] v2 Third vertex. * @return The unit-length normal of the given triangle. */ inline Eigen::Vector3f compute_face_normal(const Eigen::Vector4f& v0, const Eigen::Vector4f& v1, const Eigen::Vector4f& v2) { Eigen::Vector4f n = (v1 - v0).cross3(v2 - v0); // v0-to-v1 x v0-to-v2 return n.head<3>().normalized(); }; /** * Calculates the normal of a face (or triangle), i.e. the per-face normal. Returned normal will be unit * length. * * Assumes the triangle is given in CCW order, i.e. vertices in counterclockwise order on the screen are * front-facing. * * @param[in] v0 First vertex. * @param[in] v1 Second vertex. * @param[in] v2 Third vertex. * @return The unit-length normal of the given triangle. */ inline glm::vec3 compute_face_normal(const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2) { glm::vec3 n = glm::cross(v1 - v0, v2 - v0); // v0-to-v1 x v0-to-v2 n = glm::normalize(n); return n; }; } /* namespace render */ } /* namespace eos */ #endif /* EOS_RENDER_NORMALS_HPP */ <|endoftext|>
<commit_before>/*========================================================================= Program: openCherry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include <windows.h> #endif #include "cherryQtPlatformLogModel.h" #include "cherryPlatform.h" #include "event/cherryPlatformEvents.h" #include <sstream> #include <string> #include <iostream> #include <iomanip> #include <Poco/Message.h> #include "mbilog.h" #include <QTimer> namespace cherry { const QString QtPlatformLogModel::Error = QString("Error"); const QString QtPlatformLogModel::Warn = QString("Warn"); const QString QtPlatformLogModel::Fatal = QString("Fatal"); const QString QtPlatformLogModel::Info = QString("Info"); const QString QtPlatformLogModel::Debug = QString("Debug"); void QtPlatformLogModel::slotFlushLogEntries() { m_Mutex.lock(); std::list<ExtendedLogMessage> *tmp=m_Active; m_Active=m_Pending; m_Pending=tmp; m_Mutex.unlock(); std::list<ExtendedLogMessage>::size_type num = m_Pending->size(); if (num > 0) { int row = static_cast<int>(m_Entries.size()); this->beginInsertRows(QModelIndex(), row, row+num-1); do { m_Entries.push_back(m_Pending->front()); m_Pending->pop_front(); } while(--num); this->endInsertRows(); } } void QtPlatformLogModel::addLogEntry(const mbilog::LogMessage &msg) { m_Mutex.lock(); mbilog::BackendCout::FormatSmart(msg); m_Active->push_back(ExtendedLogMessage(msg)); m_Mutex.unlock(); emit signalFlushLogEntries(); } void QtPlatformLogModel::addLogEntry(const PlatformEvent& event) { const Poco::Message& entry = Poco::RefAnyCast<const Poco::Message>(*event.GetData()); mbilog::LogMessage msg(mbilog::Info,"n/a",-1,"n/a"); msg.message += entry.getText(); msg.category = "openCherry."+entry.getSource(); msg.moduleName = "n/a"; addLogEntry(msg); } QtPlatformLogModel::QtPlatformLogModel(QObject* parent) : QAbstractTableModel(parent) { m_Active=new std::list<ExtendedLogMessage>; m_Pending=new std::list<ExtendedLogMessage>; connect(this, SIGNAL(signalFlushLogEntries()), this, SLOT( slotFlushLogEntries() ), Qt::QueuedConnection ); Platform::GetEvents().logged += PlatformEventDelegate(this, &QtPlatformLogModel::addLogEntry); myBackend = new QtLogBackend(this); } QtPlatformLogModel::~QtPlatformLogModel() { disconnect(this, SIGNAL(signalFlushLogEntries()), this, SLOT( slotFlushLogEntries() )); // dont delete and unregister backend, only deactivate it to avoid thread syncronization issues cause mbilog::UnregisterBackend is not threadsafe // will be fixed. // delete myBackend; // delete m_Active; // delete m_Pending; m_Mutex.lock(); myBackend->Deactivate(); m_Mutex.unlock(); } // QT Binding int QtPlatformLogModel::rowCount(const QModelIndex&) const { return static_cast<int>(m_Entries.size()); } int QtPlatformLogModel::columnCount(const QModelIndex&) const { return 8; } /* struct LogEntry { LogEntry(const std::string& msg, const std::string& src, std::time_t t) : message(msg.c_str()), moduleName(src.c_str()),time(std::clock()) { } QString message; clock_t time; QString level; QString filePath; QString lineNumber; QString moduleName; QString category; QString function; LogEntry(const mbilog::LogMessage &msg) { message = msg.message.c_str(); filePath = msg.filePath; std::stringstream out; out << msg.lineNumber; lineNumber = out.str().c_str(); moduleName = msg.moduleName; category = msg.category.c_str(); function = msg.functionName; time=std::clock(); } }; */ QVariant QtPlatformLogModel::data(const QModelIndex& index, int role) const { const ExtendedLogMessage *msg = &m_Entries[index.row()]; if (role == Qt::DisplayRole) { switch (index.column()) { case 0: { std::stringstream ss; ss << std::setw(7) << std::setprecision(3) << std::fixed << ((double)msg->time)/CLOCKS_PER_SEC; return QVariant(QString(ss.str().c_str())); } case 1: { switch(msg->message.level) { default: case mbilog::Info: return QVariant(Info); case mbilog::Warn: return QVariant(Warn); case mbilog::Error: return QVariant(Error); case mbilog::Fatal: return QVariant(Fatal); case mbilog::Debug: return QVariant(Debug); } } case 2: return QVariant(QString(msg->message.message.c_str())); case 3: return QVariant(QString(msg->message.category.c_str())); case 4: return QVariant(QString(msg->message.moduleName)); case 5: return QVariant(QString(msg->message.functionName)); case 6: return QVariant(QString(msg->message.filePath)); case 7: { std::stringstream out; out << msg->message.lineNumber; return QVariant(QString(out.str().c_str())); } } } return QVariant(); } QVariant QtPlatformLogModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { switch (section) { case 0: return QVariant("Time"); case 1: return QVariant("Level"); case 2: return QVariant("Message"); case 3: return QVariant("Category"); case 4: return QVariant("Module"); case 5: return QVariant("Function"); case 6: return QVariant("File"); case 7: return QVariant("Line"); } } return QVariant(); } } <commit_msg>COMP: fix compiler warning<commit_after>/*========================================================================= Program: openCherry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include <windows.h> #endif #include "cherryQtPlatformLogModel.h" #include "cherryPlatform.h" #include "event/cherryPlatformEvents.h" #include <sstream> #include <string> #include <iostream> #include <iomanip> #include <Poco/Message.h> #include "mbilog.h" #include <QTimer> namespace cherry { const QString QtPlatformLogModel::Error = QString("Error"); const QString QtPlatformLogModel::Warn = QString("Warn"); const QString QtPlatformLogModel::Fatal = QString("Fatal"); const QString QtPlatformLogModel::Info = QString("Info"); const QString QtPlatformLogModel::Debug = QString("Debug"); void QtPlatformLogModel::slotFlushLogEntries() { m_Mutex.lock(); std::list<ExtendedLogMessage> *tmp=m_Active; m_Active=m_Pending; m_Pending=tmp; m_Mutex.unlock(); int num = static_cast<int>(m_Pending->size()); if (num > 0) { int row = static_cast<int>(m_Entries.size()); this->beginInsertRows(QModelIndex(), row, row+num-1); do { m_Entries.push_back(m_Pending->front()); m_Pending->pop_front(); } while(--num); this->endInsertRows(); } } void QtPlatformLogModel::addLogEntry(const mbilog::LogMessage &msg) { m_Mutex.lock(); mbilog::BackendCout::FormatSmart(msg); m_Active->push_back(ExtendedLogMessage(msg)); m_Mutex.unlock(); emit signalFlushLogEntries(); } void QtPlatformLogModel::addLogEntry(const PlatformEvent& event) { const Poco::Message& entry = Poco::RefAnyCast<const Poco::Message>(*event.GetData()); mbilog::LogMessage msg(mbilog::Info,"n/a",-1,"n/a"); msg.message += entry.getText(); msg.category = "openCherry."+entry.getSource(); msg.moduleName = "n/a"; addLogEntry(msg); } QtPlatformLogModel::QtPlatformLogModel(QObject* parent) : QAbstractTableModel(parent) { m_Active=new std::list<ExtendedLogMessage>; m_Pending=new std::list<ExtendedLogMessage>; connect(this, SIGNAL(signalFlushLogEntries()), this, SLOT( slotFlushLogEntries() ), Qt::QueuedConnection ); Platform::GetEvents().logged += PlatformEventDelegate(this, &QtPlatformLogModel::addLogEntry); myBackend = new QtLogBackend(this); } QtPlatformLogModel::~QtPlatformLogModel() { disconnect(this, SIGNAL(signalFlushLogEntries()), this, SLOT( slotFlushLogEntries() )); // dont delete and unregister backend, only deactivate it to avoid thread syncronization issues cause mbilog::UnregisterBackend is not threadsafe // will be fixed. // delete myBackend; // delete m_Active; // delete m_Pending; m_Mutex.lock(); myBackend->Deactivate(); m_Mutex.unlock(); } // QT Binding int QtPlatformLogModel::rowCount(const QModelIndex&) const { return static_cast<int>(m_Entries.size()); } int QtPlatformLogModel::columnCount(const QModelIndex&) const { return 8; } /* struct LogEntry { LogEntry(const std::string& msg, const std::string& src, std::time_t t) : message(msg.c_str()), moduleName(src.c_str()),time(std::clock()) { } QString message; clock_t time; QString level; QString filePath; QString lineNumber; QString moduleName; QString category; QString function; LogEntry(const mbilog::LogMessage &msg) { message = msg.message.c_str(); filePath = msg.filePath; std::stringstream out; out << msg.lineNumber; lineNumber = out.str().c_str(); moduleName = msg.moduleName; category = msg.category.c_str(); function = msg.functionName; time=std::clock(); } }; */ QVariant QtPlatformLogModel::data(const QModelIndex& index, int role) const { const ExtendedLogMessage *msg = &m_Entries[index.row()]; if (role == Qt::DisplayRole) { switch (index.column()) { case 0: { std::stringstream ss; ss << std::setw(7) << std::setprecision(3) << std::fixed << ((double)msg->time)/CLOCKS_PER_SEC; return QVariant(QString(ss.str().c_str())); } case 1: { switch(msg->message.level) { default: case mbilog::Info: return QVariant(Info); case mbilog::Warn: return QVariant(Warn); case mbilog::Error: return QVariant(Error); case mbilog::Fatal: return QVariant(Fatal); case mbilog::Debug: return QVariant(Debug); } } case 2: return QVariant(QString(msg->message.message.c_str())); case 3: return QVariant(QString(msg->message.category.c_str())); case 4: return QVariant(QString(msg->message.moduleName)); case 5: return QVariant(QString(msg->message.functionName)); case 6: return QVariant(QString(msg->message.filePath)); case 7: { std::stringstream out; out << msg->message.lineNumber; return QVariant(QString(out.str().c_str())); } } } return QVariant(); } QVariant QtPlatformLogModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { switch (section) { case 0: return QVariant("Time"); case 1: return QVariant("Level"); case 2: return QVariant("Message"); case 3: return QVariant("Category"); case 4: return QVariant("Module"); case 5: return QVariant("Function"); case 6: return QVariant("File"); case 7: return QVariant("Line"); } } return QVariant(); } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2015-2017 The Silk Network developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "proofs.h" #include "chainparams.h" #include "main.h" #include "uint256.h" #include "util.h" #include "amount.h" #include "checkpoints.h" #include <math.h> #include <stdint.h> unsigned int nStakeMinAge = 8 * 60 * 60; unsigned int nModifierInterval = 2 * 60 * 60; uint256 CBlock::GetHash() const { return GetPoWHash(); } uint256 CBlock::GetPoWHash() const { return Hash(BEGIN(nVersion), END(nNonce)); } int DetermineCoinbaseMaturity() { if(pindexBest->nHeight <= 100) { return (int)10; // This will allow for premine distribution to propogate faster } else { return (int)60; // Coinbase will take approx. 1 hr to reach confirmation } } // miner's coin base reward int64_t GetCoinbaseValue(int nHeight, CAmount nFees) { CAmount nSubsidy = 0; if(nHeight == 1) { nSubsidy = 16400000 * COIN; } return nSubsidy; } // miner's coin stake reward based on coin age spent (coin-days) int64_t GetCoinstakeValue(int64_t nCoinAge, CAmount nFees, int nHeight) { CAmount nSubsidy = 0.2 * COIN; if(nHeight <= 125146) { nSubsidy = 23 * COIN; } else if(nHeight <= 568622) { nSubsidy = 17 * COIN; } else if(nHeight <= 1012098) { nSubsidy = 11.5 * COIN; } else if(nHeight <= 1455574) { nSubsidy = 5.75 * COIN; } else if(nHeight <= 3675950) { nSubsidy = 1.85 * COIN; } else { nSubsidy = 0.2 * COIN; } return nSubsidy + nFees; } unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake) { uint256 bnTargetLimit = fProofOfStake ? Params().ProofOfStakeLimit() : Params().ProofOfWorkLimit(); if (pindexLast == NULL) return bnTargetLimit.GetCompact(); // genesis block const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake); if (pindexPrev->pprev == NULL) return bnTargetLimit.GetCompact(); // first block const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake); if (pindexPrevPrev->pprev == NULL) return bnTargetLimit.GetCompact(); // second block int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime(); if (nActualSpacing < 0) { nActualSpacing = nTargetSpacing; } else if (fProofOfStake && nActualSpacing > nTargetSpacing * 10) { nActualSpacing = nTargetSpacing * 10; } // target change every block // retarget with exponential moving toward target spacing // Includes fix for wrong retargeting difficulty by Mammix2 uint256 bnNew; bnNew.SetCompact(pindexPrev->nBits); int64_t nInterval = fProofOfStake ? 10 : 10; bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing); bnNew /= ((nInterval + 1) * nTargetSpacing); if (bnNew <= 0 || bnNew > bnTargetLimit) bnNew = bnTargetLimit; return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits) { uint256 bnTarget; bnTarget.SetCompact(nBits); // Check range if (bnTarget <= 0 || bnTarget > Params().ProofOfWorkLimit()) return error("CheckProofOfWork() : nBits below minimum work"); // Check proof of work matches claimed amount if (hash > bnTarget) return error("CheckProofOfWork() : hash doesn't match nBits"); return true; } <commit_msg>[Stake Age] Reduce<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2015-2017 The Silk Network developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "proofs.h" #include "chainparams.h" #include "main.h" #include "uint256.h" #include "util.h" #include "amount.h" #include "checkpoints.h" #include <math.h> #include <stdint.h> unsigned int nStakeMinAge = 1 * 60 * 60; unsigned int nModifierInterval = 2 * 60 * 60; uint256 CBlock::GetHash() const { return GetPoWHash(); } uint256 CBlock::GetPoWHash() const { return Hash(BEGIN(nVersion), END(nNonce)); } int DetermineCoinbaseMaturity() { if(pindexBest->nHeight <= 100) { return (int)10; // This will allow for premine distribution to propogate faster } else { return (int)60; // Coinbase will take approx. 1 hr to reach confirmation } } // miner's coin base reward int64_t GetCoinbaseValue(int nHeight, CAmount nFees) { CAmount nSubsidy = 0; if(nHeight == 1) { nSubsidy = 16400000 * COIN; } return nSubsidy; } // miner's coin stake reward based on coin age spent (coin-days) int64_t GetCoinstakeValue(int64_t nCoinAge, CAmount nFees, int nHeight) { CAmount nSubsidy = 0.2 * COIN; if(nHeight <= 125146) { nSubsidy = 23 * COIN; } else if(nHeight <= 568622) { nSubsidy = 17 * COIN; } else if(nHeight <= 1012098) { nSubsidy = 11.5 * COIN; } else if(nHeight <= 1455574) { nSubsidy = 5.75 * COIN; } else if(nHeight <= 3675950) { nSubsidy = 1.85 * COIN; } else { nSubsidy = 0.2 * COIN; } return nSubsidy + nFees; } unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake) { uint256 bnTargetLimit = fProofOfStake ? Params().ProofOfStakeLimit() : Params().ProofOfWorkLimit(); if (pindexLast == NULL) return bnTargetLimit.GetCompact(); // genesis block const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake); if (pindexPrev->pprev == NULL) return bnTargetLimit.GetCompact(); // first block const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake); if (pindexPrevPrev->pprev == NULL) return bnTargetLimit.GetCompact(); // second block int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime(); if (nActualSpacing < 0) { nActualSpacing = nTargetSpacing; } else if (fProofOfStake && nActualSpacing > nTargetSpacing * 10) { nActualSpacing = nTargetSpacing * 10; } // target change every block // retarget with exponential moving toward target spacing // Includes fix for wrong retargeting difficulty by Mammix2 uint256 bnNew; bnNew.SetCompact(pindexPrev->nBits); int64_t nInterval = fProofOfStake ? 10 : 10; bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing); bnNew /= ((nInterval + 1) * nTargetSpacing); if (bnNew <= 0 || bnNew > bnTargetLimit) bnNew = bnTargetLimit; return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits) { uint256 bnTarget; bnTarget.SetCompact(nBits); // Check range if (bnTarget <= 0 || bnTarget > Params().ProofOfWorkLimit()) return error("CheckProofOfWork() : nBits below minimum work"); // Check proof of work matches claimed amount if (hash > bnTarget) return error("CheckProofOfWork() : hash doesn't match nBits"); return true; } <|endoftext|>
<commit_before>#include "joedb/journal/Readonly_Journal.h" #include "joedb/journal/Generic_File.h" #include "joedb/Exception.h" #include <sstream> const uint32_t joedb::Readonly_Journal::version_number = 0x00000004; const uint32_t joedb::Readonly_Journal::compatible_version = 0x00000004; const int64_t joedb::Readonly_Journal::header_size = 41; ///////////////////////////////////////////////////////////////////////////// joedb::Readonly_Journal::Readonly_Journal ///////////////////////////////////////////////////////////////////////////// ( Generic_File &file, bool ignore_errors ): file(file), checkpoint_index(0), checkpoint_position(0), table_of_last_operation(0), record_of_last_operation(0), field_of_last_update(0) { auto format_exception = [ignore_errors](const char *message) { if (!ignore_errors) throw Exception(message); }; // // Check the format of an existing joedb file // if (file.get_mode() != Open_Mode::create_new) { // // First, check for initial "joedb" // if (file.read<uint8_t>() != 'j' || file.read<uint8_t>() != 'o' || file.read<uint8_t>() != 'e' || file.read<uint8_t>() != 'd' || file.read<uint8_t>() != 'b') { format_exception("File does not start by 'joedb'"); } else { // // Check version number // const uint32_t version = file.read<uint32_t>(); if (version < compatible_version || version > version_number) format_exception("Unsupported format version"); // // Find the most recent checkpoint // int64_t pos[4]; for (int i = 0; i < 4; i++) pos[i] = file.read<int64_t>(); if (pos[0] != pos[1] || pos[2] != pos[3]) format_exception("Checkpoint mismatch"); checkpoint_position = 0; for (unsigned i = 0; i < 2; i++) if (pos[2 * i] == pos[2 * i + 1] && pos[2 * i] > checkpoint_position) { if (int64_t(size_t(pos[2 * i])) != pos[2 * i]) throw Exception("size_t is too small for this file"); checkpoint_position = pos[2 * i]; checkpoint_index = i; } if (checkpoint_position < header_size) format_exception("Checkpoint too small"); // // Compare to file size (if available) // int64_t file_size = file.get_size(); if (file_size > 0 && file_size != checkpoint_position) format_exception("Checkpoint different from file size"); if (ignore_errors) checkpoint_position = file_size; } } } ///////////////////////////////////////////////////////////////////////////// std::vector<char> joedb::Readonly_Journal::get_raw_tail ///////////////////////////////////////////////////////////////////////////// ( int64_t starting_position ) { std::vector<char> result; const int64_t size = get_checkpoint_position() - starting_position; if (size > 0) { result.resize(size_t(size)); get_tail_reader(starting_position).read(result.data(), result.size()); } return result; } ///////////////////////////////////////////////////////////////////////////// void joedb::Readonly_Journal::replay_log(Writable &writable) ///////////////////////////////////////////////////////////////////////////// { rewind(); play_until_checkpoint(writable); } ///////////////////////////////////////////////////////////////////////////// void joedb::Readonly_Journal::rewind() ///////////////////////////////////////////////////////////////////////////// { file.set_position(header_size); } ///////////////////////////////////////////////////////////////////////////// void joedb::Readonly_Journal::seek(int64_t position) ///////////////////////////////////////////////////////////////////////////// { file.set_position(position); } ///////////////////////////////////////////////////////////////////////////// void joedb::Readonly_Journal::play_until(Writable &writable, int64_t end) ///////////////////////////////////////////////////////////////////////////// { while(file.get_position() < end) one_step(writable); file.set_position(file.get_position()); // get ready for writing } ///////////////////////////////////////////////////////////////////////////// bool joedb::Readonly_Journal::at_end_of_file() const ///////////////////////////////////////////////////////////////////////////// { return file.get_position() >= checkpoint_position; } ///////////////////////////////////////////////////////////////////////////// void joedb::Readonly_Journal::one_step(Writable &writable) ///////////////////////////////////////////////////////////////////////////// { switch(file.read<operation_t>()) { case operation_t::end_of_file: if (file.get_position() != checkpoint_position) throw Exception("Unexpected end of file"); break; case operation_t::create_table: { std::string name = safe_read_string(); writable.create_table(name); } break; case operation_t::drop_table: { Table_Id table_id = file.compact_read<Table_Id>(); writable.drop_table(table_id); } break; case operation_t::rename_table: { Table_Id table_id = file.compact_read<Table_Id>(); std::string name = safe_read_string(); writable.rename_table(table_id, name); } break; case operation_t::add_field: { Table_Id table_id = file.compact_read<Table_Id>(); std::string name = safe_read_string(); Type type = read_type(); writable.add_field(table_id, name, type); } break; case operation_t::drop_field: { Table_Id table_id = file.compact_read<Table_Id>(); Field_Id field_id = file.compact_read<Field_Id>(); writable.drop_field(table_id, field_id); } break; case operation_t::rename_field: { Table_Id table_id = file.compact_read<Table_Id>(); Field_Id field_id = file.compact_read<Field_Id>(); std::string name = safe_read_string(); writable.rename_field(table_id, field_id, name); } break; case operation_t::insert_into: { Table_Id table_id = file.compact_read<Table_Id>(); Record_Id record_id = file.compact_read<Record_Id>(); writable.insert_into(table_id, record_id); table_of_last_operation = table_id; record_of_last_operation = record_id; } break; case operation_t::insert_vector: { Table_Id table_id = file.compact_read<Table_Id>(); Record_Id record_id = file.compact_read<Record_Id>(); Record_Id size = file.compact_read<Record_Id>(); writable.insert_vector(table_id, record_id, size); table_of_last_operation = table_id; record_of_last_operation = record_id; } break; case operation_t::append: writable.insert_into(table_of_last_operation, ++record_of_last_operation); break; case operation_t::delete_from: { Table_Id table_id = file.compact_read<Table_Id>(); Record_Id record_id = file.compact_read<Record_Id>(); writable.delete_from(table_id, record_id); } break; #define TYPE_MACRO(cpp_type, return_type, type_id, read_method, W)\ case operation_t::update_##type_id:\ table_of_last_operation = file.compact_read<Table_Id>();\ record_of_last_operation = file.compact_read<Record_Id>();\ field_of_last_update = file.compact_read<Field_Id>();\ goto lbl_perform_update_##type_id;\ \ case operation_t::update_last_##type_id:\ field_of_last_update = file.compact_read<Field_Id>();\ goto lbl_perform_update_##type_id;\ \ case operation_t::update_next_##type_id:\ record_of_last_operation++;\ goto lbl_perform_update_##type_id;\ \ lbl_perform_update_##type_id:\ {\ cpp_type value = read_method();\ writable.update_##type_id\ (\ table_of_last_operation,\ record_of_last_operation,\ field_of_last_update,\ value\ );\ }\ break;\ \ case operation_t::update_vector_##type_id:\ {\ table_of_last_operation = file.compact_read<Table_Id>();\ record_of_last_operation = file.compact_read<Record_Id>();\ field_of_last_update = file.compact_read<Field_Id>();\ Record_Id size = file.compact_read<Record_Id>();\ if (int64_t(size) > checkpoint_position || size < 0)\ throw Exception("update_vector too big");\ Record_Id capacity;\ cpp_type *data = writable.get_own_##type_id##_storage\ (\ table_of_last_operation,\ record_of_last_operation,\ field_of_last_update,\ capacity\ );\ std::vector<cpp_type> buffer;\ if (!data)\ {\ buffer.resize(size);\ data = &buffer[0];\ }\ else if (record_of_last_operation <= 0 || record_of_last_operation + size - 1 > capacity)\ throw Exception("update_vector out of range");\ read_vector_of_##type_id(data, size);\ writable.update_vector_##type_id\ (\ table_of_last_operation,\ record_of_last_operation,\ field_of_last_update,\ size,\ data\ );\ }\ break; #include "joedb/TYPE_MACRO.h" case operation_t::custom: { std::string name = safe_read_string(); writable.custom(name); } break; case operation_t::comment: { std::string comment = safe_read_string(); writable.comment(comment); } break; case operation_t::timestamp: { int64_t timestamp = file.read<int64_t>(); writable.timestamp(timestamp); } break; case operation_t::valid_data: writable.valid_data(); break; default: { std::ostringstream error; error << "Unexpected operation: file.get_position() = "; error << file.get_position(); throw Exception(error.str()); } } } ///////////////////////////////////////////////////////////////////////////// joedb::Type joedb::Readonly_Journal::read_type() ///////////////////////////////////////////////////////////////////////////// { Type::Type_Id type_id = Type::Type_Id(file.read<Type_Id_Storage>()); if (type_id == Type::Type_Id::reference) return Type::reference(file.compact_read<Table_Id>()); else return Type(type_id); } ///////////////////////////////////////////////////////////////////////////// std::string joedb::Readonly_Journal::safe_read_string() ///////////////////////////////////////////////////////////////////////////// { return file.safe_read_string(size_t(checkpoint_position)); } #define TYPE_MACRO(cpp_type, return_type, type_id, read_method, W)\ void joedb::Readonly_Journal::read_vector_of_##type_id(cpp_type *data, size_t size)\ {\ for (size_t i = 0; i < size; i++)\ data[i] = read_method();\ } #define TYPE_MACRO_NO_INT #define TYPE_MACRO_NO_FLOAT #include "joedb/TYPE_MACRO.h" #define TYPE_MACRO(cpp_type, return_type, type_id, read_method, W)\ void joedb::Readonly_Journal::read_vector_of_##type_id(cpp_type *data, size_t size)\ {\ file.read_data((char *)data, size * sizeof(cpp_type));\ if (is_big_endian() && sizeof(cpp_type) > 1)\ for (size_t i = 0; i < size; i++)\ Generic_File::R<cpp_type, sizeof(cpp_type)>::swap(data[i]);\ } #define TYPE_MACRO_NO_STRING #define TYPE_MACRO_NO_REFERENCE #include "joedb/TYPE_MACRO.h" <commit_msg>better behaviour when ignore_errors with unknown file_size<commit_after>#include "joedb/journal/Readonly_Journal.h" #include "joedb/journal/Generic_File.h" #include "joedb/Exception.h" #include <sstream> const uint32_t joedb::Readonly_Journal::version_number = 0x00000004; const uint32_t joedb::Readonly_Journal::compatible_version = 0x00000004; const int64_t joedb::Readonly_Journal::header_size = 41; ///////////////////////////////////////////////////////////////////////////// joedb::Readonly_Journal::Readonly_Journal ///////////////////////////////////////////////////////////////////////////// ( Generic_File &file, bool ignore_errors ): file(file), checkpoint_index(0), checkpoint_position(0), table_of_last_operation(0), record_of_last_operation(0), field_of_last_update(0) { auto format_exception = [ignore_errors](const char *message) { if (!ignore_errors) throw Exception(message); }; // // Check the format of an existing joedb file // if (file.get_mode() != Open_Mode::create_new) { // // First, check for initial "joedb" // if (file.read<uint8_t>() != 'j' || file.read<uint8_t>() != 'o' || file.read<uint8_t>() != 'e' || file.read<uint8_t>() != 'd' || file.read<uint8_t>() != 'b') { format_exception("File does not start by 'joedb'"); } else { // // Check version number // const uint32_t version = file.read<uint32_t>(); if (version < compatible_version || version > version_number) format_exception("Unsupported format version"); // // Find the most recent checkpoint // int64_t pos[4]; for (int i = 0; i < 4; i++) pos[i] = file.read<int64_t>(); if (pos[0] != pos[1] || pos[2] != pos[3]) format_exception("Checkpoint mismatch"); checkpoint_position = 0; for (unsigned i = 0; i < 2; i++) if (pos[2 * i] == pos[2 * i + 1] && pos[2 * i] > checkpoint_position) { if (int64_t(size_t(pos[2 * i])) != pos[2 * i]) throw Exception("size_t is too small for this file"); checkpoint_position = pos[2 * i]; checkpoint_index = i; } if (checkpoint_position < header_size) format_exception("Checkpoint too small"); // // Compare to file size (if available) // int64_t file_size = file.get_size(); if (file_size > 0) { if (file_size != checkpoint_position) format_exception("Checkpoint different from file size"); if (ignore_errors) checkpoint_position = file_size; } } } } ///////////////////////////////////////////////////////////////////////////// std::vector<char> joedb::Readonly_Journal::get_raw_tail ///////////////////////////////////////////////////////////////////////////// ( int64_t starting_position ) { std::vector<char> result; const int64_t size = get_checkpoint_position() - starting_position; if (size > 0) { result.resize(size_t(size)); get_tail_reader(starting_position).read(result.data(), result.size()); } return result; } ///////////////////////////////////////////////////////////////////////////// void joedb::Readonly_Journal::replay_log(Writable &writable) ///////////////////////////////////////////////////////////////////////////// { rewind(); play_until_checkpoint(writable); } ///////////////////////////////////////////////////////////////////////////// void joedb::Readonly_Journal::rewind() ///////////////////////////////////////////////////////////////////////////// { file.set_position(header_size); } ///////////////////////////////////////////////////////////////////////////// void joedb::Readonly_Journal::seek(int64_t position) ///////////////////////////////////////////////////////////////////////////// { file.set_position(position); } ///////////////////////////////////////////////////////////////////////////// void joedb::Readonly_Journal::play_until(Writable &writable, int64_t end) ///////////////////////////////////////////////////////////////////////////// { while(file.get_position() < end) one_step(writable); file.set_position(file.get_position()); // get ready for writing } ///////////////////////////////////////////////////////////////////////////// bool joedb::Readonly_Journal::at_end_of_file() const ///////////////////////////////////////////////////////////////////////////// { return file.get_position() >= checkpoint_position; } ///////////////////////////////////////////////////////////////////////////// void joedb::Readonly_Journal::one_step(Writable &writable) ///////////////////////////////////////////////////////////////////////////// { switch(file.read<operation_t>()) { case operation_t::end_of_file: if (file.get_position() != checkpoint_position) throw Exception("Unexpected end of file"); break; case operation_t::create_table: { std::string name = safe_read_string(); writable.create_table(name); } break; case operation_t::drop_table: { Table_Id table_id = file.compact_read<Table_Id>(); writable.drop_table(table_id); } break; case operation_t::rename_table: { Table_Id table_id = file.compact_read<Table_Id>(); std::string name = safe_read_string(); writable.rename_table(table_id, name); } break; case operation_t::add_field: { Table_Id table_id = file.compact_read<Table_Id>(); std::string name = safe_read_string(); Type type = read_type(); writable.add_field(table_id, name, type); } break; case operation_t::drop_field: { Table_Id table_id = file.compact_read<Table_Id>(); Field_Id field_id = file.compact_read<Field_Id>(); writable.drop_field(table_id, field_id); } break; case operation_t::rename_field: { Table_Id table_id = file.compact_read<Table_Id>(); Field_Id field_id = file.compact_read<Field_Id>(); std::string name = safe_read_string(); writable.rename_field(table_id, field_id, name); } break; case operation_t::insert_into: { Table_Id table_id = file.compact_read<Table_Id>(); Record_Id record_id = file.compact_read<Record_Id>(); writable.insert_into(table_id, record_id); table_of_last_operation = table_id; record_of_last_operation = record_id; } break; case operation_t::insert_vector: { Table_Id table_id = file.compact_read<Table_Id>(); Record_Id record_id = file.compact_read<Record_Id>(); Record_Id size = file.compact_read<Record_Id>(); writable.insert_vector(table_id, record_id, size); table_of_last_operation = table_id; record_of_last_operation = record_id; } break; case operation_t::append: writable.insert_into(table_of_last_operation, ++record_of_last_operation); break; case operation_t::delete_from: { Table_Id table_id = file.compact_read<Table_Id>(); Record_Id record_id = file.compact_read<Record_Id>(); writable.delete_from(table_id, record_id); } break; #define TYPE_MACRO(cpp_type, return_type, type_id, read_method, W)\ case operation_t::update_##type_id:\ table_of_last_operation = file.compact_read<Table_Id>();\ record_of_last_operation = file.compact_read<Record_Id>();\ field_of_last_update = file.compact_read<Field_Id>();\ goto lbl_perform_update_##type_id;\ \ case operation_t::update_last_##type_id:\ field_of_last_update = file.compact_read<Field_Id>();\ goto lbl_perform_update_##type_id;\ \ case operation_t::update_next_##type_id:\ record_of_last_operation++;\ goto lbl_perform_update_##type_id;\ \ lbl_perform_update_##type_id:\ {\ cpp_type value = read_method();\ writable.update_##type_id\ (\ table_of_last_operation,\ record_of_last_operation,\ field_of_last_update,\ value\ );\ }\ break;\ \ case operation_t::update_vector_##type_id:\ {\ table_of_last_operation = file.compact_read<Table_Id>();\ record_of_last_operation = file.compact_read<Record_Id>();\ field_of_last_update = file.compact_read<Field_Id>();\ Record_Id size = file.compact_read<Record_Id>();\ if (int64_t(size) > checkpoint_position || size < 0)\ throw Exception("update_vector too big");\ Record_Id capacity;\ cpp_type *data = writable.get_own_##type_id##_storage\ (\ table_of_last_operation,\ record_of_last_operation,\ field_of_last_update,\ capacity\ );\ std::vector<cpp_type> buffer;\ if (!data)\ {\ buffer.resize(size);\ data = &buffer[0];\ }\ else if (record_of_last_operation <= 0 || record_of_last_operation + size - 1 > capacity)\ throw Exception("update_vector out of range");\ read_vector_of_##type_id(data, size);\ writable.update_vector_##type_id\ (\ table_of_last_operation,\ record_of_last_operation,\ field_of_last_update,\ size,\ data\ );\ }\ break; #include "joedb/TYPE_MACRO.h" case operation_t::custom: { std::string name = safe_read_string(); writable.custom(name); } break; case operation_t::comment: { std::string comment = safe_read_string(); writable.comment(comment); } break; case operation_t::timestamp: { int64_t timestamp = file.read<int64_t>(); writable.timestamp(timestamp); } break; case operation_t::valid_data: writable.valid_data(); break; default: { std::ostringstream error; error << "Unexpected operation: file.get_position() = "; error << file.get_position(); throw Exception(error.str()); } } } ///////////////////////////////////////////////////////////////////////////// joedb::Type joedb::Readonly_Journal::read_type() ///////////////////////////////////////////////////////////////////////////// { Type::Type_Id type_id = Type::Type_Id(file.read<Type_Id_Storage>()); if (type_id == Type::Type_Id::reference) return Type::reference(file.compact_read<Table_Id>()); else return Type(type_id); } ///////////////////////////////////////////////////////////////////////////// std::string joedb::Readonly_Journal::safe_read_string() ///////////////////////////////////////////////////////////////////////////// { return file.safe_read_string(size_t(checkpoint_position)); } #define TYPE_MACRO(cpp_type, return_type, type_id, read_method, W)\ void joedb::Readonly_Journal::read_vector_of_##type_id(cpp_type *data, size_t size)\ {\ for (size_t i = 0; i < size; i++)\ data[i] = read_method();\ } #define TYPE_MACRO_NO_INT #define TYPE_MACRO_NO_FLOAT #include "joedb/TYPE_MACRO.h" #define TYPE_MACRO(cpp_type, return_type, type_id, read_method, W)\ void joedb::Readonly_Journal::read_vector_of_##type_id(cpp_type *data, size_t size)\ {\ file.read_data((char *)data, size * sizeof(cpp_type));\ if (is_big_endian() && sizeof(cpp_type) > 1)\ for (size_t i = 0; i < size; i++)\ Generic_File::R<cpp_type, sizeof(cpp_type)>::swap(data[i]);\ } #define TYPE_MACRO_NO_STRING #define TYPE_MACRO_NO_REFERENCE #include "joedb/TYPE_MACRO.h" <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_STORAGE_HPP_INCLUDE #define TORRENT_STORAGE_HPP_INCLUDE #include <vector> #include <bitset> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/limits.hpp> #include <boost/filesystem/path.hpp> #include <boost/thread.hpp> #include <boost/shared_ptr.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/torrent_info.hpp" #include "libtorrent/config.hpp" namespace libtorrent { namespace detail { struct piece_checker_data; } class session; TORRENT_EXPORT std::wstring safe_convert(std::string const& s); TORRENT_EXPORT std::vector<std::pair<size_type, std::time_t> > get_filesizes( torrent_info const& t , boost::filesystem::path p); TORRENT_EXPORT bool match_filesizes( torrent_info const& t , boost::filesystem::path p , std::vector<std::pair<size_type, std::time_t> > const& sizes , std::string* error = 0); struct TORRENT_EXPORT file_allocation_failed: std::exception { file_allocation_failed(const char* error_msg): m_msg(error_msg) {} virtual const char* what() const throw() { return m_msg.c_str(); } virtual ~file_allocation_failed() throw() {} std::string m_msg; }; class TORRENT_EXPORT storage { public: storage( const torrent_info& info , const boost::filesystem::path& path); void swap(storage&); // may throw file_error if storage for slot does not exist size_type read(char* buf, int slot, int offset, int size); // may throw file_error if storage for slot hasn't been allocated void write(const char* buf, int slot, int offset, int size); bool move_storage(boost::filesystem::path save_path); // this will close all open files that are opened for // writing. This is called when a torrent has finished // downloading. void release_files(); #ifndef NDEBUG // overwrites some slots with the // contents of others void shuffle(); #endif private: class impl; boost::shared_ptr<impl> m_pimpl; }; class TORRENT_EXPORT piece_manager : boost::noncopyable { public: piece_manager( const torrent_info& info , const boost::filesystem::path& path); ~piece_manager(); bool check_fastresume(detail::piece_checker_data& d , std::vector<bool>& pieces, bool compact_mode); std::pair<bool, float> check_files(std::vector<bool>& pieces); void release_files(); bool is_allocating() const; void allocate_slots(int num_slots); void mark_failed(int index); unsigned long piece_crc( int slot_index , int block_size , const std::bitset<256>& bitmask); int slot_for_piece(int piece_index) const; size_type read( char* buf , int piece_index , int offset , int size); void write( const char* buf , int piece_index , int offset , int size); boost::filesystem::path const& save_path() const; bool move_storage(boost::filesystem::path const&); // fills the vector that maps all allocated // slots to the piece that is stored (or // partially stored) there. -2 is the index // of unassigned pieces and -1 is unallocated void export_piece_map(std::vector<int>& pieces) const; private: class impl; std::auto_ptr<impl> m_pimpl; }; } #endif // TORRENT_STORAGE_HPP_INCLUDED <commit_msg>fixed ifdef problem<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_STORAGE_HPP_INCLUDE #define TORRENT_STORAGE_HPP_INCLUDE #include <vector> #include <bitset> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/limits.hpp> #include <boost/filesystem/path.hpp> #include <boost/thread.hpp> #include <boost/shared_ptr.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/torrent_info.hpp" #include "libtorrent/config.hpp" namespace libtorrent { namespace detail { struct piece_checker_data; } class session; #if defined(_WIN32) && defined(UNICODE) TORRENT_EXPORT std::wstring safe_convert(std::string const& s); #endif TORRENT_EXPORT std::vector<std::pair<size_type, std::time_t> > get_filesizes( torrent_info const& t , boost::filesystem::path p); TORRENT_EXPORT bool match_filesizes( torrent_info const& t , boost::filesystem::path p , std::vector<std::pair<size_type, std::time_t> > const& sizes , std::string* error = 0); struct TORRENT_EXPORT file_allocation_failed: std::exception { file_allocation_failed(const char* error_msg): m_msg(error_msg) {} virtual const char* what() const throw() { return m_msg.c_str(); } virtual ~file_allocation_failed() throw() {} std::string m_msg; }; class TORRENT_EXPORT storage { public: storage( const torrent_info& info , const boost::filesystem::path& path); void swap(storage&); // may throw file_error if storage for slot does not exist size_type read(char* buf, int slot, int offset, int size); // may throw file_error if storage for slot hasn't been allocated void write(const char* buf, int slot, int offset, int size); bool move_storage(boost::filesystem::path save_path); // this will close all open files that are opened for // writing. This is called when a torrent has finished // downloading. void release_files(); #ifndef NDEBUG // overwrites some slots with the // contents of others void shuffle(); #endif private: class impl; boost::shared_ptr<impl> m_pimpl; }; class TORRENT_EXPORT piece_manager : boost::noncopyable { public: piece_manager( const torrent_info& info , const boost::filesystem::path& path); ~piece_manager(); bool check_fastresume(detail::piece_checker_data& d , std::vector<bool>& pieces, bool compact_mode); std::pair<bool, float> check_files(std::vector<bool>& pieces); void release_files(); bool is_allocating() const; void allocate_slots(int num_slots); void mark_failed(int index); unsigned long piece_crc( int slot_index , int block_size , const std::bitset<256>& bitmask); int slot_for_piece(int piece_index) const; size_type read( char* buf , int piece_index , int offset , int size); void write( const char* buf , int piece_index , int offset , int size); boost::filesystem::path const& save_path() const; bool move_storage(boost::filesystem::path const&); // fills the vector that maps all allocated // slots to the piece that is stored (or // partially stored) there. -2 is the index // of unassigned pieces and -1 is unallocated void export_piece_map(std::vector<int>& pieces) const; private: class impl; std::auto_ptr<impl> m_pimpl; }; } #endif // TORRENT_STORAGE_HPP_INCLUDED <|endoftext|>
<commit_before>#include <sstream> #include "pixels.h" #include "viewport.h" #include "rng.h" #include "screenmessage.h" #include "setup.h" #include "state.h" using namespace std; Pixels::Pixels (GlobalData* global) : global(global), pixels(TPixels(global->setup->pixels)), stepn(1), steps(1), stepw(1), stepe(1), speed(4) { Rng* rng = global->rng; Viewport* viewport = global->viewport; for (int i = 0; i <= global->setup->pixels-1; i++) pixels[i] = Pixel( rng->rnd () % viewport->resx, rng->rnd () % viewport->resy, viewport->mapColor (rng->rnd () % 256, rng->rnd () % 256, rng->rnd () % 256) ); } void Pixels::render () { Viewport* viewport = global->viewport; viewport->lock (); for (TPixels::const_iterator i = pixels.begin (); i != pixels.end (); i++) viewport->putpixel (i->x, i->y, i->color); viewport->unlock (); } void Pixels::tick () { if (global->state->isFrozen ()) return; Uint32 rval; Rng* rng = global->rng; Viewport* viewport = global->viewport; int shift = rng->bits - 1; int mshift = rng->bits - 2; State::ModeT mode = global->state->getMode (); int px, py, step, xmax=viewport->resx-1, ymax=viewport->resy-1; global->event_source->getMouseCoords (px, py); for (int j = 1; j <= speed; j++) { for (TPixels::iterator i = pixels.begin (); i != pixels.end (); i++) { if (shift > mshift) { rval = rng->rnd (); shift = 0; } switch (mode) { case State::Static: switch ((rval >> shift) & 3) { case 0: if ((i->x += stepe) >= xmax) i->x -= stepe; break; case 1: if ((i->x -= stepw) < 0) i->x += stepw; break; case 2: if ((i->y += steps) >= ymax) i->y -= steps; break; case 3: if ((i->y -= stepn) < 0) i->y += stepn; break; } break; case State::Magnetic: switch ((rval >> shift) & 3) { case 0: step = (px > i->x)?((px - i->x) / 10 + 1):1; step = (step>5)?10:step; if ((i->x += step) > xmax) i->x -= step; break; case 1: step = (px < i->x)?((i->x - px) / 10 + 1):1; step = (step>5)?10:step; if ((i->x -= step) < 0) i->x += step; break; case 2: step = (py > i->y)?((py - i->y) / 10 + 1):1; step = (step>5)?10:step; if ((i->y += step) > ymax) i->y -= step; break; case 3: step = (py < i->y)?((i->y - py) / 10 + 1):1; step = (step>5)?10:step; if ((i->y -= step) < 0) i->y += step; break; } break; } shift += 2; } } } void Pixels::receiveEvent (const Event& evt) { stringstream ss; ScreenMessage* messages = global->messages; switch (evt.type) { case Event::Left: if (stepe > 1) { stepe--; ss << "step width east: " << stepe; messages->pushMessage (ss.str ()); } else { stepw++; ss << "step width west: " << stepw; messages->pushMessage (ss.str ()); } break; case Event::Right: if (stepw > 1) { stepw--; ss << "step width west: " << stepw; messages->pushMessage (ss.str ()); } else { stepe++; ss << "step width east: " << stepe; messages->pushMessage (ss.str ()); } break; case Event::Up: if (steps > 1) { steps--; ss << "step width south: " << steps; messages->pushMessage (ss.str ()); } else { stepn++; ss << "step width north: " << stepn; messages->pushMessage (ss.str ()); } break; case Event::Down: if (stepn > 1) { stepn--; ss << "step width north: " << stepn; messages->pushMessage (ss.str ()); } else { steps++; ss << "step width south: " << steps; messages->pushMessage (ss.str ()); } break; case Event::SpeedUp: speed++; ss << "speed: " << speed; messages->pushMessage (ss.str ()); break; case Event::SpeedDown: if (speed > 1) speed--; ss << "speed: " << speed; messages->pushMessage (ss.str ()); break; case Event::ChangeRng: global->rng->cycle (); messages->pushMessage ("rng set to " + global->rng->name ()); break; case Event::Dump: ss << "north: " << stepn << " west: " << stepw; ss << " south: " << steps << " east: " << stepe; ss << " speed: " << speed; messages->pushMessage (ss.str ()); messages->pushMessage ("random number generator: " + global->rng-> name ()); break; } } <commit_msg>Tune magnetic mode.<commit_after>#include <sstream> #include "pixels.h" #include "viewport.h" #include "rng.h" #include "screenmessage.h" #include "setup.h" #include "state.h" using namespace std; Pixels::Pixels (GlobalData* global) : global(global), pixels(TPixels(global->setup->pixels)), stepn(1), steps(1), stepw(1), stepe(1), speed(4) { Rng* rng = global->rng; Viewport* viewport = global->viewport; for (int i = 0; i <= global->setup->pixels-1; i++) pixels[i] = Pixel( rng->rnd () % viewport->resx, rng->rnd () % viewport->resy, viewport->mapColor (rng->rnd () % 256, rng->rnd () % 256, rng->rnd () % 256) ); } void Pixels::render () { Viewport* viewport = global->viewport; viewport->lock (); for (TPixels::const_iterator i = pixels.begin (); i != pixels.end (); i++) viewport->putpixel (i->x, i->y, i->color); viewport->unlock (); } void Pixels::tick () { if (global->state->isFrozen ()) return; Uint32 rval; Rng* rng = global->rng; Viewport* viewport = global->viewport; int shift = rng->bits - 1; int mshift = rng->bits - 2; State::ModeT mode = global->state->getMode (); int px, py, step, xmax=viewport->resx-1, ymax=viewport->resy-1; global->event_source->getMouseCoords (px, py); for (int j = 1; j <= speed; j++) { for (TPixels::iterator i = pixels.begin (); i != pixels.end (); i++) { if (shift > mshift) { rval = rng->rnd (); shift = 0; } switch (mode) { case State::Static: switch ((rval >> shift) & 3) { case 0: if ((i->x += stepe) >= xmax) i->x -= stepe; break; case 1: if ((i->x -= stepw) < 0) i->x += stepw; break; case 2: if ((i->y += steps) >= ymax) i->y -= steps; break; case 3: if ((i->y -= stepn) < 0) i->y += stepn; break; } break; case State::Magnetic: switch ((rval >> shift) & 3) { case 0: step = (px > i->x)?((px - i->x) / 10 + 1):1; if (step > 7) step = 7; if ((i->x += step) > xmax) i->x -= step; break; case 1: step = (px < i->x)?((i->x - px) / 10 + 1):1; if (step > 7) step = 7; if ((i->x -= step) < 0) i->x += step; break; case 2: step = (py > i->y)?((py - i->y) / 10 + 1):1; if (step > 7) step = 7; if ((i->y += step) > ymax) i->y -= step; break; case 3: step = (py < i->y)?((i->y - py) / 10 + 1):1; if (step > 7) step = 7; if ((i->y -= step) < 0) i->y += step; break; } break; } shift += 2; } } } void Pixels::receiveEvent (const Event& evt) { stringstream ss; ScreenMessage* messages = global->messages; switch (evt.type) { case Event::Left: if (stepe > 1) { stepe--; ss << "step width east: " << stepe; messages->pushMessage (ss.str ()); } else { stepw++; ss << "step width west: " << stepw; messages->pushMessage (ss.str ()); } break; case Event::Right: if (stepw > 1) { stepw--; ss << "step width west: " << stepw; messages->pushMessage (ss.str ()); } else { stepe++; ss << "step width east: " << stepe; messages->pushMessage (ss.str ()); } break; case Event::Up: if (steps > 1) { steps--; ss << "step width south: " << steps; messages->pushMessage (ss.str ()); } else { stepn++; ss << "step width north: " << stepn; messages->pushMessage (ss.str ()); } break; case Event::Down: if (stepn > 1) { stepn--; ss << "step width north: " << stepn; messages->pushMessage (ss.str ()); } else { steps++; ss << "step width south: " << steps; messages->pushMessage (ss.str ()); } break; case Event::SpeedUp: speed++; ss << "speed: " << speed; messages->pushMessage (ss.str ()); break; case Event::SpeedDown: if (speed > 1) speed--; ss << "speed: " << speed; messages->pushMessage (ss.str ()); break; case Event::ChangeRng: global->rng->cycle (); messages->pushMessage ("rng set to " + global->rng->name ()); break; case Event::Dump: ss << "north: " << stepn << " west: " << stepw; ss << " south: " << steps << " east: " << stepe; ss << " speed: " << speed; messages->pushMessage (ss.str ()); messages->pushMessage ("random number generator: " + global->rng-> name ()); break; } } <|endoftext|>
<commit_before><commit_msg>added the while loop to main and some preliminary function definitions<commit_after><|endoftext|>
<commit_before>/***************************************************************************/ /** ** @file Option.cpp ** @brief Functions for class tOption ** ** A. Desitter - March 2004 ** ** $Id: tOption.cpp,v 1.2 2004-04-01 09:57:28 childcvs Exp $ */ /***************************************************************************/ #if !defined(HAVE_NO_NAMESPACE) # include <iostream> using namespace std; #else # include <iostream.h> #endif #include <stdlib.h> #include <string.h> #include "tOption.h" tOption::tOption(int argc, char const * const argv[]) : exeName(argv[0]), silent_mode(false), checkMeshConsistency(true), inputFile(0) { argv++; while(argc > 1){ int i = parseOptions(argv); argc -= i; argv += i; } } // Parse options one at a time. Returns number of options consumed. int tOption::parseOptions(char const * const argv[]) { const char * const thisOption = argv[0]; if (strcmp(thisOption, "--silent-mode") == 0){ silent_mode = true; return 1; } if (strcmp(thisOption, "--no-check") == 0){ checkMeshConsistency = false; return 1; } if (strcmp(thisOption, "--help") == 0){ usage(); exit(EXIT_SUCCESS); } if (thisOption[0] == '-') { usage(); exit(EXIT_FAILURE); } if (inputFile != NULL) { cerr << exeName << ": Several input files given." << endl; exit(EXIT_FAILURE); } inputFile = thisOption; return 1; } void tOption::usage() const { cerr << "Usage: " << exeName << " [options] <input file>\n" << " --help: display this help message.\n" << " --no-check: disable CheckMeshConsistency().\n" << " --silent-mode: silent mode.\n" << endl; } <commit_msg>(Arnaud) Abort when input file was not given.<commit_after>/***************************************************************************/ /** ** @file Option.cpp ** @brief Functions for class tOption ** ** A. Desitter - March 2004 ** ** $Id: tOption.cpp,v 1.3 2004-04-01 11:02:25 childcvs Exp $ */ /***************************************************************************/ #if !defined(HAVE_NO_NAMESPACE) # include <iostream> using namespace std; #else # include <iostream.h> #endif #include <stdlib.h> #include <string.h> #include "tOption.h" tOption::tOption(int argc, char const * const argv[]) : exeName(argv[0]), silent_mode(false), checkMeshConsistency(true), inputFile(0) { argv++; while(argc > 1){ int i = parseOptions(argv); argc -= i; argv += i; } if (inputFile ==NULL){ usage(); exit(EXIT_FAILURE); } } // Parse options one at a time. Returns number of options consumed. int tOption::parseOptions(char const * const argv[]) { const char * const thisOption = argv[0]; if (strcmp(thisOption, "--silent-mode") == 0){ silent_mode = true; return 1; } if (strcmp(thisOption, "--no-check") == 0){ checkMeshConsistency = false; return 1; } if (strcmp(thisOption, "--help") == 0){ usage(); exit(EXIT_SUCCESS); } if (thisOption[0] == '-') { usage(); exit(EXIT_FAILURE); } if (inputFile != NULL) { cerr << exeName << ": Several input files given." << endl; exit(EXIT_FAILURE); } inputFile = thisOption; return 1; } void tOption::usage() const { cerr << "Usage: " << exeName << " [options] <input file>\n" << " --help: display this help message.\n" << " --no-check: disable CheckMeshConsistency().\n" << " --silent-mode: silent mode.\n" << endl; } <|endoftext|>
<commit_before>/*************************************************************************\ ** ** tOutput.cpp: Functions for output objects ** ** ** ** $Id: tOutput.cpp,v 1.4 1998-02-02 17:54:18 gtucker Exp $ \*************************************************************************/ #include "tOutput.h" /*************************************************************************\ ** ** Constructor ** ** The constructor takes two arguments, a pointer to the grid mesh and ** a reference to an open input file. It reads the base name for the ** output files from the input file, and opens and initializes these. ** ** Input: gridPtr -- pointer to a tGrid object (or descendant), assumed ** valid ** infile -- reference to an open input file, assumed valid ** \*************************************************************************/ template< class tSubNode > tOutput<tSubNode>::tOutput( tGrid<tSubNode> * gridPtr, tInputFile &infile ) { //Xchar fullName[kMaxNameSize+6]; assert( gridPtr > 0 ); g = gridPtr; infile.ReadItem( baseName, "OUTFILENAME" ); /*X strcpy( fullName, baseName ); strcat( fullName, ".nodes" ); nodeofs.open( fullName ); strcpy( fullName, baseName ); strcat( fullName, ".edges" ); edgofs.open( fullName ); strcpy( fullName, baseName ); strcat( fullName, ".tri" ); triofs.open( fullName ); strcpy( fullName, baseName ); strcat( fullName, ".z" ); zofs.open( fullName ); if( !nodeofs.good() || !edgofs.good() || !triofs.good() || !zofs.good() ) ReportFatalError( "I can't create files for output. Memory may be exhausted." );*/ CreateAndOpenFile( &nodeofs, ".nodes" ); CreateAndOpenFile( &edgofs, ".edges" ); CreateAndOpenFile( &triofs, ".tri" ); CreateAndOpenFile( &zofs, ".z" ); } /*************************************************************************\ ** ** CreateAndOpenFile ** ** Opens the output file stream pointed by theOFStream, giving it the ** name <baseName><extension>, and checks to make sure that the ofstream ** is valid. ** ** Input: theOFStream -- ptr to an ofstream object ** extension -- file name extension (e.g., ".nodes") ** Output: theOFStream is initialized to create an open output file ** Assumes: extension is a null-terminated string, and the length of ** baseName plus extension doesn't exceed kMaxNameSize+6 ** (ie, the extension is expected to be <= 6 characters) ** \*************************************************************************/ template< class tSubNode > void tOutput<tSubNode>::CreateAndOpenFile( ofstream *theOFStream, char *extension ) { char fullName[kMaxNameSize+6]; strcpy( fullName, baseName ); strcat( fullName, extension ); theOFStream->open( fullName ); if( !theOFStream->good() ) ReportFatalError( "I can't create files for output. Memory may be exhausted." ); } /*************************************************************************\ ** ** WriteOutput ** ** This function writes information about the mesh to four files called ** name.nodes, name.edges, name.tri, and name.z, where "name" is a ** name that the user has specified in the input file and which is ** stored in the data member baseName. ** ** Input: time -- time of the current output time-slice ** Output: the node, edge, and triangle ID numbers are modified so that ** they are numbered according to their position on the list ** Assumes: the four file ofstreams have been opened by the constructor ** and are valid ** ** TODO: deal with option for once-only printing of mesh when mesh not ** deforming \*************************************************************************/ template< class tSubNode > void tOutput<tSubNode>::WriteOutput( double time ) { tGridListIter<tSubNode> niter( g->GetNodeList() ); tGridListIter<tEdge> eiter( g->GetEdgeList() ); tListIter<tTriangle> titer( g->GetTriList() ); tNode * cn; tEdge * ce; tTriangle * ct; int id; int nnodes = g->GetNodeList()->getSize(); int nedges = g->GetEdgeList()->getSize(); int ntri = g->GetTriList()->getSize(); cout << "tOutput::WriteOutput()\n"; // Renumber IDs in order by position on list for( cn=niter.FirstP(), id=0; id<nnodes; cn=niter.NextP(), id++ ) cn->setID( id ); for( ce=eiter.FirstP(), id=0; id<nedges; ce=eiter.NextP(), id++ ) ce->setID( id ); for( ct=titer.FirstP(), id=0; id<ntri; ct=titer.NextP(), id++ ) ct->setID( id ); // Write node file and z file nodeofs << " " << time << endl << nnodes << endl; zofs << " " << time << endl << nnodes << endl; for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() ) { nodeofs << cn->getX() << " " << cn->getY() << " " << cn->GetEdg()->getID() << " " << cn->getBoundaryFlag() << endl; zofs << cn->getZ() << endl; } // Write edge file edgofs << " " << time << endl << nedges << endl; for( ce=eiter.FirstP(); !(eiter.AtEnd()); ce=eiter.NextP() ) edgofs << ce->getOriginPtrNC()->getID() << " " << ce->getDestinationPtrNC()->getID() << " " << ce->GetCCWEdg()->getID() << endl; // Write triangle file int i; triofs << " " << time << endl << ntri << endl; for( ct=titer.FirstP(); !(titer.AtEnd()); ct=titer.NextP() ) { for( i=0; i<=2; i++ ) triofs << ct->pPtr(i)->getID() << " "; for( i=0; i<=2; i++ ) { if( ct->tPtr(i) ) triofs << ct->tPtr(i)->getID() << " "; else triofs << "-1 "; } triofs << ct->ePtr(0)->getID() << " " << ct->ePtr(1)->getID() << " " << ct->ePtr(2)->getID() << endl; } WriteNodeData( time ); } template< class tSubNode > void tOutput<tSubNode>::WriteNodeData( double time ) {} template< class tSubNode > tLOutput<tSubNode>::tLOutput( tGrid<tSubNode> *g, tInputFile &infile ) : tOutput<tSubNode>( g, infile ) // call base-class constructor { //Xchar fullName[kMaxNameSize+6]; /*Xstrcpy( fullName, baseName ); strcat( fullName, ".area" ); drareaofs.open( fullName ); strcpy( fullName, baseName ); strcat( fullName, ".net" ); netofs.open( fullName ); if( !drareaofs.good() || !netofs.good() ) ReportFatalError( "Unable to open output file. Storage space may be exhausted." ); */ CreateAndOpenFile( &drareaofs, ".area" ); CreateAndOpenFile( &netofs, ".net" ); CreateAndOpenFile( &slpofs, ".slp" ); } template< class tSubNode > void tLOutput<tSubNode>::WriteNodeData( double time ) { tGridListIter<tSubNode> ni( g->GetNodeList() ); tSubNode *cn; int nActiveNodes = g->GetNodeList()->getActiveSize(); drareaofs << " " << time << "\n " << nActiveNodes << endl; netofs << " " << time << "\n " << nActiveNodes << endl; slpofs << " " << time << "\n " << nActiveNodes << endl; for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() ) { assert( cn>0 ); drareaofs << cn->getDrArea() << endl; netofs << cn->GetDownstrmNbr()->getID() << endl; slpofs << cn->GetSlope() << endl; } } <commit_msg>added output of discharges to .q file<commit_after>/*************************************************************************\ ** ** tOutput.cpp: Functions for output objects ** ** ** ** $Id: tOutput.cpp,v 1.5 1998-02-02 20:36:45 gtucker Exp $ \*************************************************************************/ #include "tOutput.h" /*************************************************************************\ ** ** Constructor ** ** The constructor takes two arguments, a pointer to the grid mesh and ** a reference to an open input file. It reads the base name for the ** output files from the input file, and opens and initializes these. ** ** Input: gridPtr -- pointer to a tGrid object (or descendant), assumed ** valid ** infile -- reference to an open input file, assumed valid ** \*************************************************************************/ template< class tSubNode > tOutput<tSubNode>::tOutput( tGrid<tSubNode> * gridPtr, tInputFile &infile ) { //Xchar fullName[kMaxNameSize+6]; assert( gridPtr > 0 ); g = gridPtr; infile.ReadItem( baseName, "OUTFILENAME" ); /*X strcpy( fullName, baseName ); strcat( fullName, ".nodes" ); nodeofs.open( fullName ); strcpy( fullName, baseName ); strcat( fullName, ".edges" ); edgofs.open( fullName ); strcpy( fullName, baseName ); strcat( fullName, ".tri" ); triofs.open( fullName ); strcpy( fullName, baseName ); strcat( fullName, ".z" ); zofs.open( fullName ); if( !nodeofs.good() || !edgofs.good() || !triofs.good() || !zofs.good() ) ReportFatalError( "I can't create files for output. Memory may be exhausted." );*/ CreateAndOpenFile( &nodeofs, ".nodes" ); CreateAndOpenFile( &edgofs, ".edges" ); CreateAndOpenFile( &triofs, ".tri" ); CreateAndOpenFile( &zofs, ".z" ); } /*************************************************************************\ ** ** CreateAndOpenFile ** ** Opens the output file stream pointed by theOFStream, giving it the ** name <baseName><extension>, and checks to make sure that the ofstream ** is valid. ** ** Input: theOFStream -- ptr to an ofstream object ** extension -- file name extension (e.g., ".nodes") ** Output: theOFStream is initialized to create an open output file ** Assumes: extension is a null-terminated string, and the length of ** baseName plus extension doesn't exceed kMaxNameSize+6 ** (ie, the extension is expected to be <= 6 characters) ** \*************************************************************************/ template< class tSubNode > void tOutput<tSubNode>::CreateAndOpenFile( ofstream *theOFStream, char *extension ) { char fullName[kMaxNameSize+6]; strcpy( fullName, baseName ); strcat( fullName, extension ); theOFStream->open( fullName ); if( !theOFStream->good() ) ReportFatalError( "I can't create files for output. Memory may be exhausted." ); } /*************************************************************************\ ** ** WriteOutput ** ** This function writes information about the mesh to four files called ** name.nodes, name.edges, name.tri, and name.z, where "name" is a ** name that the user has specified in the input file and which is ** stored in the data member baseName. ** ** Input: time -- time of the current output time-slice ** Output: the node, edge, and triangle ID numbers are modified so that ** they are numbered according to their position on the list ** Assumes: the four file ofstreams have been opened by the constructor ** and are valid ** ** TODO: deal with option for once-only printing of mesh when mesh not ** deforming \*************************************************************************/ template< class tSubNode > void tOutput<tSubNode>::WriteOutput( double time ) { tGridListIter<tSubNode> niter( g->GetNodeList() ); tGridListIter<tEdge> eiter( g->GetEdgeList() ); tListIter<tTriangle> titer( g->GetTriList() ); tNode * cn; tEdge * ce; tTriangle * ct; int id; int nnodes = g->GetNodeList()->getSize(); int nedges = g->GetEdgeList()->getSize(); int ntri = g->GetTriList()->getSize(); cout << "tOutput::WriteOutput()\n"; // Renumber IDs in order by position on list for( cn=niter.FirstP(), id=0; id<nnodes; cn=niter.NextP(), id++ ) cn->setID( id ); for( ce=eiter.FirstP(), id=0; id<nedges; ce=eiter.NextP(), id++ ) ce->setID( id ); for( ct=titer.FirstP(), id=0; id<ntri; ct=titer.NextP(), id++ ) ct->setID( id ); // Write node file and z file nodeofs << " " << time << endl << nnodes << endl; zofs << " " << time << endl << nnodes << endl; for( cn=niter.FirstP(); !(niter.AtEnd()); cn=niter.NextP() ) { nodeofs << cn->getX() << " " << cn->getY() << " " << cn->GetEdg()->getID() << " " << cn->getBoundaryFlag() << endl; zofs << cn->getZ() << endl; } // Write edge file edgofs << " " << time << endl << nedges << endl; for( ce=eiter.FirstP(); !(eiter.AtEnd()); ce=eiter.NextP() ) edgofs << ce->getOriginPtrNC()->getID() << " " << ce->getDestinationPtrNC()->getID() << " " << ce->GetCCWEdg()->getID() << endl; // Write triangle file int i; triofs << " " << time << endl << ntri << endl; for( ct=titer.FirstP(); !(titer.AtEnd()); ct=titer.NextP() ) { for( i=0; i<=2; i++ ) triofs << ct->pPtr(i)->getID() << " "; for( i=0; i<=2; i++ ) { if( ct->tPtr(i) ) triofs << ct->tPtr(i)->getID() << " "; else triofs << "-1 "; } triofs << ct->ePtr(0)->getID() << " " << ct->ePtr(1)->getID() << " " << ct->ePtr(2)->getID() << endl; } WriteNodeData( time ); } template< class tSubNode > void tOutput<tSubNode>::WriteNodeData( double time ) {} template< class tSubNode > tLOutput<tSubNode>::tLOutput( tGrid<tSubNode> *g, tInputFile &infile ) : tOutput<tSubNode>( g, infile ) // call base-class constructor { //Xchar fullName[kMaxNameSize+6]; /*Xstrcpy( fullName, baseName ); strcat( fullName, ".area" ); drareaofs.open( fullName ); strcpy( fullName, baseName ); strcat( fullName, ".net" ); netofs.open( fullName ); if( !drareaofs.good() || !netofs.good() ) ReportFatalError( "Unable to open output file. Storage space may be exhausted." ); */ CreateAndOpenFile( &drareaofs, ".area" ); CreateAndOpenFile( &netofs, ".net" ); CreateAndOpenFile( &slpofs, ".slp" ); CreateAndOpenFile( &qofs, ".q" ); } template< class tSubNode > void tLOutput<tSubNode>::WriteNodeData( double time ) { tGridListIter<tSubNode> ni( g->GetNodeList() ); tSubNode *cn; int nActiveNodes = g->GetNodeList()->getActiveSize(); drareaofs << " " << time << "\n " << nActiveNodes << endl; netofs << " " << time << "\n " << nActiveNodes << endl; slpofs << " " << time << "\n " << nActiveNodes << endl; qofs << " " << time << "\n " << nActiveNodes << endl; for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() ) { assert( cn>0 ); drareaofs << cn->getDrArea() << endl; netofs << cn->GetDownstrmNbr()->getID() << endl; slpofs << cn->GetSlope() << endl; qofs << cn->GetQ() << endl; } } <|endoftext|>
<commit_before>#ifndef __MALC_CUSTOM_TYPE_HPP__ #define __MALC_CUSTOM_TYPE_HPP__ #include <string> #include <vector> #include <type_traits> #include <bl/base/platform.h> #include <malcpp/malcpp.hpp> // base resources to define custom log types. It won't work if you include // malc_lean.hpp before. namespace malcpp { //------------------------------------------------------------------------------ template <uint8_t type_value> struct builtin_map { static constexpr uint8_t value = type_value; }; //------------------------------------------------------------------------------ template <class T> struct builtin_type_map; template<> struct builtin_type_map<uint8_t> : public builtin_map<malc_obj_u8> {}; template<> struct builtin_type_map<int8_t> : public builtin_map<malc_obj_i8> {}; template<> struct builtin_type_map<uint16_t> : public builtin_map<malc_obj_u16> {}; template<> struct builtin_type_map<int16_t> : public builtin_map<malc_obj_i16> {}; template<> struct builtin_type_map<uint32_t> : public builtin_map<malc_obj_u32> {}; template<> struct builtin_type_map<int32_t> : public builtin_map<malc_obj_i32> {}; template<> struct builtin_type_map<uint64_t> : public builtin_map<malc_obj_u64> {}; template<> struct builtin_type_map<int64_t> : public builtin_map<malc_obj_i64> {}; template<> struct builtin_type_map<float> : public builtin_map<malc_obj_float> {}; template<> struct builtin_type_map<double> : public builtin_map<malc_obj_double> {}; //------------------------------------------------------------------------------ struct MALC_EXPORT obj_log_data { //---------------------------------------------------------------------------- static malc_obj_log_data get_as_str (char const* str, std::size_t len); //---------------------------------------------------------------------------- template <int N> static inline malc_obj_log_data get (const char (&str)[N]) { return obj_log_data::get_as_str (str, N - 1); } //---------------------------------------------------------------------------- static inline malc_obj_log_data get (std::string const& s) { return obj_log_data::get_as_str (s.c_str(), s.size()); } //---------------------------------------------------------------------------- static inline malc_obj_log_data get_null_smartptr() { return obj_log_data::get (MALC_CPP_NULL_SMART_PTR_STR); } //---------------------------------------------------------------------------- static malc_obj_log_data get( void const* addr, std::size_t count, uint8_t builtin_type ); //---------------------------------------------------------------------------- template <class T> static inline typename std::enable_if< detail::serialization::is_valid_builtin<T>::value, malc_obj_log_data >::type get (T const* first, std::size_t count) { return obj_log_data::get( (void*) &first[0], count, builtin_type_map<T>::value ); } //---------------------------------------------------------------------------- template <class T> static inline typename std::enable_if< detail::serialization::is_valid_builtin<T>::value, malc_obj_log_data >::type get (T& v) { return obj_log_data::get( (void*) &v, 1, builtin_type_map<T>::value ); } //------------------------------------------------------------------------------ template <class T> static inline malc_obj_log_data get (std::vector<T> const &v) { return obj_log_data::get (&v[0], v.size()); } //------------------------------------------------------------------------------ }; //------------------------------------------------------------------------------ class log_entry_adder { public: //---------------------------------------------------------------------------- log_entry_adder (malc_obj_push_context const& pushcontext) : pc (pushcontext) {}; //---------------------------------------------------------------------------- int push (malc_obj_log_data const& ld) const noexcept { return malc_obj_push (&pc, &ld); } //---------------------------------------------------------------------------- int push_as_str (char const* str, std::size_t len) const noexcept { return push (obj_log_data::get_as_str (str, len)); } //---------------------------------------------------------------------------- template <int N> int push (const char (&str)[N]) const noexcept { return push (obj_log_data::get_as_str (str, N - 1)); } //---------------------------------------------------------------------------- int push (std::string const& str) const noexcept { return push (obj_log_data::get (str)); } //---------------------------------------------------------------------------- int push_null_smartptr() const noexcept { return push (obj_log_data::get_null_smartptr ()); } //---------------------------------------------------------------------------- template <class T> int push (T const* first, std::size_t count) const noexcept { return push (obj_log_data::get (first, count)); } //---------------------------------------------------------------------------- template <class T> typename std::enable_if< detail::serialization::is_valid_builtin<T>::value, int >::type push (T v) const noexcept { return push (obj_log_data::get (v)); } //---------------------------------------------------------------------------- template <class T> int push (std::vector<T> const &v) const noexcept { return push (obj_log_data::get (v)); } //---------------------------------------------------------------------------- private: //---------------------------------------------------------------------------- malc_obj_push_context const& pc; //---------------------------------------------------------------------------- }; //------------------------------------------------------------------------------ template <class inherited> class custom_log_type { public: //---------------------------------------------------------------------------- using type = inherited; //---------------------------------------------------------------------------- static malc_obj_table const* get_table() { return &objtable; } //---------------------------------------------------------------------------- private: static const malc_obj_table objtable; //---------------------------------------------------------------------------- static void destroy (malc_obj_ref* obj, void const*) { static_cast<inherited*> (obj->obj)->~inherited(); } //---------------------------------------------------------------------------- static int get_data( malc_obj_ref* obj, void const* table, malc_obj_push_context const* pc, bl_alloc_tbl const* alloc ) { BL_TRY { return static_cast<inherited*> (obj->obj)->dump_value( log_entry_adder (*pc), obj->extra.context, obj->extra.flag, *alloc ); } BL_CATCH (...) { return 1; } } //---------------------------------------------------------------------------- }; //------------------------------------------------------------------------------ template <class T> const malc_obj_table custom_log_type<T>::objtable{ get_data, destroy, sizeof (T) }; //------------------------------------------------------------------------------ } // namespace malcpp #endif // _MALCPP_CUSTOM_TYPE_ <commit_msg>custom_type: get: vector: avoid illegal access<commit_after>#ifndef __MALC_CUSTOM_TYPE_HPP__ #define __MALC_CUSTOM_TYPE_HPP__ #include <string> #include <vector> #include <type_traits> #include <bl/base/platform.h> #include <malcpp/malcpp.hpp> // base resources to define custom log types. It won't work if you include // malc_lean.hpp before. namespace malcpp { //------------------------------------------------------------------------------ template <uint8_t type_value> struct builtin_map { static constexpr uint8_t value = type_value; }; //------------------------------------------------------------------------------ template <class T> struct builtin_type_map; template<> struct builtin_type_map<uint8_t> : public builtin_map<malc_obj_u8> {}; template<> struct builtin_type_map<int8_t> : public builtin_map<malc_obj_i8> {}; template<> struct builtin_type_map<uint16_t> : public builtin_map<malc_obj_u16> {}; template<> struct builtin_type_map<int16_t> : public builtin_map<malc_obj_i16> {}; template<> struct builtin_type_map<uint32_t> : public builtin_map<malc_obj_u32> {}; template<> struct builtin_type_map<int32_t> : public builtin_map<malc_obj_i32> {}; template<> struct builtin_type_map<uint64_t> : public builtin_map<malc_obj_u64> {}; template<> struct builtin_type_map<int64_t> : public builtin_map<malc_obj_i64> {}; template<> struct builtin_type_map<float> : public builtin_map<malc_obj_float> {}; template<> struct builtin_type_map<double> : public builtin_map<malc_obj_double> {}; //------------------------------------------------------------------------------ struct MALC_EXPORT obj_log_data { //---------------------------------------------------------------------------- static malc_obj_log_data get_as_str (char const* str, std::size_t len); //---------------------------------------------------------------------------- template <int N> static inline malc_obj_log_data get (const char (&str)[N]) { return obj_log_data::get_as_str (str, N - 1); } //---------------------------------------------------------------------------- static inline malc_obj_log_data get (std::string const& s) { return obj_log_data::get_as_str (s.c_str(), s.size()); } //---------------------------------------------------------------------------- static inline malc_obj_log_data get_null_smartptr() { return obj_log_data::get (MALC_CPP_NULL_SMART_PTR_STR); } //---------------------------------------------------------------------------- static malc_obj_log_data get( void const* addr, std::size_t count, uint8_t builtin_type ); //---------------------------------------------------------------------------- template <class T> static inline typename std::enable_if< detail::serialization::is_valid_builtin<T>::value, malc_obj_log_data >::type get (T const* first, std::size_t count) { return obj_log_data::get( (void*) &first[0], count, builtin_type_map<T>::value ); } //---------------------------------------------------------------------------- template <class T> static inline typename std::enable_if< detail::serialization::is_valid_builtin<T>::value, malc_obj_log_data >::type get (T& v) { return obj_log_data::get( (void*) &v, 1, builtin_type_map<T>::value ); } //------------------------------------------------------------------------------ template <class T> static inline malc_obj_log_data get (std::vector<T> const &v) { return obj_log_data::get (v.size() ? &v[0] : nullptr, v.size()); } //------------------------------------------------------------------------------ }; //------------------------------------------------------------------------------ class log_entry_adder { public: //---------------------------------------------------------------------------- log_entry_adder (malc_obj_push_context const& pushcontext) : pc (pushcontext) {}; //---------------------------------------------------------------------------- int push (malc_obj_log_data const& ld) const noexcept { return malc_obj_push (&pc, &ld); } //---------------------------------------------------------------------------- int push_as_str (char const* str, std::size_t len) const noexcept { return push (obj_log_data::get_as_str (str, len)); } //---------------------------------------------------------------------------- template <int N> int push (const char (&str)[N]) const noexcept { return push (obj_log_data::get_as_str (str, N - 1)); } //---------------------------------------------------------------------------- int push (std::string const& str) const noexcept { return push (obj_log_data::get (str)); } //---------------------------------------------------------------------------- int push_null_smartptr() const noexcept { return push (obj_log_data::get_null_smartptr ()); } //---------------------------------------------------------------------------- template <class T> int push (T const* first, std::size_t count) const noexcept { return push (obj_log_data::get (first, count)); } //---------------------------------------------------------------------------- template <class T> typename std::enable_if< detail::serialization::is_valid_builtin<T>::value, int >::type push (T v) const noexcept { return push (obj_log_data::get (v)); } //---------------------------------------------------------------------------- template <class T> int push (std::vector<T> const &v) const noexcept { return push (obj_log_data::get (v)); } //---------------------------------------------------------------------------- private: //---------------------------------------------------------------------------- malc_obj_push_context const& pc; //---------------------------------------------------------------------------- }; //------------------------------------------------------------------------------ template <class inherited> class custom_log_type { public: //---------------------------------------------------------------------------- using type = inherited; //---------------------------------------------------------------------------- static malc_obj_table const* get_table() { return &objtable; } //---------------------------------------------------------------------------- private: static const malc_obj_table objtable; //---------------------------------------------------------------------------- static void destroy (malc_obj_ref* obj, void const*) { static_cast<inherited*> (obj->obj)->~inherited(); } //---------------------------------------------------------------------------- static int get_data( malc_obj_ref* obj, void const* table, malc_obj_push_context const* pc, bl_alloc_tbl const* alloc ) { BL_TRY { return static_cast<inherited*> (obj->obj)->dump_value( log_entry_adder (*pc), obj->extra.context, obj->extra.flag, *alloc ); } BL_CATCH (...) { return 1; } } //---------------------------------------------------------------------------- }; //------------------------------------------------------------------------------ template <class T> const malc_obj_table custom_log_type<T>::objtable{ get_data, destroy, sizeof (T) }; //------------------------------------------------------------------------------ } // namespace malcpp #endif // _MALCPP_CUSTOM_TYPE_ <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #include "fileinprojectfinder.h" #include <utils/qtcassert.h> #include <QtCore/QFileInfo> #include <QtCore/QUrl> namespace Utils { /*! \class Utils::FileInProjectFinder \brief Helper class to find the 'original' file in the project directory for a given file url. Often files are copied in the build + deploy process. findFile() searches for an existing file in the project directory for a given file path: E.g. following file paths: \list \i C:/app-build-desktop/qml/app/main.qml (shadow build directory) \i C:/Private/e3026d63/qml/app/main.qml (Application data folder on Symbian device) \i /Users/x/app-build-desktop/App.app/Contents/Resources/qml/App/main.qml (folder on Mac OS X) \endlist should all be mapped to $PROJECTDIR/qml/app/main.qml */ FileInProjectFinder::FileInProjectFinder() { } static QString stripTrailingSlashes(const QString &path) { QString newPath = path; while (newPath.endsWith(QLatin1Char('/'))) newPath.remove(newPath.length() - 1, 1); return newPath; } void FileInProjectFinder::setProjectDirectory(const QString &absoluteProjectPath) { const QString newProjectPath = stripTrailingSlashes(absoluteProjectPath); if (newProjectPath == m_projectDir) return; const QFileInfo infoPath(newProjectPath); QTC_CHECK(newProjectPath.isEmpty() || (infoPath.exists() && infoPath.isAbsolute())); m_projectDir = newProjectPath; m_cache.clear(); } QString FileInProjectFinder::projectDirectory() const { return m_projectDir; } void FileInProjectFinder::setProjectFiles(const QStringList &projectFiles) { if (m_projectFiles == projectFiles) return; m_projectFiles = projectFiles; m_cache.clear(); } void FileInProjectFinder::setSysroot(const QString &sysroot) { QString newsys = sysroot; while (newsys.endsWith(QLatin1Char('/'))) newsys.remove(newsys.length() - 1, 1); if (m_sysroot == newsys) return; m_sysroot = newsys; m_cache.clear(); } /** Returns the best match for the given file url in the project directory. The method first checks whether the file inside the project directory exists. If not, the leading directory in the path is stripped, and the - now shorter - path is checked for existence, and so on. Second, it tries to locate the file in the sysroot folder specified. Third, we walk the list of project files, and search for a file name match there. If all fails, it returns the original path from the file url. */ QString FileInProjectFinder::findFile(const QUrl &fileUrl, bool *success) const { QString originalPath = fileUrl.toLocalFile(); if (originalPath.isEmpty()) // e.g. qrc:// originalPath = fileUrl.path(); if (originalPath.isEmpty()) { if (success) *success = false; return originalPath; } if (!m_projectDir.isEmpty()) { int prefixToIgnore = -1; const QChar separator = QLatin1Char('/'); if (originalPath.startsWith(m_projectDir + separator)) { #ifdef Q_OS_MAC // starting with the project path is not sufficient if the file was // copied in an insource build, e.g. into MyApp.app/Contents/Resources static const QString appResourcePath = QString::fromLatin1(".app/Contents/Resources"); if (originalPath.contains(appResourcePath)) { // the path is inside the project, but most probably as a resource of an insource build // so ignore that path prefixToIgnore = originalPath.indexOf(appResourcePath) + appResourcePath.length(); } else { #endif if (success) *success = true; return originalPath; #ifdef Q_OS_MAC } #endif } if (m_cache.contains(originalPath)) { // check if cached path is still there QString candidate = m_cache.value(originalPath); QFileInfo candidateInfo(candidate); if (candidateInfo.exists() && candidateInfo.isFile()) { if (success) *success = true; return candidate; } } // Strip directories one by one from the beginning of the path, // and see if the new relative path exists in the build directory. if (prefixToIgnore < 0) { if (!QFileInfo(originalPath).isAbsolute() && !originalPath.startsWith(separator)) { prefixToIgnore = 0; } else { prefixToIgnore = originalPath.indexOf(separator); } } while (prefixToIgnore != -1) { QString candidate = originalPath; candidate.remove(0, prefixToIgnore); candidate.prepend(m_projectDir); QFileInfo candidateInfo(candidate); if (candidateInfo.exists() && candidateInfo.isFile()) { if (success) *success = true; m_cache.insert(originalPath, candidate); return candidate; } prefixToIgnore = originalPath.indexOf(separator, prefixToIgnore + 1); } } // check if absolute path is found in sysroot if (!m_sysroot.isEmpty()) { const QString sysrootPath = m_sysroot + QLatin1Char('/') + originalPath; if (QFileInfo(sysrootPath).exists() && QFileInfo(sysrootPath).isFile()) { if (success) *success = true; m_cache.insert(originalPath, sysrootPath); return sysrootPath; } } // finally, find solely by filename in project files const QString fileName = QFileInfo(originalPath).fileName(); foreach (const QString &f, m_projectFiles) { if (QFileInfo(f).fileName() == fileName) { m_cache.insert(originalPath, f); if (success) *success = true; return f; } } if (success) *success = false; return originalPath; } } // namespace Utils <commit_msg>FileInProjectFinder: Avoid double slash in sysroot'ed path<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #include "fileinprojectfinder.h" #include <utils/qtcassert.h> #include <QtCore/QFileInfo> #include <QtCore/QUrl> namespace Utils { /*! \class Utils::FileInProjectFinder \brief Helper class to find the 'original' file in the project directory for a given file url. Often files are copied in the build + deploy process. findFile() searches for an existing file in the project directory for a given file path: E.g. following file paths: \list \i C:/app-build-desktop/qml/app/main.qml (shadow build directory) \i C:/Private/e3026d63/qml/app/main.qml (Application data folder on Symbian device) \i /Users/x/app-build-desktop/App.app/Contents/Resources/qml/App/main.qml (folder on Mac OS X) \endlist should all be mapped to $PROJECTDIR/qml/app/main.qml */ FileInProjectFinder::FileInProjectFinder() { } static QString stripTrailingSlashes(const QString &path) { QString newPath = path; while (newPath.endsWith(QLatin1Char('/'))) newPath.remove(newPath.length() - 1, 1); return newPath; } void FileInProjectFinder::setProjectDirectory(const QString &absoluteProjectPath) { const QString newProjectPath = stripTrailingSlashes(absoluteProjectPath); if (newProjectPath == m_projectDir) return; const QFileInfo infoPath(newProjectPath); QTC_CHECK(newProjectPath.isEmpty() || (infoPath.exists() && infoPath.isAbsolute())); m_projectDir = newProjectPath; m_cache.clear(); } QString FileInProjectFinder::projectDirectory() const { return m_projectDir; } void FileInProjectFinder::setProjectFiles(const QStringList &projectFiles) { if (m_projectFiles == projectFiles) return; m_projectFiles = projectFiles; m_cache.clear(); } void FileInProjectFinder::setSysroot(const QString &sysroot) { QString newsys = sysroot; while (newsys.endsWith(QLatin1Char('/'))) newsys.remove(newsys.length() - 1, 1); if (m_sysroot == newsys) return; m_sysroot = newsys; m_cache.clear(); } /** Returns the best match for the given file url in the project directory. The method first checks whether the file inside the project directory exists. If not, the leading directory in the path is stripped, and the - now shorter - path is checked for existence, and so on. Second, it tries to locate the file in the sysroot folder specified. Third, we walk the list of project files, and search for a file name match there. If all fails, it returns the original path from the file url. */ QString FileInProjectFinder::findFile(const QUrl &fileUrl, bool *success) const { QString originalPath = fileUrl.toLocalFile(); if (originalPath.isEmpty()) // e.g. qrc:// originalPath = fileUrl.path(); if (originalPath.isEmpty()) { if (success) *success = false; return originalPath; } if (!m_projectDir.isEmpty()) { int prefixToIgnore = -1; const QChar separator = QLatin1Char('/'); if (originalPath.startsWith(m_projectDir + separator)) { #ifdef Q_OS_MAC // starting with the project path is not sufficient if the file was // copied in an insource build, e.g. into MyApp.app/Contents/Resources static const QString appResourcePath = QString::fromLatin1(".app/Contents/Resources"); if (originalPath.contains(appResourcePath)) { // the path is inside the project, but most probably as a resource of an insource build // so ignore that path prefixToIgnore = originalPath.indexOf(appResourcePath) + appResourcePath.length(); } else { #endif if (success) *success = true; return originalPath; #ifdef Q_OS_MAC } #endif } if (m_cache.contains(originalPath)) { // check if cached path is still there QString candidate = m_cache.value(originalPath); QFileInfo candidateInfo(candidate); if (candidateInfo.exists() && candidateInfo.isFile()) { if (success) *success = true; return candidate; } } // Strip directories one by one from the beginning of the path, // and see if the new relative path exists in the build directory. if (prefixToIgnore < 0) { if (!QFileInfo(originalPath).isAbsolute() && !originalPath.startsWith(separator)) { prefixToIgnore = 0; } else { prefixToIgnore = originalPath.indexOf(separator); } } while (prefixToIgnore != -1) { QString candidate = originalPath; candidate.remove(0, prefixToIgnore); candidate.prepend(m_projectDir); QFileInfo candidateInfo(candidate); if (candidateInfo.exists() && candidateInfo.isFile()) { if (success) *success = true; m_cache.insert(originalPath, candidate); return candidate; } prefixToIgnore = originalPath.indexOf(separator, prefixToIgnore + 1); } } // check if absolute path is found in sysroot if (!m_sysroot.isEmpty()) { const QString sysrootPath = m_sysroot + originalPath; if (QFileInfo(sysrootPath).exists() && QFileInfo(sysrootPath).isFile()) { if (success) *success = true; m_cache.insert(originalPath, sysrootPath); return sysrootPath; } } // finally, find solely by filename in project files const QString fileName = QFileInfo(originalPath).fileName(); foreach (const QString &f, m_projectFiles) { if (QFileInfo(f).fileName() == fileName) { m_cache.insert(originalPath, f); if (success) *success = true; return f; } } if (success) *success = false; return originalPath; } } // namespace Utils <|endoftext|>
<commit_before>/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include <map> #include <qi/atomic.hpp> #include <boost/thread/recursive_mutex.hpp> #include <qitype/signal.hpp> #include <qitype/genericvalue.hpp> #include <qitype/genericobject.hpp> #include "object_p.hpp" #include "signal_p.hpp" namespace qi { SignalSubscriber::SignalSubscriber(qi::ObjectPtr target, unsigned int method) : weakLock(0), target(new qi::ObjectWeakPtr(target)), method(method), enabled(true), active(0) {} SignalSubscriber::SignalSubscriber(GenericFunction func, EventLoop* ctx, detail::WeakLock* lock) : handler(func), weakLock(lock), target(0), method(0), enabled(true), active(0) { eventLoopGetter = boost::bind(detail::eventLoopGet, ctx); } SignalSubscriber::~SignalSubscriber() { delete target; delete weakLock; } SignalSubscriber::SignalSubscriber(const SignalSubscriber& b) : weakLock(0), target(0) { *this = b; } void SignalSubscriber::operator=(const SignalSubscriber& b) { source = b.source; linkId = b.linkId; handler = b.handler; weakLock = b.weakLock?b.weakLock->clone():0; eventLoopGetter = b.eventLoopGetter; target = b.target?new ObjectWeakPtr(*b.target):0; method = b.method; enabled = b.enabled; active = 0; } static qi::atomic<long> linkUid = 1; void SignalBase::operator()( qi::AutoGenericValue p1, qi::AutoGenericValue p2, qi::AutoGenericValue p3, qi::AutoGenericValue p4, qi::AutoGenericValue p5, qi::AutoGenericValue p6, qi::AutoGenericValue p7, qi::AutoGenericValue p8) { qi::AutoGenericValue* vals[8]= {&p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8}; std::vector<qi::GenericValue> params; for (unsigned i=0; i<8; ++i) if (vals[i]->value) params.push_back(*vals[i]); // Signature construction std::string signature = "("; for (unsigned i=0; i< params.size(); ++i) signature += params[i].signature(); signature += ")"; if (signature != _p->signature) { qiLogError("qi.signal") << "Dropping emit: signature mismatch: " << signature <<" " << _p->signature; return; } trigger(params); } void SignalBase::trigger(const GenericFunctionParameters& params) { if (!_p) return; SignalSubscriberMap copy; { boost::recursive_mutex::scoped_lock sl(_p->mutex); copy = _p->subscriberMap; } SignalSubscriberMap::iterator i; for (i=copy.begin(); i!= copy.end(); ++i) { i->second->call(params); } } class FunctorCall { public: FunctorCall(GenericFunctionParameters& params, SignalSubscriber* sub) : sub(sub) { std::swap((std::vector<GenericValue>&)this->params, (std::vector<GenericValue>&)params); } FunctorCall(const FunctorCall& b) { *this = b; } void operator=(const FunctorCall& b) { std::swap((std::vector<GenericValue>&)(this->params), (std::vector<GenericValue>&)b.params); sub = b.sub; } GenericFunctionParameters params; SignalSubscriber* sub; void operator() () { if (sub->enabled) sub->handler(params); long active = --sub->active; params.destroy(); if (sub->weakLock && !active) sub->weakLock->unlock(); } }; void SignalSubscriber::call(const GenericFunctionParameters& args) { if (!enabled) return; if (handler.type) { if (weakLock) { bool locked = weakLock->tryLock(); if (!locked) { source->disconnect(linkId); return; } } EventLoop* eventLoop = 0; if (eventLoopGetter) eventLoop = eventLoopGetter(); if (eventLoop) { ++active; // Event emission is always asynchronous GenericFunctionParameters copy = args.copy(); eventLoop->asyncCall(0, FunctorCall(copy, this)); } else { handler(args); if (weakLock) weakLock->unlock(); } } else if (target) { ObjectPtr lockedTarget = target->lock(); if (!lockedTarget) source->disconnect(linkId); else lockedTarget->metaEmit(method, args); } } SignalBase::Link SignalBase::connect(GenericFunction callback, EventLoop* ctx) { return connect(SignalSubscriber(callback, ctx)); } SignalBase::Link SignalBase::connect(qi::ObjectPtr o, unsigned int slot) { return connect(SignalSubscriber(o, slot)); } SignalBase::Link SignalBase::connect(const SignalSubscriber& src) { if (!_p) { _p = boost::shared_ptr<SignalBasePrivate>(new SignalBasePrivate()); } // Check arity. Does not require to acquire weakLock. int sigArity = Signature(signature()).begin().children().size(); int subArity = -1; if (src.handler.type) { if (src.handler.type == dynamicFunctionType()) goto proceed; // no arity checking is possible subArity = src.handler.type->argumentsType().size(); } else if (src.target) { ObjectPtr locked = src.target->lock(); if (!locked) { qiLogVerbose("qi.signal") << "connecting a dead slot (weak ptr out)"; return SignalBase::invalidLink; } const MetaMethod* ms = locked->metaObject().method(src.method); if (!ms) { qiLogWarning("qi.signal") << "Method " << src.method <<" not found, proceeding anyway"; goto proceed; } else subArity = Signature(qi::signatureSplit(ms->signature())[2]).size(); } if (sigArity != subArity) { qiLogWarning("qi.signal") << "Subscriber has incorrect arity (expected " << sigArity << " , got " << subArity <<")"; return SignalBase::invalidLink; } proceed: boost::recursive_mutex::scoped_lock sl(_p->mutex); Link res = ++linkUid; _p->subscriberMap[res] = new SignalSubscriber(src); SignalSubscriber& s = *_p->subscriberMap[res]; s.linkId = res; s.source = this; return res; } bool SignalBase::disconnectAll() { if (_p) return _p->reset(); return false; } SignalBase::SignalBase(const std::string& sig) : _p(new SignalBasePrivate) { _p->signature = sig; } SignalBase::SignalBase() { } SignalBase::SignalBase(const SignalBase& b) { (*this) = b; } SignalBase& SignalBase::operator=(const SignalBase& b) { if (!b._p) { const_cast<SignalBase&>(b)._p = boost::shared_ptr<SignalBasePrivate>(new SignalBasePrivate()); } _p = b._p; return *this; } std::string SignalBase::signature() const { return _p?_p->signature:""; } bool SignalBasePrivate::disconnect(const SignalBase::Link& l) { boost::recursive_mutex::scoped_lock sl(mutex); SignalSubscriberMap::iterator it = subscriberMap.find(l); if (it == subscriberMap.end()) return false; SignalSubscriber* s = it->second; // Ensure no call on subscriber occurrs once this function returns s->enabled = false; while (*(s->active)) os::msleep(1); // FIXME too long subscriberMap.erase(it); delete s; return true; } bool SignalBase::disconnect(const Link &link) { if (!_p) return false; else return _p->disconnect(link); } SignalBase::~SignalBase() { if (!_p) return; SignalSubscriberMap::iterator i; std::vector<Link> links; for (i = _p->subscriberMap.begin(); i!= _p->subscriberMap.end(); ++i) { links.push_back(i->first); } for (unsigned i=0; i<links.size(); ++i) disconnect(links[i]); } std::vector<SignalSubscriber> SignalBase::subscribers() { std::vector<SignalSubscriber> res; if (!_p) return res; boost::recursive_mutex::scoped_lock sl(_p->mutex); SignalSubscriberMap::iterator i; for (i = _p->subscriberMap.begin(); i!= _p->subscriberMap.end(); ++i) res.push_back(*i->second); return res; } bool SignalBasePrivate::reset() { bool ret = true; boost::recursive_mutex::scoped_lock sl(mutex); SignalSubscriberMap::iterator it = subscriberMap.begin(); while (it != subscriberMap.end()) { bool b = disconnect(it->first); if (!b) ret = false; it = subscriberMap.begin(); } return ret; } QITYPE_API const SignalBase::Link SignalBase::invalidLink = ((unsigned int)-1); } <commit_msg>Signal: Reduce trigger window of a race condition.<commit_after>/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include <map> #include <qi/atomic.hpp> #include <boost/thread/recursive_mutex.hpp> #include <qitype/signal.hpp> #include <qitype/genericvalue.hpp> #include <qitype/genericobject.hpp> #include "object_p.hpp" #include "signal_p.hpp" namespace qi { SignalSubscriber::SignalSubscriber(qi::ObjectPtr target, unsigned int method) : weakLock(0), target(new qi::ObjectWeakPtr(target)), method(method), enabled(true), active(0) {} SignalSubscriber::SignalSubscriber(GenericFunction func, EventLoop* ctx, detail::WeakLock* lock) : handler(func), weakLock(lock), target(0), method(0), enabled(true), active(0) { eventLoopGetter = boost::bind(detail::eventLoopGet, ctx); } SignalSubscriber::~SignalSubscriber() { delete target; delete weakLock; } SignalSubscriber::SignalSubscriber(const SignalSubscriber& b) : weakLock(0), target(0) { *this = b; } void SignalSubscriber::operator=(const SignalSubscriber& b) { source = b.source; linkId = b.linkId; handler = b.handler; weakLock = b.weakLock?b.weakLock->clone():0; eventLoopGetter = b.eventLoopGetter; target = b.target?new ObjectWeakPtr(*b.target):0; method = b.method; enabled = b.enabled; active = 0; } static qi::atomic<long> linkUid = 1; void SignalBase::operator()( qi::AutoGenericValue p1, qi::AutoGenericValue p2, qi::AutoGenericValue p3, qi::AutoGenericValue p4, qi::AutoGenericValue p5, qi::AutoGenericValue p6, qi::AutoGenericValue p7, qi::AutoGenericValue p8) { qi::AutoGenericValue* vals[8]= {&p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8}; std::vector<qi::GenericValue> params; for (unsigned i=0; i<8; ++i) if (vals[i]->value) params.push_back(*vals[i]); // Signature construction std::string signature = "("; for (unsigned i=0; i< params.size(); ++i) signature += params[i].signature(); signature += ")"; if (signature != _p->signature) { qiLogError("qi.signal") << "Dropping emit: signature mismatch: " << signature <<" " << _p->signature; return; } trigger(params); } void SignalBase::trigger(const GenericFunctionParameters& params) { if (!_p) return; SignalSubscriberMap copy; { boost::recursive_mutex::scoped_lock sl(_p->mutex); copy = _p->subscriberMap; } SignalSubscriberMap::iterator i; for (i=copy.begin(); i!= copy.end(); ++i) { i->second->call(params); } } class FunctorCall { public: FunctorCall(GenericFunctionParameters& params, SignalSubscriber* sub) : sub(sub) { std::swap((std::vector<GenericValue>&)this->params, (std::vector<GenericValue>&)params); } FunctorCall(const FunctorCall& b) { *this = b; } void operator=(const FunctorCall& b) { std::swap((std::vector<GenericValue>&)(this->params), (std::vector<GenericValue>&)b.params); sub = b.sub; } GenericFunctionParameters params; SignalSubscriber* sub; void operator() () { if (sub->enabled) sub->handler(params); params.destroy(); long active = --sub->active; if (sub->weakLock && !active) sub->weakLock->unlock(); } }; void SignalSubscriber::call(const GenericFunctionParameters& args) { if (!enabled) return; if (handler.type) { if (weakLock) { bool locked = weakLock->tryLock(); if (!locked) { source->disconnect(linkId); return; } } EventLoop* eventLoop = 0; if (eventLoopGetter) eventLoop = eventLoopGetter(); if (eventLoop) { ++active; // Event emission is always asynchronous GenericFunctionParameters copy = args.copy(); eventLoop->asyncCall(0, FunctorCall(copy, this)); } else { handler(args); if (weakLock) weakLock->unlock(); } } else if (target) { ObjectPtr lockedTarget = target->lock(); if (!lockedTarget) source->disconnect(linkId); else lockedTarget->metaEmit(method, args); } } SignalBase::Link SignalBase::connect(GenericFunction callback, EventLoop* ctx) { return connect(SignalSubscriber(callback, ctx)); } SignalBase::Link SignalBase::connect(qi::ObjectPtr o, unsigned int slot) { return connect(SignalSubscriber(o, slot)); } SignalBase::Link SignalBase::connect(const SignalSubscriber& src) { if (!_p) { _p = boost::shared_ptr<SignalBasePrivate>(new SignalBasePrivate()); } // Check arity. Does not require to acquire weakLock. int sigArity = Signature(signature()).begin().children().size(); int subArity = -1; if (src.handler.type) { if (src.handler.type == dynamicFunctionType()) goto proceed; // no arity checking is possible subArity = src.handler.type->argumentsType().size(); } else if (src.target) { ObjectPtr locked = src.target->lock(); if (!locked) { qiLogVerbose("qi.signal") << "connecting a dead slot (weak ptr out)"; return SignalBase::invalidLink; } const MetaMethod* ms = locked->metaObject().method(src.method); if (!ms) { qiLogWarning("qi.signal") << "Method " << src.method <<" not found, proceeding anyway"; goto proceed; } else subArity = Signature(qi::signatureSplit(ms->signature())[2]).size(); } if (sigArity != subArity) { qiLogWarning("qi.signal") << "Subscriber has incorrect arity (expected " << sigArity << " , got " << subArity <<")"; return SignalBase::invalidLink; } proceed: boost::recursive_mutex::scoped_lock sl(_p->mutex); Link res = ++linkUid; _p->subscriberMap[res] = new SignalSubscriber(src); SignalSubscriber& s = *_p->subscriberMap[res]; s.linkId = res; s.source = this; return res; } bool SignalBase::disconnectAll() { if (_p) return _p->reset(); return false; } SignalBase::SignalBase(const std::string& sig) : _p(new SignalBasePrivate) { _p->signature = sig; } SignalBase::SignalBase() { } SignalBase::SignalBase(const SignalBase& b) { (*this) = b; } SignalBase& SignalBase::operator=(const SignalBase& b) { if (!b._p) { const_cast<SignalBase&>(b)._p = boost::shared_ptr<SignalBasePrivate>(new SignalBasePrivate()); } _p = b._p; return *this; } std::string SignalBase::signature() const { return _p?_p->signature:""; } bool SignalBasePrivate::disconnect(const SignalBase::Link& l) { boost::recursive_mutex::scoped_lock sl(mutex); SignalSubscriberMap::iterator it = subscriberMap.find(l); if (it == subscriberMap.end()) return false; SignalSubscriber* s = it->second; // Ensure no call on subscriber occurrs once this function returns s->enabled = false; while (*(s->active)) os::msleep(1); // FIXME too long subscriberMap.erase(it); delete s; return true; } bool SignalBase::disconnect(const Link &link) { if (!_p) return false; else return _p->disconnect(link); } SignalBase::~SignalBase() { if (!_p) return; SignalSubscriberMap::iterator i; std::vector<Link> links; for (i = _p->subscriberMap.begin(); i!= _p->subscriberMap.end(); ++i) { links.push_back(i->first); } for (unsigned i=0; i<links.size(); ++i) disconnect(links[i]); } std::vector<SignalSubscriber> SignalBase::subscribers() { std::vector<SignalSubscriber> res; if (!_p) return res; boost::recursive_mutex::scoped_lock sl(_p->mutex); SignalSubscriberMap::iterator i; for (i = _p->subscriberMap.begin(); i!= _p->subscriberMap.end(); ++i) res.push_back(*i->second); return res; } bool SignalBasePrivate::reset() { bool ret = true; boost::recursive_mutex::scoped_lock sl(mutex); SignalSubscriberMap::iterator it = subscriberMap.begin(); while (it != subscriberMap.end()) { bool b = disconnect(it->first); if (!b) ret = false; it = subscriberMap.begin(); } return ret; } QITYPE_API const SignalBase::Link SignalBase::invalidLink = ((unsigned int)-1); } <|endoftext|>
<commit_before>#pragma once /* MIT License Copyright (c) 2017 Arlen Keshabyan (arlen.albert@gmail.com) 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 <unordered_map> #include <unordered_set> #include <vector> namespace nstd { template <typename ValueType> class topological_sorter { public: using value_type = ValueType; protected: struct relations { std::size_t dependencies { 0 }; std::unordered_set<value_type> dependents {}; }; std::unordered_map<value_type, relations> _map {}; public: void add(const value_type &object) { _map.try_emplace(object, relations {}); } void add(const value_type &object, const value_type &dependency) { if (dependency == object) return; auto &dependents = _map[dependency].dependents; if (dependents.find(object) == dependents.end()) { dependents.insert(object); ++_map[object].dependencies; } } template <typename Container> void add(const value_type &object, const Container &dependencies) { static_assert(std::is_same<value_type, typename std::decay<typename Container::value_type>::type>::value, "The Container's value_type and object's type must be the same!"); for (auto const &dependency : dependencies) add(object, dependency); } void add(const value_type &object, const std::initializer_list<value_type> &dependencies) { add<std::initializer_list<value_type>>(object, dependencies); } auto sort() { std::vector<value_type> sorted, cycled; auto map { _map }; for(const auto &[object, relations] : map) if (!relations.dependencies) sorted.push_back(object); for(decltype(std::size(sorted)) idx = 0; idx < std::size(sorted); ++idx) for(auto const& object : map[sorted[idx]].dependents) if (!--map[object].dependencies) sorted.push_back(object); for(const auto &[object, relations] : map) if(relations.dependencies) cycled.push_back(std::move(object)); return std::pair(std::move(sorted), std::move(cycled)); } void clear() { _map.clear(); } }; } <commit_msg>small changes<commit_after>#pragma once /* MIT License Copyright (c) 2017 Arlen Keshabyan (arlen.albert@gmail.com) 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 <unordered_map> #include <unordered_set> #include <vector> namespace nstd { template <typename ValueType> class topological_sorter { public: using value_type = ValueType; protected: struct relations { std::size_t dependencies { 0 }; std::unordered_set<value_type> dependents {}; }; std::unordered_map<value_type, relations> _map {}; public: void add(const value_type &object) { _map.try_emplace(object, relations {}); } void add(const value_type &object, const value_type &dependency) { if (dependency == object) return; auto &dependents = _map[dependency].dependents; if (dependents.find(object) == dependents.end()) { dependents.insert(object); ++_map[object].dependencies; } } template <typename Container> void add(const value_type &object, const Container &dependencies) { for (auto const &dependency : dependencies) add(object, dependency); } void add(const value_type &object, const std::initializer_list<value_type> &dependencies) { add<std::initializer_list<value_type>>(object, dependencies); } auto sort() { std::vector<value_type> sorted, cycled; auto map { _map }; for(const auto &[object, relations] : map) if (!relations.dependencies) sorted.push_back(object); for(decltype(std::size(sorted)) idx = 0; idx < std::size(sorted); ++idx) for(auto const& object : map[sorted[idx]].dependents) if (!--map[object].dependencies) sorted.push_back(object); for(const auto &[object, relations] : map) if(relations.dependencies) cycled.push_back(std::move(object)); return std::pair(std::move(sorted), std::move(cycled)); } void clear() { _map.clear(); } }; } <|endoftext|>
<commit_before>#ifndef VSMC_CORE_PARTICLE_HPP #define VSMC_CORE_PARTICLE_HPP #include <vsmc/internal/common.hpp> #include <vsmc/internal/resampling.hpp> namespace vsmc { /// \brief Particle class representing the whole particle set /// \ingroup Core /// /// \tparam T Requirement: /// \li Constructor compatible with /// \code T(Particle<T>::size_type N) \endcode /// \li member function copy method compatible with /// \code copy(Particle<T>::size_type from, Particle<T>::size_type to) \endcode template <typename T> class Particle { public : /// The type of the number of particles typedef VSMC_SIZE_TYPE size_type; /// The type of the particle values typedef T value_type; #ifdef VSMC_USE_SEQUENTIAL_RNG /// The type of the sequential pseudo random number generator C++11 engine typedef VSMC_SEQRNG_TYPE rng_type; #else /// The type of the Counter-based random number generator typedef VSMC_CBRNG_TYPE cbrng_type; /// The type of the Counter-based random number generator C++11 engine typedef rng::Engine<cbrng_type> rng_type; #endif /// The integer type of the seed typedef rng_type::result_type seed_type; /// The type of the weight and log weight vectors typedef Eigen::VectorXd weight_type; /// \brief Construct a Particle object with a given number of particles /// /// \param N The number of particles /// \param seed The seed to the parallel RNG system /// /// \post All weights are initialized to be euqal to each other explicit Particle (size_type N, seed_type seed = VSMC_RNG_SEED) : size_(N), value_(N), ess_(N), weight_(N), log_weight_(N), inc_weight_(N), replication_(N), ess_cached_(false), weight_cached_(false), log_weight_cached_(false), resampled_(false), zconst_(0), seed_(seed) #ifndef VSMC_USE_SEQUENTIAL_RNG , prng_(N) #endif { reset_rng(); set_equal_weight(); } /// Size of the particle set size_type size () const { return size_; } /// Read and write access to particle values value_type &value () { return value_; } /// Read only access to particle values const value_type &value () const { return value_; } /// Read only access to the weights const weight_type &weight () const { if (!weight_cached_) { weight_ = log_weight().array().exp(); double sum = weight_.sum(); weight_ *= 1 / sum; weight_cached_ = true; } return weight_; } /// Read only access to the log weights const weight_type &log_weight () const { if (!log_weight_cached_) { double max_weight = log_weight_.maxCoeff(); log_weight_ = log_weight_.array() - max_weight; log_weight_cached_ = true; } return log_weight_; } /// Set equal weights for all particles void set_equal_weight () { ess_ = size_; weight_.setConstant(1.0 / size_); log_weight_.setConstant(0); ess_cached_ = true; weight_cached_ = true; log_weight_cached_ = true; } /// \brief Set the log weights with a pointer /// /// \param new_weight The position to start the reading, it shall be valid /// after increments of size() times. /// \param delta A multiplier appiled to the new log weights void set_log_weight (const double *new_weight, double delta = 1) { Eigen::Map<const weight_type> w(new_weight, size_); set_log_weight(w, delta); } /// Set the log weights with a weight_type object void set_log_weight (const weight_type &new_weight, double delta = 1) { log_weight_ = delta * new_weight.head(size_); set_log_weight(); } /// \brief Add to the log weights with a pointer /// /// \param inc_weight The position to start the reading, it shall be valid /// after increments of size() times. /// \param delta A multiplier appiled to the new incremental log weights /// \param add_zconst Whether this incremental weights shall contribute to /// the SMC normalizing constant estimate void add_log_weight (const double *inc_weight, double delta = 1, bool add_zconst = true) { Eigen::Map<const weight_type> w(inc_weight, size_); add_log_weight(w, delta, add_zconst); } /// Add to the log weights with a weight_object object void add_log_weight (const weight_type &inc_weight, double delta = 1, bool add_zconst = true) { using std::log; inc_weight_ = delta * inc_weight.head(size_); log_weight_ += inc_weight_; if (add_zconst) zconst_ += log(weight().dot(inc_weight_.array().exp().matrix())); set_log_weight(); } /// The current ESS (Effective Sample Size) double ess () const { if (!ess_cached_) { ess_ = 1 / weight().squaredNorm(); ess_cached_ = true; } return ess_; } /// Whether resampling was performed when resampling(scheme, threshold) was /// last called. bool resampled () const { return resampled_; } /// Get the value of the logarithm of SMC normalizing constant double zconst () const { return zconst_; } /// Reset the value of logarithm of SMC normalizing constant to zero void reset_zconst () { zconst_ = 0; } /// \brief Perform resampling if ess() < threshold * size() /// /// \param scheme The resampling scheme, see ResamplingScheme /// \param threshold The threshold for resampling void resample (ResampleScheme scheme, double threshold) { assert(replication_.size() == size()); // call to ess() will normalize weight first resampled_ = ess() < threshold * size_; if (resampled_) { internal::pre_resampling(&value_); switch (scheme) { case MULTINOMIAL : resample_multinomial(); break; case RESIDUAL : resample_residual(); break; case STRATIFIED : resample_stratified(); break; case SYSTEMATIC : resample_systematic(); break; case RESIDUAL_STRATIFIED : resample_residual_stratified (); break; default : resample_stratified(); break; } resample_do(); internal::post_resampling(&value_); } } /// \brief Get a C++11 RNG engine /// /// \param id The position of the particle, 0 to size() - 1 /// /// \return A reference to a C++11 RNG engine unique to particle at /// position id, and independent of others if \c VSMC_USE_SEQUENTIAL_RNG is /// not defined. Otherwise, it is the same pseudo RNG for any value of \c /// id rng_type &rng (size_type id) { #ifdef VSMC_USE_SEQUENTIAL_RNG return srng_; #else return prng_[id]; #endif } /// Reset the RNG system with a given seed void reset_rng (seed_type seed) { seed_ = seed; reset_rng(); } /// Reset the parallel RNG system with the last used seed void reset_rng () { #ifdef VSMC_USE_SEQUENTIAL_RNG srng_ = rng_type(seed_); #else for (size_type i = 0; i != size_; ++i) prng_[i] = rng_type(seed_ + i); #endif } private : typedef Eigen::Matrix<size_type, Eigen::Dynamic, 1> replication_type; size_type size_; value_type value_; mutable double ess_; mutable weight_type weight_; mutable weight_type log_weight_; mutable weight_type inc_weight_; mutable replication_type replication_; mutable bool ess_cached_; mutable bool weight_cached_; mutable bool log_weight_cached_; bool resampled_; double zconst_; seed_type seed_; #ifdef VSMC_USE_SEQUENTIAL_RNG rng_type srng_; #else std::deque<rng_type> prng_; #endif void set_log_weight () { ess_cached_ = false; weight_cached_ = false; log_weight_cached_ = false; assert(weight_.size() == size_); assert(log_weight_.size() == size_); assert(inc_weight_.size() == size_); } void resample_multinomial () { weight2replication(size_); } void resample_residual () { /// \internal Reuse weight and log_weight. weight: act as the /// fractional part of N * weight. log_weight: act as the integral /// part of N * weight. They all will be reset to equal weights after /// resampling. So it is safe to modify them here. using std::modf; for (size_type i = 0; i != size_; ++i) weight_[i] = modf(size_ * weight_[i], log_weight_.data() + i); weight2replication(weight_.sum()); for (size_type i = 0; i != size_; ++i) replication_[i] += log_weight_[i]; } void resample_stratified () { replication_.setConstant(0); size_type j = 0; size_type k = 0; rng::uniform_real_distribution<double> unif(0,1); double u = unif(rng(0)); double cw = weight_[0]; while (j != size_) { while (j < cw * size_ - u && j != size_) { ++replication_[k]; u = unif(rng(j)); ++j; } if (k == size_ - 1) break; cw += weight_[++k]; } } void resample_systematic () { replication_.setConstant(0); size_type j = 0; size_type k = 0; rng::uniform_real_distribution<double> unif(0,1); double u = unif(rng(0)); double cw = weight_[0]; while (j != size_) { while (j < cw * size_ - u && j != size_) { ++replication_[k]; ++j; } if (k == size_ - 1) break; cw += weight_[++k]; } } void resample_residual_stratified () { using std::modf; replication_.setConstant(0); for (size_type i = 0; i != size_; ++i) weight_[i] = modf(size_ * weight_[i], log_weight_.data() + i); size_type size = weight_.sum(); weight_ /= size; size_type j = 0; size_type k = 0; rng::uniform_real_distribution<double> unif(0,1); double u = unif(rng(0)); double cw = weight_[0]; while (j != size) { while (j < cw * size - u && j != size) { ++replication_[k]; u = unif(rng(j)); ++j; } if (k == size_ - 1) break; cw += weight_[++k]; } for (size_type i = 0; i != size_; ++i) replication_[i] += log_weight_[i]; } void resample_residual_systematic () { using std::modf; replication_.setConstant(0); for (size_type i = 0; i != size_; ++i) weight_[i] = modf(size_ * weight_[i], log_weight_.data() + i); size_type size = weight_.sum(); weight_ /= size; size_type j = 0; size_type k = 0; rng::uniform_real_distribution<double> unif(0,1); double u = unif(rng(0)); double cw = weight_[0]; while (j != size) { while (j < cw * size - u && j != size) { ++replication_[k]; ++j; } if (k == size_ - 1) break; cw += weight_[++k]; } for (size_type i = 0; i != size_; ++i) replication_[i] += log_weight_[i]; } void weight2replication (size_type size) { double tp = weight_.sum(); double sum_p = 0; size_type sum_n = 0; replication_.setConstant(0); for (size_type i = 0; i != size_; ++i) { if (sum_n < size && weight_[i] > 0) { rng::binomial_distribution<size_type> binom( size - sum_n, weight_[i] / (tp - sum_p)); replication_[i] = binom(rng(i)); } sum_p += weight_[i]; sum_n += replication_[i]; } } void resample_do () { // Some times the nuemrical round error can cause the total childs // differ from number of particles size_type sum = replication_.sum(); if (sum != size_) { size_type id_max; replication_.maxCoeff(&id_max); replication_[id_max] += size_ - sum; } size_type from = 0; size_type time = 0; for (size_type to = 0; to != size_; ++to) { if (!replication_[to]) { // replication_[to] has zero child, copy from elsewhere if (replication_[from] - time <= 1) { // only 1 child left on replication_[from] time = 0; do // move from to some position with at least 2 children ++from; while (replication_[from] < 2); } value_.copy(from, to); ++time; } } set_equal_weight(); } }; // class Particle } // namespace vsmc #endif // VSMC_CORE_PARTICLE_HPP <commit_msg>Use DenseBase as input to weight mutators<commit_after>#ifndef VSMC_CORE_PARTICLE_HPP #define VSMC_CORE_PARTICLE_HPP #include <vsmc/internal/common.hpp> #include <vsmc/internal/resampling.hpp> namespace vsmc { /// \brief Particle class representing the whole particle set /// \ingroup Core /// /// \tparam T Requirement: /// \li Constructor compatible with /// \code T(Particle<T>::size_type N) \endcode /// \li member function copy method compatible with /// \code copy(Particle<T>::size_type from, Particle<T>::size_type to) \endcode template <typename T> class Particle { public : /// The type of the number of particles typedef VSMC_SIZE_TYPE size_type; /// The type of the particle values typedef T value_type; #ifdef VSMC_USE_SEQUENTIAL_RNG /// The type of the sequential pseudo random number generator C++11 engine typedef VSMC_SEQRNG_TYPE rng_type; #else /// The type of the Counter-based random number generator typedef VSMC_CBRNG_TYPE cbrng_type; /// The type of the Counter-based random number generator C++11 engine typedef rng::Engine<cbrng_type> rng_type; #endif /// The integer type of the seed typedef rng_type::result_type seed_type; /// The type of the weight and log weight vectors typedef Eigen::VectorXd weight_type; /// \brief Construct a Particle object with a given number of particles /// /// \param N The number of particles /// \param seed The seed to the parallel RNG system /// /// \post All weights are initialized to be euqal to each other explicit Particle (size_type N, seed_type seed = VSMC_RNG_SEED) : size_(N), value_(N), ess_(N), weight_(N), log_weight_(N), inc_weight_(N), replication_(N), ess_cached_(false), weight_cached_(false), log_weight_cached_(false), resampled_(false), zconst_(0), seed_(seed) #ifndef VSMC_USE_SEQUENTIAL_RNG , prng_(N) #endif { reset_rng(); set_equal_weight(); } /// Size of the particle set size_type size () const { return size_; } /// Read and write access to particle values value_type &value () { return value_; } /// Read only access to particle values const value_type &value () const { return value_; } /// Read only access to the weights const weight_type &weight () const { if (!weight_cached_) { weight_ = log_weight().array().exp(); double sum = weight_.sum(); weight_ *= 1 / sum; weight_cached_ = true; } return weight_; } /// Read only access to the log weights const weight_type &log_weight () const { if (!log_weight_cached_) { double max_weight = log_weight_.maxCoeff(); log_weight_ = log_weight_.array() - max_weight; log_weight_cached_ = true; } return log_weight_; } /// Set equal weights for all particles void set_equal_weight () { ess_ = size_; weight_.setConstant(1.0 / size_); log_weight_.setConstant(0); ess_cached_ = true; weight_cached_ = true; log_weight_cached_ = true; } /// \brief Set the log weights with a pointer /// /// \param new_weight The position to start the reading, it shall be valid /// after increments of size() times. /// \param delta A multiplier appiled to the new log weights void set_log_weight (const double *new_weight, double delta = 1) { Eigen::Map<const weight_type> w(new_weight, size_); set_log_weight(w, delta); } /// Set the log weights with a weight_type object template <typename Derived> void set_log_weight (const Eigen::DenseBase<Derived> &new_weight, double delta = 1) { log_weight_ = delta * new_weight.head(size_); set_log_weight(); } /// \brief Add to the log weights with a pointer /// /// \param inc_weight The position to start the reading, it shall be valid /// after increments of size() times. /// \param delta A multiplier appiled to the new incremental log weights /// \param add_zconst Whether this incremental weights shall contribute to /// the SMC normalizing constant estimate void add_log_weight (const double *inc_weight, double delta = 1, bool add_zconst = true) { Eigen::Map<const weight_type> w(inc_weight, size_); add_log_weight(w, delta, add_zconst); } /// Add to the log weights with a weight_object object template <typename Derived> void add_log_weight (const Eigen::DenseBase<Derived> &inc_weight, double delta = 1, bool add_zconst = true) { using std::log; inc_weight_ = delta * inc_weight.head(size_); log_weight_ += inc_weight_; if (add_zconst) zconst_ += log(weight().dot(inc_weight_.array().exp().matrix())); set_log_weight(); } /// The current ESS (Effective Sample Size) double ess () const { if (!ess_cached_) { ess_ = 1 / weight().squaredNorm(); ess_cached_ = true; } return ess_; } /// Whether resampling was performed when resampling(scheme, threshold) was /// last called. bool resampled () const { return resampled_; } /// Get the value of the logarithm of SMC normalizing constant double zconst () const { return zconst_; } /// Reset the value of logarithm of SMC normalizing constant to zero void reset_zconst () { zconst_ = 0; } /// \brief Perform resampling if ess() < threshold * size() /// /// \param scheme The resampling scheme, see ResamplingScheme /// \param threshold The threshold for resampling void resample (ResampleScheme scheme, double threshold) { assert(replication_.size() == size()); // call to ess() will normalize weight first resampled_ = ess() < threshold * size_; if (resampled_) { internal::pre_resampling(&value_); switch (scheme) { case MULTINOMIAL : resample_multinomial(); break; case RESIDUAL : resample_residual(); break; case STRATIFIED : resample_stratified(); break; case SYSTEMATIC : resample_systematic(); break; case RESIDUAL_STRATIFIED : resample_residual_stratified (); break; default : resample_stratified(); break; } resample_do(); internal::post_resampling(&value_); } } /// \brief Get a C++11 RNG engine /// /// \param id The position of the particle, 0 to size() - 1 /// /// \return A reference to a C++11 RNG engine unique to particle at /// position id, and independent of others if \c VSMC_USE_SEQUENTIAL_RNG is /// not defined. Otherwise, it is the same pseudo RNG for any value of \c /// id rng_type &rng (size_type id) { #ifdef VSMC_USE_SEQUENTIAL_RNG return srng_; #else return prng_[id]; #endif } /// Reset the RNG system with a given seed void reset_rng (seed_type seed) { seed_ = seed; reset_rng(); } /// Reset the parallel RNG system with the last used seed void reset_rng () { #ifdef VSMC_USE_SEQUENTIAL_RNG srng_ = rng_type(seed_); #else for (size_type i = 0; i != size_; ++i) prng_[i] = rng_type(seed_ + i); #endif } private : typedef Eigen::Matrix<size_type, Eigen::Dynamic, 1> replication_type; size_type size_; value_type value_; mutable double ess_; mutable weight_type weight_; mutable weight_type log_weight_; mutable weight_type inc_weight_; mutable replication_type replication_; mutable bool ess_cached_; mutable bool weight_cached_; mutable bool log_weight_cached_; bool resampled_; double zconst_; seed_type seed_; #ifdef VSMC_USE_SEQUENTIAL_RNG rng_type srng_; #else std::deque<rng_type> prng_; #endif void set_log_weight () { ess_cached_ = false; weight_cached_ = false; log_weight_cached_ = false; assert(weight_.size() == size_); assert(log_weight_.size() == size_); assert(inc_weight_.size() == size_); } void resample_multinomial () { weight2replication(size_); } void resample_residual () { /// \internal Reuse weight and log_weight. weight: act as the /// fractional part of N * weight. log_weight: act as the integral /// part of N * weight. They all will be reset to equal weights after /// resampling. So it is safe to modify them here. using std::modf; for (size_type i = 0; i != size_; ++i) weight_[i] = modf(size_ * weight_[i], log_weight_.data() + i); weight2replication(weight_.sum()); for (size_type i = 0; i != size_; ++i) replication_[i] += log_weight_[i]; } void resample_stratified () { replication_.setConstant(0); size_type j = 0; size_type k = 0; rng::uniform_real_distribution<double> unif(0,1); double u = unif(rng(0)); double cw = weight_[0]; while (j != size_) { while (j < cw * size_ - u && j != size_) { ++replication_[k]; u = unif(rng(j)); ++j; } if (k == size_ - 1) break; cw += weight_[++k]; } } void resample_systematic () { replication_.setConstant(0); size_type j = 0; size_type k = 0; rng::uniform_real_distribution<double> unif(0,1); double u = unif(rng(0)); double cw = weight_[0]; while (j != size_) { while (j < cw * size_ - u && j != size_) { ++replication_[k]; ++j; } if (k == size_ - 1) break; cw += weight_[++k]; } } void resample_residual_stratified () { using std::modf; replication_.setConstant(0); for (size_type i = 0; i != size_; ++i) weight_[i] = modf(size_ * weight_[i], log_weight_.data() + i); size_type size = weight_.sum(); weight_ /= size; size_type j = 0; size_type k = 0; rng::uniform_real_distribution<double> unif(0,1); double u = unif(rng(0)); double cw = weight_[0]; while (j != size) { while (j < cw * size - u && j != size) { ++replication_[k]; u = unif(rng(j)); ++j; } if (k == size_ - 1) break; cw += weight_[++k]; } for (size_type i = 0; i != size_; ++i) replication_[i] += log_weight_[i]; } void resample_residual_systematic () { using std::modf; replication_.setConstant(0); for (size_type i = 0; i != size_; ++i) weight_[i] = modf(size_ * weight_[i], log_weight_.data() + i); size_type size = weight_.sum(); weight_ /= size; size_type j = 0; size_type k = 0; rng::uniform_real_distribution<double> unif(0,1); double u = unif(rng(0)); double cw = weight_[0]; while (j != size) { while (j < cw * size - u && j != size) { ++replication_[k]; ++j; } if (k == size_ - 1) break; cw += weight_[++k]; } for (size_type i = 0; i != size_; ++i) replication_[i] += log_weight_[i]; } void weight2replication (size_type size) { double tp = weight_.sum(); double sum_p = 0; size_type sum_n = 0; replication_.setConstant(0); for (size_type i = 0; i != size_; ++i) { if (sum_n < size && weight_[i] > 0) { rng::binomial_distribution<size_type> binom( size - sum_n, weight_[i] / (tp - sum_p)); replication_[i] = binom(rng(i)); } sum_p += weight_[i]; sum_n += replication_[i]; } } void resample_do () { // Some times the nuemrical round error can cause the total childs // differ from number of particles size_type sum = replication_.sum(); if (sum != size_) { size_type id_max; replication_.maxCoeff(&id_max); replication_[id_max] += size_ - sum; } size_type from = 0; size_type time = 0; for (size_type to = 0; to != size_; ++to) { if (!replication_[to]) { // replication_[to] has zero child, copy from elsewhere if (replication_[from] - time <= 1) { // only 1 child left on replication_[from] time = 0; do // move from to some position with at least 2 children ++from; while (replication_[from] < 2); } value_.copy(from, to); ++time; } } set_equal_weight(); } }; // class Particle } // namespace vsmc #endif // VSMC_CORE_PARTICLE_HPP <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2016, Johan Mabille and Sylvain Corlay * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XOPERATION_HPP #define XOPERATION_HPP #include <functional> #include <algorithm> #include <type_traits> #include "xfunction.hpp" #include "xscalar.hpp" namespace xt { /*********** * helpers * ***********/ template <class T> struct identity { using result_type = T; constexpr T operator()(const T& t) const noexcept { return +t; } }; template <class T> struct conditional_ternary { using result_type = T; constexpr result_type operator()(const T& t1, const T& t2, const T& t3) const noexcept { return t1 ? t2 : t3; } }; template <class T> struct conditional { using result_type = bool; constexpr result_type operator()(const T t1, const T t2) const noexcept { return t1 < t2; } }; namespace detail { template <template <class...> class F, class... E> inline auto make_xfunction(const E&... e) noexcept { using functor_type = F<common_value_type<E...>>; using result_type = typename functor_type::result_type; using type = xfunction<functor_type, result_type, get_xexpression_type<E>...>; return type(functor_type(), get_xexpression(e)...); } template <template <class...> class F, class... E> using get_xfunction_type = std::enable_if_t<has_xexpression<E...>::value, xfunction<F<common_value_type<E...>>, typename F<common_value_type<E...>>::result_type, get_xexpression_type<E>...>>; } /************* * operators * *************/ template <class E> inline auto operator+(const xexpression<E>& e) noexcept { return detail::make_xfunction<identity>(e.derived_cast()); } template <class E> inline auto operator-(const xexpression<E>& e) noexcept { return detail::make_xfunction<std::negate>(e.derived_cast()); } template <class E1, class E2> inline auto operator+(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::plus, E1, E2> { return detail::make_xfunction<std::plus>(e1, e2); } template <class E1, class E2> inline auto operator-(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::minus, E1, E2> { return detail::make_xfunction<std::minus>(e1, e2); } template <class E1, class E2> inline auto operator*(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::multiplies, E1, E2> { return detail::make_xfunction<std::multiplies>(e1, e2); } template <class E1, class E2> inline auto operator/(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::divides, E1, E2> { return detail::make_xfunction<std::divides>(e1, e2); } template <class E1, class E2> inline auto operator||(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::logical_or, E1, E2> { return detail::make_xfunction<std::logical_or>(e1, e2); } template <class E1, class E2> inline auto operator&&(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::logical_and, E1, E2> { return detail::make_xfunction<std::logical_and>(e1, e2); } template <class E> inline auto operator!(const E& e) noexcept -> detail::get_xfunction_type<std::logical_not, E> { return detail::make_xfunction<std::logical_not>(e); } template <class E1, class E2> inline auto operator<(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::less, E1, E2> { return detail::make_xfunction<std::less>(e1, e2); } template <class E1, class E2> inline auto operator<=(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::less_equal, E1, E2> { return detail::make_xfunction<std::less_equal>(e1, e2); } template <class E1, class E2> inline auto operator>(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::greater, E1, E2> { return detail::make_xfunction<std::greater>(e1, e2); } template <class E1, class E2> inline auto operator>=(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::greater_equal, E1, E2> { return detail::make_xfunction<std::greater_equal>(e1, e2); } template <class E1, class E2> inline auto equal_to(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::equal_to, E1, E2> { return detail::make_xfunction<std::equal_to>(e1, e2); } template <class E1, class E2, class E3> inline auto where(const E1& e1, const E2& e2, const E3& e3) noexcept -> detail::get_xfunction_type<conditional_ternary, E1, E2, E3> { return detail::make_xfunction<conditional_ternary>(e1, e2, e3); } template <class E1> inline auto any(const xexpression<E1>& e1) -> bool { const E1& e1_d = e1.derived_cast(); return std::any_of(e1_d.storage_begin(), e1_d.storage_end(), [](const typename E1::value_type& el) { return el; }); } template <class E1> inline auto all(const xexpression<E1>& e1) -> bool { const E1& e1_d = e1.derived_cast(); return std::all_of(e1_d.storage_begin(), e1_d.storage_end(), [](const typename E1::value_type& el) { return el; }); } } #endif <commit_msg>clean up<commit_after>/*************************************************************************** * Copyright (c) 2016, Johan Mabille and Sylvain Corlay * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XOPERATION_HPP #define XOPERATION_HPP #include <functional> #include <algorithm> #include <type_traits> #include "xfunction.hpp" #include "xscalar.hpp" namespace xt { /*********** * helpers * ***********/ namespace detail { template <class T> struct identity { using result_type = T; constexpr T operator()(const T& t) const noexcept { return +t; } }; template <class T> struct conditional_ternary { using result_type = T; constexpr result_type operator()(const T& t1, const T& t2, const T& t3) const noexcept { return t1 ? t2 : t3; } }; template <template <class...> class F, class... E> inline auto make_xfunction(const E&... e) noexcept { using functor_type = F<common_value_type<E...>>; using result_type = typename functor_type::result_type; using type = xfunction<functor_type, result_type, get_xexpression_type<E>...>; return type(functor_type(), get_xexpression(e)...); } template <template <class...> class F, class... E> using get_xfunction_type = std::enable_if_t<has_xexpression<E...>::value, xfunction<F<common_value_type<E...>>, typename F<common_value_type<E...>>::result_type, get_xexpression_type<E>...>>; } /************* * operators * *************/ template <class E> inline auto operator+(const xexpression<E>& e) noexcept { return detail::make_xfunction<detail::identity>(e.derived_cast()); } template <class E> inline auto operator-(const xexpression<E>& e) noexcept { return detail::make_xfunction<std::negate>(e.derived_cast()); } template <class E1, class E2> inline auto operator+(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::plus, E1, E2> { return detail::make_xfunction<std::plus>(e1, e2); } template <class E1, class E2> inline auto operator-(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::minus, E1, E2> { return detail::make_xfunction<std::minus>(e1, e2); } template <class E1, class E2> inline auto operator*(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::multiplies, E1, E2> { return detail::make_xfunction<std::multiplies>(e1, e2); } template <class E1, class E2> inline auto operator/(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::divides, E1, E2> { return detail::make_xfunction<std::divides>(e1, e2); } template <class E1, class E2> inline auto operator||(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::logical_or, E1, E2> { return detail::make_xfunction<std::logical_or>(e1, e2); } template <class E1, class E2> inline auto operator&&(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::logical_and, E1, E2> { return detail::make_xfunction<std::logical_and>(e1, e2); } template <class E> inline auto operator!(const E& e) noexcept -> detail::get_xfunction_type<std::logical_not, E> { return detail::make_xfunction<std::logical_not>(e); } template <class E1, class E2> inline auto operator<(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::less, E1, E2> { return detail::make_xfunction<std::less>(e1, e2); } template <class E1, class E2> inline auto operator<=(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::less_equal, E1, E2> { return detail::make_xfunction<std::less_equal>(e1, e2); } template <class E1, class E2> inline auto operator>(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::greater, E1, E2> { return detail::make_xfunction<std::greater>(e1, e2); } template <class E1, class E2> inline auto operator>=(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::greater_equal, E1, E2> { return detail::make_xfunction<std::greater_equal>(e1, e2); } template <class E1, class E2> inline auto equal_to(const E1& e1, const E2& e2) noexcept -> detail::get_xfunction_type<std::equal_to, E1, E2> { return detail::make_xfunction<std::equal_to>(e1, e2); } template <class E1, class E2, class E3> inline auto where(const E1& e1, const E2& e2, const E3& e3) noexcept -> detail::get_xfunction_type<detail::conditional_ternary, E1, E2, E3> { return detail::make_xfunction<detail::conditional_ternary>(e1, e2, e3); } template <class E1> inline auto any(const xexpression<E1>& e1) -> bool { const E1& e1_d = e1.derived_cast(); return std::any_of(e1_d.storage_begin(), e1_d.storage_end(), [](const typename E1::value_type& el) { return el; }); } template <class E1> inline auto all(const xexpression<E1>& e1) -> bool { const E1& e1_d = e1.derived_cast(); return std::all_of(e1_d.storage_begin(), e1_d.storage_end(), [](const typename E1::value_type& el) { return el; }); } } #endif <|endoftext|>
<commit_before>//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "RuntimeMathPch.h" namespace Js { // These implementations need to be compiled with /arch:sse2 #define DivImpl(type) template<> type AsmJsMath::Div(type aLeft, type aRight) { return aLeft / aRight; } #define MulImpl(type) template<> type AsmJsMath::Mul(type aLeft, type aRight) { return aLeft * aRight; } #define DivMulImpl(type) DivImpl(type) MulImpl(type) DivMulImpl(float) DivMulImpl(double) DivMulImpl(int64) DivMulImpl(uint64) MulImpl(int32) MulImpl(uint32) template<> int32 AsmJsMath::Div<int32>(int32 aLeft, int32 aRight) { return aRight == 0 ? 0 : (aLeft == (1 << 31) && aRight == -1) ? aLeft : aLeft / aRight; } template<> uint32 AsmJsMath::Div<uint32>(uint32 aLeft, uint32 aRight) { return aRight == 0 ? 0 : aLeft / aRight; } } <commit_msg>[1.4>master] Force to not inline asm.js div for double on x86 to force to use sse2<commit_after>//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "RuntimeMathPch.h" namespace Js { // These implementations need to be compiled with /arch:sse2 #define DivImpl(type, noinline) template<> noinline type AsmJsMath::Div(type aLeft, type aRight) { return aLeft / aRight; } #define MulImpl(type, noinline) template<> noinline type AsmJsMath::Mul(type aLeft, type aRight) { return aLeft * aRight; } #define DivMulImpl(type, noinline) DivImpl(type, noinline) MulImpl(type, noinline) #if _M_IX86 #define DB_NOINLINE _NOINLINE #else #define DB_NOINLINE #endif DivMulImpl(double, DB_NOINLINE) DivMulImpl(float,) DivMulImpl(int64,) DivMulImpl(uint64,) MulImpl(int32,) MulImpl(uint32,) template<> int32 AsmJsMath::Div<int32>(int32 aLeft, int32 aRight) { return aRight == 0 ? 0 : (aLeft == (1 << 31) && aRight == -1) ? aLeft : aLeft / aRight; } template<> uint32 AsmJsMath::Div<uint32>(uint32 aLeft, uint32 aRight) { return aRight == 0 ? 0 : aLeft / aRight; } } <|endoftext|>
<commit_before>#include <node.h> #include <nan.h> #include <stdlib.h> #ifdef _MSC_VER // Windows header # include <Windows.h> #else // Unix header # include <dirent.h> # include <sys/stat.h> #endif using namespace v8; // Type signature bool IsCurrentDir(const wchar_t* path); bool IsCurrentDir(const char* path); #ifdef _MSC_VER // Windows system call bool ReaddirImpl(Local<String>& path, Local<Array>& result) { int len = path->Length(); wchar_t* path_buf = new wchar_t[len + 3]; int wrote = path->Write((uint16_t*) path_buf); if(wrote < 1) { goto fail; } if(path_buf[len - 1] == L'\\') { path_buf[len] = L'*'; path_buf[len + 1] = L'\0'; } else { path_buf[len] = L'\\'; path_buf[len + 1] = L'*'; path_buf[len + 2] = L'\0'; } WIN32_FIND_DATAW find_data; HANDLE handle = FindFirstFileW(path_buf, &find_data); if(handle == INVALID_HANDLE_VALUE) { goto fail; } int index = 0; do { if(! IsCurrentDir(find_data.cFileName)) { Local<String> filename = NanNew<String>((uint16_t*) find_data.cFileName); result->Set(NanNew<Number>(index++), filename); } } while(FindNextFileW(handle, &find_data)); FindClose(handle); delete[] path_buf; return true; fail: delete[] path_buf; return false; } DWORD GetAttr(Local<String>& path) { String::Value path_value(path); if(*path_value == NULL) { return INVALID_FILE_ATTRIBUTES; } return GetFileAttributesW((const wchar_t*) *path_value); } bool IsSymbolicLinkImpl(Local<String>& path) { DWORD attr = GetAttr(path); if(attr == INVALID_FILE_ATTRIBUTES) { return false; } return attr & FILE_ATTRIBUTE_REPARSE_POINT; } bool ExistsImpl(Local<String>& path) { return GetAttr(path) != INVALID_FILE_ATTRIBUTES; } #else // Unix system call bool ReaddirImpl(Local<String>& path, Local<Array>& result) { String::Utf8Value path_value(path); if(*path_value == NULL) { return false; } struct dirent** namelist; int size = scandir(*path_value, &namelist, NULL, alphasort); if(size < 0) { return false; } int index = 0; for(int i = 0; i < size; i++) { if(IsCurrentDir(namelist[i]->d_name) == false) { Local<String> filename = NanNew<String>(namelist[i]->d_name); result->Set(NanNew<Number>(index++), filename); } free(namelist[i]); } free(namelist); return true; } bool IsSymbolicLinkImpl(Local<String>& path) { String::Utf8Value path_value(path); if(*path_value == NULL) { return false; } struct stat st; int err = lstat(*path_value, &st); if(err) { return false; } return st.st_mode & S_IFLNK; } bool ExistsImpl(Local<String>& path) { String::Utf8Value path_value(path); if(*path_value == NULL) { return false; } struct stat st; return stat(*path_value, &st) == 0; } #endif bool IsCurrentDir(const wchar_t* name) { if(name[0] == L'.') { return name[1] == L'\0' || (name[1] == L'.' && name[2] == L'\0'); } return false; } bool IsCurrentDir(const char* name) { if(name[0] == '.') { return name[1] == '\0' || (name[1] == '.' && name[2] == '\0'); } return false; } NAN_METHOD(Readdir) { NanScope(); assert(args.Length() == 1); assert(args[0]->IsString()); Local<Array> result = NanNew<Array>(); Local<String> path = args[0]->ToString(); bool success = ReaddirImpl(path, result); if(success) { NanReturnValue(result); } else { NanReturnValue(NanNull()); } } NAN_METHOD(IsSymbolicLink) { NanScope(); assert(args.Length() == 1); assert(args[0]->IsString()); Local<String> path = args[0]->ToString(); bool is_sym = IsSymbolicLinkImpl(path); NanReturnValue(is_sym ? NanTrue() : NanFalse()); } NAN_METHOD(Exists) { NanScope(); assert(args.Length() == 1); assert(args[0]->IsString()); Local<String> path = args[0]->ToString(); bool exists = ExistsImpl(path); NanReturnValue(exists ? NanTrue() : NanFalse()); } void Init(Handle<Object> exports) { NanScope(); NODE_SET_METHOD(exports, "readdirSyncSafe", Readdir); NODE_SET_METHOD(exports, "isSymbolicLinkSync", IsSymbolicLink); NODE_SET_METHOD(exports, "existsSync", Exists); } NODE_MODULE(speedup, Init) <commit_msg>Refactoring<commit_after>#include <node.h> #include <nan.h> #include <stdlib.h> #ifdef _MSC_VER // Windows header # include <Windows.h> #else // Unix header # include <dirent.h> # include <sys/stat.h> #endif using namespace v8; #ifdef _MSC_VER // Windows system call bool IsCurrentDir(const wchar_t* name) { if(name[0] == L'.') { return name[1] == L'\0' || (name[1] == L'.' && name[2] == L'\0'); } return false; } bool ReaddirImpl(Local<String>& path, Local<Array>& result) { int len = path->Length(); wchar_t* path_buf = new wchar_t[len + 3]; int wrote = path->Write((uint16_t*) path_buf); if(wrote < 1) { goto fail; } if(path_buf[len - 1] == L'\\') { path_buf[len] = L'*'; path_buf[len + 1] = L'\0'; } else { path_buf[len] = L'\\'; path_buf[len + 1] = L'*'; path_buf[len + 2] = L'\0'; } WIN32_FIND_DATAW find_data; HANDLE handle = FindFirstFileW(path_buf, &find_data); if(handle == INVALID_HANDLE_VALUE) { goto fail; } int index = 0; do { if(! IsCurrentDir(find_data.cFileName)) { Local<String> filename = NanNew((uint16_t*) find_data.cFileName); result->Set(index++, filename); } } while(FindNextFileW(handle, &find_data)); FindClose(handle); delete[] path_buf; return true; fail: delete[] path_buf; return false; } DWORD GetAttr(Local<String>& path) { String::Value path_value(path); if(*path_value == NULL) { return INVALID_FILE_ATTRIBUTES; } return GetFileAttributesW((const wchar_t*) *path_value); } bool IsSymbolicLinkImpl(Local<String>& path) { DWORD attr = GetAttr(path); if(attr == INVALID_FILE_ATTRIBUTES) { return false; } return attr & FILE_ATTRIBUTE_REPARSE_POINT; } bool ExistsImpl(Local<String>& path) { return GetAttr(path) != INVALID_FILE_ATTRIBUTES; } #else // Unix system call bool IsCurrentDir(const char* name) { if(name[0] == '.') { return name[1] == '\0' || (name[1] == '.' && name[2] == '\0'); } return false; } bool ReaddirImpl(Local<String>& path, Local<Array>& result) { String::Utf8Value path_value(path); if(*path_value == NULL) { return false; } struct dirent** namelist; int size = scandir(*path_value, &namelist, NULL, alphasort); if(size < 0) { return false; } int index = 0; for(int i = 0; i < size; i++) { if(IsCurrentDir(namelist[i]->d_name) == false) { Local<String> filename = NanNew(namelist[i]->d_name); result->Set(index++, filename); } free(namelist[i]); } free(namelist); return true; } bool IsSymbolicLinkImpl(Local<String>& path) { String::Utf8Value path_value(path); if(*path_value == NULL) { return false; } struct stat st; int err = lstat(*path_value, &st); if(err) { return false; } return st.st_mode & S_IFLNK; } bool ExistsImpl(Local<String>& path) { String::Utf8Value path_value(path); if(*path_value == NULL) { return false; } struct stat st; return stat(*path_value, &st) == 0; } #endif NAN_METHOD(Readdir) { NanScope(); assert(args.Length() == 1); assert(args[0]->IsString()); Local<Array> result = NanNew<Array>(); Local<String> path = args[0]->ToString(); bool success = ReaddirImpl(path, result); if(success) { NanReturnValue(result); } else { NanReturnValue(NanNull()); } } NAN_METHOD(IsSymbolicLink) { NanScope(); assert(args.Length() == 1); assert(args[0]->IsString()); Local<String> path = args[0]->ToString(); bool is_sym = IsSymbolicLinkImpl(path); NanReturnValue(is_sym ? NanTrue() : NanFalse()); } NAN_METHOD(Exists) { NanScope(); assert(args.Length() == 1); assert(args[0]->IsString()); Local<String> path = args[0]->ToString(); bool exists = ExistsImpl(path); NanReturnValue(exists ? NanTrue() : NanFalse()); } void Init(Handle<Object> exports) { NanScope(); NODE_SET_METHOD(exports, "readdirSyncSafe", Readdir); NODE_SET_METHOD(exports, "isSymbolicLinkSync", IsSymbolicLink); NODE_SET_METHOD(exports, "existsSync", Exists); } NODE_MODULE(speedup, Init) <|endoftext|>
<commit_before>//===-- Utils.cpp - TransformUtils Infrastructure -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the common initialization infrastructure for the // TransformUtils library. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils.h" #include "llvm-c/Initialization.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/InitializePasses.h" #include "llvm/PassRegistry.h" using namespace llvm; /// initializeTransformUtils - Initialize all passes in the TransformUtils /// library. void llvm::initializeTransformUtils(PassRegistry &Registry) { initializeAddDiscriminatorsLegacyPassPass(Registry); initializeBreakCriticalEdgesPass(Registry); initializeInstNamerPass(Registry); initializeLCSSAWrapperPassPass(Registry); initializeLibCallsShrinkWrapLegacyPassPass(Registry); initializeLoopSimplifyPass(Registry); initializeLowerInvokeLegacyPassPass(Registry); initializeLowerSwitchPass(Registry); initializeNameAnonGlobalLegacyPassPass(Registry); initializePromoteLegacyPassPass(Registry); initializeStripNonLineTableDebugInfoPass(Registry); initializeUnifyFunctionExitNodesPass(Registry); initializeInstSimplifierPass(Registry); initializeMetaRenamerPass(Registry); initializeStripGCRelocatesPass(Registry); initializePredicateInfoPrinterLegacyPassPass(Registry); } /// LLVMInitializeTransformUtils - C binding for initializeTransformUtilsPasses. void LLVMInitializeTransformUtils(LLVMPassRegistryRef R) { initializeTransformUtils(*unwrap(R)); } void LLVMAddLowerSwitchPass(LLVMPassManagerRef PM) { unwrap(PM)->add(createLowerSwitchPass()); } void LLVMAddPromoteMemoryToRegisterPass(LLVMPassManagerRef PM) { unwrap(PM)->add(createPromoteMemoryToRegisterPass()); } <commit_msg>[Transforms] Make sure to include the c binding header when defining c binding functions<commit_after>//===-- Utils.cpp - TransformUtils Infrastructure -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the common initialization infrastructure for the // TransformUtils library. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils.h" #include "llvm-c/Initialization.h" #include "llvm-c/Transforms/Scalar.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/InitializePasses.h" #include "llvm/PassRegistry.h" using namespace llvm; /// initializeTransformUtils - Initialize all passes in the TransformUtils /// library. void llvm::initializeTransformUtils(PassRegistry &Registry) { initializeAddDiscriminatorsLegacyPassPass(Registry); initializeBreakCriticalEdgesPass(Registry); initializeInstNamerPass(Registry); initializeLCSSAWrapperPassPass(Registry); initializeLibCallsShrinkWrapLegacyPassPass(Registry); initializeLoopSimplifyPass(Registry); initializeLowerInvokeLegacyPassPass(Registry); initializeLowerSwitchPass(Registry); initializeNameAnonGlobalLegacyPassPass(Registry); initializePromoteLegacyPassPass(Registry); initializeStripNonLineTableDebugInfoPass(Registry); initializeUnifyFunctionExitNodesPass(Registry); initializeInstSimplifierPass(Registry); initializeMetaRenamerPass(Registry); initializeStripGCRelocatesPass(Registry); initializePredicateInfoPrinterLegacyPassPass(Registry); } /// LLVMInitializeTransformUtils - C binding for initializeTransformUtilsPasses. void LLVMInitializeTransformUtils(LLVMPassRegistryRef R) { initializeTransformUtils(*unwrap(R)); } void LLVMAddLowerSwitchPass(LLVMPassManagerRef PM) { unwrap(PM)->add(createLowerSwitchPass()); } void LLVMAddPromoteMemoryToRegisterPass(LLVMPassManagerRef PM) { unwrap(PM)->add(createPromoteMemoryToRegisterPass()); } <|endoftext|>
<commit_before>//===-- TypeSymbolTable.cpp - Implement the TypeSymbolTable class ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the TypeSymbolTable class for the VMCore library. // //===----------------------------------------------------------------------===// #include "llvm/TypeSymbolTable.h" #include "llvm/DerivedTypes.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/RWMutex.h" #include "llvm/System/Threading.h" #include <algorithm> using namespace llvm; #define DEBUG_SYMBOL_TABLE 0 #define DEBUG_ABSTYPE 0 static ManagedStatic<sys::SmartRWMutex<true> > TypeSymbolTableLock; TypeSymbolTable::~TypeSymbolTable() { // Drop all abstract type references in the type plane... for (iterator TI = tmap.begin(), TE = tmap.end(); TI != TE; ++TI) { if (TI->second->isAbstract()) // If abstract, drop the reference... cast<DerivedType>(TI->second)->removeAbstractTypeUser(this); } } std::string TypeSymbolTable::getUniqueName(const StringRef &BaseName) const { std::string TryName = BaseName; sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock); const_iterator End = tmap.end(); // See if the name exists while (tmap.find(TryName) != End) // Loop until we find a free TryName = BaseName.str() + utostr(++LastUnique); // name in the symbol table return TryName; } // lookup a type by name - returns null on failure Type* TypeSymbolTable::lookup(const StringRef &Name) const { sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock); const_iterator TI = tmap.find(Name); Type* result = 0; if (TI != tmap.end()) result = const_cast<Type*>(TI->second); return result; } TypeSymbolTable::iterator TypeSymbolTable::find(const StringRef &Name) { sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock); return tmap.find(Name); } TypeSymbolTable::const_iterator TypeSymbolTable::find(const StringRef &Name) const { sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock); return tmap.find(Name); } // remove - Remove a type from the symbol table... Type* TypeSymbolTable::remove(iterator Entry) { TypeSymbolTableLock->writer_acquire(); assert(Entry != tmap.end() && "Invalid entry to remove!"); const Type* Result = Entry->second; #if DEBUG_SYMBOL_TABLE dump(); errs() << " Removing Value: " << Result->getName() << "\n"; #endif tmap.erase(Entry); TypeSymbolTableLock->writer_release(); // If we are removing an abstract type, remove the symbol table from it's use // list... if (Result->isAbstract()) { #if DEBUG_ABSTYPE errs() << "Removing abstract type from symtab" << Result->getDescription() << "\n"; #endif cast<DerivedType>(Result)->removeAbstractTypeUser(this); } return const_cast<Type*>(Result); } // insert - Insert a type into the symbol table with the specified name... void TypeSymbolTable::insert(const StringRef &Name, const Type* T) { assert(T && "Can't insert null type into symbol table!"); TypeSymbolTableLock->writer_acquire(); if (tmap.insert(std::make_pair(Name, T)).second) { // Type inserted fine with no conflict. #if DEBUG_SYMBOL_TABLE dump(); errs() << " Inserted type: " << Name << ": " << T->getDescription() << "\n"; #endif } else { // If there is a name conflict... // Check to see if there is a naming conflict. If so, rename this type! std::string UniqueName = Name; if (lookup(Name)) UniqueName = getUniqueName(Name); #if DEBUG_SYMBOL_TABLE dump(); errs() << " Inserting type: " << UniqueName << ": " << T->getDescription() << "\n"; #endif // Insert the tmap entry tmap.insert(make_pair(UniqueName, T)); } TypeSymbolTableLock->writer_release(); // If we are adding an abstract type, add the symbol table to it's use list. if (T->isAbstract()) { cast<DerivedType>(T)->addAbstractTypeUser(this); #if DEBUG_ABSTYPE errs() << "Added abstract type to ST: " << T->getDescription() << "\n"; #endif } } // This function is called when one of the types in the type plane are refined void TypeSymbolTable::refineAbstractType(const DerivedType *OldType, const Type *NewType) { sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock); // Loop over all of the types in the symbol table, replacing any references // to OldType with references to NewType. Note that there may be multiple // occurrences, and although we only need to remove one at a time, it's // faster to remove them all in one pass. // for (iterator I = begin(), E = end(); I != E; ++I) { if (I->second == (Type*)OldType) { // FIXME when Types aren't const. #if DEBUG_ABSTYPE errs() << "Removing type " << OldType->getDescription() << "\n"; #endif OldType->removeAbstractTypeUser(this); I->second = (Type*)NewType; // TODO FIXME when types aren't const if (NewType->isAbstract()) { #if DEBUG_ABSTYPE errs() << "Added type " << NewType->getDescription() << "\n"; #endif cast<DerivedType>(NewType)->addAbstractTypeUser(this); } } } } // Handle situation where type becomes Concreate from Abstract void TypeSymbolTable::typeBecameConcrete(const DerivedType *AbsTy) { // Loop over all of the types in the symbol table, dropping any abstract // type user entries for AbsTy which occur because there are names for the // type. sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock); for (iterator TI = begin(), TE = end(); TI != TE; ++TI) if (TI->second == const_cast<Type*>(static_cast<const Type*>(AbsTy))) AbsTy->removeAbstractTypeUser(this); } static void DumpTypes(const std::pair<const std::string, const Type*>& T ) { errs() << " '" << T.first << "' = "; T.second->dump(); errs() << "\n"; } void TypeSymbolTable::dump() const { errs() << "TypeSymbolPlane: "; sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock); for_each(tmap.begin(), tmap.end(), DumpTypes); } // vim: sw=2 ai <commit_msg>Fix the build when DEBUG_SYMBOL_TABLE is set.<commit_after>//===-- TypeSymbolTable.cpp - Implement the TypeSymbolTable class ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the TypeSymbolTable class for the VMCore library. // //===----------------------------------------------------------------------===// #include "llvm/TypeSymbolTable.h" #include "llvm/DerivedTypes.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/RWMutex.h" #include "llvm/System/Threading.h" #include <algorithm> using namespace llvm; #define DEBUG_SYMBOL_TABLE 0 #define DEBUG_ABSTYPE 0 static ManagedStatic<sys::SmartRWMutex<true> > TypeSymbolTableLock; TypeSymbolTable::~TypeSymbolTable() { // Drop all abstract type references in the type plane... for (iterator TI = tmap.begin(), TE = tmap.end(); TI != TE; ++TI) { if (TI->second->isAbstract()) // If abstract, drop the reference... cast<DerivedType>(TI->second)->removeAbstractTypeUser(this); } } std::string TypeSymbolTable::getUniqueName(const StringRef &BaseName) const { std::string TryName = BaseName; sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock); const_iterator End = tmap.end(); // See if the name exists while (tmap.find(TryName) != End) // Loop until we find a free TryName = BaseName.str() + utostr(++LastUnique); // name in the symbol table return TryName; } // lookup a type by name - returns null on failure Type* TypeSymbolTable::lookup(const StringRef &Name) const { sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock); const_iterator TI = tmap.find(Name); Type* result = 0; if (TI != tmap.end()) result = const_cast<Type*>(TI->second); return result; } TypeSymbolTable::iterator TypeSymbolTable::find(const StringRef &Name) { sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock); return tmap.find(Name); } TypeSymbolTable::const_iterator TypeSymbolTable::find(const StringRef &Name) const { sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock); return tmap.find(Name); } // remove - Remove a type from the symbol table... Type* TypeSymbolTable::remove(iterator Entry) { TypeSymbolTableLock->writer_acquire(); assert(Entry != tmap.end() && "Invalid entry to remove!"); const Type* Result = Entry->second; #if DEBUG_SYMBOL_TABLE dump(); errs() << " Removing Value: " << Result->getDescription() << "\n"; #endif tmap.erase(Entry); TypeSymbolTableLock->writer_release(); // If we are removing an abstract type, remove the symbol table from it's use // list... if (Result->isAbstract()) { #if DEBUG_ABSTYPE errs() << "Removing abstract type from symtab" << Result->getDescription() << "\n"; #endif cast<DerivedType>(Result)->removeAbstractTypeUser(this); } return const_cast<Type*>(Result); } // insert - Insert a type into the symbol table with the specified name... void TypeSymbolTable::insert(const StringRef &Name, const Type* T) { assert(T && "Can't insert null type into symbol table!"); TypeSymbolTableLock->writer_acquire(); if (tmap.insert(std::make_pair(Name, T)).second) { // Type inserted fine with no conflict. #if DEBUG_SYMBOL_TABLE dump(); errs() << " Inserted type: " << Name << ": " << T->getDescription() << "\n"; #endif } else { // If there is a name conflict... // Check to see if there is a naming conflict. If so, rename this type! std::string UniqueName = Name; if (lookup(Name)) UniqueName = getUniqueName(Name); #if DEBUG_SYMBOL_TABLE dump(); errs() << " Inserting type: " << UniqueName << ": " << T->getDescription() << "\n"; #endif // Insert the tmap entry tmap.insert(make_pair(UniqueName, T)); } TypeSymbolTableLock->writer_release(); // If we are adding an abstract type, add the symbol table to it's use list. if (T->isAbstract()) { cast<DerivedType>(T)->addAbstractTypeUser(this); #if DEBUG_ABSTYPE errs() << "Added abstract type to ST: " << T->getDescription() << "\n"; #endif } } // This function is called when one of the types in the type plane are refined void TypeSymbolTable::refineAbstractType(const DerivedType *OldType, const Type *NewType) { sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock); // Loop over all of the types in the symbol table, replacing any references // to OldType with references to NewType. Note that there may be multiple // occurrences, and although we only need to remove one at a time, it's // faster to remove them all in one pass. // for (iterator I = begin(), E = end(); I != E; ++I) { if (I->second == (Type*)OldType) { // FIXME when Types aren't const. #if DEBUG_ABSTYPE errs() << "Removing type " << OldType->getDescription() << "\n"; #endif OldType->removeAbstractTypeUser(this); I->second = (Type*)NewType; // TODO FIXME when types aren't const if (NewType->isAbstract()) { #if DEBUG_ABSTYPE errs() << "Added type " << NewType->getDescription() << "\n"; #endif cast<DerivedType>(NewType)->addAbstractTypeUser(this); } } } } // Handle situation where type becomes Concreate from Abstract void TypeSymbolTable::typeBecameConcrete(const DerivedType *AbsTy) { // Loop over all of the types in the symbol table, dropping any abstract // type user entries for AbsTy which occur because there are names for the // type. sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock); for (iterator TI = begin(), TE = end(); TI != TE; ++TI) if (TI->second == const_cast<Type*>(static_cast<const Type*>(AbsTy))) AbsTy->removeAbstractTypeUser(this); } static void DumpTypes(const std::pair<const std::string, const Type*>& T ) { errs() << " '" << T.first << "' = "; T.second->dump(); errs() << "\n"; } void TypeSymbolTable::dump() const { errs() << "TypeSymbolPlane: "; sys::SmartScopedReader<true> Reader(*TypeSymbolTableLock); for_each(tmap.begin(), tmap.end(), DumpTypes); } // vim: sw=2 ai <|endoftext|>
<commit_before>/** * @file llviewerchat.cpp * @brief Builds menus out of items. * * $LicenseInfo:firstyear=2002&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llviewerchat.h" // newview includes #include "llagent.h" // gAgent #include "llslurl.h" #include "lluicolor.h" #include "lluicolortable.h" #include "llviewercontrol.h" // gSavedSettings #include "llviewerregion.h" #include "llworld.h" #include "llinstantmessage.h" //SYSTEM_FROM #include "fskeywords.h" #include "lggcontactsets.h" #include "rlvhandler.h" #if LL_WINDOWS #include "growlmanager.h" #endif // LLViewerChat LLViewerChat::font_change_signal_t LLViewerChat::sChatFontChangedSignal; //static void LLViewerChat::getChatColor(const LLChat& chat, LLColor4& r_color, bool is_local) { if(chat.mMuted) { r_color= LLUIColorTable::instance().getColor("LtGray"); } else { switch(chat.mSourceType) { case CHAT_SOURCE_SYSTEM: r_color = LLUIColorTable::instance().getColor("SystemChatColor"); break; case CHAT_SOURCE_AGENT: if (chat.mFromID.isNull() || SYSTEM_FROM == chat.mFromName) { r_color = LLUIColorTable::instance().getColor("SystemChatColor"); } else { if(gAgentID == chat.mFromID) { r_color = LLUIColorTable::instance().getColor("UserChatColor"); } else { r_color = LLUIColorTable::instance().getColor("AgentChatColor"); } //color based on contact sets prefs if(LGGContactSets::getInstance()->hasFriendColorThatShouldShow(chat.mFromID,TRUE)) { r_color = LGGContactSets::getInstance()->getFriendColor(chat.mFromID); } } break; case CHAT_SOURCE_OBJECT: if (chat.mChatType == CHAT_TYPE_DEBUG_MSG) { r_color = LLUIColorTable::instance().getColor("ScriptErrorColor"); } else if ( chat.mChatType == CHAT_TYPE_OWNER ) { r_color = LLUIColorTable::instance().getColor("llOwnerSayChatColor"); } else if ( chat.mChatType == CHAT_TYPE_DIRECT ) { r_color = LLUIColorTable::instance().getColor("DirectChatColor"); } else if ( chat.mChatType == CHAT_TYPE_IM ) { r_color = LLUIColorTable::instance().getColor("ObjectIMColor"); } else { r_color = LLUIColorTable::instance().getColor("ObjectChatColor"); } break; default: r_color.setToWhite(); } //Keyword alerts -KC if ((gAgentID != chat.mFromID || chat.mFromName == SYSTEM_FROM) && FSKeywords::getInstance()->chatContainsKeyword(chat, is_local)) { std::string msg = chat.mFromName; std::string prefix = chat.mText.substr(0, 4); if(prefix == "/me " || prefix == "/me'") { msg = msg + chat.mText.substr(3); } else { msg = msg + ": " + chat.mText; } gGrowlManager->notify("Keyword Alert", msg, "Keyword Alert"); static LLCachedControl<bool> sFSKeywordChangeColor(gSavedPerAccountSettings, "FSKeywordChangeColor"); if (sFSKeywordChangeColor) { static LLCachedControl<LLColor4> sFSKeywordColor(gSavedPerAccountSettings, "FSKeywordColor"); r_color = sFSKeywordColor; } } if (!chat.mPosAgent.isExactlyZero()) { LLVector3 pos_agent = gAgent.getPositionAgent(); F32 distance_squared = dist_vec_squared(pos_agent, chat.mPosAgent); // <FS:CR> Aurora Sim //F32 dist_near_chat = gAgent.getNearChatRadius(); //if (!avatarp || dist_vec_squared(avatarp->getPositionAgent(), gAgent.getPositionAgent()) > say_distance_squared) F32 dist_near_chat = LLWorld::getInstance()->getSayDistance(); // </FS:CR> Aurora Sim if (distance_squared > dist_near_chat * dist_near_chat) { // diminish far-off chat r_color.mV[VALPHA] = 0.8f; } } } } //static void LLViewerChat::getChatColor(const LLChat& chat, std::string& r_color_name, F32& r_color_alpha) { if(chat.mMuted) { r_color_name = "LtGray"; } else { switch(chat.mSourceType) { case CHAT_SOURCE_SYSTEM: r_color_name = "SystemChatColor"; break; case CHAT_SOURCE_AGENT: if (chat.mFromID.isNull()) { r_color_name = "SystemChatColor"; } else { if(gAgentID == chat.mFromID) { r_color_name = "UserChatColor"; } else { r_color_name = "AgentChatColor"; } } break; case CHAT_SOURCE_OBJECT: if (chat.mChatType == CHAT_TYPE_DEBUG_MSG) { r_color_name = "ScriptErrorColor"; } else if ( chat.mChatType == CHAT_TYPE_OWNER ) { r_color_name = "llOwnerSayChatColor"; } else if ( chat.mChatType == CHAT_TYPE_DIRECT ) { r_color_name = "DirectChatColor"; } else if ( chat.mChatType == CHAT_TYPE_IM ) { r_color_name = "ObjectIMColor"; } else { r_color_name = "ObjectChatColor"; } break; default: r_color_name = "White"; } if (!chat.mPosAgent.isExactlyZero()) { LLVector3 pos_agent = gAgent.getPositionAgent(); F32 distance_squared = dist_vec_squared(pos_agent, chat.mPosAgent); // <FS:CR> Aurora som //F32 dist_near_chat = gAgent.getNearChatRadius(); F32 dist_near_chat = LLWorld::getInstance()->getSayDistance(); // </FS:CR> Aurora sim if (distance_squared > dist_near_chat * dist_near_chat) { // diminish far-off chat r_color_alpha = 0.8f; } else { r_color_alpha = 1.0f; } } } } //static LLFontGL* LLViewerChat::getChatFont() { S32 font_size = gSavedSettings.getS32("ChatFontSize"); LLFontGL* fontp = NULL; switch(font_size) { case 0: fontp = LLFontGL::getFontSansSerifSmall(); break; default: case 1: fontp = LLFontGL::getFontSansSerif(); break; case 2: fontp = LLFontGL::getFontSansSerifBig(); break; case 3: fontp = LLFontGL::getFontSansSerifHuge(); break; } return fontp; } //static S32 LLViewerChat::getChatFontSize() { return gSavedSettings.getS32("ChatFontSize"); } //static void LLViewerChat::formatChatMsg(const LLChat& chat, std::string& formated_msg) { std::string tmpmsg = chat.mText; if(chat.mChatStyle == CHAT_STYLE_IRC) { formated_msg = chat.mFromName + tmpmsg.substr(3); } else { formated_msg = tmpmsg; } } //static std::string LLViewerChat::getSenderSLURL(const LLChat& chat, const LLSD& args) { switch (chat.mSourceType) { case CHAT_SOURCE_AGENT: return LLSLURL("agent", chat.mFromID, "about").getSLURLString(); case CHAT_SOURCE_OBJECT: return getObjectImSLURL(chat, args); // <FS:Ansariel> Stop spamming the log when processing system messages case CHAT_SOURCE_SYSTEM: return LLStringUtil::null; // </FS:Ansariel> default: llwarns << "Getting SLURL for an unsupported sender type: " << chat.mSourceType << llendl; } return LLStringUtil::null; } //static std::string LLViewerChat::getObjectImSLURL(const LLChat& chat, const LLSD& args) { std::string url = LLSLURL("objectim", chat.mFromID, "").getSLURLString(); url += "?name=" + chat.mFromName; url += "&owner=" + chat.mOwnerID.asString(); std::string slurl = args["slurl"].asString(); if (slurl.empty()) { LLViewerRegion *region = LLWorld::getInstance()->getRegionFromPosAgent(chat.mPosAgent); if(region) { LLSLURL region_slurl(region->getName(), chat.mPosAgent); slurl = region_slurl.getLocationString(); } } url += "&slurl=" + LLURI::escape(slurl); return url; } //static boost::signals2::connection LLViewerChat::setFontChangedCallback(const font_change_signal_t::slot_type& cb) { return sChatFontChangedSignal.connect(cb); } //static void LLViewerChat::signalChatFontChanged() { // Notify all observers that our font has changed sChatFontChangedSignal(getChatFont()); } <commit_msg>FIRE-5889: Object IM's Not Triggering Growl Notifications<commit_after>/** * @file llviewerchat.cpp * @brief Builds menus out of items. * * $LicenseInfo:firstyear=2002&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llviewerchat.h" // newview includes #include "llagent.h" // gAgent #include "llslurl.h" #include "lluicolor.h" #include "lluicolortable.h" #include "llviewercontrol.h" // gSavedSettings #include "llviewerregion.h" #include "llworld.h" #include "llinstantmessage.h" //SYSTEM_FROM #include "fskeywords.h" #include "lggcontactsets.h" #include "rlvhandler.h" #if LL_WINDOWS #include "growlmanager.h" #endif // LLViewerChat LLViewerChat::font_change_signal_t LLViewerChat::sChatFontChangedSignal; //static void LLViewerChat::getChatColor(const LLChat& chat, LLColor4& r_color, bool is_local) { if(chat.mMuted) { r_color= LLUIColorTable::instance().getColor("LtGray"); } else { switch(chat.mSourceType) { case CHAT_SOURCE_SYSTEM: r_color = LLUIColorTable::instance().getColor("SystemChatColor"); break; case CHAT_SOURCE_AGENT: if (chat.mFromID.isNull() || SYSTEM_FROM == chat.mFromName) { r_color = LLUIColorTable::instance().getColor("SystemChatColor"); } else { if(gAgentID == chat.mFromID) { r_color = LLUIColorTable::instance().getColor("UserChatColor"); } else { r_color = LLUIColorTable::instance().getColor("AgentChatColor"); } //color based on contact sets prefs if(LGGContactSets::getInstance()->hasFriendColorThatShouldShow(chat.mFromID,TRUE)) { r_color = LGGContactSets::getInstance()->getFriendColor(chat.mFromID); } } break; case CHAT_SOURCE_OBJECT: if (chat.mChatType == CHAT_TYPE_DEBUG_MSG) { r_color = LLUIColorTable::instance().getColor("ScriptErrorColor"); } else if ( chat.mChatType == CHAT_TYPE_OWNER ) { r_color = LLUIColorTable::instance().getColor("llOwnerSayChatColor"); } else if ( chat.mChatType == CHAT_TYPE_DIRECT ) { r_color = LLUIColorTable::instance().getColor("DirectChatColor"); } else if ( chat.mChatType == CHAT_TYPE_IM ) { r_color = LLUIColorTable::instance().getColor("ObjectIMColor"); // <FS:LO> FIRE-5889: Object IM's Not Triggering Growl Notifications std::string msg = chat.mFromName; std::string prefix = chat.mText.substr(0, 4); if(prefix == "/me " || prefix == "/me'") { msg = msg + chat.mText.substr(3); } else { msg = msg + ": " + chat.mText; } gGrowlManager->notify(chat.mFromName, msg, GROWL_IM_MESSAGE_TYPE); // </FS:LO> } else { r_color = LLUIColorTable::instance().getColor("ObjectChatColor"); } break; default: r_color.setToWhite(); } //Keyword alerts -KC if ((gAgentID != chat.mFromID || chat.mFromName == SYSTEM_FROM) && FSKeywords::getInstance()->chatContainsKeyword(chat, is_local)) { std::string msg = chat.mFromName; std::string prefix = chat.mText.substr(0, 4); if(prefix == "/me " || prefix == "/me'") { msg = msg + chat.mText.substr(3); } else { msg = msg + ": " + chat.mText; } gGrowlManager->notify("Keyword Alert", msg, "Keyword Alert"); static LLCachedControl<bool> sFSKeywordChangeColor(gSavedPerAccountSettings, "FSKeywordChangeColor"); if (sFSKeywordChangeColor) { static LLCachedControl<LLColor4> sFSKeywordColor(gSavedPerAccountSettings, "FSKeywordColor"); r_color = sFSKeywordColor; } } if (!chat.mPosAgent.isExactlyZero()) { LLVector3 pos_agent = gAgent.getPositionAgent(); F32 distance_squared = dist_vec_squared(pos_agent, chat.mPosAgent); // <FS:CR> Aurora Sim //F32 dist_near_chat = gAgent.getNearChatRadius(); //if (!avatarp || dist_vec_squared(avatarp->getPositionAgent(), gAgent.getPositionAgent()) > say_distance_squared) F32 dist_near_chat = LLWorld::getInstance()->getSayDistance(); // </FS:CR> Aurora Sim if (distance_squared > dist_near_chat * dist_near_chat) { // diminish far-off chat r_color.mV[VALPHA] = 0.8f; } } } } //static void LLViewerChat::getChatColor(const LLChat& chat, std::string& r_color_name, F32& r_color_alpha) { if(chat.mMuted) { r_color_name = "LtGray"; } else { switch(chat.mSourceType) { case CHAT_SOURCE_SYSTEM: r_color_name = "SystemChatColor"; break; case CHAT_SOURCE_AGENT: if (chat.mFromID.isNull()) { r_color_name = "SystemChatColor"; } else { if(gAgentID == chat.mFromID) { r_color_name = "UserChatColor"; } else { r_color_name = "AgentChatColor"; } } break; case CHAT_SOURCE_OBJECT: if (chat.mChatType == CHAT_TYPE_DEBUG_MSG) { r_color_name = "ScriptErrorColor"; } else if ( chat.mChatType == CHAT_TYPE_OWNER ) { r_color_name = "llOwnerSayChatColor"; } else if ( chat.mChatType == CHAT_TYPE_DIRECT ) { r_color_name = "DirectChatColor"; } else if ( chat.mChatType == CHAT_TYPE_IM ) { r_color_name = "ObjectIMColor"; } else { r_color_name = "ObjectChatColor"; } break; default: r_color_name = "White"; } if (!chat.mPosAgent.isExactlyZero()) { LLVector3 pos_agent = gAgent.getPositionAgent(); F32 distance_squared = dist_vec_squared(pos_agent, chat.mPosAgent); // <FS:CR> Aurora som //F32 dist_near_chat = gAgent.getNearChatRadius(); F32 dist_near_chat = LLWorld::getInstance()->getSayDistance(); // </FS:CR> Aurora sim if (distance_squared > dist_near_chat * dist_near_chat) { // diminish far-off chat r_color_alpha = 0.8f; } else { r_color_alpha = 1.0f; } } } } //static LLFontGL* LLViewerChat::getChatFont() { S32 font_size = gSavedSettings.getS32("ChatFontSize"); LLFontGL* fontp = NULL; switch(font_size) { case 0: fontp = LLFontGL::getFontSansSerifSmall(); break; default: case 1: fontp = LLFontGL::getFontSansSerif(); break; case 2: fontp = LLFontGL::getFontSansSerifBig(); break; case 3: fontp = LLFontGL::getFontSansSerifHuge(); break; } return fontp; } //static S32 LLViewerChat::getChatFontSize() { return gSavedSettings.getS32("ChatFontSize"); } //static void LLViewerChat::formatChatMsg(const LLChat& chat, std::string& formated_msg) { std::string tmpmsg = chat.mText; if(chat.mChatStyle == CHAT_STYLE_IRC) { formated_msg = chat.mFromName + tmpmsg.substr(3); } else { formated_msg = tmpmsg; } } //static std::string LLViewerChat::getSenderSLURL(const LLChat& chat, const LLSD& args) { switch (chat.mSourceType) { case CHAT_SOURCE_AGENT: return LLSLURL("agent", chat.mFromID, "about").getSLURLString(); case CHAT_SOURCE_OBJECT: return getObjectImSLURL(chat, args); // <FS:Ansariel> Stop spamming the log when processing system messages case CHAT_SOURCE_SYSTEM: return LLStringUtil::null; // </FS:Ansariel> default: llwarns << "Getting SLURL for an unsupported sender type: " << chat.mSourceType << llendl; } return LLStringUtil::null; } //static std::string LLViewerChat::getObjectImSLURL(const LLChat& chat, const LLSD& args) { std::string url = LLSLURL("objectim", chat.mFromID, "").getSLURLString(); url += "?name=" + chat.mFromName; url += "&owner=" + chat.mOwnerID.asString(); std::string slurl = args["slurl"].asString(); if (slurl.empty()) { LLViewerRegion *region = LLWorld::getInstance()->getRegionFromPosAgent(chat.mPosAgent); if(region) { LLSLURL region_slurl(region->getName(), chat.mPosAgent); slurl = region_slurl.getLocationString(); } } url += "&slurl=" + LLURI::escape(slurl); return url; } //static boost::signals2::connection LLViewerChat::setFontChangedCallback(const font_change_signal_t::slot_type& cb) { return sChatFontChangedSignal.connect(cb); } //static void LLViewerChat::signalChatFontChanged() { // Notify all observers that our font has changed sChatFontChangedSignal(getChatFont()); } <|endoftext|>
<commit_before>#include "teensy3/WProgram.h" #include "teensy3/core_pins.h" #include "teensy3/usb_serial.h" #define ROWS 15 #define COLS 112 #define SYNC 10 #define CLK 11 #define DAT 12 #define HIBANK 3 #define LOBANK 4 #define BIT0 0 #define BIT1 1 #define BIT2 2 #define bufferSize 2048 int serialbuffer[bufferSize]; int img1[ROWS][COLS]; int img2[ROWS][COLS]; int currentRow; int serialEnd; void setRow(int row) { digitalWrite(LOBANK, HIGH); digitalWrite(HIBANK, HIGH); digitalWrite(BIT0, row & 1); digitalWrite(BIT1, row & 2); digitalWrite(BIT2, row & 4); if ((row < 8) & (row < 16) & (row >= 0)) { digitalWrite(HIBANK, LOW); } else if ((row >= 8) & (row < 16)) { digitalWrite(LOBANK, LOW); } } void initialize() { pinMode(CLK, OUTPUT); pinMode(DAT, OUTPUT); pinMode(LOBANK, OUTPUT); pinMode(HIBANK, OUTPUT); pinMode(BIT0, OUTPUT); pinMode(BIT1, OUTPUT); pinMode(BIT2, OUTPUT); pinMode(SYNC, OUTPUT); currentRow = 0; serialEnd = 0; } extern "C" int main(void) { initialize(); elapsedMillis refresh = 0; int* img = (int*)img1; int *nimg = (int*)img2; int ledState = 0; Serial.begin(9600); while(1) { setRow(16); digitalWrite(SYNC, currentRow); for(int col = 0; col < COLS; col++) { digitalWrite(DAT, img[currentRow*COLS + col] ? HIGH : LOW); digitalWrite(CLK, LOW); delayMicroseconds(2); digitalWrite(CLK, HIGH); } setRow(ROWS - currentRow - 1); currentRow++; currentRow %= 16; for (int i=0; i<118; i++) { if (Serial.available()) { serialbuffer[serialEnd] = Serial.read(); serialEnd++; } if (serialEnd == 1) { if (serialbuffer[0] != 0xCA) { serialEnd = 0; } } if (serialEnd == 2) { if (serialbuffer[1] != 0xFE) { serialEnd = 0; } } if (serialEnd > 2) { if (serialbuffer[2] == 0x00) { //Blit frame if (img == (int*)img1) { img = (int*)img2; nimg = (int*)img1; } else { img = (int*)img1; nimg = (int*)img2; } serialEnd = 0; } if ((serialbuffer[2] == 0x01) & (serialEnd == COLS*ROWS+3)) { for (int i=0; i<COLS*ROWS; i++) { nimg[i] = serialbuffer[i+3]; } serialEnd = 0; } } if (serialEnd > bufferSize) { serialEnd = 0; } } refresh = 0; } } <commit_msg>Blink LED while serial data is received<commit_after>#include "teensy3/WProgram.h" #include "teensy3/core_pins.h" #include "teensy3/usb_serial.h" #define ROWS 15 #define COLS 112 #define SYNC 10 #define CLK 11 #define DAT 12 #define HIBANK 3 #define LOBANK 4 #define BIT0 0 #define BIT1 1 #define BIT2 2 #define bufferSize 2048 int serialbuffer[bufferSize]; int img1[ROWS][COLS]; int img2[ROWS][COLS]; int currentRow; int serialEnd; void setRow(int row) { digitalWrite(LOBANK, HIGH); digitalWrite(HIBANK, HIGH); digitalWrite(BIT0, row & 1); digitalWrite(BIT1, row & 2); digitalWrite(BIT2, row & 4); if ((row < 8) & (row < 16) & (row >= 0)) { digitalWrite(HIBANK, LOW); } else if ((row >= 8) & (row < 16)) { digitalWrite(LOBANK, LOW); } } void initialize() { pinMode(CLK, OUTPUT); pinMode(DAT, OUTPUT); pinMode(LOBANK, OUTPUT); pinMode(HIBANK, OUTPUT); pinMode(BIT0, OUTPUT); pinMode(BIT1, OUTPUT); pinMode(BIT2, OUTPUT); pinMode(SYNC, OUTPUT); pinMode(13, OUTPUT); currentRow = 0; serialEnd = 0; } extern "C" int main(void) { initialize(); elapsedMillis refresh = 0; int* img = (int*)img1; int *nimg = (int*)img2; int ledState = 0; Serial.begin(9600); while(1) { setRow(16); digitalWrite(SYNC, currentRow); for(int col = 0; col < COLS; col++) { digitalWrite(DAT, img[currentRow*COLS + col] ? HIGH : LOW); digitalWrite(CLK, LOW); delayMicroseconds(2); digitalWrite(CLK, HIGH); } setRow(ROWS - currentRow - 1); currentRow++; currentRow %= 16; for (int i=0; i<118; i++) { if (Serial.available()) { digitalWrite(13, HIGH); serialbuffer[serialEnd] = Serial.read(); serialEnd++; } if (serialEnd == 1) { if (serialbuffer[0] != 0xCA) { digitalWrite(13, LOW); serialEnd = 0; } } if (serialEnd == 2) { if (serialbuffer[1] != 0xFE) { digitalWrite(13, LOW); serialEnd = 0; } } if (serialEnd > 2) { if (serialbuffer[2] == 0x00) { //Blit frame digitalWrite(13, LOW); if (img == (int*)img1) { img = (int*)img2; nimg = (int*)img1; } else { img = (int*)img1; nimg = (int*)img2; } serialEnd = 0; } if ((serialbuffer[2] == 0x01) & (serialEnd == COLS*ROWS+3)) { for (int i=0; i<COLS*ROWS; i++) { nimg[i] = serialbuffer[i+3]; } digitalWrite(13, LOW); serialEnd = 0; } } if (serialEnd > bufferSize) { digitalWrite(13, LOW); serialEnd = 0; } } refresh = 0; } } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_ELLIPTIC_HH #define DUNE_GDT_OPERATORS_ELLIPTIC_HH #include <dune/grid/common/gridview.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/memory.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/la/container.hh> #include <dune/gdt/localevaluation/elliptic.hh> #include <dune/gdt/localoperator/integrals.hh> #include <dune/gdt/operators/interfaces.hh> #include <dune/gdt/operators/default.hh> #include <dune/gdt/spaces/interface.hh> namespace Dune { namespace GDT { template <class DiffusionFactorType, typename DiffusionTensorType, // may be void class GridView, class Range, class Source = Range, class Field = typename Range::RangeFieldType> class EllipticLocalizableProduct : public LocalizableProductDefault<GridView, Range, Source, Field> { typedef LocalizableProductDefault<GridView, Range, Source, Field> BaseType; typedef LocalVolumeIntegralOperator<LocalEvaluation::Elliptic<DiffusionFactorType, DiffusionTensorType>> LocalEllipticOperatorType; public: // Usually, we only hace to hold the data functions for the local operator and perfect forward the rest of the // arguments to BaseType. Here, it is a bit more complicated, since DiffusionTensorType might be void (and // DiffusionFactorType is the the only diffusion). To handle this case we require the enable_if hacks below to // disable half of the ctors if DiffusionTensorType is void. In addition we require each ctor twice, once with // over_integrate, once without (since the perfect forwarding does not allow for default arguments). template <typename DiffusionImp // This ctor is only enabled if we are given a single diffusion data function. , typename = typename std::enable_if<(std::is_same<DiffusionTensorType, void>::value) // && (std::is_same<DiffusionImp, DiffusionFactorType>::value) && sizeof(DiffusionImp)>::type, class... Args> explicit EllipticLocalizableProduct(const DiffusionImp& diffusion, Args&&... args) : BaseType(std::forward<Args>(args)...) , local_elliptic_operator_(diffusion) { this->add(local_elliptic_operator_); } template <typename DiffusionImp // This ctor is only enabled if we are given a single diffusion data function. , typename = typename std::enable_if<(std::is_same<DiffusionTensorType, void>::value) && (std::is_same<DiffusionImp, DiffusionFactorType>::value) && sizeof(DiffusionImp)>::type, class... Args> explicit EllipticLocalizableProduct(const size_t over_integrate, const DiffusionImp& diffusion, Args&&... args) : BaseType(std::forward<Args>(args)...) , local_elliptic_operator_(over_integrate, diffusion) { this->add(local_elliptic_operator_); } template <typename DiffusionFactorImp // This ctor is only enabled , typename DiffusionTensorImp // if we are given two diffusion data functions (factor and tensor). , typename = typename std::enable_if<(!std::is_same<DiffusionTensorType, void>::value) && (std::is_same<DiffusionFactorImp, DiffusionFactorType>::value) && sizeof(DiffusionFactorImp)>::type, class... Args> explicit EllipticLocalizableProduct(const DiffusionFactorImp& diffusion_factor, const DiffusionTensorImp& diffusion_tensor, Args&&... args) : BaseType(std::forward<Args>(args)...) , local_elliptic_operator_(diffusion_factor, diffusion_tensor) { this->add(local_elliptic_operator_); } template <typename DiffusionFactorImp // This ctor is only enabled , typename DiffusionTensorImp // if we are given two diffusion data functions (factor and tensor). , typename = typename std::enable_if<(!std::is_same<DiffusionTensorType, void>::value) && (std::is_same<DiffusionFactorImp, DiffusionFactorType>::value) && sizeof(DiffusionFactorImp)>::type, class... Args> explicit EllipticLocalizableProduct(const size_t over_integrate, const DiffusionFactorImp& diffusion_factor, const DiffusionTensorImp& diffusion_tensor, Args&&... args) : BaseType(std::forward<Args>(args)...) , local_elliptic_operator_(over_integrate, diffusion_factor, diffusion_tensor) { this->add(local_elliptic_operator_); } private: const LocalEllipticOperatorType local_elliptic_operator_; }; // class EllipticLocalizableProduct /** * \sa EllipticLocalizableProduct, especially for the role of diffusion. */ template <class DiffusionType, class GridViewType, class RangeType, class SourceType> typename std::enable_if<Stuff::is_localizable_function<DiffusionType>::value && Stuff::is_localizable_function<RangeType>::value && Stuff::is_localizable_function<SourceType>::value, std::unique_ptr<EllipticLocalizableProduct<DiffusionType, void, GridViewType, RangeType, SourceType>>>::type make_elliptic_localizable_product(const DiffusionType& diffusion, const GridViewType& grid_view, const RangeType& range, const SourceType& source, const size_t over_integrate = 0) { return DSC::make_unique<EllipticLocalizableProduct<DiffusionType, void, GridViewType, RangeType, SourceType>>( over_integrate, diffusion, grid_view, range, source); } /** * \sa EllipticLocalizableProduct, especially for the role of diffusion_factor and diffusion_tensor. */ template <class DiffusionFactorType, class DiffusionTensorType, class GridViewType, class RangeType, class SourceType> typename std::enable_if<Stuff::is_localizable_function<DiffusionFactorType>::value && Stuff::is_localizable_function<DiffusionTensorType>::value && Stuff::is_localizable_function<RangeType>::value && Stuff::is_localizable_function<SourceType>::value, std::unique_ptr<EllipticLocalizableProduct<DiffusionFactorType, DiffusionTensorType, GridViewType, RangeType, SourceType>>>::type make_elliptic_localizable_product(const DiffusionFactorType& diffusion_factor, const DiffusionTensorType& diffusion_tensor, const GridViewType& grid_view, const RangeType& range, const SourceType& source, const size_t over_integrate = 0) { return DSC::make_unique<EllipticLocalizableProduct<DiffusionFactorType, DiffusionTensorType, GridViewType, RangeType, SourceType>>( over_integrate, diffusion_factor, diffusion_tensor, grid_view, range, source); } } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_ELLIPTIC_HH <commit_msg>[operators.elliptic] add delimiters<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_ELLIPTIC_HH #define DUNE_GDT_OPERATORS_ELLIPTIC_HH #include <dune/grid/common/gridview.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/memory.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/la/container.hh> #include <dune/gdt/localevaluation/elliptic.hh> #include <dune/gdt/localoperator/integrals.hh> #include <dune/gdt/operators/interfaces.hh> #include <dune/gdt/operators/default.hh> #include <dune/gdt/spaces/interface.hh> namespace Dune { namespace GDT { // ////////////////////////// // // EllipticLocalizableProduct // // ////////////////////////// // template <class DiffusionFactorType, typename DiffusionTensorType, // may be void class GridView, class Range, class Source = Range, class Field = typename Range::RangeFieldType> class EllipticLocalizableProduct : public LocalizableProductDefault<GridView, Range, Source, Field> { typedef LocalizableProductDefault<GridView, Range, Source, Field> BaseType; typedef LocalVolumeIntegralOperator<LocalEvaluation::Elliptic<DiffusionFactorType, DiffusionTensorType>> LocalEllipticOperatorType; public: // Usually, we only hace to hold the data functions for the local operator and perfect forward the rest of the // arguments to BaseType. Here, it is a bit more complicated, since DiffusionTensorType might be void (and // DiffusionFactorType is the the only diffusion). To handle this case we require the enable_if hacks below to // disable half of the ctors if DiffusionTensorType is void. In addition we require each ctor twice, once with // over_integrate, once without (since the perfect forwarding does not allow for default arguments). template <typename DiffusionImp // This ctor is only enabled if we are given a single diffusion data function. , typename = typename std::enable_if<(std::is_same<DiffusionTensorType, void>::value) // && (std::is_same<DiffusionImp, DiffusionFactorType>::value) && sizeof(DiffusionImp)>::type, class... Args> explicit EllipticLocalizableProduct(const DiffusionImp& diffusion, Args&&... args) : BaseType(std::forward<Args>(args)...) , local_elliptic_operator_(diffusion) { this->add(local_elliptic_operator_); } template <typename DiffusionImp // This ctor is only enabled if we are given a single diffusion data function. , typename = typename std::enable_if<(std::is_same<DiffusionTensorType, void>::value) && (std::is_same<DiffusionImp, DiffusionFactorType>::value) && sizeof(DiffusionImp)>::type, class... Args> explicit EllipticLocalizableProduct(const size_t over_integrate, const DiffusionImp& diffusion, Args&&... args) : BaseType(std::forward<Args>(args)...) , local_elliptic_operator_(over_integrate, diffusion) { this->add(local_elliptic_operator_); } template <typename DiffusionFactorImp // This ctor is only enabled , typename DiffusionTensorImp // if we are given two diffusion data functions (factor and tensor). , typename = typename std::enable_if<(!std::is_same<DiffusionTensorType, void>::value) && (std::is_same<DiffusionFactorImp, DiffusionFactorType>::value) && sizeof(DiffusionFactorImp)>::type, class... Args> explicit EllipticLocalizableProduct(const DiffusionFactorImp& diffusion_factor, const DiffusionTensorImp& diffusion_tensor, Args&&... args) : BaseType(std::forward<Args>(args)...) , local_elliptic_operator_(diffusion_factor, diffusion_tensor) { this->add(local_elliptic_operator_); } template <typename DiffusionFactorImp // This ctor is only enabled , typename DiffusionTensorImp // if we are given two diffusion data functions (factor and tensor). , typename = typename std::enable_if<(!std::is_same<DiffusionTensorType, void>::value) && (std::is_same<DiffusionFactorImp, DiffusionFactorType>::value) && sizeof(DiffusionFactorImp)>::type, class... Args> explicit EllipticLocalizableProduct(const size_t over_integrate, const DiffusionFactorImp& diffusion_factor, const DiffusionTensorImp& diffusion_tensor, Args&&... args) : BaseType(std::forward<Args>(args)...) , local_elliptic_operator_(over_integrate, diffusion_factor, diffusion_tensor) { this->add(local_elliptic_operator_); } private: const LocalEllipticOperatorType local_elliptic_operator_; }; // class EllipticLocalizableProduct // ///////////////////////////////// // // make_elliptic_localizable_product // // ///////////////////////////////// // /** * \sa EllipticLocalizableProduct, especially for the role of diffusion. */ template <class DiffusionType, class GridViewType, class RangeType, class SourceType> typename std::enable_if<Stuff::is_localizable_function<DiffusionType>::value && Stuff::is_localizable_function<RangeType>::value && Stuff::is_localizable_function<SourceType>::value, std::unique_ptr<EllipticLocalizableProduct<DiffusionType, void, GridViewType, RangeType, SourceType>>>::type make_elliptic_localizable_product(const DiffusionType& diffusion, const GridViewType& grid_view, const RangeType& range, const SourceType& source, const size_t over_integrate = 0) { return DSC::make_unique<EllipticLocalizableProduct<DiffusionType, void, GridViewType, RangeType, SourceType>>( over_integrate, diffusion, grid_view, range, source); } /** * \sa EllipticLocalizableProduct, especially for the role of diffusion_factor and diffusion_tensor. */ template <class DiffusionFactorType, class DiffusionTensorType, class GridViewType, class RangeType, class SourceType> typename std::enable_if<Stuff::is_localizable_function<DiffusionFactorType>::value && Stuff::is_localizable_function<DiffusionTensorType>::value && Stuff::is_localizable_function<RangeType>::value && Stuff::is_localizable_function<SourceType>::value, std::unique_ptr<EllipticLocalizableProduct<DiffusionFactorType, DiffusionTensorType, GridViewType, RangeType, SourceType>>>::type make_elliptic_localizable_product(const DiffusionFactorType& diffusion_factor, const DiffusionTensorType& diffusion_tensor, const GridViewType& grid_view, const RangeType& range, const SourceType& source, const size_t over_integrate = 0) { return DSC::make_unique<EllipticLocalizableProduct<DiffusionFactorType, DiffusionTensorType, GridViewType, RangeType, SourceType>>( over_integrate, diffusion_factor, diffusion_tensor, grid_view, range, source); } } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_ELLIPTIC_HH <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_SPACES_CONSTRAINTS_HH #define DUNE_GDT_SPACES_CONSTRAINTS_HH #include <ostream> #include <dune/common/dynvector.hh> #include <dune/common/dynmatrix.hh> #include <dune/stuff/grid/boundaryinfo.hh> #include <dune/stuff/common/crtp.hh> namespace Dune { namespace GDT { namespace Spaces { template< class Traits, class ValueImp = double > class ConstraintsInterface : public Stuff::CRTPInterface< ConstraintsInterface< Traits, ValueImp >, Traits > { public: typedef typename Traits::derived_type derived_type; typedef ValueImp ValueType; inline size_t rows() const { CHECK_CRTP(this->as_imp().rows()); return this->as_imp().rows(); } inline size_t cols() const { CHECK_CRTP(this->as_imp().cols()); return this->as_imp().cols(); } inline size_t global_row(const size_t ii) const { CHECK_CRTP(this->as_imp().global_row(ii)); return this->as_imp().global_row(ii); } inline size_t global_col(const size_t jj) const { CHECK_CRTP(this->as_imp().global_col(jj)); return this->as_imp().global_col(jj); } inline ValueType value(const size_t ii, const size_t jj) const { CHECK_CRTP(this->as_imp().value(ii, jj)); return this->as_imp().value(ii, jj); } private: template< class T, class V > friend std::ostream& operator<<(std::ostream& /*out*/, const ConstraintsInterface< T, V >& /*constraints*/); }; // class ConstraintsInterface template< class T, class V > std::ostream& operator<<(std::ostream& out, const ConstraintsInterface< T, V >& constraints) { out << "gdt.spaces.constraints of size " << constraints.rows() << " x " << constraints.cols() << ", containing\n"; for (size_t ii = 0; ii < constraints.rows(); ++ii) for (size_t jj = 0; jj < constraints.cols(); ++jj) out << " " << constraints.global_row(ii) << ", " << constraints.global_col(jj) << ": " << constraints.value(ii, jj) << "\n"; return out; } // ... operator<<(...) namespace Constraints { namespace internal { template< class DerivedTraits, class ValueImp > class Default : public ConstraintsInterface< DerivedTraits, ValueImp > { typedef ConstraintsInterface< DerivedTraits, ValueImp > BaseType; public: typedef DerivedTraits Traits; typedef typename BaseType::ValueType ValueType; private: typedef DynamicVector< size_t > IndicesType; typedef DynamicMatrix< ValueType > ValuesType; public: Default(const size_t rws, const size_t cls) : rows_(rws) , cols_(cls) , global_rows_(rows_) , global_cols_(cols_) , values_(rows_, cols_) {} size_t rows() const { return rows_; } size_t cols() const { return cols_; } void set_size(const size_t rr, const size_t cc) { rows_ = rr; cols_ = cc; bool changed = false; if (rows_ > global_rows_.size()) { global_rows_.resize(rows_, 0); changed = true; } if (cols_ > global_cols_.size()) { global_cols_.resize(cols_, 0); changed = true; } if (changed) values_.resize(global_rows_.size(), global_cols_.size(), 0); } // ... set_size(...) size_t& global_row(const size_t ii) { assert(ii < std::min(rows_, global_rows_.size())); return global_rows_[ii]; } size_t global_row(const size_t ii) const { assert(ii < std::min(rows_, global_rows_.size())); return global_rows_[ii]; } size_t& global_col(const size_t jj) { assert(jj < std::min(cols_, global_cols_.size())); return global_cols_[jj]; } size_t global_col(const size_t jj) const { assert(jj < std::min(cols_, global_cols_.size())); return global_cols_[jj]; } ValueType& value(const size_t ii, const size_t jj) { assert(ii < std::min(rows_, global_rows_.size())); assert(jj < std::min(cols_, global_cols_.size())); return values_[ii][jj]; } ValueType value(const size_t ii, const size_t jj) const { assert(ii < std::min(rows_, global_rows_.size())); assert(jj < std::min(cols_, global_cols_.size())); return values_[ii][jj]; } private: size_t rows_; size_t cols_; IndicesType global_rows_; IndicesType global_cols_; ValuesType values_; }; // class Default } // namespace internal template< class IntersectionType, class ValueImp = double > class Dirichlet; namespace internal { template< class IntersectionType, class ValueImp > class DirichletTraits { public: typedef Dirichlet< IntersectionType, ValueImp > derived_type; }; } // namespace internal template< class IntersectionType, class ValueImp > class Dirichlet : public internal::Default< internal::DirichletTraits< IntersectionType, ValueImp >, ValueImp > { typedef internal::Default< internal::DirichletTraits< IntersectionType, ValueImp >, ValueImp > BaseType; public: typedef Stuff::Grid::BoundaryInfoInterface< IntersectionType > BoundaryInfoType; Dirichlet(const BoundaryInfoType& bnd_info, const size_t rws, const size_t cls, const bool set_rw = true) : BaseType(rws, cls) , boundary_info_(bnd_info) , set_row_(set_rw) {} const BoundaryInfoType& boundary_info() const { return boundary_info_; } bool set_row() const { return set_row_; } private: const BoundaryInfoType& boundary_info_; const bool set_row_; }; // class Dirichlet } // namespace Constraints } // namespace Spaces } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACES_CONSTRAINTS_HH <commit_msg>[spaces.constraints] refactor, refs #51<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_SPACES_CONSTRAINTS_HH #define DUNE_GDT_SPACES_CONSTRAINTS_HH #include <ostream> #include <dune/stuff/common/crtp.hh> #include <dune/stuff/grid/boundaryinfo.hh> #include <dune/stuff/la/container/interfaces.hh> namespace Dune { namespace GDT { namespace Spaces { /** * \brief CRTP interface for all implementations of constraints. * * We need this interface for template matching in the SystemAssembler. */ template< class Traits > class ConstraintsInterface : public Stuff::CRTPInterface< ConstraintsInterface< Traits >, Traits > { public: typedef typename Traits::derived_type derived_type; }; // class ConstraintsInterface // forward template< class IntersectionType > class DirichletConstraints; namespace internal { template< class IntersectionType > class DirichletConstraintsTraits { public: typedef DirichletConstraints< IntersectionType > derived_type; }; } // namespace internal template< class IntersectionType > class DirichletConstraints : public ConstraintsInterface< internal::DirichletConstraintsTraits< IntersectionType > > { public: typedef internal::DirichletConstraintsTraits< IntersectionType > Traits; typedef Stuff::Grid::BoundaryInfoInterface< IntersectionType > BoundaryInfoType; DirichletConstraints(const BoundaryInfoType& bnd_info, const size_t sz, const bool set = true) : boundary_info_(bnd_info) , size_(sz) , set_(set) {} const BoundaryInfoType& boundary_info() const { return boundary_info_; } inline void insert(const size_t DoF) { assert(DoF < size_); dirichlet_DoFs_.insert(DoF); } template< class M > void apply(Stuff::LA::MatrixInterface< M >& matrix) const { assert(matrix.rows() == size_); if (set_) { for (const auto& DoF : dirichlet_DoFs_) matrix.unit_row(DoF); } else { for (const auto& DoF : dirichlet_DoFs_) matrix.clear_row(DoF); } } // ... apply(...) template< class V > void apply(Stuff::LA::VectorInterface< V >& vector) const { assert(vector.size() == size_); for (const auto& DoF : dirichlet_DoFs_) vector[DoF] = 0.0; } template< class M, class V > void apply(Stuff::LA::MatrixInterface< M >& matrix, Stuff::LA::VectorInterface< V >& vector) const { assert(matrix.rows() == size_); assert(vector.size() == size_); if (set_) { for (const auto& DoF : dirichlet_DoFs_) { matrix.unit_row(DoF); vector[DoF] = 0.0; } } else { for (const auto& DoF : dirichlet_DoFs_) { matrix.clear_row(DoF); vector[DoF] = 0.0; } } } // ... apply(...) private: const BoundaryInfoType& boundary_info_; const size_t size_; const bool set_; std::set< size_t > dirichlet_DoFs_; }; // class DirichletConstraints } // namespace Spaces } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACES_CONSTRAINTS_HH <|endoftext|>
<commit_before>/* * class.hpp - Copyright (C) 2007 by Nathan Reed * Implementation of the class__ class from luabridge.hpp. */ /* * Container for registered class names, with awareness of const types */ template <typename T> struct classname { static const char *name_; static const char *name () { return classname<T>::name_; } static bool is_const () { return false; } static void set_name (const char *name) { classname<T>::name_ = name; } }; // Initial type names are unknown template <typename T> const char *classname<T>::name_ = classname_unknown; // Specialization for const types, mapping to same names template <typename T> struct classname <const T> { static const char *name () { return classname<T>::name_; } static bool is_const () { return true; } static void set_name (const char *name) { classname<T>::name_ = name; } }; /* * Lua-registerable C function template for destructors. Objects are stored * in Lua as userdata containing a shared_ptr, and this is registered as the * __gc metamethod. The expected classname is passed as an upvalue so that * we can ensure that we are destructing the right kind of object. */ template <typename T> int destructor_dispatch (lua_State *L) { void *obj = checkclass(L, 1, lua_tostring(L, lua_upvalueindex(1)), true); shared_ptr<T> &ptr = *((shared_ptr<T> *)obj); ptr.~shared_ptr(); return 0; } /* * Functions for metatable construction. These functions create a metatable and * leave it in the top element of the Lua stack (in addition to registering it * wherever it needs to be registered). */ template <typename T> void create_metatable (lua_State *L, const char *name) { luaL_newmetatable(L, name); // Set it as its own metatable lua_pushvalue(L, -1); lua_setmetatable(L, -2); // Set subclass_indexer as the __index metamethod lua_pushcfunction(L, &subclass_indexer); lua_setfield(L, -2, "__index"); // Set the __gc metamethod to call the class destructor lua_pushstring(L, name); lua_pushcclosure(L, &destructor_dispatch<T>, 1); lua_setfield(L, -2, "__gc"); // Set the __type metafield to the name of the class lua_pushstring(L, name); lua_setfield(L, -2, "__type"); } template <typename T> void create_const_metatable (lua_State *L, const char *name) { std::string constname = std::string("const ") + name; luaL_newmetatable(L, constname.c_str()); lua_pushvalue(L, -1); lua_setmetatable(L, -2); lua_pushcfunction(L, &subclass_indexer); lua_setfield(L, -2, "__index"); lua_pushstring(L, constname.c_str()); lua_pushcclosure(L, &destructor_dispatch<T>, 1); lua_setfield(L, -2, "__gc"); lua_pushstring(L, constname.c_str()); lua_setfield(L, -2, "__type"); } template <typename T> void create_static_table (lua_State *L, const char *name) { lua_newtable(L); // Set it as its own metatable lua_pushvalue(L, -1); lua_setmetatable(L, -2); // Set subclass_indexer as the __index metamethod lua_pushcfunction(L, &subclass_indexer); lua_setfield(L, -2, "__index"); // Install it in the global environment lua_pushvalue(L, -1); lua_setglobal(L, name); } /* * class__ constructors */ template <typename T> class__<T>::class__ (lua_State *L_): L(L_) { assert(classname<T>::name() != classname_unknown); } template <typename T> class__<T>::class__ (lua_State *L_, const char *name): L(L_) { assert(!classname<T>::is_const()); classname<T>::set_name(name); // Create metatable for this class. The metatable is stored in the Lua // registry, keyed by the given class name. create_metatable<T>(L, name); // Create const metatable for this class. This is identical to the // previous metatable, except that it has "const " prepended to the __type // field. Const methods will be added to the const metatable, non-const // methods to the normal metatable. create_const_metatable<T>(L, name); // Set __const metafield to point to the const metatable lua_setfield(L, -2, "__const"); // Pop the original metatable lua_pop(L, 1); // Create static table for this class. This is stored in the global // environment, keyed by the given class name. Its __call metamethod // will be the constructor, and it will also contain static members. create_static_table<T>(L, name); lua_pop(L, 1); } template <typename T> class__<T>::class__ (lua_State *L_, const char *name, const char *basename): L(L_) { assert(!classname<T>::is_const()); classname<T>::set_name(name); // Create metatable for this class create_metatable<T>(L, name); // Set the __parent metafield to the base class's metatable luaL_getmetatable(L, basename); lua_setfield(L, -2, "__parent"); // Create const metatable for this class. Its __parent field will points // to the const metatable of the parent class. create_const_metatable<T>(L, name); std::string base_constname = std::string("const ") + basename; luaL_getmetatable(L, base_constname.c_str()); lua_setfield(L, -2, "__parent"); // Set __const metafield to point to the const metatable lua_setfield(L, -2, "__const"); // Pop the original metatable lua_pop(L, 1); // Create static table for this class create_static_table<T>(L, name); // Set the __parent metafield to the base class's static table lua_getglobal(L, basename); lua_setfield(L, -2, "__parent"); lua_pop(L, 1); } /* * Lua-registerable C function template for constructor proxies. These are * registered to Lua as global functions with the name of the class, with the * appropriate metatable passed as an upvalue. They allocate a new userdata, * initialize it with a shared_ptr to an appropriately constructed new class * object, and set the metatable so that Lua can use the object. */ template <typename T, typename Params> int constructor_proxy (lua_State *L) { // Allocate a new userdata and construct a shared_ptr<T> in-place there void *block = lua_newuserdata(L, sizeof(shared_ptr<T>)); arglist<Params, 2> args(L); new(block) shared_ptr<T>(constructor<T, Params>::apply(args)); // Set the userdata's metatable lua_pushvalue(L, lua_upvalueindex(1)); lua_setmetatable(L, -2); return 1; } /* * Perform constructor registration in a class. */ template <typename T> template <typename FnPtr> class__<T>& class__<T>::constructor () { // Get a reference to the class's static table lua_getglobal(L, classname<T>::name()); // Push the constructor proxy, with the class's metatable as an upvalue luaL_getmetatable(L, classname<T>::name()); lua_pushcclosure(L, &constructor_proxy<T, typename fnptr<FnPtr>::params>, 1); // Set the constructor proxy as the __call metamethod of the static table lua_setfield(L, -2, "__call"); lua_pop(L, 1); return *this; } /* * Lua-registerable C function templates for method proxies. These are * registered with the expected classname as upvalue 1 and the member function * pointer as upvalue 2. When called from Lua, they will receive the object * on which they are called as argument 1 and all the method arguments as * args 2 and up. */ template <typename FnPtr, typename Ret = typename fnptr<FnPtr>::resulttype> struct method_proxy { typedef typename fnptr<FnPtr>::classtype classtype; typedef typename fnptr<FnPtr>::params params; static int f (lua_State *L) { classtype *obj = ((shared_ptr<classtype> *)checkclass(L, 1, lua_tostring(L, lua_upvalueindex(1))))->get(); FnPtr fp = *(FnPtr *)lua_touserdata(L, lua_upvalueindex(2)); arglist<params, 2> args(L); tdstack<Ret>::push(L, fnptr<FnPtr>::apply(obj, fp, args)); return 1; } }; template <typename FnPtr> struct method_proxy <FnPtr, void> { typedef typename fnptr<FnPtr>::classtype classtype; typedef typename fnptr<FnPtr>::params params; static int f (lua_State *L) { classtype *obj = ((shared_ptr<classtype> *)checkclass(L, 1, lua_tostring(L, lua_upvalueindex(1))))->get(); FnPtr fp = *(FnPtr *)lua_touserdata(L, lua_upvalueindex(2)); arglist<params, 2> args(L); fnptr<FnPtr>::apply(obj, fp, args); return 1; } }; /* * Perform method registration in a class. The method proxies are all * registered as values in the class's metatable, which is searched by the * subclass_indexer function we've installed as __index metamethod. */ template <typename T> template <typename FnPtr> class__<T>& class__<T>::method (const char *name, FnPtr fp) { assert(fnptr<FnPtr>::mfp); std::string metatable_name = classname<T>::name(); if (fnptr<FnPtr>::const_mfp) metatable_name = "const " + metatable_name; luaL_getmetatable(L, metatable_name.c_str()); lua_pushstring(L, metatable_name.c_str()); void *v = lua_newuserdata(L, sizeof(FnPtr)); memcpy(v, &fp, sizeof(FnPtr)); lua_pushcclosure(L, &method_proxy<FnPtr>::f, 2); lua_setfield(L, -2, name); lua_pop(L, 1); return *this; } /* * Static method registration. Method proxies are registered as values * in the class's static table. We use the global function proxies defined * in module.hpp, since static methods are really just hidden globals. */ template <typename T> template <typename FnPtr> class__<T>& class__<T>::static_method (const char *name, FnPtr fp) { assert(!fnptr<FnPtr>::mfp); lua_getglobal(L, classname<T>::name()); lua_pushlightuserdata(L, (void *)fp); lua_pushcclosure(L, &function_proxy<FnPtr>::f, 1); lua_setfield(L, -2, name); lua_pop(L, 1); return *this; } <commit_msg>Minor change to destructor_dispatch that makes g++ 4 happier.<commit_after>/* * class.hpp - Copyright (C) 2007 by Nathan Reed * Implementation of the class__ class from luabridge.hpp. */ /* * Container for registered class names, with awareness of const types */ template <typename T> struct classname { static const char *name_; static const char *name () { return classname<T>::name_; } static bool is_const () { return false; } static void set_name (const char *name) { classname<T>::name_ = name; } }; // Initial type names are unknown template <typename T> const char *classname<T>::name_ = classname_unknown; // Specialization for const types, mapping to same names template <typename T> struct classname <const T> { static const char *name () { return classname<T>::name_; } static bool is_const () { return true; } static void set_name (const char *name) { classname<T>::name_ = name; } }; /* * Lua-registerable C function template for destructors. Objects are stored * in Lua as userdata containing a shared_ptr, and this is registered as the * __gc metamethod. The expected classname is passed as an upvalue so that * we can ensure that we are destructing the right kind of object. */ template <typename T> int destructor_dispatch (lua_State *L) { void *obj = checkclass(L, 1, lua_tostring(L, lua_upvalueindex(1)), true); shared_ptr<T> &ptr = *((shared_ptr<T> *)obj); ptr.~shared_ptr<T>(); return 0; } /* * Functions for metatable construction. These functions create a metatable and * leave it in the top element of the Lua stack (in addition to registering it * wherever it needs to be registered). */ template <typename T> void create_metatable (lua_State *L, const char *name) { luaL_newmetatable(L, name); // Set it as its own metatable lua_pushvalue(L, -1); lua_setmetatable(L, -2); // Set subclass_indexer as the __index metamethod lua_pushcfunction(L, &subclass_indexer); lua_setfield(L, -2, "__index"); // Set the __gc metamethod to call the class destructor lua_pushstring(L, name); lua_pushcclosure(L, &destructor_dispatch<T>, 1); lua_setfield(L, -2, "__gc"); // Set the __type metafield to the name of the class lua_pushstring(L, name); lua_setfield(L, -2, "__type"); } template <typename T> void create_const_metatable (lua_State *L, const char *name) { std::string constname = std::string("const ") + name; luaL_newmetatable(L, constname.c_str()); lua_pushvalue(L, -1); lua_setmetatable(L, -2); lua_pushcfunction(L, &subclass_indexer); lua_setfield(L, -2, "__index"); lua_pushstring(L, constname.c_str()); lua_pushcclosure(L, &destructor_dispatch<T>, 1); lua_setfield(L, -2, "__gc"); lua_pushstring(L, constname.c_str()); lua_setfield(L, -2, "__type"); } template <typename T> void create_static_table (lua_State *L, const char *name) { lua_newtable(L); // Set it as its own metatable lua_pushvalue(L, -1); lua_setmetatable(L, -2); // Set subclass_indexer as the __index metamethod lua_pushcfunction(L, &subclass_indexer); lua_setfield(L, -2, "__index"); // Install it in the global environment lua_pushvalue(L, -1); lua_setglobal(L, name); } /* * class__ constructors */ template <typename T> class__<T>::class__ (lua_State *L_): L(L_) { assert(classname<T>::name() != classname_unknown); } template <typename T> class__<T>::class__ (lua_State *L_, const char *name): L(L_) { assert(!classname<T>::is_const()); classname<T>::set_name(name); // Create metatable for this class. The metatable is stored in the Lua // registry, keyed by the given class name. create_metatable<T>(L, name); // Create const metatable for this class. This is identical to the // previous metatable, except that it has "const " prepended to the __type // field. Const methods will be added to the const metatable, non-const // methods to the normal metatable. create_const_metatable<T>(L, name); // Set __const metafield to point to the const metatable lua_setfield(L, -2, "__const"); // Pop the original metatable lua_pop(L, 1); // Create static table for this class. This is stored in the global // environment, keyed by the given class name. Its __call metamethod // will be the constructor, and it will also contain static members. create_static_table<T>(L, name); lua_pop(L, 1); } template <typename T> class__<T>::class__ (lua_State *L_, const char *name, const char *basename): L(L_) { assert(!classname<T>::is_const()); classname<T>::set_name(name); // Create metatable for this class create_metatable<T>(L, name); // Set the __parent metafield to the base class's metatable luaL_getmetatable(L, basename); lua_setfield(L, -2, "__parent"); // Create const metatable for this class. Its __parent field will points // to the const metatable of the parent class. create_const_metatable<T>(L, name); std::string base_constname = std::string("const ") + basename; luaL_getmetatable(L, base_constname.c_str()); lua_setfield(L, -2, "__parent"); // Set __const metafield to point to the const metatable lua_setfield(L, -2, "__const"); // Pop the original metatable lua_pop(L, 1); // Create static table for this class create_static_table<T>(L, name); // Set the __parent metafield to the base class's static table lua_getglobal(L, basename); lua_setfield(L, -2, "__parent"); lua_pop(L, 1); } /* * Lua-registerable C function template for constructor proxies. These are * registered to Lua as global functions with the name of the class, with the * appropriate metatable passed as an upvalue. They allocate a new userdata, * initialize it with a shared_ptr to an appropriately constructed new class * object, and set the metatable so that Lua can use the object. */ template <typename T, typename Params> int constructor_proxy (lua_State *L) { // Allocate a new userdata and construct a shared_ptr<T> in-place there void *block = lua_newuserdata(L, sizeof(shared_ptr<T>)); arglist<Params, 2> args(L); new(block) shared_ptr<T>(constructor<T, Params>::apply(args)); // Set the userdata's metatable lua_pushvalue(L, lua_upvalueindex(1)); lua_setmetatable(L, -2); return 1; } /* * Perform constructor registration in a class. */ template <typename T> template <typename FnPtr> class__<T>& class__<T>::constructor () { // Get a reference to the class's static table lua_getglobal(L, classname<T>::name()); // Push the constructor proxy, with the class's metatable as an upvalue luaL_getmetatable(L, classname<T>::name()); lua_pushcclosure(L, &constructor_proxy<T, typename fnptr<FnPtr>::params>, 1); // Set the constructor proxy as the __call metamethod of the static table lua_setfield(L, -2, "__call"); lua_pop(L, 1); return *this; } /* * Lua-registerable C function templates for method proxies. These are * registered with the expected classname as upvalue 1 and the member function * pointer as upvalue 2. When called from Lua, they will receive the object * on which they are called as argument 1 and all the method arguments as * args 2 and up. */ template <typename FnPtr, typename Ret = typename fnptr<FnPtr>::resulttype> struct method_proxy { typedef typename fnptr<FnPtr>::classtype classtype; typedef typename fnptr<FnPtr>::params params; static int f (lua_State *L) { classtype *obj = ((shared_ptr<classtype> *)checkclass(L, 1, lua_tostring(L, lua_upvalueindex(1))))->get(); FnPtr fp = *(FnPtr *)lua_touserdata(L, lua_upvalueindex(2)); arglist<params, 2> args(L); tdstack<Ret>::push(L, fnptr<FnPtr>::apply(obj, fp, args)); return 1; } }; template <typename FnPtr> struct method_proxy <FnPtr, void> { typedef typename fnptr<FnPtr>::classtype classtype; typedef typename fnptr<FnPtr>::params params; static int f (lua_State *L) { classtype *obj = ((shared_ptr<classtype> *)checkclass(L, 1, lua_tostring(L, lua_upvalueindex(1))))->get(); FnPtr fp = *(FnPtr *)lua_touserdata(L, lua_upvalueindex(2)); arglist<params, 2> args(L); fnptr<FnPtr>::apply(obj, fp, args); return 1; } }; /* * Perform method registration in a class. The method proxies are all * registered as values in the class's metatable, which is searched by the * subclass_indexer function we've installed as __index metamethod. */ template <typename T> template <typename FnPtr> class__<T>& class__<T>::method (const char *name, FnPtr fp) { assert(fnptr<FnPtr>::mfp); std::string metatable_name = classname<T>::name(); if (fnptr<FnPtr>::const_mfp) metatable_name = "const " + metatable_name; luaL_getmetatable(L, metatable_name.c_str()); lua_pushstring(L, metatable_name.c_str()); void *v = lua_newuserdata(L, sizeof(FnPtr)); memcpy(v, &fp, sizeof(FnPtr)); lua_pushcclosure(L, &method_proxy<FnPtr>::f, 2); lua_setfield(L, -2, name); lua_pop(L, 1); return *this; } /* * Static method registration. Method proxies are registered as values * in the class's static table. We use the global function proxies defined * in module.hpp, since static methods are really just hidden globals. */ template <typename T> template <typename FnPtr> class__<T>& class__<T>::static_method (const char *name, FnPtr fp) { assert(!fnptr<FnPtr>::mfp); lua_getglobal(L, classname<T>::name()); lua_pushlightuserdata(L, (void *)fp); lua_pushcclosure(L, &function_proxy<FnPtr>::f, 1); lua_setfield(L, -2, name); lua_pop(L, 1); return *this; } <|endoftext|>
<commit_before>// Copyright (c) 2014-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "validation.h" #include "net.h" #include "test/test_gulden.h" #include <boost/signals2/signal.hpp> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(main_tests, TestingSetup) static void TestBlockSubsidyHalvings(const Consensus::Params& consensusParams) { int maxHalvings = 64; CAmount nInitialSubsidy = 50 * COIN; CAmount nPreviousSubsidy = nInitialSubsidy * 2; // for height == 0 BOOST_CHECK_EQUAL(nPreviousSubsidy, nInitialSubsidy * 2); for (int nHalvings = 0; nHalvings < maxHalvings; nHalvings++) { int nHeight = nHalvings * consensusParams.nSubsidyHalvingInterval; CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams); BOOST_CHECK(nSubsidy <= nInitialSubsidy); BOOST_CHECK_EQUAL(nSubsidy, nPreviousSubsidy / 2); nPreviousSubsidy = nSubsidy; } BOOST_CHECK_EQUAL(GetBlockSubsidy(maxHalvings * consensusParams.nSubsidyHalvingInterval, consensusParams), 0); } static void TestBlockSubsidyHalvings(int nSubsidyHalvingInterval) { Consensus::Params consensusParams; consensusParams.nSubsidyHalvingInterval = nSubsidyHalvingInterval; TestBlockSubsidyHalvings(consensusParams); } BOOST_AUTO_TEST_CASE(block_subsidy_test) { const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); TestBlockSubsidyHalvings(chainParams->GetConsensus()); // As in main TestBlockSubsidyHalvings(150); // As in regtest TestBlockSubsidyHalvings(1000); // Just another interval } BOOST_AUTO_TEST_CASE(subsidy_limit_test) { const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); CAmount nSum = 0; for (int nHeight = 0; nHeight < 14000000; nHeight += 1000) { CAmount nSubsidy = GetBlockSubsidy(nHeight, chainParams->GetConsensus()); BOOST_CHECK(nSubsidy <= 50 * COIN); nSum += nSubsidy * 1000; BOOST_CHECK(MoneyRange(nSum)); } BOOST_CHECK_EQUAL(nSum, 2099999997690000ULL); } bool ReturnFalse() { return false; } bool ReturnTrue() { return true; } BOOST_AUTO_TEST_CASE(test_combiner_all) { boost::signals2::signal<bool (), CombinerAll> Test; BOOST_CHECK(Test()); Test.connect(&ReturnFalse); BOOST_CHECK(!Test()); Test.connect(&ReturnTrue); BOOST_CHECK(!Test()); Test.disconnect(&ReturnFalse); BOOST_CHECK(Test()); Test.disconnect(&ReturnTrue); BOOST_CHECK(Test()); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>(tests) fix main_tests (all pass)<commit_after>// Copyright (c) 2014-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "validation.h" #include "net.h" #include "test/test_gulden.h" #include <boost/signals2/signal.hpp> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(main_tests, TestingSetup) BOOST_AUTO_TEST_CASE(block_subsidy_test) { const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); BOOST_CHECK_EQUAL(GetBlockSubsidy(1, chainParams->GetConsensus()), COIN * 170000000); BOOST_CHECK_EQUAL(GetBlockSubsidy(250000, chainParams->GetConsensus()), COIN * 1000); BOOST_CHECK_EQUAL(GetBlockSubsidy(250001, chainParams->GetConsensus()), COIN * 100); BOOST_CHECK_EQUAL(GetBlockSubsidy(12850000, chainParams->GetConsensus()), COIN * 100); BOOST_CHECK_EQUAL(GetBlockSubsidy(12850001, chainParams->GetConsensus()), COIN * 0); } BOOST_AUTO_TEST_CASE(subsidy_limit_test) { const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); CAmount nSum = 0; for (int nHeight = 0; nHeight < 14000000; nHeight++) { CAmount nSubsidy = GetBlockSubsidy(nHeight, chainParams->GetConsensus()); nSum += nSubsidy; BOOST_CHECK(MoneyRange(nSum)); } BOOST_CHECK_EQUAL(nSum, 168000000000000000LL); } bool ReturnFalse() { return false; } bool ReturnTrue() { return true; } BOOST_AUTO_TEST_CASE(test_combiner_all) { boost::signals2::signal<bool (), CombinerAll> Test; BOOST_CHECK(Test()); Test.connect(&ReturnFalse); BOOST_CHECK(!Test()); Test.connect(&ReturnTrue); BOOST_CHECK(!Test()); Test.disconnect(&ReturnFalse); BOOST_CHECK(Test()); Test.disconnect(&ReturnTrue); BOOST_CHECK(Test()); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osgUtil/Optimizer> #include <osgDB/ReadFile> #include <osgProducer/Viewer> #include <osg/Material> #include <osg/Geode> #include <osg/BlendFunc> #include <osg/Depth> #include <osg/Projection> #include <osg/MatrixTransform> #include <osgText/Text> osg::Node* createHUD() { osg::Geode* geode = new osg::Geode(); std::string timesFont("fonts/times.ttf"); // turn lighting off for the text and disable depth test to ensure its always ontop. osg::StateSet* stateset = geode->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF); osg::Vec3 position(150.0f,800.0f,0.0f); osg::Vec3 delta(0.0f,-120.0f,0.0f); { osgText::Text* text = new osgText::Text; geode->addDrawable( text ); text->setFont(timesFont); text->setPosition(position); text->setText("Head Up Displays are simple :-)"); position += delta; } { osgText::Text* text = new osgText::Text; geode->addDrawable( text ); text->setFont(timesFont); text->setAutoScaleToScreen(true); text->setPosition(position); text->setText("All you need to do is create your text in a subgraph."); position += delta; } { osgText::Text* text = new osgText::Text; geode->addDrawable( text ); text->setFont(timesFont); text->setPosition(position); text->setText("Disable depth test in this subgraph to ensure its always ontop."); position += delta; } { osgText::Text* text = new osgText::Text; geode->addDrawable( text ); text->setFont(timesFont); text->setPosition(position); text->setText("Then place an osg::Projection node above the subgraph\nto create an orthographic projection."); position += delta; } { osgText::Text* text = new osgText::Text; geode->addDrawable( text ); text->setFont(timesFont); text->setPosition(position); text->setText("And add an osg::ModelViewMatrix set to ABSOLUTE to ensure\nit remains independent from any external model view matrices."); position += delta; } // create the hud. osg::MatrixTransform* modelview_abs = new osg::MatrixTransform; modelview_abs->setReferenceFrame(osg::Transform::RELATIVE_TO_ABSOLUTE); modelview_abs->setMatrix(osg::Matrix::identity()); modelview_abs->addChild(geode); osg::Projection* projection = new osg::Projection; projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024)); projection->addChild(modelview_abs); return projection; } int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates how to do Head Up Displays."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] [filename] ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); // construct the viewer. osgProducer::Viewer viewer(arguments); // set up the value with sensible default event handlers. viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS); // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } // read the scene from the list of file specified commandline args. osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments); osg::ref_ptr<osg::Group> group = dynamic_cast<osg::Group*>(scene.get()); if (!group) { group = new osg::Group; group->addChild(scene.get()); } // add the HUD subgraph. group->addChild(createHUD()); // set the scene to render viewer.setSceneData(group.get()); // create the windows and run the threads. viewer.realize(); while( !viewer.done() ) { // wait for all cull and draw threads to complete. viewer.sync(); // update the scene by traversing it with the the update visitor which will // call all node update callbacks and animations. viewer.update(); // fire off the cull and draw traversals of the scene. viewer.frame(); } // wait for all cull and draw threads to complete before exit. viewer.sync(); return 0; } <commit_msg>Reverted the test of setAutoScaleToScreen.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osgUtil/Optimizer> #include <osgDB/ReadFile> #include <osgProducer/Viewer> #include <osg/Material> #include <osg/Geode> #include <osg/BlendFunc> #include <osg/Depth> #include <osg/Projection> #include <osg/MatrixTransform> #include <osgText/Text> osg::Node* createHUD() { osg::Geode* geode = new osg::Geode(); std::string timesFont("fonts/times.ttf"); // turn lighting off for the text and disable depth test to ensure its always ontop. osg::StateSet* stateset = geode->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF); osg::Vec3 position(150.0f,800.0f,0.0f); osg::Vec3 delta(0.0f,-120.0f,0.0f); { osgText::Text* text = new osgText::Text; geode->addDrawable( text ); text->setFont(timesFont); text->setPosition(position); text->setText("Head Up Displays are simple :-)"); position += delta; } { osgText::Text* text = new osgText::Text; geode->addDrawable( text ); text->setFont(timesFont); text->setPosition(position); text->setText("All you need to do is create your text in a subgraph."); position += delta; } { osgText::Text* text = new osgText::Text; geode->addDrawable( text ); text->setFont(timesFont); text->setPosition(position); text->setText("Disable depth test in this subgraph to ensure its always ontop."); position += delta; } { osgText::Text* text = new osgText::Text; geode->addDrawable( text ); text->setFont(timesFont); text->setPosition(position); text->setText("Then place an osg::Projection node above the subgraph\nto create an orthographic projection."); position += delta; } { osgText::Text* text = new osgText::Text; geode->addDrawable( text ); text->setFont(timesFont); text->setPosition(position); text->setText("And add an osg::ModelViewMatrix set to ABSOLUTE to ensure\nit remains independent from any external model view matrices."); position += delta; } // create the hud. osg::MatrixTransform* modelview_abs = new osg::MatrixTransform; modelview_abs->setReferenceFrame(osg::Transform::RELATIVE_TO_ABSOLUTE); modelview_abs->setMatrix(osg::Matrix::identity()); modelview_abs->addChild(geode); osg::Projection* projection = new osg::Projection; projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024)); projection->addChild(modelview_abs); return projection; } int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates how to do Head Up Displays."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] [filename] ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); // construct the viewer. osgProducer::Viewer viewer(arguments); // set up the value with sensible default event handlers. viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS); // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } // read the scene from the list of file specified commandline args. osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments); osg::ref_ptr<osg::Group> group = dynamic_cast<osg::Group*>(scene.get()); if (!group) { group = new osg::Group; group->addChild(scene.get()); } // add the HUD subgraph. group->addChild(createHUD()); // set the scene to render viewer.setSceneData(group.get()); // create the windows and run the threads. viewer.realize(); while( !viewer.done() ) { // wait for all cull and draw threads to complete. viewer.sync(); // update the scene by traversing it with the the update visitor which will // call all node update callbacks and animations. viewer.update(); // fire off the cull and draw traversals of the scene. viewer.frame(); } // wait for all cull and draw threads to complete before exit. viewer.sync(); return 0; } <|endoftext|>
<commit_before>#include <taichi/taichi> #include <taichi/util.h> TC_NAMESPACE_BEGIN auto diff_conv = [](const std::vector<std::string> args) { int grid_resolution = 256; TC_ASSERT(args.size() == 2); auto f = fopen(args[0].c_str(), "rb"); int n = pow<3>(grid_resolution); TC_ASSERT(f); std::vector<float32> ret1(n); std::fread(ret1.data(), sizeof(float32), ret1.size(), f); std::fclose(f); f = fopen(args[1].c_str(), "rb"); TC_ASSERT(f); std::vector<float32> ret2(n); std::fread(ret2.data(), sizeof(float32), ret2.size(), f); std::fclose(f); int counter[2] = {0, 0}; for (int i = 0; i < n; i++) { bool same = std::abs(ret1[i] - ret2[i]) < 1e-3f; if (same) counter[0]++; else counter[1]++; } TC_INFO("same {} {}%", counter[0], 100.0f * counter[0] / n); }; TC_REGISTER_TASK(diff_conv); TC_NAMESPACE_END <commit_msg>threshold<commit_after>#include <taichi/taichi> #include <taichi/util.h> TC_NAMESPACE_BEGIN auto diff_conv = [](const std::vector<std::string> args) { int grid_resolution = 256; TC_ASSERT(args.size() == 3); float th = std::stof(args[2]); TC_P(th); auto f = fopen(args[0].c_str(), "rb"); int n = pow<3>(grid_resolution); TC_ASSERT(f); std::vector<float32> ret1(n); std::fread(ret1.data(), sizeof(float32), ret1.size(), f); std::fclose(f); f = fopen(args[1].c_str(), "rb"); TC_ASSERT(f); std::vector<float32> ret2(n); std::fread(ret2.data(), sizeof(float32), ret2.size(), f); std::fclose(f); int counter[2] = {0, 0}; for (int i = 0; i < n; i++) { bool same = std::abs(ret1[i] - ret2[i]) < 1e-3f; if (same) counter[0]++; else counter[1]++; } TC_INFO("same {} {}%", counter[0], 100.0f * counter[0] / n); }; TC_REGISTER_TASK(diff_conv); TC_NAMESPACE_END <|endoftext|>
<commit_before>#line 2 "togo/serializer.hpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file @brief Serializer interface. @ingroup serialization @ingroup serializer */ #pragma once #include <togo/config.hpp> #include <togo/traits.hpp> #include <togo/serialization_types.hpp> #include <type_traits> #include <utility> /** @cond INTERNAL */ namespace togo { namespace detail { struct unimplemented {}; } // namespace detail } // namespace togo // Unimplemented captures (least-sticky acceptor) template<class... P> togo::detail::unimplemented serialize(togo::serializer_tag, P&&...); template<class... P> togo::detail::unimplemented read(togo::serializer_tag, P&&...); template<class... P> togo::detail::unimplemented write(togo::serializer_tag, P&&...); /** @endcond */ // INTERNAL namespace togo { /** @addtogroup serializer @{ */ namespace { template<class Ser, class T> struct has_serializer_serialize { using ser_type = remove_cvr<Ser>; using unimpl_capture = is_same< detail::unimplemented, decltype(serialize( serializer_tag{}, std::declval<ser_type&>(), std::declval<T&>() )) >; static constexpr bool const value = !unimpl_capture::value; }; template<class Ser, class T> struct has_serializer_read { using ser_type = remove_cvr<Ser>; using unimpl_capture_lvalue = is_same< detail::unimplemented, decltype(read( serializer_tag{}, std::declval<ser_type&>(), std::declval<T&>() )) >; using unimpl_capture_rvalue = is_same< detail::unimplemented, decltype(read( serializer_tag{}, std::declval<ser_type&>(), std::declval<T&&>() )) >; static constexpr bool const value = !unimpl_capture_lvalue::value || !unimpl_capture_rvalue::value ; }; template<class Ser, class T> struct has_serializer_write { using ser_type = remove_cvr<Ser>; using unimpl_capture = is_same< detail::unimplemented, decltype(write( serializer_tag{}, std::declval<ser_type&>(), std::declval<T const&>() )) >; static constexpr bool const value = !unimpl_capture::value; }; template<class Ser, class T> inline constexpr unsigned serializer_read_num_defined() { return has_serializer_read<Ser, T>::value + has_serializer_serialize<Ser, T>::value ; } template<class Ser, class T> inline constexpr unsigned serializer_write_num_defined() { return has_serializer_write<Ser, T>::value + has_serializer_serialize<Ser, T>::value ; } } // anonymous namespace namespace serializer { template<class Ser, class T> inline enable_if<has_serializer_serialize<Ser, T>::value> read(Ser& ser, T&& value) { serialize(serializer_tag{}, ser, std::forward<T>(value)); } template<class Ser, class T> inline enable_if<has_serializer_read<Ser, T>::value> read(Ser& ser, T&& value) { read(serializer_tag{}, ser, std::forward<T>(value)); } template<class Ser, class T> inline enable_if<has_serializer_serialize<Ser, T>::value> write(Ser& ser, T const& value) { serialize(serializer_tag{}, ser, const_cast<remove_cvr<T>&>(value)); } template<class Ser, class T> inline enable_if<has_serializer_write<Ser, T>::value> write(Ser& ser, T const& value) { write(serializer_tag{}, ser, value); } } // namespace serializer // BaseSerializer implementation template<class Impl> inline Impl& BaseSerializer<Impl>::impl() { return static_cast<Impl&>(*this); } // InputSerializer implementation /// Read value. template<class Impl, class T> inline enable_if<serializer_read_num_defined<Impl, T>() == 1, Impl&> operator%( InputSerializer<Impl>& ser, T&& value ) { serializer::read(ser.impl(), std::forward<T>(value)); return ser.impl(); } /** @cond INTERNAL */ template<class Impl, class T> inline enable_if<serializer_read_num_defined<Impl, T>() != 1, Impl&> operator%( InputSerializer<Impl>& /*ser*/, T&& /*value*/ ) { static_assert( serializer_read_num_defined<Impl, T>() != 0, "no read-serialize function defined for T with this serializer" ); static_assert( serializer_read_num_defined<Impl, T>() <= 1, "ambiguous serialization interface defined for T with this serializer" " (both read() and serialize() are defined)" ); } /** @endcond */ // INTERNAL // OutputSerializer implementation /// Write value. template<class Impl, class T> inline enable_if<serializer_write_num_defined<Impl, T>() == 1, Impl&> operator%( OutputSerializer<Impl>& ser, T const& value ) { serializer::write(ser.impl(), value); return ser.impl(); } /** @cond INTERNAL */ template<class Impl, class T> inline enable_if<serializer_write_num_defined<Impl, T>() != 1, Impl&> operator%( OutputSerializer<Impl>& /*ser*/, T const& /*value*/ ) { static_assert( serializer_write_num_defined<Impl, T>() != 0, "no write-serialize function defined for T with this serializer" ); static_assert( serializer_write_num_defined<Impl, T>() <= 1, "ambiguous serialization interface defined for T with this serializer" " (both write() and serialize() are defined)" ); } /** @endcond */ // INTERNAL /** @} */ // end of doc-group serializer } // namespace togo <commit_msg>serializer: tidy.<commit_after>#line 2 "togo/serializer.hpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file @brief Serializer interface. @ingroup serialization @ingroup serializer */ #pragma once #include <togo/config.hpp> #include <togo/traits.hpp> #include <togo/serialization_types.hpp> #include <type_traits> #include <utility> /** @cond INTERNAL */ namespace togo { namespace detail { struct unimplemented {}; } // namespace detail } // namespace togo // Unimplemented captures (least-sticky acceptor) template<class... P> togo::detail::unimplemented serialize(togo::serializer_tag, P&&...); template<class... P> togo::detail::unimplemented read(togo::serializer_tag, P&&...); template<class... P> togo::detail::unimplemented write(togo::serializer_tag, P&&...); /** @endcond */ // INTERNAL namespace togo { /** @addtogroup serializer @{ */ namespace { template<class Ser, class T> struct has_serializer_serialize { using ser_type = remove_cvr<Ser>; using unimpl_capture = is_same< detail::unimplemented, decltype(serialize( serializer_tag{}, std::declval<ser_type&>(), std::declval<T&>() )) >; static constexpr bool const value = !unimpl_capture::value; }; template<class Ser, class T> struct has_serializer_read { using ser_type = remove_cvr<Ser>; using unimpl_capture_lvalue = is_same< detail::unimplemented, decltype(read( serializer_tag{}, std::declval<ser_type&>(), std::declval<T&>() )) >; using unimpl_capture_rvalue = is_same< detail::unimplemented, decltype(read( serializer_tag{}, std::declval<ser_type&>(), std::declval<T&&>() )) >; static constexpr bool const value = !unimpl_capture_lvalue::value || !unimpl_capture_rvalue::value ; }; template<class Ser, class T> struct has_serializer_write { using ser_type = remove_cvr<Ser>; using unimpl_capture = is_same< detail::unimplemented, decltype(write( serializer_tag{}, std::declval<ser_type&>(), std::declval<T const&>() )) >; static constexpr bool const value = !unimpl_capture::value; }; template<class Ser, class T> inline constexpr unsigned serializer_read_num_defined() { return has_serializer_read<Ser, T>::value + has_serializer_serialize<Ser, T>::value ; } template<class Ser, class T> inline constexpr unsigned serializer_write_num_defined() { return has_serializer_write<Ser, T>::value + has_serializer_serialize<Ser, T>::value ; } } // anonymous namespace namespace serializer { template<class Ser, class T> inline enable_if<has_serializer_serialize<Ser, T>::value, void> read(Ser& ser, T&& value) { serialize(serializer_tag{}, ser, std::forward<T>(value)); } template<class Ser, class T> inline enable_if<has_serializer_read<Ser, T>::value, void> read(Ser& ser, T&& value) { read(serializer_tag{}, ser, std::forward<T>(value)); } template<class Ser, class T> inline enable_if<has_serializer_serialize<Ser, T>::value, void> write(Ser& ser, T const& value) { serialize(serializer_tag{}, ser, const_cast<remove_cvr<T>&>(value)); } template<class Ser, class T> inline enable_if<has_serializer_write<Ser, T>::value, void> write(Ser& ser, T const& value) { write(serializer_tag{}, ser, value); } } // namespace serializer // BaseSerializer implementation template<class Impl> inline Impl& BaseSerializer<Impl>::impl() { return static_cast<Impl&>(*this); } // InputSerializer implementation /// Read value. template<class Impl, class T> inline enable_if<serializer_read_num_defined<Impl, T>() == 1, Impl&> operator%( InputSerializer<Impl>& ser, T&& value ) { serializer::read(ser.impl(), std::forward<T>(value)); return ser.impl(); } /** @cond INTERNAL */ template<class Impl, class T> inline enable_if<serializer_read_num_defined<Impl, T>() != 1, Impl&> operator%( InputSerializer<Impl>& /*ser*/, T&& /*value*/ ) { static_assert( serializer_read_num_defined<Impl, T>() != 0, "no read-serialize function defined for T with this serializer" ); static_assert( serializer_read_num_defined<Impl, T>() <= 1, "ambiguous serialization interface defined for T with this serializer" " (both read() and serialize() are defined)" ); } /** @endcond */ // INTERNAL // OutputSerializer implementation /// Write value. template<class Impl, class T> inline enable_if<serializer_write_num_defined<Impl, T>() == 1, Impl&> operator%( OutputSerializer<Impl>& ser, T const& value ) { serializer::write(ser.impl(), value); return ser.impl(); } /** @cond INTERNAL */ template<class Impl, class T> inline enable_if<serializer_write_num_defined<Impl, T>() != 1, Impl&> operator%( OutputSerializer<Impl>& /*ser*/, T const& /*value*/ ) { static_assert( serializer_write_num_defined<Impl, T>() != 0, "no write-serialize function defined for T with this serializer" ); static_assert( serializer_write_num_defined<Impl, T>() <= 1, "ambiguous serialization interface defined for T with this serializer" " (both write() and serialize() are defined)" ); } /** @endcond */ // INTERNAL /** @} */ // end of doc-group serializer } // namespace togo <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2012 Heiko Strathmann */ #include <shogun/base/init.h> #include <shogun/statistics/QuadraticTimeMMD.h> #include <shogun/kernel/GaussianKernel.h> #include <shogun/kernel/CustomKernel.h> #include <shogun/features/DenseFeatures.h> #include <shogun/mathematics/Statistics.h> #include <shogun/features/DataGenerator.h> using namespace shogun; /** tests the quadratic mmd statistic for a single data case and ensures * equality with matlab implementation */ void test_quadratic_mmd_fixed() { index_t n=2; index_t d=3; float64_t sigma=2; float64_t sq_sigma_twice=sigma*sigma*2; SGMatrix<float64_t> data(d,2*n); for (index_t i=0; i<2*d*n; ++i) data.matrix[i]=i; CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data); CGaussianKernel* kernel=new CGaussianKernel(10, sq_sigma_twice); kernel->init(features, features); CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, n); /* unbiased statistic */ mmd->set_statistic_type(UNBIASED); float64_t difference=CMath::abs(mmd->compute_statistic()-0.051325806508381); ASSERT(difference<=10E-16); /* biased statistic */ mmd->set_statistic_type(BIASED); difference=CMath::abs(mmd->compute_statistic()-1.017107688196714); ASSERT(difference<=10E-16); SG_UNREF(mmd); } /** tests the quadratic mmd statistic bootstrapping for a random data case and * ensures equality with matlab implementation (unbiased statistic) */ void test_quadratic_mmd_bootstrap() { index_t dimension=3; index_t m=100; float64_t difference=0.5; float64_t sigma=2; index_t num_iterations=1000; num_iterations=10; //speed up SGMatrix<float64_t> data=CDataGenerator::generate_mean_data(m, dimension, difference); CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data); /* shoguns kernel width is different */ CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2); CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, m); mmd->set_statistic_type(UNBIASED); mmd->set_bootstrap_iterations(num_iterations); /* use fixed seed */ CMath::init_random(1); SGVector<float64_t> null_samples=mmd->bootstrap_null(); float64_t mean=CStatistics::mean(null_samples); float64_t var=CStatistics::variance(null_samples); /* MATLAB mean 2-sigma confidence interval for 1000 repretitions is * [-3.169406734013459e-04, 3.296399498466372e-04] */ SG_SPRINT("mean %f\n", mean); // ASSERT(mean>-3.169406734013459e-04); // ASSERT(mean<3.296399498466372e-04); /* MATLAB variance 2-sigma confidence interval for 1000 repretitions is * [2.194192869469228e-05,2.936672859339959e-05] */ SG_SPRINT("var %f\n", var); // ASSERT(var>2.194192869469228e-05); // ASSERT(var<2.936672859339959e-05); /* now again but with a precomputed kernel, same features. * This avoids re-computing the kernel matrix in every bootstrapping * iteration and should be num_iterations times faster */ SG_REF(features); CCustomKernel* precomputed_kernel=new CCustomKernel(kernel); SG_UNREF(mmd); mmd=new CQuadraticTimeMMD(precomputed_kernel, features, m); mmd->set_statistic_type(UNBIASED); mmd->set_bootstrap_iterations(num_iterations); CMath::init_random(1); null_samples=mmd->bootstrap_null(); /* assert that results do not change */ SG_SPRINT("mean %f, var %f\n", CStatistics::mean(null_samples), CStatistics::variance(null_samples)); ASSERT(CMath::abs(mean-CStatistics::mean(null_samples))<10E-5); ASSERT(CMath::abs(var-CStatistics::variance(null_samples))<10E-5); SG_UNREF(mmd); SG_UNREF(features); } #ifdef HAVE_LAPACK /** tests the quadratic mmd statistic threshold method spectrum for radnom data * case and ensures equality with matlab implementation */ void test_quadratic_mmd_spectrum() { index_t dimension=3; index_t m=100; float64_t difference=0.5; float64_t sigma=2; SGMatrix<float64_t> data=CDataGenerator::generate_mean_data(m, dimension, difference); CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data); /* shoguns kernel width is different */ CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2); CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, m); mmd->set_num_samples_sepctrum(1000); mmd->set_num_samples_sepctrum(10); //speed up mmd->set_num_eigenvalues_spectrum(m); mmd->set_null_approximation_method(MMD2_SPECTRUM); mmd->set_statistic_type(BIASED); /* compute p-value for a fixed statistic value */ float64_t p=mmd->compute_p_value(2); /* MATLAB 1000 iterations 3 sigma confidence interval is * [0.021240218376709, 0.060875781623291] */ SG_SPRINT("p %f\n", p); // ASSERT(p>0.021240218376709); // ASSERT(p<0.060875781623291); SG_UNREF(mmd); } #endif // HAVE_LAPACK /** tests the quadratic mmd statistic threshold method gamma for fixed data * case and ensures equality with matlab implementation */ void test_quadratic_mmd_gamma() { index_t dimension=3; index_t m=100; float64_t sigma=4; /* note: fixed data this time */ SGMatrix<float64_t> data(dimension, 2*m); for (index_t i=0; i<2*dimension*m; ++i) data.matrix[i]=i; CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data); /* shoguns kernel width is different */ CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2); CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, m); mmd->set_null_approximation_method(MMD2_GAMMA); mmd->set_statistic_type(BIASED); /* compute p-value for a fixed statistic value */ float64_t p=mmd->compute_p_value(2); SG_SPRINT("p: %f\n", p); /* MATLAB 1000 iterations mean: 0.511547577996229 with variance 10E-15, * asserting with only 10-12 to avoid problems. Shold never fail. */ ASSERT(CMath::abs(p-0.511547577996229)<10E-12); SG_UNREF(mmd); } /** tests the quadratic mmd statistic for a random data case (fixed distribution * and ensures equality with matlab implementation (unbiased case) */ void test_quadratic_mmd_random() { index_t dimension=3; index_t m=300; float64_t difference=0.5; float64_t sigma=2; index_t num_runs=100; num_runs=10; //speed up SGVector<float64_t> mmds(num_runs); /* pre-allocate data matrix and features, just change elements later */ SGMatrix<float64_t> data(dimension, 2*m); CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data); /* shoguns kernel width is different */ CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2); CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, m); mmd->set_statistic_type(UNBIASED); for (index_t i=0; i<num_runs; ++i) { /* use pre-allocated space for data generation */ CDataGenerator::generate_mean_data(m, dimension, difference, data); kernel->init(features, features); mmds[i]=mmd->compute_statistic(); } /* MATLAB 95% mean confidence interval 0.007495841715582 0.037960088792417 */ float64_t mean=CStatistics::mean(mmds); SG_SPRINT("mean %f\n", mean); // ASSERT((mean>0.007495841715582) && (mean<0.037960088792417)); /* MATLAB variance is 5.800439687240292e-05 quite stable */ float64_t variance=CStatistics::variance(mmds); SG_SPRINT("variance: %f\n", variance); // ASSERT(CMath::abs(variance-5.800439687240292e-05)<10E-5); SG_UNREF(mmd); } int main(int argc, char** argv) { init_shogun_with_defaults(); // sg_io->set_loglevel(MSG_DEBUG); /* all tests have been "speed up" by reducing the number of runs/samples. * If you have any doubts in the results, set all num_runs to original * numbers and activate asserts. If they fail, something is wrong. */ test_quadratic_mmd_fixed(); test_quadratic_mmd_random(); test_quadratic_mmd_bootstrap(); #ifdef HAVE_LAPACK test_quadratic_mmd_spectrum(); #endif test_quadratic_mmd_gamma(); exit_shogun(); return 0; } <commit_msg>made example work for recent bootstrapping changes<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2012 Heiko Strathmann */ #include <shogun/base/init.h> #include <shogun/statistics/QuadraticTimeMMD.h> #include <shogun/kernel/GaussianKernel.h> #include <shogun/kernel/CustomKernel.h> #include <shogun/features/DenseFeatures.h> #include <shogun/mathematics/Statistics.h> #include <shogun/features/DataGenerator.h> using namespace shogun; /** tests the quadratic mmd statistic for a single data case and ensures * equality with matlab implementation */ void test_quadratic_mmd_fixed() { index_t n=2; index_t d=3; float64_t sigma=2; float64_t sq_sigma_twice=sigma*sigma*2; SGMatrix<float64_t> data(d,2*n); for (index_t i=0; i<2*d*n; ++i) data.matrix[i]=i; CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data); CGaussianKernel* kernel=new CGaussianKernel(10, sq_sigma_twice); kernel->init(features, features); CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, n); /* unbiased statistic */ mmd->set_statistic_type(UNBIASED); float64_t difference=CMath::abs(mmd->compute_statistic()-0.051325806508381); ASSERT(difference<=10E-16); /* biased statistic */ mmd->set_statistic_type(BIASED); difference=CMath::abs(mmd->compute_statistic()-1.017107688196714); ASSERT(difference<=10E-16); SG_UNREF(mmd); } /** tests the quadratic mmd statistic bootstrapping for a random data case and * ensures equality with matlab implementation (unbiased statistic) */ void test_quadratic_mmd_bootstrap() { /* reproducable results */ CMath::init_random(1); index_t dimension=3; index_t m=100; float64_t difference=0.5; float64_t sigma=2; index_t num_iterations=1000; num_iterations=10; //speed up SGMatrix<float64_t> data=CDataGenerator::generate_mean_data(m, dimension, difference); CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data); /* shoguns kernel width is different */ CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2); CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, m); mmd->set_statistic_type(UNBIASED); mmd->set_bootstrap_iterations(num_iterations); /* use fixed seed */ CMath::init_random(1); SGVector<float64_t> null_samples=mmd->bootstrap_null(); float64_t mean=CStatistics::mean(null_samples); float64_t var=CStatistics::variance(null_samples); /* MATLAB mean 2-sigma confidence interval for 1000 repretitions is * [-3.169406734013459e-04, 3.296399498466372e-04] */ SG_SPRINT("mean %f\n", mean); // ASSERT(mean>-3.169406734013459e-04); // ASSERT(mean<3.296399498466372e-04); /* MATLAB variance 2-sigma confidence interval for 1000 repretitions is * [2.194192869469228e-05,2.936672859339959e-05] */ SG_SPRINT("var %f\n", var); // ASSERT(var>2.194192869469228e-05); // ASSERT(var<2.936672859339959e-05); /* now again but with a precomputed kernel, same features. * This avoids re-computing the kernel matrix in every bootstrapping * iteration and should be num_iterations times faster */ SG_REF(features); /* re-init kernel before kernel matrix is computed: this is due to a design * error in subsets and should be worked on! */ kernel->init(features, features); CCustomKernel* precomputed_kernel=new CCustomKernel(kernel); SG_UNREF(mmd); mmd=new CQuadraticTimeMMD(precomputed_kernel, features, m); mmd->set_statistic_type(UNBIASED); mmd->set_bootstrap_iterations(num_iterations); CMath::init_random(1); null_samples=mmd->bootstrap_null(); /* assert that results do not change */ SG_SPRINT("mean %f, var %f\n", CStatistics::mean(null_samples), CStatistics::variance(null_samples)); ASSERT(CMath::abs(mean-CStatistics::mean(null_samples))<10E-5); ASSERT(CMath::abs(var-CStatistics::variance(null_samples))<10E-5); SG_UNREF(mmd); SG_UNREF(features); } #ifdef HAVE_LAPACK /** tests the quadratic mmd statistic threshold method spectrum for radnom data * case and ensures equality with matlab implementation */ void test_quadratic_mmd_spectrum() { index_t dimension=3; index_t m=100; float64_t difference=0.5; float64_t sigma=2; SGMatrix<float64_t> data=CDataGenerator::generate_mean_data(m, dimension, difference); CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data); /* shoguns kernel width is different */ CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2); CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, m); mmd->set_num_samples_sepctrum(1000); mmd->set_num_samples_sepctrum(10); //speed up mmd->set_num_eigenvalues_spectrum(m); mmd->set_null_approximation_method(MMD2_SPECTRUM); mmd->set_statistic_type(BIASED); /* compute p-value for a fixed statistic value */ float64_t p=mmd->compute_p_value(2); /* MATLAB 1000 iterations 3 sigma confidence interval is * [0.021240218376709, 0.060875781623291] */ SG_SPRINT("p %f\n", p); // ASSERT(p>0.021240218376709); // ASSERT(p<0.060875781623291); SG_UNREF(mmd); } #endif // HAVE_LAPACK /** tests the quadratic mmd statistic threshold method gamma for fixed data * case and ensures equality with matlab implementation */ void test_quadratic_mmd_gamma() { index_t dimension=3; index_t m=100; float64_t sigma=4; /* note: fixed data this time */ SGMatrix<float64_t> data(dimension, 2*m); for (index_t i=0; i<2*dimension*m; ++i) data.matrix[i]=i; CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data); /* shoguns kernel width is different */ CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2); CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, m); mmd->set_null_approximation_method(MMD2_GAMMA); mmd->set_statistic_type(BIASED); /* compute p-value for a fixed statistic value */ float64_t p=mmd->compute_p_value(2); SG_SPRINT("p: %f\n", p); /* MATLAB 1000 iterations mean: 0.511547577996229 with variance 10E-15, * asserting with only 10-12 to avoid problems. Shold never fail. */ ASSERT(CMath::abs(p-0.511547577996229)<10E-12); SG_UNREF(mmd); } /** tests the quadratic mmd statistic for a random data case (fixed distribution * and ensures equality with matlab implementation (unbiased case) */ void test_quadratic_mmd_random() { index_t dimension=3; index_t m=300; float64_t difference=0.5; float64_t sigma=2; index_t num_runs=100; num_runs=10; //speed up SGVector<float64_t> mmds(num_runs); /* pre-allocate data matrix and features, just change elements later */ SGMatrix<float64_t> data(dimension, 2*m); CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>(data); /* shoguns kernel width is different */ CGaussianKernel* kernel=new CGaussianKernel(100, sigma*sigma*2); CQuadraticTimeMMD* mmd=new CQuadraticTimeMMD(kernel, features, m); mmd->set_statistic_type(UNBIASED); for (index_t i=0; i<num_runs; ++i) { /* use pre-allocated space for data generation */ CDataGenerator::generate_mean_data(m, dimension, difference, data); kernel->init(features, features); mmds[i]=mmd->compute_statistic(); } /* MATLAB 95% mean confidence interval 0.007495841715582 0.037960088792417 */ float64_t mean=CStatistics::mean(mmds); SG_SPRINT("mean %f\n", mean); // ASSERT((mean>0.007495841715582) && (mean<0.037960088792417)); /* MATLAB variance is 5.800439687240292e-05 quite stable */ float64_t variance=CStatistics::variance(mmds); SG_SPRINT("variance: %f\n", variance); // ASSERT(CMath::abs(variance-5.800439687240292e-05)<10E-5); SG_UNREF(mmd); } int main(int argc, char** argv) { init_shogun_with_defaults(); // sg_io->set_loglevel(MSG_DEBUG); /* all tests have been "speed up" by reducing the number of runs/samples. * If you have any doubts in the results, set all num_runs to original * numbers and activate asserts. If they fail, something is wrong. */ test_quadratic_mmd_fixed(); test_quadratic_mmd_random(); test_quadratic_mmd_bootstrap(); #ifdef HAVE_LAPACK test_quadratic_mmd_spectrum(); #endif test_quadratic_mmd_gamma(); exit_shogun(); return 0; } <|endoftext|>
<commit_before>#include <check.hpp> #include <kdb.hpp> #include <plugin.hpp> #include <modules.hpp> #include <cmdline.hpp> #include <iostream> using namespace std; using namespace kdb; using namespace kdb::tools; CheckCommand::CheckCommand() {} int printProblems(Key k, std::string action, int off) { bool wo = k.getMeta<const kdb::Key>("warnings"); bool eo = k.getMeta<const kdb::Key>("error"); if (wo || eo) std::cerr << action << " of kdb yield following problems:" << std::endl; printWarnings(cerr, k); return (wo + eo * 2) << off; } int CheckCommand::execute(Cmdline const& cl) { if (cl.arguments.size() == 0) { int ret = 0; Key x; KDB kdb (x); ret += printProblems(x, "opening", 0); KeySet ks; Key a("/", KEY_END); kdb.get(ks, a); ret += printProblems(a, "getting", 2); if (cl.force) { Key b("/", KEY_END); kdb.set(ks, b); ret += printProblems(b, "setting", 4); } Key y; kdb.close(y); ret += printProblems(y, "closing", 6); return ret; } if (cl.arguments.size() != 1) { throw invalid_argument ("One argument required"); } std::string name = cl.arguments[0]; Modules modules; if (cl.verbose) cout << "will try check the plugin " << name << endl; vector<string> warnings; try { KeySet ks = cl.getPluginsConfig(); PluginPtr plugin; if (ks.size() == 0) { plugin = modules.load(name); } else { plugin = modules.load(name, ks); } plugin->check(warnings); } catch (NoPlugin const& p) { cerr << p.what() << endl; return 1; } catch (PluginCheckException const& p) { cerr << "Plugin did not pass all checks:" << endl; cerr << "See description below:" << endl; cerr << p.what() << endl; return 2; } if (warnings.size() > 0) { cerr << "There are " << warnings.size() << " Warnings for this plugin" << endl; cerr << "For high quality plugins there should be no warning" << endl; for (size_t i = 0; i < warnings.size(); ++i) { cerr << "Warning #" << i << ": " << warnings[i] << endl; } return 3; } return 0; } CheckCommand::~CheckCommand() {} <commit_msg>fix problem discussed in #304<commit_after>#include <check.hpp> #include <kdb.hpp> #include <plugin.hpp> #include <modules.hpp> #include <cmdline.hpp> #include <iostream> using namespace std; using namespace kdb; using namespace kdb::tools; CheckCommand::CheckCommand() {} int printProblems(Key k, std::string action, int off) { bool wo = k.getMeta<const kdb::Key>("warnings"); bool eo = k.getMeta<const kdb::Key>("error"); if (wo || eo) std::cerr << "\n======\n" << action << " of kdb yield following problems:" << std::endl; printWarnings(cerr, k); printError(cerr, k); return (wo + eo * 2) << off; } int CheckCommand::execute(Cmdline const& cl) { if (cl.arguments.size() == 0) { Key x; try { int ret = 0; KDB kdb (x); ret += printProblems(x, "opening", 0); KeySet ks; Key a("/", KEY_END); try {kdb.get(ks, a);} catch(...) {} ret += printProblems(a, "getting", 2); if (cl.force) { Key b("/", KEY_END); try{kdb.set(ks, b);} catch(...) {} ret += printProblems(b, "setting", 4); } Key y; kdb.close(y); ret += printProblems(y, "closing", 6); return ret; } catch(KDBException const & e) { std::cerr << "a fatal problem occurred, could not open KDB. This should not happen" << std::endl; return printProblems(x, "opening", 0); } } if (cl.arguments.size() != 1) { throw invalid_argument ("One argument required"); } std::string name = cl.arguments[0]; Modules modules; if (cl.verbose) cout << "will try check the plugin " << name << endl; vector<string> warnings; try { KeySet ks = cl.getPluginsConfig(); PluginPtr plugin; if (ks.size() == 0) { plugin = modules.load(name); } else { plugin = modules.load(name, ks); } plugin->check(warnings); } catch (NoPlugin const& p) { cerr << p.what() << endl; return 1; } catch (PluginCheckException const& p) { cerr << "Plugin did not pass all checks:" << endl; cerr << "See description below:" << endl; cerr << p.what() << endl; return 2; } if (warnings.size() > 0) { cerr << "There are " << warnings.size() << " Warnings for this plugin" << endl; cerr << "For high quality plugins there should be no warning" << endl; for (size_t i = 0; i < warnings.size(); ++i) { cerr << "Warning #" << i << ": " << warnings[i] << endl; } return 3; } return 0; } CheckCommand::~CheckCommand() {} <|endoftext|>
<commit_before>#include "tracefilelister.h" #include "ui_tracefilelister.h" #include <QVBoxLayout> #include <QLabel> #include <QDir> #include <QFile> #include <QFileInfo> #include <QTreeWidgetItem> #include <QDebug> TraceFileLister::TraceFileLister(QWidget *parent) : QDockWidget("Traces", parent) { tree = new QTreeWidget(this); tree->setColumnCount(1); tree->clear(); tree->setHeaderLabel("Filename"); this->setWidget(tree); connect(tree, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(traceSelected(QTreeWidgetItem*,int))); } TraceFileLister::~TraceFileLister() {} void TraceFileLister::addFolderToTree(QTreeWidgetItem * parent, QString dir) { QDir * root = new QDir(dir); QStringList l = root->entryList(); QTreeWidgetItem * j; for (auto o : l) { if (o != "." && o != "..") { j = new QTreeWidgetItem(parent); j->setText(0, o); QString newDir = root->absoluteFilePath(o); QFileInfo * fi = new QFileInfo(newDir); if (fi->isDir()) { addFolderToTree(j, newDir); } delete fi; } } delete root; } void TraceFileLister::update(QString path) { QFileInfo * fi = new QFileInfo(path); if (fi->isDir()) { tree->clear(); tree->setHeaderLabel(fi->absoluteFilePath()); QTreeWidgetItem * j = new QTreeWidgetItem(tree); j->setText(0, fi->absoluteFilePath()); addFolderToTree(j, path); } delete fi; } void TraceFileLister::traceSelected(QTreeWidgetItem * i, int col) { QString fullPath; do { fullPath.insert(0, "/" + i->text(col)); i = i->parent(); } while (i != 0); fullPath.remove(0, 1); emit traceChosen(fullPath); } <commit_msg>File list starts expanded<commit_after>#include "tracefilelister.h" #include "ui_tracefilelister.h" #include <QVBoxLayout> #include <QLabel> #include <QDir> #include <QFile> #include <QFileInfo> #include <QTreeWidgetItem> #include <QDebug> TraceFileLister::TraceFileLister(QWidget *parent) : QDockWidget("Traces", parent) { tree = new QTreeWidget(this); tree->setColumnCount(1); tree->clear(); tree->setHeaderLabel("Filename"); this->setWidget(tree); connect(tree, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(traceSelected(QTreeWidgetItem*,int))); } TraceFileLister::~TraceFileLister() {} void TraceFileLister::addFolderToTree(QTreeWidgetItem * parent, QString dir) { QDir * root = new QDir(dir); QStringList l = root->entryList(); QTreeWidgetItem * j; for (auto o : l) { if (o != "." && o != "..") { j = new QTreeWidgetItem(parent); j->setText(0, o); QString newDir = root->absoluteFilePath(o); QFileInfo * fi = new QFileInfo(newDir); if (fi->isDir()) { addFolderToTree(j, newDir); } delete fi; } } delete root; } void TraceFileLister::update(QString path) { QFileInfo * fi = new QFileInfo(path); if (fi->isDir()) { tree->clear(); tree->setHeaderLabel(fi->absoluteFilePath()); QTreeWidgetItem * j = new QTreeWidgetItem(tree); j->setText(0, fi->absoluteFilePath()); addFolderToTree(j, path); j->setExpanded(true); } delete fi; } void TraceFileLister::traceSelected(QTreeWidgetItem * i, int col) { QString fullPath; do { fullPath.insert(0, "/" + i->text(col)); i = i->parent(); } while (i != 0); fullPath.remove(0, 1); emit traceChosen(fullPath); } <|endoftext|>
<commit_before>/* Copyright (c) 2003, 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 <vector> #include <iostream> #include <cctype> #include <iomanip> #include <sstream> #include "zlib.h" #include "libtorrent/tracker_manager.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/udp_tracker_connection.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/torrent.hpp" using namespace libtorrent; namespace { enum { minimum_tracker_response_length = 3, http_buffer_size = 2048 }; enum { FTEXT = 0x01, FHCRC = 0x02, FEXTRA = 0x04, FNAME = 0x08, FCOMMENT = 0x10, FRESERVED = 0xe0, GZIP_MAGIC0 = 0x1f, GZIP_MAGIC1 = 0x8b }; } namespace libtorrent { // returns -1 if gzip header is invalid or the header size in bytes int gzip_header(const char* buf, int size) { assert(buf != 0); assert(size > 0); const unsigned char* buffer = reinterpret_cast<const unsigned char*>(buf); const int total_size = size; // The zip header cannot be shorter than 10 bytes if (size < 10) return -1; // check the magic header of gzip if ((buffer[0] != GZIP_MAGIC0) || (buffer[1] != GZIP_MAGIC1)) return -1; int method = buffer[2]; int flags = buffer[3]; // check for reserved flag and make sure it's compressed with the correct metod if (method != Z_DEFLATED || (flags & FRESERVED) != 0) return -1; // skip time, xflags, OS code size -= 10; buffer += 10; if (flags & FEXTRA) { int extra_len; if (size < 2) return -1; extra_len = (buffer[1] << 8) | buffer[0]; if (size < (extra_len+2)) return -1; size -= (extra_len + 2); buffer += (extra_len + 2); } if (flags & FNAME) { while (size && *buffer) { --size; ++buffer; } if (!size || *buffer) return -1; --size; ++buffer; } if (flags & FCOMMENT) { while (size && *buffer) { --size; ++buffer; } if (!size || *buffer) return -1; --size; ++buffer; } if (flags & FHCRC) { if (size < 2) return -1; size -= 2; buffer += 2; } return total_size - size; } bool inflate_gzip( std::vector<char>& buffer , request_callback* requester , int maximum_tracker_response_length) { assert(maximum_tracker_response_length > 0); int header_len = gzip_header(&buffer[0], (int)buffer.size()); if (header_len < 0) { requester->tracker_request_error(200, "invalid gzip header in tracker response"); return true; } // start off wth one kilobyte and grow // if needed std::vector<char> inflate_buffer(1024); // initialize the zlib-stream z_stream str; // subtract 8 from the end of the buffer since that's CRC32 and input size // and those belong to the gzip file str.avail_in = (int)buffer.size() - header_len - 8; str.next_in = reinterpret_cast<Bytef*>(&buffer[header_len]); str.next_out = reinterpret_cast<Bytef*>(&inflate_buffer[0]); str.avail_out = (int)inflate_buffer.size(); str.zalloc = Z_NULL; str.zfree = Z_NULL; str.opaque = 0; // -15 is really important. It will make inflate() not look for a zlib header // and just deflate the buffer if (inflateInit2(&str, -15) != Z_OK) { requester->tracker_request_error(200, "gzip out of memory"); return true; } // inflate and grow inflate_buffer as needed int ret = inflate(&str, Z_SYNC_FLUSH); while (ret == Z_OK) { if (str.avail_out == 0) { if (inflate_buffer.size() >= (unsigned)maximum_tracker_response_length) { inflateEnd(&str); requester->tracker_request_error(200, "tracker response too large"); return true; } int new_size = (int)inflate_buffer.size() * 2; if (new_size > maximum_tracker_response_length) new_size = maximum_tracker_response_length; int old_size = (int)inflate_buffer.size(); inflate_buffer.resize(new_size); str.next_out = reinterpret_cast<Bytef*>(&inflate_buffer[old_size]); str.avail_out = new_size - old_size; } ret = inflate(&str, Z_SYNC_FLUSH); } inflate_buffer.resize(inflate_buffer.size() - str.avail_out); inflateEnd(&str); if (ret != Z_STREAM_END) { requester->tracker_request_error(200, "gzip error"); return true; } // commit the resulting buffer std::swap(buffer, inflate_buffer); return false; } std::string base64encode(const std::string& s) { static const char base64_table[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; unsigned char inbuf[3]; unsigned char outbuf[4]; std::string ret; for (std::string::const_iterator i = s.begin(); i != s.end();) { // available input is 1,2 or 3 bytes // since we read 3 bytes at a time at most int available_input = std::min(3, (int)std::distance(i, s.end())); // clear input buffer std::fill(inbuf, inbuf+3, 0); // read a chunk of input into inbuf for (int j = 0; j < available_input; ++j) { inbuf[j] = *i; ++i; } // encode inbuf to outbuf outbuf[0] = (inbuf[0] & 0xfc) >> 2; outbuf[1] = ((inbuf[0] & 0x03) << 4) | ((inbuf [1] & 0xf0) >> 4); outbuf[2] = ((inbuf[1] & 0x0f) << 2) | ((inbuf [2] & 0xc0) >> 6); outbuf[3] = inbuf[2] & 0x3f; // write output for (int j = 0; j < available_input+1; ++j) { ret += base64_table[outbuf[j]]; } // write pad for (int j = 0; j < 3 - available_input; ++j) { ret += '='; } } return ret; } void tracker_manager::tick() { std::vector<boost::shared_ptr<tracker_connection> >::iterator i; for (i = m_connections.begin(); i != m_connections.end(); ++i) { boost::shared_ptr<tracker_connection>& c = *i; try { if (!c->tick()) return; } catch (const std::exception& e) { if (c->requester()) c->requester()->tracker_request_error(-1, e.what()); } if (c->requester()) c->requester()->m_manager = 0; m_connections.erase(i); --i; // compensate for the remove } } void tracker_manager::queue_request( tracker_request const& req , request_callback* c , std::string const& password) { try { std::string hostname; // hostname only std::string protocol; // should be http int port = 80; // PARSE URL std::string::const_iterator start = req.url.begin(); std::string::const_iterator end = std::find(req.url.begin(), req.url.end(), ':'); protocol = std::string(start, end); if (end == req.url.end()) throw std::runtime_error("invalid url"); ++end; if (end == req.url.end()) throw std::runtime_error("invalid url"); if (*end != '/') throw std::runtime_error("invalid url"); ++end; if (end == req.url.end()) throw std::runtime_error("invalid url"); if (*end != '/') throw std::runtime_error("invalid url"); ++end; start = end; end = std::find(start, req.url.end(), '/'); std::string::const_iterator port_pos = std::find(start, req.url.end(), ':'); if (port_pos < end) { hostname.assign(start, port_pos); ++port_pos; try { port = boost::lexical_cast<int>(std::string(port_pos, end)); } catch(boost::bad_lexical_cast&) { throw std::runtime_error("invalid url"); } } else { hostname.assign(start, end); } start = end; std::string request_string = std::string(start, req.url.end()); boost::shared_ptr<tracker_connection> con; if (protocol == "http") { con.reset(new http_tracker_connection( req , hostname , port , request_string , c , m_settings , password)); } else if (protocol == "udp") { con.reset(new udp_tracker_connection( req , hostname , port , c , m_settings)); } else { throw std::runtime_error("unkown protocol in tracker url"); } m_connections.push_back(con); if (con->requester()) con->requester()->m_manager = this; } catch (std::exception& e) { if (c) c->tracker_request_error(-1, e.what()); } } void tracker_manager::abort_request(request_callback* c) { assert(c != 0); std::vector<boost::shared_ptr<tracker_connection> >::iterator i; for (i = m_connections.begin(); i != m_connections.end(); ++i) { if ((*i)->requester() == c) { m_connections.erase(i); break; } } } void tracker_manager::abort_all_requests() { // removes all connections from m_connections // except those with a requester == 0 (since those are // 'event=stopped'-requests) std::vector<boost::shared_ptr<tracker_connection> > keep_connections; for (std::vector<boost::shared_ptr<tracker_connection> >::const_iterator i = m_connections.begin(); i != m_connections.end(); ++i) { if ((*i)->requester() == 0) keep_connections.push_back(*i); } std::swap(m_connections, keep_connections); } bool tracker_manager::send_finished() const { for (std::vector<boost::shared_ptr<tracker_connection> >::const_iterator i = m_connections.begin(); i != m_connections.end(); ++i) { if (!(*i)->send_finished()) return false; } return true; } } <commit_msg>*** empty log message ***<commit_after>/* Copyright (c) 2003, 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 <vector> #include <iostream> #include <cctype> #include <iomanip> #include <sstream> #include "zlib.h" #include "libtorrent/tracker_manager.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/udp_tracker_connection.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/torrent.hpp" using namespace libtorrent; namespace { enum { minimum_tracker_response_length = 3, http_buffer_size = 2048 }; enum { FTEXT = 0x01, FHCRC = 0x02, FEXTRA = 0x04, FNAME = 0x08, FCOMMENT = 0x10, FRESERVED = 0xe0, GZIP_MAGIC0 = 0x1f, GZIP_MAGIC1 = 0x8b }; } namespace libtorrent { // returns -1 if gzip header is invalid or the header size in bytes int gzip_header(const char* buf, int size) { assert(buf != 0); assert(size > 0); const unsigned char* buffer = reinterpret_cast<const unsigned char*>(buf); const int total_size = size; // The zip header cannot be shorter than 10 bytes if (size < 10) return -1; // check the magic header of gzip if ((buffer[0] != GZIP_MAGIC0) || (buffer[1] != GZIP_MAGIC1)) return -1; int method = buffer[2]; int flags = buffer[3]; // check for reserved flag and make sure it's compressed with the correct metod if (method != Z_DEFLATED || (flags & FRESERVED) != 0) return -1; // skip time, xflags, OS code size -= 10; buffer += 10; if (flags & FEXTRA) { int extra_len; if (size < 2) return -1; extra_len = (buffer[1] << 8) | buffer[0]; if (size < (extra_len+2)) return -1; size -= (extra_len + 2); buffer += (extra_len + 2); } if (flags & FNAME) { while (size && *buffer) { --size; ++buffer; } if (!size || *buffer) return -1; --size; ++buffer; } if (flags & FCOMMENT) { while (size && *buffer) { --size; ++buffer; } if (!size || *buffer) return -1; --size; ++buffer; } if (flags & FHCRC) { if (size < 2) return -1; size -= 2; buffer += 2; } return total_size - size; } bool inflate_gzip( std::vector<char>& buffer , request_callback* requester , int maximum_tracker_response_length) { assert(maximum_tracker_response_length > 0); int header_len = gzip_header(&buffer[0], (int)buffer.size()); if (header_len < 0) { requester->tracker_request_error(200, "invalid gzip header in tracker response"); return true; } // start off wth one kilobyte and grow // if needed std::vector<char> inflate_buffer(1024); // initialize the zlib-stream z_stream str; // subtract 8 from the end of the buffer since that's CRC32 and input size // and those belong to the gzip file str.avail_in = (int)buffer.size() - header_len - 8; str.next_in = reinterpret_cast<Bytef*>(&buffer[header_len]); str.next_out = reinterpret_cast<Bytef*>(&inflate_buffer[0]); str.avail_out = (int)inflate_buffer.size(); str.zalloc = Z_NULL; str.zfree = Z_NULL; str.opaque = 0; // -15 is really important. It will make inflate() not look for a zlib header // and just deflate the buffer if (inflateInit2(&str, -15) != Z_OK) { requester->tracker_request_error(200, "gzip out of memory"); return true; } // inflate and grow inflate_buffer as needed int ret = inflate(&str, Z_SYNC_FLUSH); while (ret == Z_OK) { if (str.avail_out == 0) { if (inflate_buffer.size() >= (unsigned)maximum_tracker_response_length) { inflateEnd(&str); requester->tracker_request_error(200, "tracker response too large"); return true; } int new_size = (int)inflate_buffer.size() * 2; if (new_size > maximum_tracker_response_length) new_size = maximum_tracker_response_length; int old_size = (int)inflate_buffer.size(); inflate_buffer.resize(new_size); str.next_out = reinterpret_cast<Bytef*>(&inflate_buffer[old_size]); str.avail_out = new_size - old_size; } ret = inflate(&str, Z_SYNC_FLUSH); } inflate_buffer.resize(inflate_buffer.size() - str.avail_out); inflateEnd(&str); if (ret != Z_STREAM_END) { requester->tracker_request_error(200, "gzip error"); return true; } // commit the resulting buffer std::swap(buffer, inflate_buffer); return false; } std::string base64encode(const std::string& s) { static const char base64_table[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; unsigned char inbuf[3]; unsigned char outbuf[4]; std::string ret; for (std::string::const_iterator i = s.begin(); i != s.end();) { // available input is 1,2 or 3 bytes // since we read 3 bytes at a time at most int available_input = std::min(3, (int)std::distance(i, s.end())); // clear input buffer std::fill(inbuf, inbuf+3, 0); // read a chunk of input into inbuf for (int j = 0; j < available_input; ++j) { inbuf[j] = *i; ++i; } // encode inbuf to outbuf outbuf[0] = (inbuf[0] & 0xfc) >> 2; outbuf[1] = ((inbuf[0] & 0x03) << 4) | ((inbuf [1] & 0xf0) >> 4); outbuf[2] = ((inbuf[1] & 0x0f) << 2) | ((inbuf [2] & 0xc0) >> 6); outbuf[3] = inbuf[2] & 0x3f; // write output for (int j = 0; j < available_input+1; ++j) { ret += base64_table[outbuf[j]]; } // write pad for (int j = 0; j < 3 - available_input; ++j) { ret += '='; } } return ret; } void tracker_manager::tick() { std::vector<boost::shared_ptr<tracker_connection> >::iterator i; for (i = m_connections.begin(); i != m_connections.end(); ++i) { boost::shared_ptr<tracker_connection>& c = *i; try { if (!c->tick()) continue; } catch (const std::exception& e) { if (c->requester()) c->requester()->tracker_request_error(-1, e.what()); } if (c->requester()) c->requester()->m_manager = 0; m_connections.erase(i); --i; // compensate for the remove } } void tracker_manager::queue_request( tracker_request const& req , request_callback* c , std::string const& password) { try { std::string hostname; // hostname only std::string protocol; // should be http int port = 80; // PARSE URL std::string::const_iterator start = req.url.begin(); std::string::const_iterator end = std::find(req.url.begin(), req.url.end(), ':'); protocol = std::string(start, end); if (end == req.url.end()) throw std::runtime_error("invalid url"); ++end; if (end == req.url.end()) throw std::runtime_error("invalid url"); if (*end != '/') throw std::runtime_error("invalid url"); ++end; if (end == req.url.end()) throw std::runtime_error("invalid url"); if (*end != '/') throw std::runtime_error("invalid url"); ++end; start = end; end = std::find(start, req.url.end(), '/'); std::string::const_iterator port_pos = std::find(start, req.url.end(), ':'); if (port_pos < end) { hostname.assign(start, port_pos); ++port_pos; try { port = boost::lexical_cast<int>(std::string(port_pos, end)); } catch(boost::bad_lexical_cast&) { throw std::runtime_error("invalid url"); } } else { hostname.assign(start, end); } start = end; std::string request_string = std::string(start, req.url.end()); boost::shared_ptr<tracker_connection> con; if (protocol == "http") { con.reset(new http_tracker_connection( req , hostname , port , request_string , c , m_settings , password)); } else if (protocol == "udp") { con.reset(new udp_tracker_connection( req , hostname , port , c , m_settings)); } else { throw std::runtime_error("unkown protocol in tracker url"); } m_connections.push_back(con); if (con->requester()) con->requester()->m_manager = this; } catch (std::exception& e) { if (c) c->tracker_request_error(-1, e.what()); } } void tracker_manager::abort_request(request_callback* c) { assert(c != 0); std::vector<boost::shared_ptr<tracker_connection> >::iterator i; for (i = m_connections.begin(); i != m_connections.end(); ++i) { if ((*i)->requester() == c) { m_connections.erase(i); break; } } } void tracker_manager::abort_all_requests() { // removes all connections from m_connections // except those with a requester == 0 (since those are // 'event=stopped'-requests) std::vector<boost::shared_ptr<tracker_connection> > keep_connections; for (std::vector<boost::shared_ptr<tracker_connection> >::const_iterator i = m_connections.begin(); i != m_connections.end(); ++i) { if ((*i)->requester() == 0) keep_connections.push_back(*i); } std::swap(m_connections, keep_connections); } bool tracker_manager::send_finished() const { for (std::vector<boost::shared_ptr<tracker_connection> >::const_iterator i = m_connections.begin(); i != m_connections.end(); ++i) { if (!(*i)->send_finished()) return false; } return true; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2008 Google, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include "Gradient.h" #include "CSSParser.h" #include "GraphicsContext.h" #include "SkGradientShader.h" #include "SkiaUtils.h" namespace WebCore { void Gradient::platformDestroy() { if (m_gradient) m_gradient->safeUnref(); m_gradient = 0; } static inline U8CPU F2B(float x) { return static_cast<int>(x * 255); } static SkColor makeSkColor(float a, float r, float g, float b) { return SkColorSetARGB(F2B(a), F2B(r), F2B(g), F2B(b)); } // Determine the total number of stops needed, including pseudo-stops at the // ends as necessary. static size_t total_stops_needed(const Gradient::ColorStop* stopData, size_t count) { const Gradient::ColorStop* stop = stopData; size_t count_used = count; if (count < 1 || stop->stop > 0.0) count_used++; stop += count - 1; if (count < 2 || stop->stop < 1.0) count_used++; return count_used; } // Collect sorted stop position and color information into the pos and colors // buffers, ensuring stops at both 0.0 and 1.0. The buffers must be large // enough to hold information for all stops, including the new endpoints if // stops at 0.0 and 1.0 aren't already included. static void fill_stops(const Gradient::ColorStop* stopData, size_t count, SkScalar* pos, SkColor* colors) { const Gradient::ColorStop* stop = stopData; size_t start = 0; if (count < 1) { // A gradient with no stops must be transparent black. pos[0] = WebCoreFloatToSkScalar(0.0); colors[0] = makeSkColor(0.0, 0.0, 0.0, 0.0); start = 1; } else if (stop->stop > 0.0) { // Copy the first stop to 0.0. The first stop position may have a slight // rounding error, but we don't care in this float comparison, since // 0.0 comes through cleanly and people aren't likely to want a gradient // with a stop at (0 + epsilon). pos[0] = WebCoreFloatToSkScalar(0.0); colors[0] = makeSkColor(stop->alpha, stop->red, stop->green, stop->blue); start = 1; } for (size_t i = start; i < start + count; i++) { pos[i] = WebCoreFloatToSkScalar(stop->stop); colors[i] = makeSkColor(stop->alpha, stop->red, stop->green, stop->blue); ++stop; } // Copy the last stop to 1.0 if needed. See comment above about this float // comparison. if (count < 1 || (--stop)->stop < 1.0) { pos[start + count] = WebCoreFloatToSkScalar(1.0); colors[start + count] = colors[start + count - 1]; } } SkShader* Gradient::platformGradient() { if (m_gradient) return m_gradient; size_t count_used = total_stops_needed(m_stops.data(), m_stops.size()); ASSERT(count_used >= 2); ASSERT(count_used >= m_stops.size()); // FIXME: Why is all this manual pointer math needed?! SkAutoMalloc storage(count_used * (sizeof(SkColor) + sizeof(SkScalar))); SkColor* colors = (SkColor*)storage.get(); SkScalar* pos = (SkScalar*)(colors + count_used); fill_stops(m_stops.data(), m_stops.size(), pos, colors); if (m_radial) { // TODO(mmoss) CSS radial Gradients allow an offset focal point (the // "start circle"), but skia doesn't seem to support that, so this just // ignores m_p0/m_r0 and draws the gradient centered in the "end // circle" (m_p1/m_r1). // See http://webkit.org/blog/175/introducing-css-gradients/ for a // description of the expected behavior. m_gradient = SkGradientShader::CreateRadial(m_p1, WebCoreFloatToSkScalar(m_r1), colors, pos, static_cast<int>(count_used), SkShader::kClamp_TileMode); } else { SkPoint pts[2] = { m_p0, m_p1 }; m_gradient = SkGradientShader::CreateLinear(pts, colors, pos, static_cast<int>(count_used), SkShader::kClamp_TileMode); } return m_gradient; } void Gradient::fill(GraphicsContext* context, const FloatRect& rect) { context->setFillGradient(this); context->fillRect(rect); } } // namespace WebCore <commit_msg>Sort gradient stops before processing.<commit_after>/* * Copyright (C) 2008 Google, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include "Gradient.h" #include "CSSParser.h" #include "GraphicsContext.h" #include "SkGradientShader.h" #include "SkiaUtils.h" namespace WebCore { void Gradient::platformDestroy() { if (m_gradient) m_gradient->safeUnref(); m_gradient = 0; } static inline U8CPU F2B(float x) { return static_cast<int>(x * 255); } static SkColor makeSkColor(float a, float r, float g, float b) { return SkColorSetARGB(F2B(a), F2B(r), F2B(g), F2B(b)); } // Determine the total number of stops needed, including pseudo-stops at the // ends as necessary. static size_t total_stops_needed(const Gradient::ColorStop* stopData, size_t count) { const Gradient::ColorStop* stop = stopData; size_t count_used = count; if (count < 1 || stop->stop > 0.0) count_used++; stop += count - 1; if (count < 2 || stop->stop < 1.0) count_used++; return count_used; } // Collect sorted stop position and color information into the pos and colors // buffers, ensuring stops at both 0.0 and 1.0. The buffers must be large // enough to hold information for all stops, including the new endpoints if // stops at 0.0 and 1.0 aren't already included. static void fill_stops(const Gradient::ColorStop* stopData, size_t count, SkScalar* pos, SkColor* colors) { const Gradient::ColorStop* stop = stopData; size_t start = 0; if (count < 1) { // A gradient with no stops must be transparent black. pos[0] = WebCoreFloatToSkScalar(0.0); colors[0] = makeSkColor(0.0, 0.0, 0.0, 0.0); start = 1; } else if (stop->stop > 0.0) { // Copy the first stop to 0.0. The first stop position may have a slight // rounding error, but we don't care in this float comparison, since // 0.0 comes through cleanly and people aren't likely to want a gradient // with a stop at (0 + epsilon). pos[0] = WebCoreFloatToSkScalar(0.0); colors[0] = makeSkColor(stop->alpha, stop->red, stop->green, stop->blue); start = 1; } for (size_t i = start; i < start + count; i++) { pos[i] = WebCoreFloatToSkScalar(stop->stop); colors[i] = makeSkColor(stop->alpha, stop->red, stop->green, stop->blue); ++stop; } // Copy the last stop to 1.0 if needed. See comment above about this float // comparison. if (count < 1 || (--stop)->stop < 1.0) { pos[start + count] = WebCoreFloatToSkScalar(1.0); colors[start + count] = colors[start + count - 1]; } } static inline bool compareStops(const Gradient::ColorStop& a, const Gradient::ColorStop& b) { return a.stop < b.stop; } SkShader* Gradient::platformGradient() { if (m_gradient) return m_gradient; size_t count_used = total_stops_needed(m_stops.data(), m_stops.size()); ASSERT(count_used >= 2); ASSERT(count_used >= m_stops.size()); // FIXME: Why is all this manual pointer math needed?! SkAutoMalloc storage(count_used * (sizeof(SkColor) + sizeof(SkScalar))); SkColor* colors = (SkColor*)storage.get(); SkScalar* pos = (SkScalar*)(colors + count_used); // TODO: This and compareStops() are also in Gradient.cpp and // CSSGradientValue.cpp; probably should refactor in WebKit. if (!m_stopsSorted) { if (m_stops.size()) std::stable_sort(m_stops.begin(), m_stops.end(), compareStops); m_stopsSorted = true; } fill_stops(m_stops.data(), m_stops.size(), pos, colors); if (m_radial) { // TODO(mmoss) CSS radial Gradients allow an offset focal point (the // "start circle"), but skia doesn't seem to support that, so this just // ignores m_p0/m_r0 and draws the gradient centered in the "end // circle" (m_p1/m_r1). // See http://webkit.org/blog/175/introducing-css-gradients/ for a // description of the expected behavior. m_gradient = SkGradientShader::CreateRadial(m_p1, WebCoreFloatToSkScalar(m_r1), colors, pos, static_cast<int>(count_used), SkShader::kClamp_TileMode); } else { SkPoint pts[2] = { m_p0, m_p1 }; m_gradient = SkGradientShader::CreateLinear(pts, colors, pos, static_cast<int>(count_used), SkShader::kClamp_TileMode); } return m_gradient; } void Gradient::fill(GraphicsContext* context, const FloatRect& rect) { context->setFillGradient(this); context->fillRect(rect); } } // namespace WebCore <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/video_coding/main/source/receiver.h" #include <assert.h> #include "webrtc/modules/video_coding/main/source/encoded_frame.h" #include "webrtc/modules/video_coding/main/source/internal_defines.h" #include "webrtc/modules/video_coding/main/source/media_opt_util.h" #include "webrtc/system_wrappers/interface/clock.h" #include "webrtc/system_wrappers/interface/trace.h" #include "webrtc/system_wrappers/interface/trace_event.h" namespace webrtc { enum { kMaxReceiverDelayMs = 10000 }; VCMReceiver::VCMReceiver(VCMTiming* timing, Clock* clock, EventFactory* event_factory, int32_t vcm_id, int32_t receiver_id, bool master) : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()), vcm_id_(vcm_id), clock_(clock), receiver_id_(receiver_id), master_(master), jitter_buffer_(clock_, event_factory, vcm_id, receiver_id, master), timing_(timing), render_wait_event_(event_factory->CreateEvent()), state_(kPassive), max_video_delay_ms_(kMaxVideoDelayMs) {} VCMReceiver::~VCMReceiver() { render_wait_event_->Set(); delete crit_sect_; } void VCMReceiver::Reset() { CriticalSectionScoped cs(crit_sect_); if (!jitter_buffer_.Running()) { jitter_buffer_.Start(); } else { jitter_buffer_.Flush(); } render_wait_event_->Reset(); if (master_) { state_ = kReceiving; } else { state_ = kPassive; } } int32_t VCMReceiver::Initialize() { CriticalSectionScoped cs(crit_sect_); Reset(); if (!master_) { SetNackMode(kNoNack, -1, -1); } return VCM_OK; } void VCMReceiver::UpdateRtt(uint32_t rtt) { jitter_buffer_.UpdateRtt(rtt); } int32_t VCMReceiver::InsertPacket(const VCMPacket& packet, uint16_t frame_width, uint16_t frame_height) { if (packet.frameType == kVideoFrameKey) { WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "Inserting key frame packet seqnum=%u, timestamp=%u", packet.seqNum, packet.timestamp); } // Insert the packet into the jitter buffer. The packet can either be empty or // contain media at this point. bool retransmitted = false; const VCMFrameBufferEnum ret = jitter_buffer_.InsertPacket(packet, &retransmitted); if (ret == kOldPacket) { return VCM_OK; } else if (ret == kFlushIndicator) { return VCM_FLUSH_INDICATOR; } else if (ret < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "Error inserting packet seqnum=%u, timestamp=%u", packet.seqNum, packet.timestamp); return VCM_JITTER_BUFFER_ERROR; } if (ret == kCompleteSession && !retransmitted) { // We don't want to include timestamps which have suffered from // retransmission here, since we compensate with extra retransmission // delay within the jitter estimate. timing_->IncomingTimestamp(packet.timestamp, clock_->TimeInMilliseconds()); } if (master_) { // Only trace the primary receiver to make it possible to parse and plot // the trace file. WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "Packet seqnum=%u timestamp=%u inserted at %u", packet.seqNum, packet.timestamp, MaskWord64ToUWord32(clock_->TimeInMilliseconds())); } return VCM_OK; } VCMEncodedFrame* VCMReceiver::FrameForDecoding( uint16_t max_wait_time_ms, int64_t& next_render_time_ms, bool render_timing, VCMReceiver* dual_receiver) { const int64_t start_time_ms = clock_->TimeInMilliseconds(); uint32_t frame_timestamp = 0; // Exhaust wait time to get a complete frame for decoding. bool found_frame = jitter_buffer_.NextCompleteTimestamp( max_wait_time_ms, &frame_timestamp); if (!found_frame) { // Get an incomplete frame when enabled. const bool dual_receiver_enabled_and_passive = (dual_receiver != NULL && dual_receiver->State() == kPassive && dual_receiver->NackMode() == kNack); if (dual_receiver_enabled_and_passive && !jitter_buffer_.CompleteSequenceWithNextFrame()) { // Jitter buffer state might get corrupt with this frame. dual_receiver->CopyJitterBufferStateFromReceiver(*this); } found_frame = jitter_buffer_.NextMaybeIncompleteTimestamp( &frame_timestamp); } if (!found_frame) { return NULL; } // We have a frame - Set timing and render timestamp. timing_->SetJitterDelay(jitter_buffer_.EstimatedJitterMs()); const int64_t now_ms = clock_->TimeInMilliseconds(); timing_->UpdateCurrentDelay(frame_timestamp); next_render_time_ms = timing_->RenderTimeMs(frame_timestamp, now_ms); // Check render timing. bool timing_error = false; // Assume that render timing errors are due to changes in the video stream. if (next_render_time_ms < 0) { timing_error = true; } else if (abs(next_render_time_ms - now_ms) > max_video_delay_ms_) { WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "This frame is out of our delay bounds, resetting jitter " "buffer: %d > %d", static_cast<int>(abs(next_render_time_ms - now_ms)), max_video_delay_ms_); timing_error = true; } else if (static_cast<int>(timing_->TargetVideoDelay()) > max_video_delay_ms_) { WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "More than %u ms target delay. Flushing jitter buffer and" "resetting timing.", max_video_delay_ms_); timing_error = true; } if (timing_error) { // Timing error => reset timing and flush the jitter buffer. jitter_buffer_.Flush(); timing_->Reset(); return NULL; } if (!render_timing) { // Decode frame as close as possible to the render timestamp. const int32_t available_wait_time = max_wait_time_ms - static_cast<int32_t>(clock_->TimeInMilliseconds() - start_time_ms); uint16_t new_max_wait_time = static_cast<uint16_t>( VCM_MAX(available_wait_time, 0)); uint32_t wait_time_ms = timing_->MaxWaitingTime( next_render_time_ms, clock_->TimeInMilliseconds()); if (new_max_wait_time < wait_time_ms) { // We're not allowed to wait until the frame is supposed to be rendered, // waiting as long as we're allowed to avoid busy looping, and then return // NULL. Next call to this function might return the frame. render_wait_event_->Wait(max_wait_time_ms); return NULL; } // Wait until it's time to render. render_wait_event_->Wait(wait_time_ms); } // Extract the frame from the jitter buffer and set the render time. VCMEncodedFrame* frame = jitter_buffer_.ExtractAndSetDecode(frame_timestamp); if (frame == NULL) { return NULL; } frame->SetRenderTime(next_render_time_ms); TRACE_EVENT_ASYNC_STEP1("webrtc", "Video", frame->TimeStamp(), "SetRenderTS", "render_time", next_render_time_ms); if (dual_receiver != NULL) { dual_receiver->UpdateState(*frame); } if (!frame->Complete()) { // Update stats for incomplete frames. bool retransmitted = false; const int64_t last_packet_time_ms = jitter_buffer_.LastPacketTime(frame, &retransmitted); if (last_packet_time_ms >= 0 && !retransmitted) { // We don't want to include timestamps which have suffered from // retransmission here, since we compensate with extra retransmission // delay within the jitter estimate. timing_->IncomingTimestamp(frame_timestamp, last_packet_time_ms); } } return frame; } void VCMReceiver::ReleaseFrame(VCMEncodedFrame* frame) { jitter_buffer_.ReleaseFrame(frame); } void VCMReceiver::ReceiveStatistics(uint32_t* bitrate, uint32_t* framerate) { assert(bitrate); assert(framerate); jitter_buffer_.IncomingRateStatistics(framerate, bitrate); } void VCMReceiver::ReceivedFrameCount(VCMFrameCount* frame_count) const { assert(frame_count); jitter_buffer_.FrameStatistics(&frame_count->numDeltaFrames, &frame_count->numKeyFrames); } uint32_t VCMReceiver::DiscardedPackets() const { return jitter_buffer_.num_discarded_packets(); } void VCMReceiver::SetNackMode(VCMNackMode nackMode, int low_rtt_nack_threshold_ms, int high_rtt_nack_threshold_ms) { CriticalSectionScoped cs(crit_sect_); // Default to always having NACK enabled in hybrid mode. jitter_buffer_.SetNackMode(nackMode, low_rtt_nack_threshold_ms, high_rtt_nack_threshold_ms); if (!master_) { state_ = kPassive; // The dual decoder defaults to passive. } } void VCMReceiver::SetNackSettings(size_t max_nack_list_size, int max_packet_age_to_nack, int max_incomplete_time_ms) { jitter_buffer_.SetNackSettings(max_nack_list_size, max_packet_age_to_nack, max_incomplete_time_ms); } VCMNackMode VCMReceiver::NackMode() const { CriticalSectionScoped cs(crit_sect_); return jitter_buffer_.nack_mode(); } VCMNackStatus VCMReceiver::NackList(uint16_t* nack_list, uint16_t size, uint16_t* nack_list_length) { bool request_key_frame = false; uint16_t* internal_nack_list = jitter_buffer_.GetNackList( nack_list_length, &request_key_frame); if (*nack_list_length > size) { *nack_list_length = 0; return kNackNeedMoreMemory; } if (internal_nack_list != NULL && *nack_list_length > 0) { memcpy(nack_list, internal_nack_list, *nack_list_length * sizeof(uint16_t)); } if (request_key_frame) { return kNackKeyFrameRequest; } return kNackOk; } // Decide whether we should change decoder state. This should be done if the // dual decoder has caught up with the decoder decoding with packet losses. bool VCMReceiver::DualDecoderCaughtUp(VCMEncodedFrame* dual_frame, VCMReceiver& dual_receiver) const { if (dual_frame == NULL) { return false; } if (jitter_buffer_.LastDecodedTimestamp() == dual_frame->TimeStamp()) { dual_receiver.UpdateState(kWaitForPrimaryDecode); return true; } return false; } void VCMReceiver::CopyJitterBufferStateFromReceiver( const VCMReceiver& receiver) { jitter_buffer_.CopyFrom(receiver.jitter_buffer_); } VCMReceiverState VCMReceiver::State() const { CriticalSectionScoped cs(crit_sect_); return state_; } void VCMReceiver::SetDecodeErrorMode(VCMDecodeErrorMode decode_error_mode) { jitter_buffer_.SetDecodeErrorMode(decode_error_mode); } VCMDecodeErrorMode VCMReceiver::DecodeErrorMode() const { return jitter_buffer_.decode_error_mode(); } int VCMReceiver::SetMinReceiverDelay(int desired_delay_ms) { CriticalSectionScoped cs(crit_sect_); if (desired_delay_ms < 0 || desired_delay_ms > kMaxReceiverDelayMs) { return -1; } max_video_delay_ms_ = desired_delay_ms + kMaxVideoDelayMs; // Initializing timing to the desired delay. timing_->set_min_playout_delay(desired_delay_ms); return 0; } int VCMReceiver::RenderBufferSizeMs() { uint32_t timestamp_start = 0u; uint32_t timestamp_end = 0u; // Render timestamps are computed just prior to decoding. Therefore this is // only an estimate based on frames' timestamps and current timing state. jitter_buffer_.RenderBufferSize(&timestamp_start, &timestamp_end); if (timestamp_start == timestamp_end) { return 0; } // Update timing. const int64_t now_ms = clock_->TimeInMilliseconds(); timing_->SetJitterDelay(jitter_buffer_.EstimatedJitterMs()); // Get render timestamps. uint32_t render_start = timing_->RenderTimeMs(timestamp_start, now_ms); uint32_t render_end = timing_->RenderTimeMs(timestamp_end, now_ms); return render_end - render_start; } void VCMReceiver::UpdateState(VCMReceiverState new_state) { CriticalSectionScoped cs(crit_sect_); assert(!(state_ == kPassive && new_state == kWaitForPrimaryDecode)); state_ = new_state; } void VCMReceiver::UpdateState(const VCMEncodedFrame& frame) { if (jitter_buffer_.nack_mode() == kNoNack) { // Dual decoder mode has not been enabled. return; } // Update the dual receiver state. if (frame.Complete() && frame.FrameType() == kVideoFrameKey) { UpdateState(kPassive); } if (State() == kWaitForPrimaryDecode && frame.Complete() && !frame.MissingFrame()) { UpdateState(kPassive); } if (frame.MissingFrame() || !frame.Complete()) { // State was corrupted, enable dual receiver. UpdateState(kReceiving); } } } // namespace webrtc <commit_msg>Avoid recursively taking critical section.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/video_coding/main/source/receiver.h" #include <assert.h> #include "webrtc/modules/video_coding/main/source/encoded_frame.h" #include "webrtc/modules/video_coding/main/source/internal_defines.h" #include "webrtc/modules/video_coding/main/source/media_opt_util.h" #include "webrtc/system_wrappers/interface/clock.h" #include "webrtc/system_wrappers/interface/trace.h" #include "webrtc/system_wrappers/interface/trace_event.h" namespace webrtc { enum { kMaxReceiverDelayMs = 10000 }; VCMReceiver::VCMReceiver(VCMTiming* timing, Clock* clock, EventFactory* event_factory, int32_t vcm_id, int32_t receiver_id, bool master) : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()), vcm_id_(vcm_id), clock_(clock), receiver_id_(receiver_id), master_(master), jitter_buffer_(clock_, event_factory, vcm_id, receiver_id, master), timing_(timing), render_wait_event_(event_factory->CreateEvent()), state_(kPassive), max_video_delay_ms_(kMaxVideoDelayMs) {} VCMReceiver::~VCMReceiver() { render_wait_event_->Set(); delete crit_sect_; } void VCMReceiver::Reset() { CriticalSectionScoped cs(crit_sect_); if (!jitter_buffer_.Running()) { jitter_buffer_.Start(); } else { jitter_buffer_.Flush(); } render_wait_event_->Reset(); if (master_) { state_ = kReceiving; } else { state_ = kPassive; } } int32_t VCMReceiver::Initialize() { Reset(); CriticalSectionScoped cs(crit_sect_); if (!master_) { SetNackMode(kNoNack, -1, -1); } return VCM_OK; } void VCMReceiver::UpdateRtt(uint32_t rtt) { jitter_buffer_.UpdateRtt(rtt); } int32_t VCMReceiver::InsertPacket(const VCMPacket& packet, uint16_t frame_width, uint16_t frame_height) { if (packet.frameType == kVideoFrameKey) { WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "Inserting key frame packet seqnum=%u, timestamp=%u", packet.seqNum, packet.timestamp); } // Insert the packet into the jitter buffer. The packet can either be empty or // contain media at this point. bool retransmitted = false; const VCMFrameBufferEnum ret = jitter_buffer_.InsertPacket(packet, &retransmitted); if (ret == kOldPacket) { return VCM_OK; } else if (ret == kFlushIndicator) { return VCM_FLUSH_INDICATOR; } else if (ret < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "Error inserting packet seqnum=%u, timestamp=%u", packet.seqNum, packet.timestamp); return VCM_JITTER_BUFFER_ERROR; } if (ret == kCompleteSession && !retransmitted) { // We don't want to include timestamps which have suffered from // retransmission here, since we compensate with extra retransmission // delay within the jitter estimate. timing_->IncomingTimestamp(packet.timestamp, clock_->TimeInMilliseconds()); } if (master_) { // Only trace the primary receiver to make it possible to parse and plot // the trace file. WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "Packet seqnum=%u timestamp=%u inserted at %u", packet.seqNum, packet.timestamp, MaskWord64ToUWord32(clock_->TimeInMilliseconds())); } return VCM_OK; } VCMEncodedFrame* VCMReceiver::FrameForDecoding( uint16_t max_wait_time_ms, int64_t& next_render_time_ms, bool render_timing, VCMReceiver* dual_receiver) { const int64_t start_time_ms = clock_->TimeInMilliseconds(); uint32_t frame_timestamp = 0; // Exhaust wait time to get a complete frame for decoding. bool found_frame = jitter_buffer_.NextCompleteTimestamp( max_wait_time_ms, &frame_timestamp); if (!found_frame) { // Get an incomplete frame when enabled. const bool dual_receiver_enabled_and_passive = (dual_receiver != NULL && dual_receiver->State() == kPassive && dual_receiver->NackMode() == kNack); if (dual_receiver_enabled_and_passive && !jitter_buffer_.CompleteSequenceWithNextFrame()) { // Jitter buffer state might get corrupt with this frame. dual_receiver->CopyJitterBufferStateFromReceiver(*this); } found_frame = jitter_buffer_.NextMaybeIncompleteTimestamp( &frame_timestamp); } if (!found_frame) { return NULL; } // We have a frame - Set timing and render timestamp. timing_->SetJitterDelay(jitter_buffer_.EstimatedJitterMs()); const int64_t now_ms = clock_->TimeInMilliseconds(); timing_->UpdateCurrentDelay(frame_timestamp); next_render_time_ms = timing_->RenderTimeMs(frame_timestamp, now_ms); // Check render timing. bool timing_error = false; // Assume that render timing errors are due to changes in the video stream. if (next_render_time_ms < 0) { timing_error = true; } else if (abs(next_render_time_ms - now_ms) > max_video_delay_ms_) { WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "This frame is out of our delay bounds, resetting jitter " "buffer: %d > %d", static_cast<int>(abs(next_render_time_ms - now_ms)), max_video_delay_ms_); timing_error = true; } else if (static_cast<int>(timing_->TargetVideoDelay()) > max_video_delay_ms_) { WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "More than %u ms target delay. Flushing jitter buffer and" "resetting timing.", max_video_delay_ms_); timing_error = true; } if (timing_error) { // Timing error => reset timing and flush the jitter buffer. jitter_buffer_.Flush(); timing_->Reset(); return NULL; } if (!render_timing) { // Decode frame as close as possible to the render timestamp. const int32_t available_wait_time = max_wait_time_ms - static_cast<int32_t>(clock_->TimeInMilliseconds() - start_time_ms); uint16_t new_max_wait_time = static_cast<uint16_t>( VCM_MAX(available_wait_time, 0)); uint32_t wait_time_ms = timing_->MaxWaitingTime( next_render_time_ms, clock_->TimeInMilliseconds()); if (new_max_wait_time < wait_time_ms) { // We're not allowed to wait until the frame is supposed to be rendered, // waiting as long as we're allowed to avoid busy looping, and then return // NULL. Next call to this function might return the frame. render_wait_event_->Wait(max_wait_time_ms); return NULL; } // Wait until it's time to render. render_wait_event_->Wait(wait_time_ms); } // Extract the frame from the jitter buffer and set the render time. VCMEncodedFrame* frame = jitter_buffer_.ExtractAndSetDecode(frame_timestamp); if (frame == NULL) { return NULL; } frame->SetRenderTime(next_render_time_ms); TRACE_EVENT_ASYNC_STEP1("webrtc", "Video", frame->TimeStamp(), "SetRenderTS", "render_time", next_render_time_ms); if (dual_receiver != NULL) { dual_receiver->UpdateState(*frame); } if (!frame->Complete()) { // Update stats for incomplete frames. bool retransmitted = false; const int64_t last_packet_time_ms = jitter_buffer_.LastPacketTime(frame, &retransmitted); if (last_packet_time_ms >= 0 && !retransmitted) { // We don't want to include timestamps which have suffered from // retransmission here, since we compensate with extra retransmission // delay within the jitter estimate. timing_->IncomingTimestamp(frame_timestamp, last_packet_time_ms); } } return frame; } void VCMReceiver::ReleaseFrame(VCMEncodedFrame* frame) { jitter_buffer_.ReleaseFrame(frame); } void VCMReceiver::ReceiveStatistics(uint32_t* bitrate, uint32_t* framerate) { assert(bitrate); assert(framerate); jitter_buffer_.IncomingRateStatistics(framerate, bitrate); } void VCMReceiver::ReceivedFrameCount(VCMFrameCount* frame_count) const { assert(frame_count); jitter_buffer_.FrameStatistics(&frame_count->numDeltaFrames, &frame_count->numKeyFrames); } uint32_t VCMReceiver::DiscardedPackets() const { return jitter_buffer_.num_discarded_packets(); } void VCMReceiver::SetNackMode(VCMNackMode nackMode, int low_rtt_nack_threshold_ms, int high_rtt_nack_threshold_ms) { CriticalSectionScoped cs(crit_sect_); // Default to always having NACK enabled in hybrid mode. jitter_buffer_.SetNackMode(nackMode, low_rtt_nack_threshold_ms, high_rtt_nack_threshold_ms); if (!master_) { state_ = kPassive; // The dual decoder defaults to passive. } } void VCMReceiver::SetNackSettings(size_t max_nack_list_size, int max_packet_age_to_nack, int max_incomplete_time_ms) { jitter_buffer_.SetNackSettings(max_nack_list_size, max_packet_age_to_nack, max_incomplete_time_ms); } VCMNackMode VCMReceiver::NackMode() const { CriticalSectionScoped cs(crit_sect_); return jitter_buffer_.nack_mode(); } VCMNackStatus VCMReceiver::NackList(uint16_t* nack_list, uint16_t size, uint16_t* nack_list_length) { bool request_key_frame = false; uint16_t* internal_nack_list = jitter_buffer_.GetNackList( nack_list_length, &request_key_frame); if (*nack_list_length > size) { *nack_list_length = 0; return kNackNeedMoreMemory; } if (internal_nack_list != NULL && *nack_list_length > 0) { memcpy(nack_list, internal_nack_list, *nack_list_length * sizeof(uint16_t)); } if (request_key_frame) { return kNackKeyFrameRequest; } return kNackOk; } // Decide whether we should change decoder state. This should be done if the // dual decoder has caught up with the decoder decoding with packet losses. bool VCMReceiver::DualDecoderCaughtUp(VCMEncodedFrame* dual_frame, VCMReceiver& dual_receiver) const { if (dual_frame == NULL) { return false; } if (jitter_buffer_.LastDecodedTimestamp() == dual_frame->TimeStamp()) { dual_receiver.UpdateState(kWaitForPrimaryDecode); return true; } return false; } void VCMReceiver::CopyJitterBufferStateFromReceiver( const VCMReceiver& receiver) { jitter_buffer_.CopyFrom(receiver.jitter_buffer_); } VCMReceiverState VCMReceiver::State() const { CriticalSectionScoped cs(crit_sect_); return state_; } void VCMReceiver::SetDecodeErrorMode(VCMDecodeErrorMode decode_error_mode) { jitter_buffer_.SetDecodeErrorMode(decode_error_mode); } VCMDecodeErrorMode VCMReceiver::DecodeErrorMode() const { return jitter_buffer_.decode_error_mode(); } int VCMReceiver::SetMinReceiverDelay(int desired_delay_ms) { CriticalSectionScoped cs(crit_sect_); if (desired_delay_ms < 0 || desired_delay_ms > kMaxReceiverDelayMs) { return -1; } max_video_delay_ms_ = desired_delay_ms + kMaxVideoDelayMs; // Initializing timing to the desired delay. timing_->set_min_playout_delay(desired_delay_ms); return 0; } int VCMReceiver::RenderBufferSizeMs() { uint32_t timestamp_start = 0u; uint32_t timestamp_end = 0u; // Render timestamps are computed just prior to decoding. Therefore this is // only an estimate based on frames' timestamps and current timing state. jitter_buffer_.RenderBufferSize(&timestamp_start, &timestamp_end); if (timestamp_start == timestamp_end) { return 0; } // Update timing. const int64_t now_ms = clock_->TimeInMilliseconds(); timing_->SetJitterDelay(jitter_buffer_.EstimatedJitterMs()); // Get render timestamps. uint32_t render_start = timing_->RenderTimeMs(timestamp_start, now_ms); uint32_t render_end = timing_->RenderTimeMs(timestamp_end, now_ms); return render_end - render_start; } void VCMReceiver::UpdateState(VCMReceiverState new_state) { CriticalSectionScoped cs(crit_sect_); assert(!(state_ == kPassive && new_state == kWaitForPrimaryDecode)); state_ = new_state; } void VCMReceiver::UpdateState(const VCMEncodedFrame& frame) { if (jitter_buffer_.nack_mode() == kNoNack) { // Dual decoder mode has not been enabled. return; } // Update the dual receiver state. if (frame.Complete() && frame.FrameType() == kVideoFrameKey) { UpdateState(kPassive); } if (State() == kWaitForPrimaryDecode && frame.Complete() && !frame.MissingFrame()) { UpdateState(kPassive); } if (frame.MissingFrame() || !frame.Complete()) { // State was corrupted, enable dual receiver. UpdateState(kReceiving); } } } // namespace webrtc <|endoftext|>
<commit_before>#include "GraphicsHandler.h" int GraphicsHandler::IncreaseArraySize() { GraphicsComponent** newArray = new GraphicsComponent*[this->m_maxGraphicsComponents + ARRAY_INC]; for (int i = 0; i < this->m_maxGraphicsComponents; i++) { newArray[i] = this->m_graphicsComponents[i]; } delete[] this->m_graphicsComponents; this->m_graphicsComponents = newArray; this->m_maxGraphicsComponents += ARRAY_INC; return 1; } int GraphicsHandler::DecreaseArraySize() { this->m_maxGraphicsComponents -= ARRAY_INC; GraphicsComponent** newArray = new GraphicsComponent*[this->m_maxGraphicsComponents]; for (int i = 0; i < this->m_maxGraphicsComponents; i++) { newArray[i] = this->m_graphicsComponents[i]; } for (int i = this->m_maxGraphicsComponents; i < this->m_maxGraphicsComponents + ARRAY_INC; i++) { if (this->m_graphicsComponents[i]) { delete this->m_graphicsComponents[i]; } } delete[] this->m_graphicsComponents; this->m_graphicsComponents = newArray; return 1; } GraphicsHandler::GraphicsHandler() { this->m_d3dHandler = nullptr; this->m_deferredSH = nullptr; this->m_lightSH = nullptr; this->m_indexBuffer = nullptr; this->m_vertexBuffer = nullptr; this->m_camera = nullptr; this->m_graphicsComponents = nullptr; this->m_nrOfGraphicsComponents = 0; this->m_maxGraphicsComponents = 5; } GraphicsHandler::~GraphicsHandler() { } int GraphicsHandler::Initialize(HWND * windowHandle, const DirectX::XMINT2& resolution) { this->m_d3dHandler = new Direct3DHandler; if (this->m_d3dHandler->Initialize(windowHandle, resolution)) { return 1; } Resources::ResourceHandler::GetInstance()->LoadLevel(UINT(1337)); //placeholder id this->m_deferredSH = new DeferredShaderHandler; if (this->m_deferredSH->Initialize(this->m_d3dHandler->GetDevice(), windowHandle, resolution)) { return 1; } this->m_lightSH = new LightShaderHandler; if (this->m_lightSH->Initialize(this->m_d3dHandler->GetDevice(), windowHandle, resolution)) { return 1; } this->m_camera = new Camera; this->m_camera->Initialize(); //Setup projection matrix //fieldOfView = 3.141592654f / 4.0f; float fieldOfView = (float)DirectX::XM_PI / 4.0f; float screenAspect = (float)resolution.x / (float)resolution.y; DirectX::XMStoreFloat4x4(&m_projectionMatrix, DirectX::XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, 0.1f, 1000.0f)); this->CreateTriangle(); this->m_graphicsComponents = new GraphicsComponent*[this->m_maxGraphicsComponents]; for (int i = 0; i < this->m_maxGraphicsComponents; i++) { this->m_graphicsComponents[i] = nullptr; } DirectX::XMMATRIX tempWorld = DirectX::XMMatrixIdentity(); //DirectX::XMFLOAT4X4 worldMatrix; //DirectX::XMStoreFloat4x4(&worldMatrix, tempWorld); this->m_graphicsComponents[this->m_nrOfGraphicsComponents] = new GraphicsComponent; this->m_graphicsComponents[this->m_nrOfGraphicsComponents]->worldMatrix = tempWorld; this->m_nrOfGraphicsComponents++; tempWorld = DirectX::XMMatrixTranslation(1.f, 0.f, 6.f); tempWorld = DirectX::XMMatrixMultiply(tempWorld, DirectX::XMMatrixRotationZ(.3f)); //DirectX::XMStoreFloat4x4(&worldMatrix, tempWorld); this->m_graphicsComponents[this->m_nrOfGraphicsComponents] = new GraphicsComponent; this->m_graphicsComponents[this->m_nrOfGraphicsComponents]->worldMatrix = tempWorld; this->m_nrOfGraphicsComponents++; tempWorld = DirectX::XMMatrixTranslation(-1.f, 0.5f, 6.f); tempWorld = DirectX::XMMatrixMultiply(tempWorld, DirectX::XMMatrixRotationZ(.3f)); tempWorld = DirectX::XMMatrixMultiply(tempWorld, DirectX::XMMatrixScaling(0.5f, 0.5f, 0.5f)); //DirectX::XMStoreFloat4x4(&worldMatrix, tempWorld); this->m_graphicsComponents[this->m_nrOfGraphicsComponents] = new GraphicsComponent; this->m_graphicsComponents[this->m_nrOfGraphicsComponents]->worldMatrix = tempWorld; this->m_nrOfGraphicsComponents++; return 0; } Camera* GraphicsHandler::SetCamera(Camera * newCamera) { int result = 1; Camera* tempCam = this->m_camera; this->m_camera = newCamera; return tempCam; } int GraphicsHandler::Render() { this->m_deferredSH->ClearRenderTargetViews(this->m_d3dHandler->GetDeviceContext()); DirectX::XMMATRIX viewMatrix; this->m_camera->GetViewMatrix(viewMatrix); this->SetTriangle(); this->m_deferredSH->SetActive(this->m_d3dHandler->GetDeviceContext(), ShaderLib::ShaderType::Normal); ShaderLib::DeferredConstantBufferWorld* shaderParamsWorld = new ShaderLib::DeferredConstantBufferWorld; ShaderLib::DeferredConstantBufferVP* shaderParamsVP = new ShaderLib::DeferredConstantBufferVP; ShaderLib::DeferredConstantBufferWorldxm * shaderParamsXM = new ShaderLib::DeferredConstantBufferWorldxm; shaderParamsVP->viewMatrix = *this->m_camera->GetViewMatrix(); shaderParamsVP->projectionMatrix = this->m_projectionMatrix; this->m_deferredSH->SetShaderParameters(this->m_d3dHandler->GetDeviceContext(), shaderParamsVP, ShaderLib::VIEW_PROJECTION); /*TEMP*/ Resources::Model* modelPtr; Resources::ResourceHandler::GetInstance()->GetModel(UINT(111337),modelPtr); Resources::Mesh* meshPtr = modelPtr->GetMesh(); ID3D11Buffer* vBuf = meshPtr->GetVerticesBuffer(); ID3D11Buffer* iBuf = meshPtr->GetIndicesBuffer(); UINT32 size = sizeof(Resources::Mesh::Vertex); UINT32 offset = 0; ID3D11DeviceContext* dev = m_d3dHandler->GetDeviceContext(); dev->IASetVertexBuffers(0, 1, &vBuf, &size, &offset); m_d3dHandler->GetDeviceContext()->IASetIndexBuffer(iBuf, DXGI_FORMAT::DXGI_FORMAT_R32_UINT, 0); Resources::Material * mat = modelPtr->GetMaterial(); Resources::Texture** textures = mat->GetAllTextures(); ID3D11ShaderResourceView* resViews[5]; UINT numViews = 0; for (size_t i = 0; i < 5; i++) { if (textures[i] == nullptr) continue; resViews[numViews] = textures[i]->GetResourceView(); numViews += 1; } m_d3dHandler->GetDeviceContext()->PSSetShaderResources(0, numViews, resViews); /********/ ////TEST ROTATION //static DirectX::XMMATRIX rotation = DirectX::XMMatrixIdentity(); //rotation = DirectX::XMMatrixMultiply(rotation, DirectX::XMMatrixRotationY(0.0000000005f)); //this->m_graphicsComponents[0]->worldMatrix = DirectX::XMMatrixMultiply(rotation, this->m_graphicsComponents[0]->worldMatrix); ////END TEST ROTATION shaderParamsWorld->worldMatrix = DirectX::XMFLOAT4X4(); for (int i = 0; i < this->m_nrOfGraphicsComponents; i++) { shaderParamsXM->worldMatrix = this->m_graphicsComponents[i]->worldMatrix; //DirectX::XMStoreFloat4x4(&shaderParamsWorld->worldMatrix, this->m_graphicsComponents[i]->worldMatrix); this->m_deferredSH->SetShaderParameters(this->m_d3dHandler->GetDeviceContext(), shaderParamsXM, ShaderLib::WORLD); //this->m_d3dHandler->GetDeviceContext()->DrawIndexed(3, 0, 0); this->m_d3dHandler->GetDeviceContext()->DrawIndexed(meshPtr->GetNumIndices(), 0, 0); } delete shaderParamsVP; delete shaderParamsWorld; this->m_d3dHandler->ClearDepthAndRTV(this->m_deferredSH->GetDSV()); this->m_d3dHandler->SetBackBuffer(this->m_deferredSH->GetDSV()); this->m_lightSH->SetActive(this->m_d3dHandler->GetDeviceContext(), ShaderLib::ShaderType::Normal); ShaderLib::LightConstantBuffer* lShaderParams = new ShaderLib::LightConstantBuffer; lShaderParams->camPos = this->m_camera->GetCameraPos(); lShaderParams->camDir = this->m_camera->GetLookAt(); this->m_lightSH->SetShaderParameters(this->m_d3dHandler->GetDeviceContext(), lShaderParams, this->m_deferredSH->GetShaderResourceViews()); delete lShaderParams; this->m_d3dHandler->GetDeviceContext()->DrawIndexed(6, 0, 0); this->m_lightSH->ResetPSShaderResources(this->m_d3dHandler->GetDeviceContext()); this->m_d3dHandler->PresentScene(); return 0; } void GraphicsHandler::Shutdown() { if (this->m_d3dHandler) { this->m_d3dHandler->Shutdown(); delete this->m_d3dHandler; this->m_d3dHandler = nullptr; } if (this->m_deferredSH) { this->m_deferredSH->Shutdown(); delete this->m_deferredSH; this->m_deferredSH = nullptr; } if (this->m_lightSH) { this->m_lightSH->Shutdown(); delete this->m_lightSH; this->m_lightSH = nullptr; } if (this->m_indexBuffer) { this->m_indexBuffer->Release(); this->m_indexBuffer = nullptr; } if (this->m_vertexBuffer) { this->m_vertexBuffer->Release(); this->m_vertexBuffer = nullptr; } if (this->m_windowHandle) { this->m_windowHandle = nullptr; } for (int i = 0; i < this->m_nrOfGraphicsComponents; i++) { if (this->m_graphicsComponents[i]) { delete this->m_graphicsComponents[i]; this->m_graphicsComponents[i] = nullptr; } } delete[] this->m_graphicsComponents; } int GraphicsHandler::CreateTriangle() { DirectX::XMFLOAT3 vertices[3]; unsigned long indices[3]; int sizeVertices = 3; int sizeIndices = 3; D3D11_BUFFER_DESC vertexBufferDesc; D3D11_BUFFER_DESC indexBufferDesc; D3D11_SUBRESOURCE_DATA vertexData; D3D11_SUBRESOURCE_DATA indexData; HRESULT hresult; vertices[0] = DirectX::XMFLOAT3(-.5f, -.5f, 2.0f); //bottom left vertices[1] = DirectX::XMFLOAT3(0.0f, .5f, 2.0f); //top mid vertices[2] = DirectX::XMFLOAT3(.5f, -.5f, 2.0f); //bottom right //Load the index array with data for (int i = 0; i < sizeIndices; i++) { indices[i] = i; } //Set the description of the static vertex buffer ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc)); vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT; vertexBufferDesc.ByteWidth = sizeof(DirectX::XMFLOAT3) * sizeVertices; vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexBufferDesc.CPUAccessFlags = 0; vertexBufferDesc.MiscFlags = 0; vertexBufferDesc.StructureByteStride = 0; //Give the subresource structure a pointer to the vertex data ZeroMemory(&vertexData, sizeof(vertexData)); vertexData.pSysMem = &vertices; vertexData.SysMemPitch = 0; vertexData.SysMemSlicePitch = 0; //Create the vertex buffer hresult = this->m_d3dHandler->GetDevice()->CreateBuffer(&vertexBufferDesc, &vertexData, &this->m_vertexBuffer); if (FAILED(hresult)) { return 1; } //Set up the description of the static index buffer ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc)); indexBufferDesc.Usage = D3D11_USAGE_DEFAULT; indexBufferDesc.ByteWidth = sizeof(unsigned long) * sizeIndices; indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; indexBufferDesc.CPUAccessFlags = 0; indexBufferDesc.MiscFlags = 0; indexBufferDesc.StructureByteStride = 0; ZeroMemory(&indexData, sizeof(indexData)); indexData.pSysMem = &indices; indexData.SysMemPitch = 0; indexData.SysMemSlicePitch = 0; //Create the index buffer hresult = this->m_d3dHandler->GetDevice()->CreateBuffer(&indexBufferDesc, &indexData, &this->m_indexBuffer); if (FAILED(hresult)) { return 1; } return 0; } int GraphicsHandler::SetTriangle() { unsigned int stride; unsigned offset; //Set vertex buffer stride and offset stride = sizeof(DirectX::XMFLOAT3); offset = 0; //Set the vertex buffer to active in the input assembly so it can rendered this->m_d3dHandler->GetDeviceContext()->IASetVertexBuffers(0, 1, &this->m_vertexBuffer, &stride, &offset); //Set the index buffer to active in the input assembler so it can be rendered this->m_d3dHandler->GetDeviceContext()->IASetIndexBuffer(this->m_indexBuffer, DXGI_FORMAT_R32_UINT, 0); //Set the type od primitiv that should be rendered from this vertex buffer, in this case triangles this->m_d3dHandler->GetDeviceContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); return 0; } <commit_msg>UPDATE cleanup<commit_after>#include "GraphicsHandler.h" int GraphicsHandler::IncreaseArraySize() { GraphicsComponent** newArray = new GraphicsComponent*[this->m_maxGraphicsComponents + ARRAY_INC]; for (int i = 0; i < this->m_maxGraphicsComponents; i++) { newArray[i] = this->m_graphicsComponents[i]; } delete[] this->m_graphicsComponents; this->m_graphicsComponents = newArray; this->m_maxGraphicsComponents += ARRAY_INC; return 1; } int GraphicsHandler::DecreaseArraySize() { this->m_maxGraphicsComponents -= ARRAY_INC; GraphicsComponent** newArray = new GraphicsComponent*[this->m_maxGraphicsComponents]; for (int i = 0; i < this->m_maxGraphicsComponents; i++) { newArray[i] = this->m_graphicsComponents[i]; } for (int i = this->m_maxGraphicsComponents; i < this->m_maxGraphicsComponents + ARRAY_INC; i++) { if (this->m_graphicsComponents[i]) { delete this->m_graphicsComponents[i]; } } delete[] this->m_graphicsComponents; this->m_graphicsComponents = newArray; return 1; } GraphicsHandler::GraphicsHandler() { this->m_d3dHandler = nullptr; this->m_deferredSH = nullptr; this->m_lightSH = nullptr; this->m_indexBuffer = nullptr; this->m_vertexBuffer = nullptr; this->m_camera = nullptr; this->m_graphicsComponents = nullptr; this->m_nrOfGraphicsComponents = 0; this->m_maxGraphicsComponents = 5; } GraphicsHandler::~GraphicsHandler() { } int GraphicsHandler::Initialize(HWND * windowHandle, const DirectX::XMINT2& resolution) { this->m_d3dHandler = new Direct3DHandler; if (this->m_d3dHandler->Initialize(windowHandle, resolution)) { return 1; } Resources::ResourceHandler::GetInstance()->LoadLevel(UINT(1337)); //placeholder id this->m_deferredSH = new DeferredShaderHandler; if (this->m_deferredSH->Initialize(this->m_d3dHandler->GetDevice(), windowHandle, resolution)) { return 1; } this->m_lightSH = new LightShaderHandler; if (this->m_lightSH->Initialize(this->m_d3dHandler->GetDevice(), windowHandle, resolution)) { return 1; } this->m_camera = new Camera; this->m_camera->Initialize(); //Setup projection matrix //fieldOfView = 3.141592654f / 4.0f; float fieldOfView = (float)DirectX::XM_PI / 4.0f; float screenAspect = (float)resolution.x / (float)resolution.y; DirectX::XMStoreFloat4x4(&m_projectionMatrix, DirectX::XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, 0.1f, 1000.0f)); this->CreateTriangle(); this->m_graphicsComponents = new GraphicsComponent*[this->m_maxGraphicsComponents]; for (int i = 0; i < this->m_maxGraphicsComponents; i++) { this->m_graphicsComponents[i] = nullptr; } DirectX::XMMATRIX tempWorld = DirectX::XMMatrixIdentity(); //DirectX::XMFLOAT4X4 worldMatrix; //DirectX::XMStoreFloat4x4(&worldMatrix, tempWorld); this->m_graphicsComponents[this->m_nrOfGraphicsComponents] = new GraphicsComponent; this->m_graphicsComponents[this->m_nrOfGraphicsComponents]->worldMatrix = tempWorld; this->m_nrOfGraphicsComponents++; tempWorld = DirectX::XMMatrixTranslation(1.f, 0.f, 6.f); tempWorld = DirectX::XMMatrixMultiply(tempWorld, DirectX::XMMatrixRotationZ(.3f)); //DirectX::XMStoreFloat4x4(&worldMatrix, tempWorld); this->m_graphicsComponents[this->m_nrOfGraphicsComponents] = new GraphicsComponent; this->m_graphicsComponents[this->m_nrOfGraphicsComponents]->worldMatrix = tempWorld; this->m_nrOfGraphicsComponents++; tempWorld = DirectX::XMMatrixTranslation(-1.f, 0.5f, 6.f); tempWorld = DirectX::XMMatrixMultiply(tempWorld, DirectX::XMMatrixRotationZ(.3f)); tempWorld = DirectX::XMMatrixMultiply(tempWorld, DirectX::XMMatrixScaling(0.5f, 0.5f, 0.5f)); //DirectX::XMStoreFloat4x4(&worldMatrix, tempWorld); this->m_graphicsComponents[this->m_nrOfGraphicsComponents] = new GraphicsComponent; this->m_graphicsComponents[this->m_nrOfGraphicsComponents]->worldMatrix = tempWorld; this->m_nrOfGraphicsComponents++; return 0; } Camera* GraphicsHandler::SetCamera(Camera * newCamera) { int result = 1; Camera* tempCam = this->m_camera; this->m_camera = newCamera; return tempCam; } int GraphicsHandler::Render() { this->m_deferredSH->ClearRenderTargetViews(this->m_d3dHandler->GetDeviceContext()); DirectX::XMMATRIX viewMatrix; this->m_camera->GetViewMatrix(viewMatrix); this->SetTriangle(); this->m_deferredSH->SetActive(this->m_d3dHandler->GetDeviceContext(), ShaderLib::ShaderType::Normal); ShaderLib::DeferredConstantBufferWorld* shaderParamsWorld = new ShaderLib::DeferredConstantBufferWorld; ShaderLib::DeferredConstantBufferVP* shaderParamsVP = new ShaderLib::DeferredConstantBufferVP; ShaderLib::DeferredConstantBufferWorldxm * shaderParamsXM = new ShaderLib::DeferredConstantBufferWorldxm; shaderParamsVP->viewMatrix = *this->m_camera->GetViewMatrix(); shaderParamsVP->projectionMatrix = this->m_projectionMatrix; this->m_deferredSH->SetShaderParameters(this->m_d3dHandler->GetDeviceContext(), shaderParamsVP, ShaderLib::VIEW_PROJECTION); /*TEMP*/ Resources::Model* modelPtr; Resources::ResourceHandler::GetInstance()->GetModel(UINT(111337),modelPtr); Resources::Mesh* meshPtr = modelPtr->GetMesh(); ID3D11Buffer* vBuf = meshPtr->GetVerticesBuffer(); ID3D11Buffer* iBuf = meshPtr->GetIndicesBuffer(); UINT32 size = sizeof(Resources::Mesh::Vertex); UINT32 offset = 0; ID3D11DeviceContext* dev = m_d3dHandler->GetDeviceContext(); dev->IASetVertexBuffers(0, 1, &vBuf, &size, &offset); m_d3dHandler->GetDeviceContext()->IASetIndexBuffer(iBuf, DXGI_FORMAT::DXGI_FORMAT_R32_UINT, 0); Resources::Material * mat = modelPtr->GetMaterial(); Resources::Texture** textures = mat->GetAllTextures(); ID3D11ShaderResourceView* resViews[5]; UINT numViews = 0; for (size_t i = 0; i < 5; i++) { if (textures[i] == nullptr) continue; resViews[numViews] = textures[i]->GetResourceView(); numViews += 1; } m_d3dHandler->GetDeviceContext()->PSSetShaderResources(0, numViews, resViews); /********/ ////TEST ROTATION //static DirectX::XMMATRIX rotation = DirectX::XMMatrixIdentity(); //rotation = DirectX::XMMatrixMultiply(rotation, DirectX::XMMatrixRotationY(0.0000000005f)); //this->m_graphicsComponents[0]->worldMatrix = DirectX::XMMatrixMultiply(rotation, this->m_graphicsComponents[0]->worldMatrix); ////END TEST ROTATION for (int i = 0; i < this->m_nrOfGraphicsComponents; i++) { shaderParamsXM->worldMatrix = this->m_graphicsComponents[i]->worldMatrix; //DirectX::XMStoreFloat4x4(&shaderParamsWorld->worldMatrix, this->m_graphicsComponents[i]->worldMatrix); this->m_deferredSH->SetShaderParameters(this->m_d3dHandler->GetDeviceContext(), shaderParamsXM, ShaderLib::WORLD); //this->m_d3dHandler->GetDeviceContext()->DrawIndexed(3, 0, 0); this->m_d3dHandler->GetDeviceContext()->DrawIndexed(meshPtr->GetNumIndices(), 0, 0); } delete shaderParamsVP; delete shaderParamsWorld; this->m_d3dHandler->ClearDepthAndRTV(this->m_deferredSH->GetDSV()); this->m_d3dHandler->SetBackBuffer(this->m_deferredSH->GetDSV()); this->m_lightSH->SetActive(this->m_d3dHandler->GetDeviceContext(), ShaderLib::ShaderType::Normal); ShaderLib::LightConstantBuffer* lShaderParams = new ShaderLib::LightConstantBuffer; lShaderParams->camPos = this->m_camera->GetCameraPos(); lShaderParams->camDir = this->m_camera->GetLookAt(); this->m_lightSH->SetShaderParameters(this->m_d3dHandler->GetDeviceContext(), lShaderParams, this->m_deferredSH->GetShaderResourceViews()); delete lShaderParams; this->m_d3dHandler->GetDeviceContext()->DrawIndexed(6, 0, 0); this->m_lightSH->ResetPSShaderResources(this->m_d3dHandler->GetDeviceContext()); this->m_d3dHandler->PresentScene(); return 0; } void GraphicsHandler::Shutdown() { if (this->m_d3dHandler) { this->m_d3dHandler->Shutdown(); delete this->m_d3dHandler; this->m_d3dHandler = nullptr; } if (this->m_deferredSH) { this->m_deferredSH->Shutdown(); delete this->m_deferredSH; this->m_deferredSH = nullptr; } if (this->m_lightSH) { this->m_lightSH->Shutdown(); delete this->m_lightSH; this->m_lightSH = nullptr; } if (this->m_indexBuffer) { this->m_indexBuffer->Release(); this->m_indexBuffer = nullptr; } if (this->m_vertexBuffer) { this->m_vertexBuffer->Release(); this->m_vertexBuffer = nullptr; } if (this->m_windowHandle) { this->m_windowHandle = nullptr; } for (int i = 0; i < this->m_nrOfGraphicsComponents; i++) { if (this->m_graphicsComponents[i]) { delete this->m_graphicsComponents[i]; this->m_graphicsComponents[i] = nullptr; } } delete[] this->m_graphicsComponents; } int GraphicsHandler::CreateTriangle() { DirectX::XMFLOAT3 vertices[3]; unsigned long indices[3]; int sizeVertices = 3; int sizeIndices = 3; D3D11_BUFFER_DESC vertexBufferDesc; D3D11_BUFFER_DESC indexBufferDesc; D3D11_SUBRESOURCE_DATA vertexData; D3D11_SUBRESOURCE_DATA indexData; HRESULT hresult; vertices[0] = DirectX::XMFLOAT3(-.5f, -.5f, 2.0f); //bottom left vertices[1] = DirectX::XMFLOAT3(0.0f, .5f, 2.0f); //top mid vertices[2] = DirectX::XMFLOAT3(.5f, -.5f, 2.0f); //bottom right //Load the index array with data for (int i = 0; i < sizeIndices; i++) { indices[i] = i; } //Set the description of the static vertex buffer ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc)); vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT; vertexBufferDesc.ByteWidth = sizeof(DirectX::XMFLOAT3) * sizeVertices; vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexBufferDesc.CPUAccessFlags = 0; vertexBufferDesc.MiscFlags = 0; vertexBufferDesc.StructureByteStride = 0; //Give the subresource structure a pointer to the vertex data ZeroMemory(&vertexData, sizeof(vertexData)); vertexData.pSysMem = &vertices; vertexData.SysMemPitch = 0; vertexData.SysMemSlicePitch = 0; //Create the vertex buffer hresult = this->m_d3dHandler->GetDevice()->CreateBuffer(&vertexBufferDesc, &vertexData, &this->m_vertexBuffer); if (FAILED(hresult)) { return 1; } //Set up the description of the static index buffer ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc)); indexBufferDesc.Usage = D3D11_USAGE_DEFAULT; indexBufferDesc.ByteWidth = sizeof(unsigned long) * sizeIndices; indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; indexBufferDesc.CPUAccessFlags = 0; indexBufferDesc.MiscFlags = 0; indexBufferDesc.StructureByteStride = 0; ZeroMemory(&indexData, sizeof(indexData)); indexData.pSysMem = &indices; indexData.SysMemPitch = 0; indexData.SysMemSlicePitch = 0; //Create the index buffer hresult = this->m_d3dHandler->GetDevice()->CreateBuffer(&indexBufferDesc, &indexData, &this->m_indexBuffer); if (FAILED(hresult)) { return 1; } return 0; } int GraphicsHandler::SetTriangle() { unsigned int stride; unsigned offset; //Set vertex buffer stride and offset stride = sizeof(DirectX::XMFLOAT3); offset = 0; //Set the vertex buffer to active in the input assembly so it can rendered this->m_d3dHandler->GetDeviceContext()->IASetVertexBuffers(0, 1, &this->m_vertexBuffer, &stride, &offset); //Set the index buffer to active in the input assembler so it can be rendered this->m_d3dHandler->GetDeviceContext()->IASetIndexBuffer(this->m_indexBuffer, DXGI_FORMAT_R32_UINT, 0); //Set the type od primitiv that should be rendered from this vertex buffer, in this case triangles this->m_d3dHandler->GetDeviceContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); return 0; } <|endoftext|>